#!/usr/bin/env python3 """Create the local Lab 7 CA and service certificates without printing keys.""" from __future__ import annotations import argparse import shutil import stat import subprocess import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] CERT_DIR = ROOT / "certs" PRIVATE_DIR = CERT_DIR / "private" OPENSSL_IMAGE = "alpine/openssl:3.3.2" SERVER_IDENTITIES = { "public": ["DNS:localhost", "IP:127.0.0.1"], "api": ["DNS:api"], "rabbitmq": ["DNS:rabbitmq"], "otel-collector": ["DNS:otel-collector", "DNS:otel-gateway"], "openbao": ["DNS:openbao", "IP:127.0.0.1"], "postgres": ["DNS:postgres"], "redis": ["DNS:redis"], "minio": ["DNS:minio"], } CLIENT_IDENTITIES = ("lb", "worker-client", "api-client") def _find_openssl() -> str | None: found = shutil.which("openssl") if found: return found for candidate in ( r"C:\Program Files\Git\usr\bin\openssl.exe", r"C:\Program Files (x86)\Git\usr\bin\openssl.exe", ): if Path(candidate).exists(): return candidate return None def _container_path(path: Path) -> str: return "/work/" + path.resolve().relative_to(ROOT.resolve()).as_posix() def _run_openssl(args: list[str]) -> None: executable = _find_openssl() if executable: command = [executable, *args] else: if not shutil.which("docker"): raise RuntimeError("openssl and docker are both unavailable") converted = [] for arg in args: try: converted.append(_container_path(Path(arg)) if Path(arg).is_absolute() else arg) except ValueError: converted.append(arg) command = [ "docker", "run", "--rm", "-v", f"{ROOT}:/work", "-w", "/work", OPENSSL_IMAGE, *converted, ] subprocess.run(command, check=True, stdout=subprocess.DEVNULL) def _protect(path: Path) -> None: try: path.chmod(stat.S_IRUSR | stat.S_IWUSR) except OSError: pass def _write_extension(identity: str, sans: list[str], usage: str) -> Path: handle = tempfile.NamedTemporaryFile( mode="w", encoding="utf-8", prefix=f"{identity}-", suffix=".cnf", dir=CERT_DIR, delete=False ) with handle: handle.write("[v3]\n") handle.write("basicConstraints=critical,CA:FALSE\n") handle.write("keyUsage=critical,digitalSignature,keyEncipherment\n") handle.write(f"extendedKeyUsage={usage}\n") if sans: handle.write("subjectAltName=" + ",".join(sans) + "\n") return Path(handle.name) def issue_leaf(identity: str, days: int = 90, force: bool = False) -> tuple[Path, Path]: if identity in SERVER_IDENTITIES: sans = SERVER_IDENTITIES[identity] usage = "serverAuth,clientAuth" if identity != "public" else "serverAuth" elif identity in CLIENT_IDENTITIES or identity == "rollover-demo": sans = [f"DNS:{identity}"] usage = "clientAuth" else: raise ValueError(f"unknown PKI identity: {identity}") cert = CERT_DIR / f"{identity}.crt" key = PRIVATE_DIR / f"{identity}.key" if cert.exists() and key.exists() and not force: return cert, key csr = CERT_DIR / f".{identity}.csr" serial = CERT_DIR / "ca.srl" extension = _write_extension(identity, sans, usage) try: _run_openssl( [ "req", "-new", "-newkey", "rsa:2048", "-nodes", "-keyout", str(key), "-out", str(csr), "-subj", f"/O=MTUSI Lab 7/CN={identity}", ] ) command = [ "x509", "-req", "-in", str(csr), "-CA", str(CERT_DIR / "ca.crt"), "-CAkey", str(PRIVATE_DIR / "ca.key"), "-out", str(cert), "-days", str(days), "-sha256", "-extfile", str(extension), "-extensions", "v3", ] if serial.exists(): command.extend(["-CAserial", str(serial)]) else: command.append("-CAcreateserial") _run_openssl(command) finally: csr.unlink(missing_ok=True) extension.unlink(missing_ok=True) _protect(key) return cert, key def _combined(identity: str) -> None: target = PRIVATE_DIR / f"{identity}.pem" cert = CERT_DIR / f"{identity}.crt" key = PRIVATE_DIR / f"{identity}.key" target.write_bytes(cert.read_bytes() + key.read_bytes()) _protect(target) def bootstrap(force: bool = False, days: int = 90) -> None: CERT_DIR.mkdir(exist_ok=True) PRIVATE_DIR.mkdir(exist_ok=True) ca_cert = CERT_DIR / "ca.crt" ca_key = PRIVATE_DIR / "ca.key" if force or not (ca_cert.exists() and ca_key.exists()): _run_openssl( [ "req", "-x509", "-newkey", "rsa:4096", "-nodes", "-keyout", str(ca_key), "-out", str(ca_cert), "-days", "3650", "-sha256", "-subj", "/O=MTUSI Lab 7/CN=ca", "-addext", "basicConstraints=critical,CA:TRUE,pathlen:0", "-addext", "keyUsage=critical,keyCertSign,cRLSign", ] ) _protect(ca_key) for identity in (*SERVER_IDENTITIES, *CLIENT_IDENTITIES): issue_leaf(identity, days=days, force=force) _combined("public") _combined("lb") revoked = CERT_DIR / "revoked_serials.txt" if not revoked.exists(): revoked.write_text("# one uppercase certificate serial per line\n", encoding="ascii") print("PKI ready: public certificates are in certs/; private keys remain in ignored certs/private/") def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--force", action="store_true", help="replace the CA and every leaf") parser.add_argument("--days", type=int, default=90) args = parser.parse_args() if args.days < 1: parser.error("--days must be at least 1") bootstrap(force=args.force, days=args.days) return 0 if __name__ == "__main__": raise SystemExit(main())