From ff6796af9f17601fa40a7914aee5d0e189ec3ea2 Mon Sep 17 00:00:00 2001 From: Fedorov Dmitriy Date: Wed, 26 Aug 2026 23:24:38 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A0=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D0=BB=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D1=8E?= =?UTF-8?q?=20=D0=B8=D0=BC=D0=BF=D0=BE=D1=80=D1=82=D0=B0=20=D1=81=D0=B5?= =?UTF-8?q?=D1=80=D1=82=D0=B8=D1=84=D0=B8=D0=BA=D0=B0=D1=82=D0=BE=D0=B2.?= =?UTF-8?q?=20=D0=95=D1=81=D0=BB=D0=B8=20=D0=BE=D0=BD=20=D0=B5=D1=81=D1=82?= =?UTF-8?q?=D1=8C=20=D0=BE=D0=BD=D0=B0=20=D0=BE=D0=B1=D0=BD=D0=BE=D0=B2?= =?UTF-8?q?=D0=BB=D1=8F=D0=B5=D1=82,=20=D0=B5=D1=81=D0=BB=D0=B8=20=D1=81?= =?UTF-8?q?=D0=B5=D1=80=D1=82=D0=B8=D1=84=D0=B8=D0=BA=D0=B0=D1=82=20=D0=B1?= =?UTF-8?q?=D1=8B=D0=BB=D0=BE=20=D0=BF=D0=BE=20=D1=83=D0=BC=D0=BE=D0=BB?= =?UTF-8?q?=D0=BD=D1=87=D0=B0=D0=B8=D1=8E=20=D0=BE=D0=BD=D0=B0=20=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=B2=D0=BB=D1=8F=D0=B5=D1=82=20=D0=BF=D0=BE?= =?UTF-8?q?=20=D1=83=D0=BC=D0=BE=D0=BB=D1=87=D0=B0=D0=BD=D0=B8=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- caddy_worker.py | 129 ++++++++++++++++++++++++++++++++++++++---- dsm_worker.py | 130 ++++++++++++++++++++++++++++++++++++++++++- main.py | 73 +++++++++++++++++++++++- service_functions.py | 43 +++++++++++++- structs.py | 21 +++++-- 5 files changed, 375 insertions(+), 21 deletions(-) diff --git a/caddy_worker.py b/caddy_worker.py index 314fd9a..d82b1c9 100644 --- a/caddy_worker.py +++ b/caddy_worker.py @@ -2,7 +2,7 @@ from structs import CertInfo, DSMInfo from pathlib import Path from cryptography import x509 -from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives import hashes, serialization import logging logging.basicConfig(level=logging.INFO) @@ -39,32 +39,137 @@ class CaddyWorker: def get_cert_info(self, path_to_crt_file) -> CertInfo | None: - path = Path(path_to_crt_file) - if not path.is_file(): - logging.error(f"Certificate file not found: {path}") + cert_path = Path(path_to_crt_file) + if not cert_path.is_file(): + logging.error(f"Certificate file not found: {cert_path}") return None try: - with open(path, "rb") as file: + with open(cert_path, "rb") as file: cert_data = file.read() 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 try: certificate = x509.load_pem_x509_certificate(cert_data) except ValueError as e: - logging.error(f"Invalid certificate {path}: {e}") + logging.error(f"Invalid certificate {cert_path}: {e}") return None - fingerprint = certificate.fingerprint( - hashes.SHA256() - ).hex(":").upper() + fingerprint = certificate.fingerprint(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( domain_name=domain_name, fingerprint=fingerprint, 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, + ) \ No newline at end of file diff --git a/dsm_worker.py b/dsm_worker.py index e60389d..4db8ab8 100644 --- a/dsm_worker.py +++ b/dsm_worker.py @@ -1,6 +1,6 @@ from service_functions import ServiceFunctions -from structs import DSMAuthInfo, DSMCredentials +from structs import DSMAuthInfo, DSMInfo import logging import requests @@ -17,6 +17,10 @@ class DSMWorker: CERT_VERSION = "1" CERT_METHOD_LIST = "list" + CERT_IMPORT_API = "SYNO.Core.Certificate" + CERT_IMPORT_VERSION = "1" + CERT_IMPORT_METHOD = "import" + def __init__(self, dsm_url: str): self.dsm_url = dsm_url.rstrip("/") @@ -138,4 +142,126 @@ class DSMWorker: ) return None - return result.get("data") \ No newline at end of file + 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 \ No newline at end of file diff --git a/main.py b/main.py index 014aa62..0251faf 100644 --- a/main.py +++ b/main.py @@ -1,26 +1,97 @@ 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(): + + service_worker = ServiceFunctions() worker = CaddyWorker() + #### Тест CaddyWorker ################## + pem_cert = None + + print(f"search_cert_caddy") cert_path = worker.search_cert_caddy( "D:/Work/Programming/Python/CaddyToDSM/TestData/certs", "wud.stadidisk.ru" ) print(f"Path to cert: {cert_path}") + print(f"\n") if cert_path: + print(f"get_cert_info") 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"Fingerprint: {cert_info.fingerprint}") print(f"Expires at: {cert_info.expires_at}") 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: 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__": main() \ No newline at end of file diff --git a/service_functions.py b/service_functions.py index 6d58fc5..04e1416 100644 --- a/service_functions.py +++ b/service_functions.py @@ -1,7 +1,8 @@ import json -from structs import CertInfo +from structs import CertInfo, DSMCredentials from pathlib import Path from dataclasses import asdict +import logging class ServiceFunctions: @@ -18,4 +19,44 @@ class ServiceFunctions: (save_dir / cert_info.dir_cert.name).write_text( json.dumps(data, indent=4, ensure_ascii=False), 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, ) \ No newline at end of file diff --git a/structs.py b/structs.py index fab1f5c..3ccc0c2 100644 --- a/structs.py +++ b/structs.py @@ -1,18 +1,29 @@ from dataclasses import dataclass from datetime import datetime - +from pathlib import Path @dataclass class CertInfo: domain_name: str fingerprint: str expires_at: datetime - path_to_key: str + path_to_key: Path + dir_cert: Path @dataclass class DSMInfo: certificate_name: str - private_key_path: str - certificate_pem_path: str - private_key_pem_path: str \ No newline at end of file + private_key_path: Path + certificate_pem_path: Path + path_to_fullchain: Path + +@dataclass +class DSMAuthInfo: + sid: str + token: str + +@dataclass +class DSMCredentials: + user_name: str + password: str \ No newline at end of file