71 lines
2.2 KiB
Python
71 lines
2.2 KiB
Python
from structs import CertInfo, DSMInfo
|
|
from pathlib import Path
|
|
|
|
from cryptography import x509
|
|
from cryptography.hazmat.primitives import hashes
|
|
|
|
import logging
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
class CaddyWorker:
|
|
|
|
def search_cert_caddy(self, path_to_caddy_certs, site_name):
|
|
directory = Path(path_to_caddy_certs)
|
|
|
|
cert_folder = directory / site_name
|
|
|
|
if cert_folder.is_dir():
|
|
logging.info(f"Found certificate folder: {cert_folder}")
|
|
|
|
crt_path = cert_folder / f"{site_name}.crt"
|
|
|
|
if crt_path.is_file():
|
|
logging.info(f"Found certificate file: {crt_path}")
|
|
|
|
key_path = cert_folder / f"{site_name}.key"
|
|
if key_path.is_file():
|
|
logging.info(f"Found key file: {key_path}")
|
|
return crt_path
|
|
else:
|
|
logging.info(f"No key file: {key_path}")
|
|
return None
|
|
|
|
logging.info(f"No certificate file: {cert_folder}")
|
|
return None
|
|
else:
|
|
logging.info(f"No certificate folder: {cert_folder}")
|
|
return None
|
|
|
|
|
|
|
|
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}")
|
|
return None
|
|
|
|
try:
|
|
with open(path, "rb") as file:
|
|
cert_data = file.read()
|
|
except OSError as e:
|
|
logging.error(f"Cannot open certificate file {path}: {e}")
|
|
return None
|
|
|
|
try:
|
|
certificate = x509.load_pem_x509_certificate(cert_data)
|
|
except ValueError as e:
|
|
logging.error(f"Invalid certificate {path}: {e}")
|
|
return None
|
|
|
|
fingerprint = certificate.fingerprint(
|
|
hashes.SHA256()
|
|
).hex(":").upper()
|
|
|
|
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"),
|
|
)
|