#!/usr/bin/env python3 """Renew a legacy Trojan container's certificate using host systemd scheduling.""" import fcntl import hashlib import json import os from pathlib import Path import socket import ssl import subprocess import tempfile import time def run(args, **kwargs): return subprocess.run(args, check=True, timeout=900, **kwargs) def main(): container = os.environ.get("TROJAN_CONTAINER", "trojan") lock = open("/run/lock/trojan-certificate-renew.lock", "w") try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: print("Another renewal check is running", flush=True) return info = json.loads(run(["docker", "inspect", container], capture_output=True).stdout)[0] if not info["State"]["Running"]: raise RuntimeError("Trojan container is not running") def host_path(path): for mount in sorted(info["Mounts"], key=lambda m: len(m["Destination"]), reverse=True): dest = mount["Destination"].rstrip("/") if path.startswith(dest + "/"): root = Path(mount["Source"]).resolve() target = (root / path[len(dest) + 1:]).resolve() if root not in target.parents: raise RuntimeError("Certificate path escapes its bind mount") return target raise RuntimeError("Certificate/config must be stored in a persistent bind mount: " + path) config = json.loads(host_path("/usr/local/etc/trojan/config.json").read_text()) domain = config["ssl"]["sni"] if not domain or any(c not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-" for c in domain): raise RuntimeError("Invalid certificate domain") port = int(config["local_port"]) acme_home = "/root/.acme.sh" source_cert = host_path(f"{acme_home}/{domain}_ecc/fullchain.cer") source_key = host_path(f"{acme_home}/{domain}_ecc/{domain}.key") target_cert = host_path(config["ssl"]["cert"]) target_key = host_path(config["ssl"]["key"]) # Use the running TLS endpoint as the before-state: acme.sh may have already # replaced source files during an earlier, interrupted renewal attempt. def served_fingerprint(verify=False): context = ssl.create_default_context() if verify else ssl._create_unverified_context() with socket.create_connection(("127.0.0.1", port), timeout=10) as sock: with context.wrap_socket(sock, server_hostname=domain) as tls: return hashlib.sha256(tls.getpeercert(binary_form=True)).hexdigest() try: before = served_fingerprint() except (OSError, ssl.SSLError): before = None run(["docker", "exec", container, "systemctl", "start", "trojan-acme-challenge"]) result = subprocess.run([ "docker", "exec", container, acme_home + "/acme.sh", "--renew", "--home", acme_home, "-d", domain, "--ecc", "--webroot", "/var/lib/trojan-acme-webroot", ], timeout=900) # acme.sh returns 2 when a certificate is not yet due for renewal. if result.returncode not in (0, 2): raise RuntimeError(f"acme.sh renewal failed: {result.returncode}") run(["openssl", "x509", "-in", str(source_cert), "-noout", "-checkend", "604800"]) run(["openssl", "x509", "-in", str(source_cert), "-noout", "-checkhost", domain]) cert_pub = run(["openssl", "x509", "-in", str(source_cert), "-pubkey", "-noout"], capture_output=True).stdout key_pub = run(["openssl", "pkey", "-in", str(source_key), "-pubout"], capture_output=True).stdout if cert_pub != key_pub: raise RuntimeError("Certificate and private key do not match") der = run(["openssl", "x509", "-in", str(source_cert), "-outform", "DER"], capture_output=True).stdout expected = hashlib.sha256(der).hexdigest() def install(source, target, mode): if source == target: os.chmod(target, mode) return target.parent.mkdir(parents=True, exist_ok=True) fd, temp = tempfile.mkstemp(prefix=".renew-", dir=target.parent) try: with os.fdopen(fd, "wb") as output: os.fchmod(output.fileno(), mode) output.write(source.read_bytes()) output.flush() os.fsync(output.fileno()) os.replace(temp, target) finally: if os.path.exists(temp): os.unlink(temp) install(source_key, target_key, 0o600) install(source_cert, target_cert, 0o644) if before != expected: run(["docker", "exec", container, "systemctl", "restart", "trojan"]) print("Restarted Trojan to load renewed certificate", flush=True) for attempt in range(10): try: if served_fingerprint(verify=True) == expected: print(f"OK: {domain}, active certificate SHA256={expected}", flush=True) return except (OSError, ssl.SSLError): pass time.sleep(1) raise RuntimeError("Running Trojan did not present the expected valid certificate") if __name__ == "__main__": main()