forked from mtusi2026/mtusi2026lab7
152 lines
5.7 KiB
Python
152 lines
5.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Create a disposable CA and role-specific credentials outside the worktree."""
|
|
import argparse
|
|
import os
|
|
from pathlib import Path
|
|
import secrets
|
|
import subprocess
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
STATE = Path(os.getenv("LAB7_STATE", f"/private/tmp/mtusi2026lab7-{os.getuid()}")).resolve()
|
|
|
|
|
|
def openssl(*args):
|
|
subprocess.run(["openssl", *map(str, args)], check=True,
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, cwd=STATE / "authority")
|
|
|
|
|
|
def public(path):
|
|
path.chmod(0o444)
|
|
|
|
|
|
def issue(directory, stem, identity, usage, names=()):
|
|
target = STATE / directory
|
|
target.mkdir(mode=0o755, exist_ok=True)
|
|
cert, key = target / f"{stem}.crt", target / f"{stem}.key"
|
|
if cert.exists() and key.exists():
|
|
return
|
|
csr = STATE / "authority/request.pem"
|
|
extensions = STATE / "authority/extensions"
|
|
extensions.write_text("basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\n"
|
|
f"extendedKeyUsage={usage}\n"
|
|
+ ("subjectAltName=" + ",".join(names) + "\n" if names else ""))
|
|
openssl("req", "-new", "-newkey", "rsa:2048", "-nodes", "-subj", f"/CN={identity}",
|
|
"-keyout", key, "-out", csr)
|
|
openssl("ca", "-batch", "-notext", "-config", "ca.cnf", "-extfile", extensions,
|
|
"-in", csr, "-out", cert)
|
|
public(cert)
|
|
public(key)
|
|
(target / f"{stem}.pem").write_bytes(cert.read_bytes() + key.read_bytes())
|
|
public(target / f"{stem}.pem")
|
|
|
|
|
|
def crl():
|
|
authority = STATE / "authority"
|
|
openssl("ca", "-config", "ca.cnf", "-gencrl", "-out", authority / "next.crl")
|
|
path = STATE / "trust/ca.crl"
|
|
public(authority / "next.crl")
|
|
(authority / "next.crl").replace(path)
|
|
|
|
|
|
def secret(directory, name):
|
|
path = STATE / directory / name
|
|
if not path.exists():
|
|
path.write_text(secrets.token_hex(24))
|
|
public(path)
|
|
|
|
|
|
def init():
|
|
if STATE == ROOT or ROOT in STATE.parents:
|
|
raise SystemExit("LAB7_STATE must be outside the repository")
|
|
STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
STATE.chmod(0o700)
|
|
authority = STATE / "authority"
|
|
authority.mkdir(mode=0o700, exist_ok=True)
|
|
trust = STATE / "trust"
|
|
trust.mkdir(mode=0o755, exist_ok=True)
|
|
if not (authority / "ca.key").exists():
|
|
openssl("req", "-x509", "-newkey", "rsa:3072", "-nodes", "-days", "365",
|
|
"-addext", "keyUsage=critical,keyCertSign,cRLSign",
|
|
"-subj", "/CN=MTUSI Lab7 local CA", "-keyout", "ca.key", "-out", "ca.crt")
|
|
(authority / "ca.key").chmod(0o600)
|
|
(authority / "ca.cnf").write_text("""[ca]
|
|
default_ca = local
|
|
[local]
|
|
database = index.txt
|
|
new_certs_dir = issued
|
|
certificate = ca.crt
|
|
private_key = ca.key
|
|
serial = serial
|
|
default_md = sha256
|
|
default_days = 30
|
|
default_crl_days = 30
|
|
unique_subject = no
|
|
policy = names
|
|
[names]
|
|
commonName = supplied
|
|
""")
|
|
(authority / "issued").mkdir()
|
|
(authority / "index.txt").touch()
|
|
(authority / "serial").write_text("1000\n")
|
|
if not (trust / "ca.crt").exists():
|
|
(trust / "ca.crt").write_bytes((authority / "ca.crt").read_bytes())
|
|
public(trust / "ca.crt")
|
|
if not (trust / "ca.crl").exists():
|
|
crl()
|
|
for name in ("lb", "api-a-tls", "api-b-tls", "postgres", "s3", "broker",
|
|
"openbao", "otel", "prometheus", "loki", "tempo", "grafana"):
|
|
aliases = [f"DNS:{name}"]
|
|
if name in ("lb", "openbao", "grafana"):
|
|
aliases += ["DNS:localhost", "IP:127.0.0.1"]
|
|
if name == "otel":
|
|
aliases.append("DNS:otel-collector")
|
|
issue(name, "server", name, "serverAuth", aliases)
|
|
for source, target in (("server.crt", "public.crt"), ("server.key", "private.key")):
|
|
path = STATE / "s3" / target
|
|
if not path.exists():
|
|
path.write_bytes((STATE / "s3" / source).read_bytes())
|
|
public(path)
|
|
for name in ("api-a", "api-b", "publisher", "worker", "recovery"):
|
|
issue(name, "bao", name, "clientAuth", (f"DNS:{name}.bao.lab",))
|
|
issue(name, "otel", name, "clientAuth")
|
|
for name in ("publisher", "worker", "ops"):
|
|
issue(name, "amqp", name if name != "ops" else "ops-redeliver", "clientAuth")
|
|
for owner, role in (("lb", "lb-to-api"), ("otel", "collector-export"),
|
|
("prometheus", "prometheus-scrape"), ("grafana", "grafana-query"),
|
|
("probe", "prohibited-service")):
|
|
issue(owner, "client", role, "clientAuth")
|
|
(STATE / "s3/CAs").mkdir(exist_ok=True)
|
|
foreign = STATE / "probe/foreign.crt"
|
|
if not foreign.exists():
|
|
openssl("req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "10",
|
|
"-subj", "/CN=foreign", "-keyout", foreign.with_suffix(".key"), "-out", foreign)
|
|
public(foreign)
|
|
public(foreign.with_suffix(".key"))
|
|
(STATE / "rotation").mkdir(mode=0o755, exist_ok=True)
|
|
for directory, names in {
|
|
"postgres": ("admin", "migrator", "api_blue", "publisher", "worker", "recovery", "ops"),
|
|
"s3": ("admin", "api", "worker", "recovery"), "grafana": ("admin",),
|
|
}.items():
|
|
for name in names:
|
|
secret(directory, name)
|
|
operator = STATE / "operator"
|
|
operator.mkdir(mode=0o700, exist_ok=True)
|
|
print(STATE)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("action", choices=("init", "issue-lb", "revoke-lb"))
|
|
args = parser.parse_args()
|
|
if args.action == "init":
|
|
init()
|
|
elif args.action == "issue-lb":
|
|
issue("rotation", "client", "lb-to-api", "clientAuth")
|
|
else:
|
|
openssl("ca", "-config", "ca.cnf", "-revoke", STATE / "rotation/old.pem")
|
|
crl()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|