forked from mtusi2026/mtusi2026lab7
179 lines
7.1 KiB
Python
Executable File
179 lines
7.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Operator-side CA, short-lived leaf issuance, and staged ingress rotation."""
|
|
import argparse
|
|
from datetime import datetime, timedelta, timezone
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import tempfile
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
SECRETS = ROOT / "secrets"
|
|
OPERATOR = SECRETS / "operator"
|
|
RUN = SECRETS / "runtime"
|
|
MESH_ROLES = {
|
|
"api": "DNS:api",
|
|
"worker": "DNS:worker",
|
|
"ingress": "DNS:ingress",
|
|
"postgres": "DNS:postgres",
|
|
"rabbitmq": "DNS:rabbitmq",
|
|
"rustfs": "DNS:rustfs",
|
|
"collector": "DNS:collector",
|
|
"prometheus": "DNS:prometheus",
|
|
"loki": "DNS:loki",
|
|
"tempo": "DNS:tempo",
|
|
"grafana": "DNS:grafana,DNS:localhost,IP:127.0.0.1",
|
|
"openbao": "DNS:openbao,DNS:localhost,IP:127.0.0.1",
|
|
"auditor": "DNS:auditor",
|
|
}
|
|
EDGE_SAN = "DNS:localhost,IP:127.0.0.1"
|
|
|
|
|
|
def run(*arguments):
|
|
return subprocess.check_output(["openssl", *map(str, arguments)], stderr=subprocess.PIPE)
|
|
|
|
|
|
def write(path, data, mode=0o644):
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
if path.parent.parent == RUN:
|
|
path.parent.chmod(0o755)
|
|
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as file:
|
|
file.write(data)
|
|
temporary = Path(file.name)
|
|
temporary.chmod(mode)
|
|
temporary.replace(path)
|
|
|
|
|
|
def make_ca(name):
|
|
folder = OPERATOR / name
|
|
if (folder / "ca.crt").exists():
|
|
return folder
|
|
folder.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
run("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1",
|
|
"-noenc", "-x509", "-sha256", "-days", 365, "-subj", f"/CN=MTUSI Lab7 {name}",
|
|
"-addext", "basicConstraints=critical,CA:TRUE,pathlen:0",
|
|
"-addext", "keyUsage=critical,keyCertSign,cRLSign",
|
|
"-out", folder / "ca.crt", "-keyout", folder / "ca.key")
|
|
(folder / "ca.key").chmod(0o600)
|
|
return folder
|
|
|
|
|
|
def issue(authority, role, san, lifetime, target):
|
|
ca = make_ca(authority)
|
|
with tempfile.TemporaryDirectory(dir=OPERATOR) as temporary:
|
|
work = Path(temporary)
|
|
run("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1",
|
|
"-noenc", "-subj", f"/CN={role}", "-out", work / "req", "-keyout", work / "key")
|
|
(work / "index").touch()
|
|
(work / "serial").write_text(os.urandom(16).hex().upper() + "\n")
|
|
config = work / "ca.conf"
|
|
config.write_text(f"""[ca]
|
|
default_ca = issuer
|
|
[issuer]
|
|
database = {work / "index"}
|
|
serial = {work / "serial"}
|
|
new_certs_dir = {work}
|
|
certificate = {ca / "ca.crt"}
|
|
private_key = {ca / "ca.key"}
|
|
default_md = sha256
|
|
policy = names
|
|
unique_subject = no
|
|
[names]
|
|
commonName = supplied
|
|
[leaf]
|
|
basicConstraints = critical,CA:FALSE
|
|
keyUsage = critical,digitalSignature
|
|
extendedKeyUsage = serverAuth,clientAuth
|
|
subjectAltName = {san},URI:spiffe://lab7/{role}
|
|
""")
|
|
now = datetime.now(timezone.utc)
|
|
start = (now - timedelta(minutes=2)).strftime("%Y%m%d%H%M%SZ")
|
|
end = (now + timedelta(seconds=lifetime)).strftime("%Y%m%d%H%M%SZ")
|
|
run("ca", "-batch", "-notext", "-config", config, "-extensions", "leaf", "-in",
|
|
work / "req", "-out", work / "cert", "-startdate", start, "-enddate", end)
|
|
key = (work / "key").read_bytes()
|
|
cert = (work / "cert").read_bytes()
|
|
target.mkdir(parents=True, exist_ok=True)
|
|
write(target / "service.key", key)
|
|
write(target / "service.crt", cert)
|
|
write(target / "service.pem", cert + key)
|
|
write(target / "ca.crt", (ca / "ca.crt").read_bytes())
|
|
return run("x509", "-in", target / "service.crt", "-serial", "-noout").decode().strip().split("=")[1]
|
|
|
|
|
|
def init():
|
|
SECRETS.mkdir(mode=0o700, exist_ok=True)
|
|
OPERATOR.mkdir(mode=0o700, exist_ok=True)
|
|
RUN.mkdir(mode=0o700, exist_ok=True)
|
|
for role, san in MESH_ROLES.items():
|
|
path = RUN / role
|
|
if not (path / "service.crt").exists():
|
|
issue("mesh", role, san, 7 * 86400, path)
|
|
if not (RUN / "foreign" / "service.crt").exists():
|
|
issue("foreign", "auditor", "DNS:foreign", 7 * 86400, RUN / "foreign")
|
|
for role in ("openbao", "grafana"):
|
|
write(SECRETS / "trust" / f"{role}.crt", (RUN / role / "ca.crt").read_bytes())
|
|
if not (RUN / "api" / "ingress-serials").exists():
|
|
serial = run("x509", "-in", RUN / "ingress" / "service.crt", "-serial", "-noout")
|
|
write(RUN / "api" / "ingress-serials", serial.split(b"=")[1])
|
|
if not (RUN / "edge" / "service.crt").exists():
|
|
issue("edge-a", "edge", EDGE_SAN, 86400, RUN / "edge")
|
|
for authority in ("edge-a", "mesh"):
|
|
write(SECRETS / "trust" / f"{authority}.crt", (OPERATOR / authority / "ca.crt").read_bytes())
|
|
if not (SECRETS / "trust" / "edge.crt").exists():
|
|
write(SECRETS / "trust" / "edge.crt", (OPERATOR / "edge-a" / "ca.crt").read_bytes())
|
|
|
|
|
|
def renew_edge(authority, lifetime, threshold, reload):
|
|
leaf = RUN / "edge" / "service.crt"
|
|
try:
|
|
run("x509", "-in", leaf, "-checkend", threshold, "-noout")
|
|
premise = run("verify", "-CAfile", OPERATOR / authority / "ca.crt", leaf)
|
|
if premise:
|
|
return False
|
|
except subprocess.CalledProcessError:
|
|
pass
|
|
issue(authority, "edge", EDGE_SAN, lifetime, RUN / "edge")
|
|
if reload:
|
|
subprocess.run(["docker", "compose", "kill", "-s", "USR2", "haproxy"], cwd=ROOT, check=True)
|
|
return True
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
sub = parser.add_subparsers(dest="action", required=True)
|
|
sub.add_parser("init")
|
|
for name in ("edge-issue", "edge-renew", "edge-trust", "edge-retire"):
|
|
command = sub.add_parser(name)
|
|
command.add_argument("authority", choices=("edge-a", "edge-b"))
|
|
if name in ("edge-issue", "edge-renew"):
|
|
command.add_argument("--lifetime", type=int, default=86400)
|
|
command.add_argument("--reload", action="store_true")
|
|
if name == "edge-renew":
|
|
command.add_argument("--threshold", type=int, default=1800)
|
|
args = parser.parse_args()
|
|
if args.action == "init":
|
|
init()
|
|
elif args.action == "edge-issue":
|
|
issue(args.authority, "edge", EDGE_SAN, args.lifetime, RUN / "edge")
|
|
if args.reload:
|
|
subprocess.run(["docker", "compose", "kill", "-s", "USR2", "haproxy"], cwd=ROOT, check=True)
|
|
elif args.action == "edge-renew":
|
|
print("Renewed" if renew_edge(args.authority, args.lifetime, args.threshold, args.reload) else "Leaf current")
|
|
else:
|
|
ca = (make_ca(args.authority) / "ca.crt").read_bytes()
|
|
path = SECRETS / "trust" / "edge.crt"
|
|
write(SECRETS / "trust" / f"{args.authority}.crt", ca)
|
|
if args.action == "edge-trust" and ca not in path.read_bytes():
|
|
write(path, path.read_bytes() + ca)
|
|
if args.action == "edge-retire":
|
|
run("verify", "-CAfile", OPERATOR / args.authority / "ca.crt", RUN / "edge" / "service.crt")
|
|
write(path, ca)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except subprocess.CalledProcessError as error:
|
|
raise SystemExit((error.stderr or b"OpenSSL/Docker command failed").decode(errors="replace")) from None
|