#!/usr/bin/env python3 """Local PKI of the lab 7 stand: two CAs and one leaf certificate per service, in ./secrets/pki. .venv/Scripts/python scripts/init_pki.py (also called by scripts/init_secrets.py) Needs the `cryptography` package (requirements-test.txt). Idempotent: existing files are kept, so re-running never replaces a CA that already signed the running stand. Prints file names only, never key material. ./secrets is git-ignored and docker-ignored; nothing here is committed or baked into an image. Delete ./secrets/pki to start a new PKI (then recreate the containers). Two trust domains (contracts/trust-matrix.md): public-ca signs ONLY what people connect to: the HTTPS ingress (HAProxy, :8443) and the Grafana UI, SAN localhost / 127.0.0.1 / ::1. Its certificate is the CA_FILE of the public tests; it may be given to anyone. It is trusted by NO service. internal-ca signs the service identities. SAN = the compose service name (the DNS name the peer dials), EKU serverAuth and/or clientAuth by role. Services trust only it. The CA private keys (*-ca.key) are mounted into no container: only this script uses them. Test-only material (never trusted by the stand): `foreign-ca` and a client certificate signed by it with the allowed SAN `lb` - proves that the right name from a wrong CA is refused. """ from __future__ import annotations import datetime as dt import ipaddress import os import sys from pathlib import Path try: from cryptography import x509 from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID except ImportError: # pragma: no cover - message for a missing venv sys.exit("init_pki.py needs `cryptography`: python -m venv .venv && " ".venv/Scripts/python -m pip install -r requirements-test.txt") ROOT = Path(__file__).resolve().parents[1] PKI = ROOT / "secrets" / "pki" CA_DAYS = 5 * 365 LEAF_DAYS = 365 SERVER, CLIENT = ExtendedKeyUsageOID.SERVER_AUTH, ExtendedKeyUsageOID.CLIENT_AUTH LOCAL = ["localhost", "127.0.0.1"] # only for services whose own healthcheck/CLI dials loopback over TLS # name -> (CA, extra SANs besides the name itself, EKUs). The name is the identity: CN and SAN. LEAVES = { # Public trust domain: what the user's client verifies (hostname localhost, both loopbacks). "ingress": ("public-ca", ["127.0.0.1", "::1"], [SERVER], "localhost"), "grafana-ui": ("public-ca", ["127.0.0.1", "::1"], [SERVER], "localhost"), # Internal trust domain. "lb": ("internal-ca", [], [CLIENT], None), # client of every API replica "api": ("internal-ca", [], [SERVER, CLIENT], None), # server for lb, client of collector "relay": ("internal-ca", [], [CLIENT], None), "worker": ("internal-ca", [], [CLIENT], None), "postgres": ("internal-ca", LOCAL, [SERVER], None), "valkey": ("internal-ca", LOCAL, [SERVER], None), "s3": ("internal-ca", LOCAL, [SERVER], None), "broker": ("internal-ca", LOCAL, [SERVER], None), "otel-collector": ("internal-ca", [], [SERVER, CLIENT], None), # server for apps, client of backends "prometheus": ("internal-ca", LOCAL, [SERVER, CLIENT], None), # client: scrapes loki/tempo "loki": ("internal-ca", LOCAL, [SERVER], None), "tempo": ("internal-ca", LOCAL, [SERVER], None), "grafana": ("internal-ca", [], [CLIENT], None), # client of the three datasources "openbao": ("internal-ca", LOCAL, [SERVER], None), # Test only: right SAN, wrong CA. "foreign-lb": ("foreign-ca", [], [CLIENT], "lb"), } CAS = {"public-ca": "MTUSI lab7 public CA", "internal-ca": "MTUSI lab7 internal CA", "foreign-ca": "Foreign CA (test only, trusted by nobody)"} def now() -> dt.datetime: return dt.datetime.now(dt.timezone.utc) def save(path: Path, data: bytes) -> None: path.write_bytes(data) # bytes: PEM keeps LF on Windows too # Readable by the unprivileged container users through the bind mount (postgres copies its # key to a 0600 file at start). The folder ./secrets itself is 0700 for the host user. os.chmod(path, 0o644) print(f"created secrets/pki/{path.name}") def pem_key(key) -> bytes: return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()) def load(name: str): cert = x509.load_pem_x509_certificate((PKI / f"{name}.crt").read_bytes()) key = serialization.load_pem_private_key((PKI / f"{name}.key").read_bytes(), None) return cert, key def make_ca(name: str) -> None: if (PKI / f"{name}.crt").exists(): print(f"keep secrets/pki/{name}.crt") return key = ec.generate_private_key(ec.SECP256R1()) subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, CAS[name])]) cert = (x509.CertificateBuilder().subject_name(subject).issuer_name(subject) .public_key(key.public_key()).serial_number(x509.random_serial_number()) .not_valid_before(now() - dt.timedelta(minutes=5)).not_valid_after(now() + dt.timedelta(days=CA_DAYS)) .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True) .add_extension(x509.KeyUsage(digital_signature=False, content_commitment=False, key_encipherment=False, data_encipherment=False, key_agreement=False, key_cert_sign=True, crl_sign=True, encipher_only=False, decipher_only=False), critical=True) .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False) .sign(key, hashes.SHA256())) save(PKI / f"{name}.key", pem_key(key)) save(PKI / f"{name}.crt", cert.public_bytes(serialization.Encoding.PEM)) def san_entry(value: str) -> x509.GeneralName: try: return x509.IPAddress(ipaddress.ip_address(value)) except ValueError: return x509.DNSName(value) def make_leaf(name: str, ca_name: str, extra: list[str], ekus: list, dns_name: str | None) -> None: if (PKI / f"{name}.crt").exists(): print(f"keep secrets/pki/{name}.crt") return ca_cert, ca_key = load(ca_name) identity = dns_name or name key = ec.generate_private_key(ec.SECP256R1()) sans = [san_entry(v) for v in dict.fromkeys([identity, *extra])] cert = (x509.CertificateBuilder() .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, identity)])) .issuer_name(ca_cert.subject).public_key(key.public_key()).serial_number(x509.random_serial_number()) .not_valid_before(now() - dt.timedelta(minutes=5)).not_valid_after(now() + dt.timedelta(days=LEAF_DAYS)) .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) .add_extension(x509.KeyUsage(digital_signature=True, content_commitment=False, key_encipherment=False, data_encipherment=False, key_agreement=True, key_cert_sign=False, crl_sign=False, encipher_only=False, decipher_only=False), critical=True) .add_extension(x509.ExtendedKeyUsage(ekus), critical=False) .add_extension(x509.SubjectAlternativeName(sans), critical=False) .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), critical=False) .sign(ca_key, hashes.SHA256())) cert_pem = cert.public_bytes(serialization.Encoding.PEM) save(PKI / f"{name}.key", pem_key(key)) save(PKI / f"{name}.crt", cert_pem) def bundle(name: str) -> None: """HAProxy wants certificate + key in one PEM file.""" target = PKI / f"{name}.pem" if target.exists(): print(f"keep secrets/pki/{target.name}") return save(target, (PKI / f"{name}.crt").read_bytes() + (PKI / f"{name}.key").read_bytes()) def main() -> int: PKI.mkdir(parents=True, exist_ok=True) os.chmod(PKI.parent, 0o700) for ca in CAS: make_ca(ca) for name, (ca, extra, ekus, dns_name) in LEAVES.items(): make_leaf(name, ca, extra, ekus, dns_name) bundle("ingress") # HAProxy :8443 server certificate bundle("lb") # HAProxy client certificate towards the API replicas print("CA_FILE for the public tests:", (PKI / "public-ca.crt").as_posix()) return 0 if __name__ == "__main__": sys.exit(main())