Complete Lab 7 security and PKI track

This commit is contained in:
2026-12-05 23:43:41 +03:00
parent 20afc2c790
commit d8ecd2aad9
93 changed files with 6714 additions and 133 deletions
+222
View File
@@ -0,0 +1,222 @@
#!/usr/bin/env python3
"""Issue and atomically stage a replacement leaf; operator recreates its consumers."""
from __future__ import annotations
import argparse
from datetime import datetime, timezone
import getpass
import os
from pathlib import Path
import subprocess
import tempfile
from bao_bootstrap import Bao, CLIENT_CERTS, OPENSSL, PKI, SERVER_CERTS
ROOT = Path(__file__).resolve().parents[1]
SECRETS = ROOT / "secrets"
IDENTITIES = {
**{role: (cn, names, "server") for role, (cn, names, _kind) in SERVER_CERTS.items()},
**{role: (cn, [], "client") for role, cn in CLIENT_CERTS.items()},
}
def openssl(args: list[str], step: str) -> bytes:
try:
completed = subprocess.run(
[OPENSSL, *args], check=True, capture_output=True, text=True
)
return completed.stdout.encode("ascii")
except subprocess.CalledProcessError as exc:
detail = (exc.stderr or "").strip().splitlines()
suffix = f": {detail[-1][:240]}" if detail else ""
raise RuntimeError(f"OpenSSL {step} failed{suffix}") from None
def stage(bao: Bao, role: str) -> tuple[Path, Path, str]:
cn, dns_names, kind = IDENTITIES[role]
result = bao.request("POST", f"pki_int/issue/{role}", {
"common_name": cn,
"alt_names": ",".join(dns_names),
"ttl": "6h",
}).get("data", {})
cert, key = result.get("certificate"), result.get("private_key")
if not cert or not key:
raise RuntimeError("OpenBao did not issue a replacement leaf")
chain = result.get("ca_chain") or []
certificate = cert.rstrip() + "\n" + "\n".join(item.rstrip() for item in chain) + "\n"
target_cert = PKI / f"{role}.crt"
target_key = PKI / f"{role}.key"
PKI.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="renew-", dir=PKI) as tmp:
candidate_cert = Path(tmp) / "candidate.crt"
candidate_chain = Path(tmp) / "candidate-chain.crt"
candidate_key = Path(tmp) / "candidate.key"
candidate_cert.write_text(cert.rstrip() + "\n", encoding="ascii")
if chain:
candidate_chain.write_text("\n".join(item.rstrip() for item in chain) + "\n", encoding="ascii")
candidate_key.write_text(key.rstrip() + "\n", encoding="ascii")
trust_args = ["verify", "-CAfile", str(PKI / "internal-ca.crt")]
if chain:
trust_args.extend(["-untrusted", str(candidate_chain)])
openssl([*trust_args, str(candidate_cert)], "certificate-chain verification")
if kind == "server":
openssl(["x509", "-in", str(candidate_cert), "-noout", "-checkhost", cn], "server-name verification")
else:
client_args = ["verify", "-purpose", "sslclient", "-CAfile", str(PKI / "internal-ca.crt")]
if chain:
client_args.extend(["-untrusted", str(candidate_chain)])
openssl([*client_args, str(candidate_cert)], "client-purpose verification")
cert_public = openssl(["x509", "-in", str(candidate_cert), "-noout", "-pubkey"], "certificate public-key extraction")
key_public = openssl(["pkey", "-in", str(candidate_key), "-pubout"], "private-key match verification")
if cert_public.strip() != key_public.strip():
raise RuntimeError("replacement private key does not match the issued certificate")
cert_backup = PKI / f"{role}.previous.crt"
key_backup = PKI / f"{role}.previous.key"
candidate_bundle = Path(tmp) / "candidate-bundle.crt"
candidate_bundle.write_text(certificate, encoding="ascii")
if target_cert.exists() and target_key.exists():
cert_backup.write_bytes(target_cert.read_bytes())
key_backup.write_bytes(target_key.read_bytes())
os.replace(candidate_bundle, target_cert)
os.replace(candidate_key, target_key)
return target_cert, target_key, datetime.now(timezone.utc).isoformat()
def publish_crl(bao: Bao) -> Path:
intermediate_crl = bao.request_text("pki_int/crl/pem")
if not intermediate_crl.startswith("-----BEGIN X509 CRL-----"):
raise RuntimeError("OpenBao returned an invalid PKI CRL")
root_crl_path = PKI / "root-ca.crl.pem"
if not root_crl_path.is_file():
raise RuntimeError("Offline root CRL is missing; rerun scripts/bootstrap-local.ps1")
PKI.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="crl-", dir=PKI) as tmp:
root_candidate = Path(tmp) / "root.crl.pem"
intermediate_candidate = Path(tmp) / "intermediate.crl.pem"
candidate = Path(tmp) / "candidate.crl.pem"
root_candidate.write_bytes(root_crl_path.read_bytes())
intermediate_candidate.write_text(intermediate_crl.rstrip() + "\n", encoding="ascii")
openssl(["crl", "-in", str(root_candidate), "-noout"], "root CRL parsing")
openssl(["crl", "-in", str(intermediate_candidate), "-noout"], "intermediate CRL parsing")
openssl(["crl", "-in", str(root_candidate), "-CAfile", str(PKI / "internal-ca.crt"), "-verify", "-noout"], "root CRL signature verification")
intermediate = PKI / "pki-int.crt"
if not intermediate.is_file():
raise RuntimeError("OpenBao intermediate certificate is missing; rerun the operator bootstrap")
openssl(["crl", "-in", str(intermediate_candidate), "-CAfile", str(intermediate), "-verify", "-noout"], "intermediate CRL signature verification")
parts = [root_candidate.read_bytes().rstrip(), intermediate_candidate.read_bytes().rstrip()]
rollover_crl = bao.request_text("pki_rollover/crl/pem", allow_missing=True)
if rollover_crl:
rollover_ca = PKI / "pki-rollover.crt"
if not rollover_crl.startswith("-----BEGIN X509 CRL-----") or not rollover_ca.is_file():
raise RuntimeError("Rollover issuer CRL or certificate is invalid")
rollover_candidate = Path(tmp) / "rollover.crl.pem"
rollover_candidate.write_text(rollover_crl.rstrip() + "\n", encoding="ascii")
openssl(["crl", "-in", str(rollover_candidate), "-noout"], "rollover intermediate CRL parsing")
openssl(["crl", "-in", str(rollover_candidate), "-CAfile", str(rollover_ca), "-verify", "-noout"], "rollover intermediate CRL signature verification")
parts.append(rollover_candidate.read_bytes().rstrip())
candidate.write_bytes(b"\n".join(parts) + b"\n")
target = PKI / "pki-int.crl.pem"
os.replace(candidate, target)
return PKI / "pki-int.crl.pem"
def revoke_previous(bao: Bao, role: str) -> str:
previous_cert = PKI / f"{role}.previous.crt"
previous_key = PKI / f"{role}.previous.key"
if not previous_cert.is_file() or not previous_key.is_file():
raise RuntimeError(f"No backed-up previous certificate pair exists for {role}")
serial_output = openssl(["x509", "-in", str(previous_cert), "-noout", "-serial"], "previous certificate serial extraction")
serial_line = serial_output.decode("ascii").strip()
if not serial_line.lower().startswith("serial="):
raise RuntimeError("OpenSSL returned no serial for the previous certificate")
serial_hex = serial_line.split("=", 1)[1].strip().replace(":", "")
if not serial_hex or any(char not in "0123456789abcdefABCDEF" for char in serial_hex):
raise RuntimeError("OpenSSL returned a malformed previous certificate serial")
if len(serial_hex) % 2:
serial_hex = "0" + serial_hex
serial = ":".join(serial_hex[index:index + 2].lower() for index in range(0, len(serial_hex), 2))
current_cert = PKI / f"{role}.crt"
if current_cert.is_file():
current_serial = openssl(["x509", "-in", str(current_cert), "-noout", "-serial"], "current certificate serial extraction")
if current_serial.decode("ascii").strip().split("=", 1)[-1].replace(":", "").lower() == serial_hex.lower():
raise RuntimeError("saved previous certificate is also the current certificate; refusing to revoke the active leaf")
issuer_line = openssl(["x509", "-in", str(previous_cert), "-noout", "-issuer", "-nameopt", "RFC2253"], "previous certificate issuer extraction").decode("ascii").strip()
issuer_name = issuer_line.split("=", 1)[-1]
issuer_mount = None
for mount, issuer_file in (("pki_int", PKI / "pki-int.crt"), ("pki_rollover", PKI / "pki-rollover.crt")):
if not issuer_file.is_file():
continue
subject_line = openssl(["x509", "-in", str(issuer_file), "-noout", "-subject", "-nameopt", "RFC2253"], "issuer subject extraction").decode("ascii").strip()
if subject_line.split("=", 1)[-1] == issuer_name:
issuer_mount = mount
break
if issuer_mount is None:
raise RuntimeError("saved previous certificate issuer does not match a configured intermediate; refusing revocation")
bao.request("POST", issuer_mount + "/revoke", {"serial_number": serial}, include_errors=True)
crl_path = publish_crl(bao)
if role == "lb-client":
probe_dir = SECRETS / "revocation-probe"
probe_dir.mkdir(parents=True, exist_ok=True)
(probe_dir / "lb-client.previous.crt").write_bytes(previous_cert.read_bytes())
(probe_dir / "lb-client.previous.key").write_bytes(previous_key.read_bytes())
return serial
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("role", nargs="?", choices=sorted(IDENTITIES))
parser.add_argument("--all", action="store_true", help="renew every OpenBao-issued leaf")
parser.add_argument("--revoke-previous", action="store_true", help="after renewing one role, revoke its backed-up prior serial and publish the CRL")
parser.add_argument("--revoke-saved-previous", action="store_true", help="revoke a role's already-saved previous certificate without issuing another leaf")
parser.add_argument("--refresh-crl", action="store_true", help="download and validate the current issuer CRL without renewing leaves")
args = parser.parse_args()
if sum((args.all, args.role is not None, args.refresh_crl)) != 1:
parser.error("choose one identity role, --all, or --refresh-crl")
if args.revoke_previous and args.revoke_saved_previous:
parser.error("choose only one revocation mode")
if (args.revoke_previous or args.revoke_saved_previous) and (args.all or args.role is None or args.refresh_crl):
parser.error("a revocation mode requires exactly one identity role")
if args.revoke_previous and not (
(PKI / f"{args.role}.crt").is_file() and (PKI / f"{args.role}.key").is_file()
):
parser.error("--revoke-previous requires an existing certificate/key pair to rotate")
if args.revoke_saved_previous and not (
(PKI / f"{args.role}.previous.crt").is_file() and (PKI / f"{args.role}.previous.key").is_file()
):
parser.error("--revoke-saved-previous requires an existing saved previous certificate/key pair")
if not (PKI / "internal-ca.crt").is_file():
raise SystemExit("Run scripts/bootstrap-local.ps1 first")
token = getpass.getpass("OpenBao operator root token (not saved): ")
if not token:
raise SystemExit("An operator token is required")
roles = sorted(IDENTITIES) if args.all else [args.role]
current_role = "OpenBao authentication"
try:
bao = Bao(token)
if args.refresh_crl:
crl = publish_crl(bao)
print(f"Validated current issuer CRL at {crl.name}; no certificates were changed.")
return
for role in roles:
current_role = role
if args.revoke_saved_previous:
serial = revoke_previous(bao, role)
print(f"Revoked saved previous {role} serial {serial}; validated and published pki-int.crl.pem.")
else:
cert, key, issued_at = stage(bao, role)
print(f"Staged replacement for {role} at {issued_at}; files are {cert.name} and {key.name}.")
if args.revoke_previous:
serial = revoke_previous(bao, role)
print(f"Revoked the previous {role} serial {serial}; validated and published pki-int.crl.pem.")
except (RuntimeError, OSError, subprocess.CalledProcessError) as exc:
raise SystemExit(f"Leaf renewal stopped for {current_role}: {exc}; do not recreate consumers yet") from None
if not args.revoke_saved_previous:
print(f"Staged {len(roles)} replacement leaf certificate(s).")
print("Compose file secrets are snapshots: recreate consumers only after all replacements are staged, then verify readiness.")
if not (args.revoke_previous or args.revoke_saved_previous):
print("Previous leaves remain unrevoked. Use one role with --revoke-previous for a revocation experiment.")
if __name__ == "__main__":
main()