Complete Lab 7 security and PKI track
This commit is contained in:
@@ -0,0 +1,311 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Initialize OpenBao policies, PKI and scoped app secrets for the local lab."""
|
||||
from __future__ import annotations
|
||||
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SECRETS = ROOT / "secrets"
|
||||
PKI = SECRETS / "pki"
|
||||
BAO_ADDR = os.environ.get("BAO_ADDR", "https://localhost:8200").rstrip("/")
|
||||
def _openssl_path() -> str:
|
||||
configured = os.environ.get("OPENSSL")
|
||||
if configured:
|
||||
return configured
|
||||
found = shutil.which("openssl")
|
||||
if found:
|
||||
return found
|
||||
git = shutil.which("git")
|
||||
if git:
|
||||
candidate = Path(git).resolve().parents[1] / "usr" / "bin" / "openssl.exe"
|
||||
if candidate.is_file():
|
||||
return str(candidate)
|
||||
return "openssl"
|
||||
|
||||
|
||||
OPENSSL = _openssl_path()
|
||||
|
||||
SERVER_CERTS = {
|
||||
"ingress": ("localhost", ["localhost"], "server"),
|
||||
"api-server": ("api", ["api"], "server"),
|
||||
"postgres-server": ("db", ["db", "postgres"], "server"),
|
||||
"s3-server": ("s3", ["s3"], "server"),
|
||||
"redis-server": ("redis", ["redis"], "server"),
|
||||
"broker-server": ("broker", ["broker"], "server"),
|
||||
"otel-server": ("otel-collector", ["otel-collector"], "server"),
|
||||
"otel-gateway-server": ("otel-gateway", ["otel-gateway"], "server"),
|
||||
"prometheus-server": ("prometheus", ["prometheus", "localhost"], "server"),
|
||||
"loki-server": ("loki", ["loki"], "server"),
|
||||
"tempo-server": ("tempo", ["tempo"], "server"),
|
||||
"grafana-server": ("grafana", ["grafana", "localhost"], "server"),
|
||||
}
|
||||
CLIENT_CERTS = {
|
||||
"lb-client": "messenger-lb",
|
||||
"api-client": "messenger-api",
|
||||
"worker-client": "messenger-worker",
|
||||
"dispatcher-client": "messenger-dispatcher",
|
||||
"otel-client": "messenger-otel-collector",
|
||||
"prometheus-client": "messenger-prometheus",
|
||||
"grafana-client": "messenger-grafana",
|
||||
}
|
||||
|
||||
|
||||
class Bao:
|
||||
def __init__(self, token: str):
|
||||
if urlsplit(BAO_ADDR).scheme != "https":
|
||||
raise RuntimeError("OpenBao operator API must use HTTPS")
|
||||
self.token = token
|
||||
self.context = ssl.create_default_context(cafile=str(PKI / "internal-ca.crt"))
|
||||
|
||||
def request(self, method: str, path: str, payload: dict | None = None, *, allow_missing: bool = False, include_errors: bool = False) -> dict:
|
||||
body = json.dumps(payload, separators=(",", ":")).encode("utf-8") if payload is not None else None
|
||||
headers = {"Content-Type": "application/json", "X-Vault-Token": self.token}
|
||||
request = Request(f"{BAO_ADDR}/v1/{path}", data=body, headers=headers, method=method)
|
||||
try:
|
||||
with urlopen(request, context=self.context, timeout=5) as response:
|
||||
raw = response.read(2_000_000)
|
||||
return json.loads(raw) if raw else {}
|
||||
except HTTPError as exc:
|
||||
if allow_missing and exc.code == 404:
|
||||
return {}
|
||||
detail = ""
|
||||
if include_errors:
|
||||
try:
|
||||
error_body = json.loads(exc.read(2048))
|
||||
errors = error_body.get("errors", [])
|
||||
safe_errors = [str(item).replace(self.token, "[redacted]").replace("\r", " ").replace("\n", " ")[:200] for item in errors[:3]]
|
||||
if safe_errors:
|
||||
detail = ": " + "; ".join(safe_errors)
|
||||
except (ValueError, AttributeError, TypeError):
|
||||
pass
|
||||
raise RuntimeError(f"OpenBao rejected {method} {path} (HTTP {exc.code}){detail}") from None
|
||||
except (URLError, TimeoutError, ValueError) as exc:
|
||||
reason = getattr(exc, "reason", None)
|
||||
detail = str(reason or exc)
|
||||
raise RuntimeError(
|
||||
f"OpenBao request failed at {method} {path} ({type(exc).__name__}): {detail}"
|
||||
) from None
|
||||
|
||||
def request_text(self, path: str, *, allow_missing: bool = False) -> str:
|
||||
request = Request(
|
||||
f"{BAO_ADDR}/v1/{path}",
|
||||
headers={"X-Vault-Token": self.token},
|
||||
method="GET",
|
||||
)
|
||||
try:
|
||||
with urlopen(request, context=self.context, timeout=5) as response:
|
||||
return response.read(2_000_000).decode("ascii").strip()
|
||||
except HTTPError as exc:
|
||||
if allow_missing and exc.code == 404:
|
||||
return ""
|
||||
raise RuntimeError(f"OpenBao rejected GET {path} (HTTP {exc.code})") from None
|
||||
except (URLError, TimeoutError, UnicodeDecodeError) as exc:
|
||||
reason = getattr(exc, "reason", None)
|
||||
detail = str(reason or exc)
|
||||
raise RuntimeError(
|
||||
f"OpenBao request failed at GET {path} ({type(exc).__name__}): {detail}"
|
||||
) from None
|
||||
|
||||
def ensure_mount(self, path: str, kind: str, options: dict | None = None) -> None:
|
||||
mounts = self.request("GET", "sys/mounts")
|
||||
if path + "/" not in mounts.get("data", {}):
|
||||
self.request("POST", "sys/mounts/" + path, {"type": kind, "options": options or {}})
|
||||
|
||||
|
||||
def _read_secret(name: str) -> str:
|
||||
value = (SECRETS / name).read_text(encoding="utf-8").strip()
|
||||
if not value:
|
||||
raise RuntimeError(f"Local bootstrap file is empty: {name}")
|
||||
return value
|
||||
|
||||
|
||||
def _issue_leaf(bao: Bao, role: str, common_name: str, names: list[str], usage: str, *, ttl: str = "6h") -> None:
|
||||
cert_path = PKI / f"{role}.crt"
|
||||
key_path = PKI / f"{role}.key"
|
||||
if cert_path.exists() and key_path.exists():
|
||||
return
|
||||
body = {"common_name": common_name, "ttl": ttl}
|
||||
if names:
|
||||
body["alt_names"] = ",".join(names)
|
||||
result = bao.request("POST", f"pki_int/issue/{role}", body).get("data", {})
|
||||
certificate = result.get("certificate")
|
||||
private_key = result.get("private_key")
|
||||
if not certificate or not private_key:
|
||||
raise RuntimeError(f"OpenBao did not issue {role}")
|
||||
chain = result.get("ca_chain") or []
|
||||
cert_path.write_text(certificate.rstrip() + "\n" + "\n".join(item.rstrip() for item in chain) + "\n", encoding="ascii")
|
||||
key_path.write_text(private_key.rstrip() + "\n", encoding="ascii")
|
||||
|
||||
|
||||
def _setup_intermediate(bao: Bao) -> str:
|
||||
mounts = bao.request("GET", "sys/mounts").get("data", {})
|
||||
if "pki_int/" not in mounts:
|
||||
bao.request("POST", "sys/mounts/pki_int", {"type": "pki"})
|
||||
bao.request("POST", "sys/mounts/pki_int/tune", {"max_lease_ttl": "87600h"})
|
||||
|
||||
current = bao.request_text("pki_int/ca/pem", allow_missing=True)
|
||||
if current:
|
||||
return current
|
||||
|
||||
generated = bao.request("POST", "pki_int/intermediate/generate/internal", {
|
||||
"common_name": "MTUSI Lab7 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 intermediate CSR")
|
||||
csr_path = PKI / "pki-int.csr"
|
||||
cert_path = PKI / "pki-int.crt"
|
||||
ext_path = PKI / "pki-int.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",
|
||||
)
|
||||
try:
|
||||
subprocess.run([
|
||||
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),
|
||||
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
raise RuntimeError("Could not sign the OpenBao intermediate with the offline lab CA") from None
|
||||
signed = cert_path.read_text(encoding="ascii")
|
||||
bao.request("POST", "pki_int/intermediate/set-signed", {"certificate": signed})
|
||||
csr_path.unlink(missing_ok=True)
|
||||
ext_path.unlink(missing_ok=True)
|
||||
return bao.request_text("pki_int/ca/pem")
|
||||
|
||||
|
||||
def _configure(bao: Bao) -> None:
|
||||
bao.ensure_mount("kv", "kv", {"version": "2"})
|
||||
auth_methods = bao.request("GET", "sys/auth").get("data", {})
|
||||
if "cert/" not in auth_methods:
|
||||
bao.request("POST", "sys/auth/cert", {"type": "cert"})
|
||||
intermediate = _setup_intermediate(bao)
|
||||
if not intermediate:
|
||||
raise RuntimeError("OpenBao PKI intermediate certificate is empty")
|
||||
bao.request("POST", "pki_int/config/urls", {
|
||||
"issuing_certificates": f"{BAO_ADDR}/v1/pki_int/ca",
|
||||
"crl_distribution_points": f"{BAO_ADDR}/v1/pki_int/crl",
|
||||
})
|
||||
|
||||
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():
|
||||
names = {"server": (True, False, ["ServerAuth"]), "client": (False, True, ["ClientAuth"])}[kind]
|
||||
domains = sorted(set([common_name, *dns_names]))
|
||||
bao.request("POST", f"pki_int/roles/{role}", {
|
||||
"allowed_domains": domains,
|
||||
"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": names[0],
|
||||
"client_flag": names[1],
|
||||
"key_usage": ["DigitalSignature", "KeyEncipherment"],
|
||||
"ext_key_usage": names[2],
|
||||
})
|
||||
_issue_leaf(bao, role, common_name, dns_names, kind)
|
||||
|
||||
policies = {
|
||||
"messenger-api": 'path "kv/data/messenger/api" { capabilities = ["read"] }',
|
||||
"messenger-worker": 'path "kv/data/messenger/worker" { capabilities = ["read"] }',
|
||||
"messenger-dispatcher": 'path "kv/data/messenger/dispatcher" { capabilities = ["read"] }',
|
||||
}
|
||||
for name, policy in policies.items():
|
||||
bao.request("PUT", f"sys/policies/acl/{name}", {"policy": policy})
|
||||
|
||||
for name, common_name in (("messenger-api", "messenger-api"), ("messenger-worker", "messenger-worker"), ("messenger-dispatcher", "messenger-dispatcher")):
|
||||
bao.request("POST", f"auth/cert/certs/{name}", {
|
||||
"display_name": name,
|
||||
"certificate": (PKI / "internal-ca.crt").read_text(encoding="ascii"),
|
||||
"allowed_common_names": [common_name],
|
||||
"token_policies": name,
|
||||
"token_ttl": "15m",
|
||||
"token_max_ttl": "1h",
|
||||
})
|
||||
|
||||
def redis_url(username: str, secret_name: str, cert: str) -> str:
|
||||
password = _read_secret(secret_name)
|
||||
return (
|
||||
f"rediss://{username}:{password}@{{host}}:6379/0"
|
||||
f"?ssl_cert_reqs=required&ssl_ca_certs=/run/secrets/internal-ca.crt"
|
||||
f"&ssl_certfile=/run/secrets/{cert}.crt&ssl_keyfile=/run/secrets/{cert}.key"
|
||||
)
|
||||
|
||||
api = {
|
||||
"cache_url": redis_url("api", "redis_api_password", "api-client").format(host="redis"),
|
||||
"s3_access_key_id": _read_secret("s3_access_key_id"),
|
||||
"s3_secret_access_key": _read_secret("s3_secret_access_key"),
|
||||
}
|
||||
worker = {
|
||||
"broker_url": redis_url("messenger-worker", "redis_worker_password", "worker-client").format(host="broker"),
|
||||
"s3_access_key_id": _read_secret("s3_worker_access_key_id"),
|
||||
"s3_secret_access_key": _read_secret("s3_worker_secret_access_key"),
|
||||
}
|
||||
dispatcher = {
|
||||
"broker_url": redis_url("messenger-dispatcher", "redis_dispatcher_password", "dispatcher-client").format(host="broker"),
|
||||
}
|
||||
for role, values in (("api", api), ("worker", worker), ("dispatcher", dispatcher)):
|
||||
bao.request("POST", f"kv/data/messenger/{role}", {"data": values})
|
||||
|
||||
# Nginx consumes the issuer's signed CRL to reject revoked LB client leaves.
|
||||
# Keep it in the local ignored secrets directory and refresh it before API
|
||||
# containers are created.
|
||||
intermediate_crl = bao.request_text("pki_int/crl/pem")
|
||||
root_crl_path = PKI / "root-ca.crl.pem"
|
||||
if not intermediate_crl.startswith("-----BEGIN X509 CRL-----"):
|
||||
raise RuntimeError("OpenBao returned an invalid PKI CRL")
|
||||
if not root_crl_path.is_file() or not root_crl_path.read_text(encoding="ascii").startswith("-----BEGIN X509 CRL-----"):
|
||||
raise RuntimeError("Offline root CRL is missing; rerun scripts/bootstrap-local.ps1")
|
||||
crl_path = PKI / "pki-int.crl.pem"
|
||||
crl_tmp = PKI / "pki-int.crl.pem.tmp"
|
||||
rollover_crl = bao.request_text("pki_rollover/crl/pem", allow_missing=True)
|
||||
if rollover_crl and not rollover_crl.startswith("-----BEGIN X509 CRL-----"):
|
||||
raise RuntimeError("OpenBao returned an invalid rollover intermediate CRL")
|
||||
crl_tmp.write_text(
|
||||
root_crl_path.read_text(encoding="ascii").rstrip() + "\n" + intermediate_crl.rstrip() + "\n"
|
||||
+ (rollover_crl.rstrip() + "\n" if rollover_crl else ""),
|
||||
encoding="ascii",
|
||||
)
|
||||
os.replace(crl_tmp, crl_path)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if not (PKI / "internal-ca.crt").exists() or not (PKI / "internal-ca.key.pem").exists():
|
||||
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")
|
||||
try:
|
||||
_configure(Bao(token))
|
||||
except RuntimeError as exc:
|
||||
raise SystemExit(str(exc)) from None
|
||||
print("OpenBao policies, short-lived PKI roles, and service secrets are ready; token was not saved.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user