Реализовал функцию импорта сертификатов. Если он есть она обновляет, если сертификат было по умолнчаию она оставляет по умолчанию
This commit is contained in:
+117
-12
@@ -2,7 +2,7 @@ from structs import CertInfo, DSMInfo
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from cryptography import x509
|
from cryptography import x509
|
||||||
from cryptography.hazmat.primitives import hashes
|
from cryptography.hazmat.primitives import hashes, serialization
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
@@ -39,32 +39,137 @@ class CaddyWorker:
|
|||||||
|
|
||||||
|
|
||||||
def get_cert_info(self, path_to_crt_file) -> CertInfo | None:
|
def get_cert_info(self, path_to_crt_file) -> CertInfo | None:
|
||||||
path = Path(path_to_crt_file)
|
cert_path = Path(path_to_crt_file)
|
||||||
if not path.is_file():
|
if not cert_path.is_file():
|
||||||
logging.error(f"Certificate file not found: {path}")
|
logging.error(f"Certificate file not found: {cert_path}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(path, "rb") as file:
|
with open(cert_path, "rb") as file:
|
||||||
cert_data = file.read()
|
cert_data = file.read()
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
logging.error(f"Cannot open certificate file {path}: {e}")
|
logging.error(f"Cannot open certificate file {cert_path}: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
certificate = x509.load_pem_x509_certificate(cert_data)
|
certificate = x509.load_pem_x509_certificate(cert_data)
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
logging.error(f"Invalid certificate {path}: {e}")
|
logging.error(f"Invalid certificate {cert_path}: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
fingerprint = certificate.fingerprint(
|
fingerprint = certificate.fingerprint(hashes.SHA256()).hex(":").upper()
|
||||||
hashes.SHA256()
|
|
||||||
).hex(":").upper()
|
|
||||||
|
|
||||||
domain_name =certificate.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME)[0].value
|
domain_name = certificate.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME)[0].value
|
||||||
return CertInfo(
|
return CertInfo(
|
||||||
domain_name=domain_name,
|
domain_name=domain_name,
|
||||||
fingerprint=fingerprint,
|
fingerprint=fingerprint,
|
||||||
expires_at=certificate.not_valid_after_utc,
|
expires_at=certificate.not_valid_after_utc,
|
||||||
path_to_key=path_to_crt_file.with_suffix(".key"),
|
path_to_key=cert_path.with_suffix(".key"),
|
||||||
|
dir_cert=cert_path.parent,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def convert_to_dsm(self, path_to_dir_cert, path_to_save) -> DSMInfo | None:
|
||||||
|
|
||||||
|
cert_dir = Path(path_to_dir_cert)
|
||||||
|
save_dir = Path(path_to_save) / cert_dir.name / "tmp"
|
||||||
|
|
||||||
|
site_name = cert_dir.name
|
||||||
|
crt_file = cert_dir / f"{site_name}.crt"
|
||||||
|
key_file = cert_dir / f"{site_name}.key"
|
||||||
|
|
||||||
|
if not crt_file:
|
||||||
|
logging.error(f"No certificate found in: {cert_dir}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
if not key_file:
|
||||||
|
logging.error(f"No key found in: {cert_dir}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(crt_file, "rb") as file:
|
||||||
|
cert_data = file.read()
|
||||||
|
|
||||||
|
certificate = x509.load_pem_x509_certificate(cert_data)
|
||||||
|
|
||||||
|
except (OSError, ValueError) as e:
|
||||||
|
logging.error(f"Invalid certificate {crt_file}: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
common_names = certificate.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME)
|
||||||
|
|
||||||
|
if not common_names:
|
||||||
|
logging.error(f"Certificate has no Common Name: {crt_file}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
domain_name = common_names[0].value
|
||||||
|
|
||||||
|
save_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
cert_pem_path = save_dir / "cert.pem"
|
||||||
|
fullchain_pem_path = save_dir / "fullchain.pem"
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
certificates = [
|
||||||
|
x509.load_pem_x509_certificate(cert + b"-----END CERTIFICATE-----")
|
||||||
|
for cert in cert_data.split(b"-----END CERTIFICATE-----")
|
||||||
|
if b"-----BEGIN CERTIFICATE-----" in cert
|
||||||
|
]
|
||||||
|
|
||||||
|
if len(certificates) < 2:
|
||||||
|
logging.error(f"Certificate chain is too short: {crt_file}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
cert_pem_path.write_bytes(
|
||||||
|
certificates[0].public_bytes(serialization.Encoding.PEM)
|
||||||
|
)
|
||||||
|
|
||||||
|
fullchain_pem_path.write_bytes(
|
||||||
|
b"".join(
|
||||||
|
cert.public_bytes(serialization.Encoding.PEM)
|
||||||
|
for cert in certificates[1:]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
except OSError as e:
|
||||||
|
logging.error(f"Cannot save certificates: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(key_file, "rb") as file:
|
||||||
|
private_key = serialization.load_pem_private_key(
|
||||||
|
file.read(),
|
||||||
|
password=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
cert_public_key = certificate.public_key().public_bytes(
|
||||||
|
serialization.Encoding.DER,
|
||||||
|
serialization.PublicFormat.SubjectPublicKeyInfo,
|
||||||
|
)
|
||||||
|
|
||||||
|
key_public_key = private_key.public_key().public_bytes(
|
||||||
|
serialization.Encoding.DER,
|
||||||
|
serialization.PublicFormat.SubjectPublicKeyInfo,
|
||||||
|
)
|
||||||
|
|
||||||
|
if cert_public_key != key_public_key:
|
||||||
|
logging.error(
|
||||||
|
f"Certificate and private key do not match: {key_file}"
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
|
except (OSError, ValueError, TypeError) as e:
|
||||||
|
logging.error(f"Invalid private key {key_file}: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
except (OSError, ValueError, TypeError) as e:
|
||||||
|
logging.error(f"Invalid private key {key_file}: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
return DSMInfo(
|
||||||
|
certificate_name=domain_name,
|
||||||
|
private_key_path=key_file,
|
||||||
|
certificate_pem_path=cert_pem_path,
|
||||||
|
path_to_fullchain=fullchain_pem_path,
|
||||||
|
)
|
||||||
+128
-2
@@ -1,6 +1,6 @@
|
|||||||
|
|
||||||
from service_functions import ServiceFunctions
|
from service_functions import ServiceFunctions
|
||||||
from structs import DSMAuthInfo, DSMCredentials
|
from structs import DSMAuthInfo, DSMInfo
|
||||||
import logging
|
import logging
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
@@ -17,6 +17,10 @@ class DSMWorker:
|
|||||||
CERT_VERSION = "1"
|
CERT_VERSION = "1"
|
||||||
CERT_METHOD_LIST = "list"
|
CERT_METHOD_LIST = "list"
|
||||||
|
|
||||||
|
CERT_IMPORT_API = "SYNO.Core.Certificate"
|
||||||
|
CERT_IMPORT_VERSION = "1"
|
||||||
|
CERT_IMPORT_METHOD = "import"
|
||||||
|
|
||||||
def __init__(self, dsm_url: str):
|
def __init__(self, dsm_url: str):
|
||||||
self.dsm_url = dsm_url.rstrip("/")
|
self.dsm_url = dsm_url.rstrip("/")
|
||||||
|
|
||||||
@@ -138,4 +142,126 @@ class DSMWorker:
|
|||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
return result.get("data")
|
return result.get("data")
|
||||||
|
|
||||||
|
|
||||||
|
def import_cert(self, dsm_info: DSMInfo) -> bool:
|
||||||
|
if not self.sid or not self.token:
|
||||||
|
logging.error("DSM authentication required")
|
||||||
|
return False
|
||||||
|
|
||||||
|
if not dsm_info.private_key_path.is_file():
|
||||||
|
logging.error(
|
||||||
|
f"Private key not found: {dsm_info.private_key_path}"
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
if not dsm_info.certificate_pem_path.is_file():
|
||||||
|
logging.error(
|
||||||
|
f"Certificate not found: {dsm_info.certificate_pem_path}"
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
if not dsm_info.path_to_fullchain.is_file():
|
||||||
|
logging.error(
|
||||||
|
f"Fullchain certificate not found: "
|
||||||
|
f"{dsm_info.path_to_fullchain}"
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
certificates_json = self.get_list_certs()
|
||||||
|
|
||||||
|
if certificates_json is None:
|
||||||
|
logging.error("Unable to get certificate list from DSM")
|
||||||
|
return False
|
||||||
|
|
||||||
|
certificates = certificates_json.get("certificates", [])
|
||||||
|
|
||||||
|
cert_id = ""
|
||||||
|
is_default = False
|
||||||
|
|
||||||
|
# Поиск сертификата в списке
|
||||||
|
for certificate in certificates:
|
||||||
|
if certificate.get("desc") != dsm_info.certificate_name:
|
||||||
|
continue
|
||||||
|
|
||||||
|
cert_id = certificate.get("id", "")
|
||||||
|
is_default = certificate.get("is_default", False)
|
||||||
|
|
||||||
|
logging.info(
|
||||||
|
f"Found existing certificate: "
|
||||||
|
f"{dsm_info.certificate_name}, id={cert_id}"
|
||||||
|
)
|
||||||
|
|
||||||
|
break
|
||||||
|
|
||||||
|
url = f"{self.dsm_url}/webapi/entry.cgi"
|
||||||
|
|
||||||
|
params = {
|
||||||
|
"api": self.CERT_IMPORT_API,
|
||||||
|
"version": self.CERT_IMPORT_VERSION,
|
||||||
|
"method": self.CERT_IMPORT_METHOD,
|
||||||
|
"SynoToken": self.token,
|
||||||
|
"_sid": self.sid,
|
||||||
|
}
|
||||||
|
|
||||||
|
data = {
|
||||||
|
"id": "",
|
||||||
|
"desc": dsm_info.certificate_name,
|
||||||
|
}
|
||||||
|
|
||||||
|
if is_default:
|
||||||
|
data["as_default"] = "true"
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(dsm_info.private_key_path, "rb") as key_file, \
|
||||||
|
open(dsm_info.certificate_pem_path, "rb") as cert_file, \
|
||||||
|
open(dsm_info.path_to_fullchain, "rb") as fullchain_file:
|
||||||
|
|
||||||
|
files = {
|
||||||
|
"key": ("private.key", key_file),
|
||||||
|
"cert": ("cert.pem", cert_file),
|
||||||
|
"inter_cert": ("inter_cert.pem", fullchain_file),
|
||||||
|
"id": (None, cert_id),
|
||||||
|
"desc": (None, dsm_info.certificate_name),
|
||||||
|
}
|
||||||
|
|
||||||
|
response = requests.post(
|
||||||
|
url,
|
||||||
|
params=params,
|
||||||
|
data=data,
|
||||||
|
files=files,
|
||||||
|
timeout=30,
|
||||||
|
verify=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
except OSError as e:
|
||||||
|
logging.error(f"Cannot open certificate files: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
except requests.RequestException as e:
|
||||||
|
logging.error(f"Certificate import request failed: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = response.json()
|
||||||
|
except ValueError as e:
|
||||||
|
logging.error(f"DSM returned invalid JSON: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
if not result.get("success"):
|
||||||
|
error = result.get("error", {})
|
||||||
|
|
||||||
|
logging.error(
|
||||||
|
f"Certificate import failed: "
|
||||||
|
f"code={error.get('code')}"
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
logging.info(
|
||||||
|
f"Certificate successfully imported: "
|
||||||
|
f"{dsm_info.certificate_name}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return True
|
||||||
@@ -1,26 +1,97 @@
|
|||||||
|
|
||||||
from caddy_worker import CaddyWorker
|
from caddy_worker import CaddyWorker
|
||||||
|
from service_functions import ServiceFunctions
|
||||||
|
from dsm_worker import DSMWorker
|
||||||
|
from pathlib import Path
|
||||||
|
from structs import CertInfo, DSMAuthInfo
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
|
||||||
|
service_worker = ServiceFunctions()
|
||||||
worker = CaddyWorker()
|
worker = CaddyWorker()
|
||||||
|
|
||||||
|
#### Тест CaddyWorker ##################
|
||||||
|
pem_cert = None
|
||||||
|
|
||||||
|
print(f"search_cert_caddy")
|
||||||
cert_path = worker.search_cert_caddy(
|
cert_path = worker.search_cert_caddy(
|
||||||
"D:/Work/Programming/Python/CaddyToDSM/TestData/certs",
|
"D:/Work/Programming/Python/CaddyToDSM/TestData/certs",
|
||||||
"wud.stadidisk.ru"
|
"wud.stadidisk.ru"
|
||||||
)
|
)
|
||||||
|
|
||||||
print(f"Path to cert: {cert_path}")
|
print(f"Path to cert: {cert_path}")
|
||||||
|
print(f"\n")
|
||||||
|
|
||||||
if cert_path:
|
if cert_path:
|
||||||
|
print(f"get_cert_info")
|
||||||
cert_info = worker.get_cert_info(cert_path)
|
cert_info = worker.get_cert_info(cert_path)
|
||||||
|
service_worker.save_cert_info(cert_info, Path("D:/Work/Programming/Python/CaddyToDSM/TestData/pems"))
|
||||||
|
|
||||||
|
|
||||||
print(f"Domain: {cert_info.domain_name}")
|
print(f"Domain: {cert_info.domain_name}")
|
||||||
print(f"Fingerprint: {cert_info.fingerprint}")
|
print(f"Fingerprint: {cert_info.fingerprint}")
|
||||||
print(f"Expires at: {cert_info.expires_at}")
|
print(f"Expires at: {cert_info.expires_at}")
|
||||||
print(f"Key path: {cert_info.path_to_key}")
|
print(f"Key path: {cert_info.path_to_key}")
|
||||||
|
print(f"Dir cert: {cert_info.dir_cert}")
|
||||||
|
print(f"\n")
|
||||||
|
|
||||||
|
print(f"convert_to_dsm")
|
||||||
|
pem_cert = worker.convert_to_dsm(cert_info.dir_cert,
|
||||||
|
"D:/Work/Programming/Python/CaddyToDSM/TestData/pems")
|
||||||
|
|
||||||
|
if(pem_cert):
|
||||||
|
print(f"Cert Name: {pem_cert.certificate_name}")
|
||||||
|
print(f"Path to private key: {pem_cert.private_key_path}")
|
||||||
|
print(f"Path to pem: {pem_cert.private_key_path}")
|
||||||
|
print(f"Path to fullchain: {pem_cert.private_key_path}")
|
||||||
|
print(f"\n")
|
||||||
|
else:
|
||||||
|
print("Convert Certificate Fail")
|
||||||
|
print(f"\n")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
print("Certificate not found")
|
print("Certificate not found")
|
||||||
|
print(f"\n")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
######### Тест DSM worker #################
|
||||||
|
|
||||||
|
dsm_worker = DSMWorker("http://stadidisk.local")
|
||||||
|
auth_info = dsm_worker.auth_in_DSM(Path("D:/Work/Programming/Python/CaddyToDSM/TestData/.secret"))
|
||||||
|
print("Starting dsm_worker\n")
|
||||||
|
|
||||||
|
|
||||||
|
if auth_info:
|
||||||
|
print(f"Session id: {auth_info.sid}")
|
||||||
|
print(f"Token: {auth_info.token}")
|
||||||
|
print("\n")
|
||||||
|
|
||||||
|
print("Starting get_list_certs\n")
|
||||||
|
list_certs = dsm_worker.get_list_certs()
|
||||||
|
|
||||||
|
if list_certs:
|
||||||
|
print(f"Cert list: {list_certs}\n")
|
||||||
|
|
||||||
|
print("Starting dsm_worker\n")
|
||||||
|
isOkImport = dsm_worker.import_cert(pem_cert)
|
||||||
|
if isOkImport:
|
||||||
|
print(f"Cert Import Success\n")
|
||||||
|
else:
|
||||||
|
print(f"Cert Import Fail\n")
|
||||||
|
|
||||||
|
|
||||||
|
else:
|
||||||
|
print("Cert list is empty\n")
|
||||||
|
|
||||||
|
else:
|
||||||
|
print(f"Error getting auth data")
|
||||||
|
print("\n")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
+42
-1
@@ -1,7 +1,8 @@
|
|||||||
import json
|
import json
|
||||||
from structs import CertInfo
|
from structs import CertInfo, DSMCredentials
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from dataclasses import asdict
|
from dataclasses import asdict
|
||||||
|
import logging
|
||||||
|
|
||||||
class ServiceFunctions:
|
class ServiceFunctions:
|
||||||
|
|
||||||
@@ -18,4 +19,44 @@ class ServiceFunctions:
|
|||||||
(save_dir / cert_info.dir_cert.name).write_text(
|
(save_dir / cert_info.dir_cert.name).write_text(
|
||||||
json.dumps(data, indent=4, ensure_ascii=False),
|
json.dumps(data, indent=4, ensure_ascii=False),
|
||||||
encoding="utf-8"
|
encoding="utf-8"
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_login_pass_from_file(path_to_file: Path):
|
||||||
|
|
||||||
|
if not path_to_file.is_file():
|
||||||
|
logging.error(f"Secret file not found: {path_to_file}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
lines = path_to_file.read_text(encoding="utf-8").splitlines()
|
||||||
|
except OSError as e:
|
||||||
|
logging.error(f"Cannot read secret file {path_to_file}: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
secret = {}
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
line = line.strip()
|
||||||
|
|
||||||
|
if not line or "=" not in line:
|
||||||
|
continue
|
||||||
|
|
||||||
|
key, value = line.split("=", 1)
|
||||||
|
secret[key.strip()] = value.strip()
|
||||||
|
|
||||||
|
user_name = secret.get("username")
|
||||||
|
password = secret.get("password")
|
||||||
|
|
||||||
|
if not user_name:
|
||||||
|
logging.error("user_name is not specified in secret")
|
||||||
|
return None
|
||||||
|
|
||||||
|
if not password:
|
||||||
|
logging.error("password is not specified in secret")
|
||||||
|
return None
|
||||||
|
|
||||||
|
return DSMCredentials(
|
||||||
|
user_name=user_name,
|
||||||
|
password=password,
|
||||||
)
|
)
|
||||||
+16
-5
@@ -1,18 +1,29 @@
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class CertInfo:
|
class CertInfo:
|
||||||
domain_name: str
|
domain_name: str
|
||||||
fingerprint: str
|
fingerprint: str
|
||||||
expires_at: datetime
|
expires_at: datetime
|
||||||
path_to_key: str
|
path_to_key: Path
|
||||||
|
dir_cert: Path
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class DSMInfo:
|
class DSMInfo:
|
||||||
certificate_name: str
|
certificate_name: str
|
||||||
private_key_path: str
|
private_key_path: Path
|
||||||
certificate_pem_path: str
|
certificate_pem_path: Path
|
||||||
private_key_pem_path: str
|
path_to_fullchain: Path
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class DSMAuthInfo:
|
||||||
|
sid: str
|
||||||
|
token: str
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class DSMCredentials:
|
||||||
|
user_name: str
|
||||||
|
password: str
|
||||||
Reference in New Issue
Block a user