#!/usr/bin/env python3 """Prepare or activate a new OpenBao intermediate while the old CA remains trusted.""" from __future__ import annotations import argparse import getpass import os from pathlib import Path import subprocess import tempfile from bao_bootstrap import BAO_ADDR, Bao, CLIENT_CERTS, OPENSSL, PKI, SERVER_CERTS ROOT = Path(__file__).resolve().parents[1] SECRETS = ROOT / "secrets" MOUNT = "pki_rollover" ROLE = "lb-client" def openssl(args: list[str], step: str) -> bytes: try: result = subprocess.run([OPENSSL, *args], check=True, capture_output=True, text=True) return result.stdout.encode("ascii") except (OSError, subprocess.CalledProcessError) as exc: detail = "" if isinstance(exc, subprocess.CalledProcessError) and exc.stderr: lines = exc.stderr.strip().splitlines() if lines: detail = ": " + lines[-1][:240] raise RuntimeError(f"OpenSSL {step} failed{detail}") from None def prepare_mount(bao: Bao) -> None: mounts = bao.request("GET", "sys/mounts").get("data", {}) if MOUNT + "/" not in mounts: bao.request("POST", "sys/mounts/" + MOUNT, {"type": "pki"}) bao.request("POST", "sys/mounts/" + MOUNT + "/tune", {"max_lease_ttl": "87600h"}) issuer = bao.request_text(MOUNT + "/ca/pem", allow_missing=True) if not issuer: generated = bao.request("POST", MOUNT + "/intermediate/generate/internal", { "common_name": "MTUSI Lab7 Rollover Intermediate CA", "key_type": "rsa", "key_bits": 4096, "ttl": "43800h", }).get("data", {}) csr = generated.get("csr") if not csr: raise RuntimeError("OpenBao did not generate the rollover intermediate CSR") with tempfile.TemporaryDirectory(prefix="pki-rollover-", dir=PKI) as tmp: tmp_path = Path(tmp) csr_path = tmp_path / "rollover.csr" cert_path = tmp_path / "rollover.crt" ext_path = tmp_path / "rollover.ext" csr_path.write_text(csr, encoding="ascii") ext_path.write_text( "basicConstraints=critical,CA:TRUE,pathlen:0\n" "keyUsage=critical,keyCertSign,cRLSign\n" "subjectKeyIdentifier=hash\n" "authorityKeyIdentifier=keyid,issuer\n", encoding="ascii", ) openssl([ "x509", "-req", "-sha256", "-in", str(csr_path), "-CA", str(PKI / "internal-ca.crt"), "-CAkey", str(PKI / "internal-ca.key.pem"), "-CAcreateserial", "-days", "1825", "-extfile", str(ext_path), "-out", str(cert_path), ], "offline-root signing of rollover intermediate") bao.request("POST", MOUNT + "/intermediate/set-signed", { "certificate": cert_path.read_text(encoding="ascii"), }) issuer = bao.request_text(MOUNT + "/ca/pem") if not issuer.startswith("-----BEGIN CERTIFICATE-----"): raise RuntimeError("OpenBao returned an invalid rollover intermediate") (PKI / "pki-rollover.crt").write_text(issuer.rstrip() + "\n", encoding="ascii") bao.request("POST", MOUNT + "/config/urls", { "issuing_certificates": f"{BAO_ADDR}/v1/{MOUNT}/ca", "crl_distribution_points": f"{BAO_ADDR}/v1/{MOUNT}/crl", }) def configure_roles(bao: Bao) -> None: identities: dict[str, tuple[str, list[str], str]] = { **SERVER_CERTS, **{name: (cn, [], "client") for name, cn in CLIENT_CERTS.items()}, } for role, (common_name, dns_names, kind) in identities.items(): server = kind == "server" bao.request("POST", f"{MOUNT}/roles/{role}", { "allowed_domains": sorted(set([common_name, *dns_names])), "allow_bare_domains": True, "allow_subdomains": False, "allow_wildcard_certificates": False, "enforce_hostnames": True, "allow_ip_sans": False, "max_ttl": "12h", "key_type": "rsa", "key_bits": 2048, "server_flag": server, "client_flag": not server, "key_usage": ["DigitalSignature", "KeyEncipherment"], "ext_key_usage": ["ServerAuth"] if server else ["ClientAuth"], }) def publish_overlap_crl(bao: Bao) -> None: root_crl_path = PKI / "root-ca.crl.pem" old_ca = PKI / "pki-int.crt" new_ca = PKI / "pki-rollover.crt" if not root_crl_path.is_file() or not old_ca.is_file() or not new_ca.is_file(): raise RuntimeError("Root or intermediate CA material is missing") crls = [ (root_crl_path.read_text(encoding="ascii"), PKI / "internal-ca.crt", "root"), (bao.request_text("pki_int/crl/pem"), old_ca, "current intermediate"), (bao.request_text(MOUNT + "/crl/pem"), new_ca, "rollover intermediate"), ] with tempfile.TemporaryDirectory(prefix="crl-overlap-", dir=PKI) as tmp: pieces: list[bytes] = [] for index, (pem, issuer, label) in enumerate(crls): if not pem.startswith("-----BEGIN X509 CRL-----"): raise RuntimeError(f"OpenBao returned an invalid {label} CRL") path = Path(tmp) / f"crl-{index}.pem" path.write_text(pem.rstrip() + "\n", encoding="ascii") openssl(["crl", "-in", str(path), "-CAfile", str(issuer), "-verify", "-noout"], f"{label} CRL signature verification") pieces.append(path.read_bytes().rstrip()) candidate = Path(tmp) / "combined.crl.pem" candidate.write_bytes(b"\n".join(pieces) + b"\n") os.replace(candidate, PKI / "pki-int.crl.pem") def stage_lb_leaf(bao: Bao) -> None: issued = bao.request("POST", f"{MOUNT}/issue/{ROLE}", { "common_name": CLIENT_CERTS[ROLE], "ttl": "6h", }).get("data", {}) certificate, private_key = issued.get("certificate"), issued.get("private_key") if not certificate or not private_key: raise RuntimeError("OpenBao did not issue a rollover LB certificate") chain = issued.get("ca_chain") or [] combined = certificate.rstrip() + "\n" + "\n".join(item.rstrip() for item in chain) + "\n" rollover_dir = PKI / "rollover" rollover_dir.mkdir(parents=True, exist_ok=True) probe_dir = SECRETS / "revocation-probe" probe_dir.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix="rollover-leaf-", dir=rollover_dir) as tmp: tmp_path = Path(tmp) cert = tmp_path / "lb-client.crt" key = tmp_path / "lb-client.key" cert.write_text(combined, encoding="ascii") key.write_text(private_key.rstrip() + "\n", encoding="ascii") openssl([ "verify", "-purpose", "sslclient", "-CAfile", str(PKI / "internal-ca.crt"), "-untrusted", str(PKI / "pki-rollover.crt"), str(cert), ], "rollover leaf chain verification") openssl(["x509", "-in", str(cert), "-noout", "-checkhost", CLIENT_CERTS[ROLE]], "rollover leaf identity verification") cert_target = rollover_dir / "lb-client.crt" key_target = rollover_dir / "lb-client.key" os.replace(cert, cert_target) os.replace(key, key_target) (probe_dir / "lb-client.rollover.crt").write_bytes((rollover_dir / "lb-client.crt").read_bytes()) (probe_dir / "lb-client.rollover.key").write_bytes((rollover_dir / "lb-client.key").read_bytes()) def activate_lb_leaf() -> None: rollover_dir = PKI / "rollover" source_cert = rollover_dir / "lb-client.crt" source_key = rollover_dir / "lb-client.key" current_cert = PKI / "lb-client.crt" current_key = PKI / "lb-client.key" if not source_cert.is_file() or not source_key.is_file() or not current_cert.is_file() or not current_key.is_file(): raise RuntimeError("Staged rollover leaf or current LB pair is missing; run prepare first") if current_cert.read_bytes() == source_cert.read_bytes() and current_key.read_bytes() == source_key.read_bytes(): raise RuntimeError("Staged rollover leaf is already active; refusing to overwrite the saved previous pair") (PKI / "lb-client.previous.crt").write_bytes(current_cert.read_bytes()) (PKI / "lb-client.previous.key").write_bytes(current_key.read_bytes()) with tempfile.TemporaryDirectory(prefix="activate-rollover-", dir=PKI) as tmp: tmp_path = Path(tmp) cert_tmp = tmp_path / "lb-client.crt" key_tmp = tmp_path / "lb-client.key" cert_tmp.write_bytes(source_cert.read_bytes()) key_tmp.write_bytes(source_key.read_bytes()) os.replace(cert_tmp, current_cert) os.replace(key_tmp, current_key) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("prepare", "activate")) args = parser.parse_args() if not (PKI / "internal-ca.crt").is_file() or not (PKI / "internal-ca.key.pem").is_file(): raise SystemExit("Run scripts/bootstrap-local.ps1 first") try: if args.action == "prepare": token = getpass.getpass("OpenBao operator root token (not saved): ") if not token: raise SystemExit("An operator token is required") bao = Bao(token) prepare_mount(bao) configure_roles(bao) publish_overlap_crl(bao) stage_lb_leaf(bao) print("Prepared a new offline-root-signed intermediate and a staged LB leaf.") print("Recreate API first to load both intermediate CRLs; security-probe should accept old and staged LB identities.") print("Then run action 'activate', recreate LB, revoke saved previous leaf, and recreate API.") else: activate_lb_leaf() print("Activated the staged rollover LB leaf; the previous LB pair remains saved for revocation.") print("Recreate LB before revoking the saved previous leaf.") except (OSError, RuntimeError, subprocess.CalledProcessError) as exc: raise SystemExit(f"Intermediate rollover stopped ({type(exc).__name__}): {exc}") from None if __name__ == "__main__": main()