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
+311
View File
@@ -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()
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
"""Prove service cert-auth can read only its own KV v2 path."""
from __future__ import annotations
import json
import os
import ssl
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
ROOT = Path(__file__).resolve().parents[1]
PKI = ROOT / "secrets" / "pki"
ADDR = os.environ.get("BAO_ADDR", "https://localhost:8200").rstrip("/")
WORKLOADS = {
"api": ("messenger-api", "messenger/api"),
"worker": ("messenger-worker", "messenger/worker"),
"dispatcher": ("messenger-dispatcher", "messenger/dispatcher"),
}
def call(context: ssl.SSLContext, path: str, *, token: str | None = None, method: str = "GET", body: dict | None = None) -> tuple[int, dict]:
headers = {"Content-Type": "application/json"}
if token:
headers["X-Vault-Token"] = token
payload = json.dumps(body).encode() if body is not None else None
req = Request(f"{ADDR}/v1/{path}", data=payload, headers=headers, method=method)
try:
with urlopen(req, context=context, timeout=4) as response:
return response.status, json.loads(response.read(1_000_000) or b"{}")
except HTTPError as exc:
return exc.code, {}
except (URLError, TimeoutError) as exc:
raise RuntimeError(f"OpenBao probe failed ({type(exc).__name__})") from None
def main() -> None:
for service, (auth_name, own_path) in WORKLOADS.items():
context = ssl.create_default_context(cafile=str(PKI / "internal-ca.crt"))
context.load_cert_chain(str(PKI / f"{service}-client.crt"), str(PKI / f"{service}-client.key"))
status, login = call(context, "auth/cert/login", method="POST", body={"name": auth_name})
assert status == 200 and login.get("auth", {}).get("client_token"), f"{service}: cert auth failed"
token = login["auth"]["client_token"]
assert call(context, f"kv/data/{own_path}", token=token)[0] == 200, f"{service}: own secret denied"
other_path = "messenger/worker" if service != "worker" else "messenger/api"
assert call(context, f"kv/data/{other_path}", token=token)[0] == 403, f"{service}: cross-service read was not denied"
assert call(context, "sys/policies/acl/attacker", token=token, method="PUT", body={"policy": 'path "*" { capabilities=["read"] }'})[0] == 403, f"{service}: policy write was not denied"
print("PASS: each workload reads only its own KV v2 path; cross-read and policy write denied")
if __name__ == "__main__":
main()
+152
View File
@@ -0,0 +1,152 @@
$ErrorActionPreference = 'Stop'
$repo = Split-Path -Parent $PSScriptRoot
$secretRoot = Join-Path $repo 'secrets'
$pkiRoot = Join-Path $secretRoot 'pki'
$openssl = (Get-Command openssl -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Source)
if (-not $openssl) {
$git = Get-Command git -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Source
if ($git) {
$candidate = Join-Path (Split-Path (Split-Path $git -Parent) -Parent) 'usr\bin\openssl.exe'
if (Test-Path -LiteralPath $candidate) { $openssl = $candidate }
}
}
if (-not $openssl) { throw 'OpenSSL is required. Install Git for Windows or OpenSSL and retry.' }
New-Item -ItemType Directory -Force -Path $pkiRoot | Out-Null
$rootKey = Join-Path $pkiRoot 'internal-ca.key.pem'
$rootCert = Join-Path $pkiRoot 'internal-ca.crt'
$hasRootKey = Test-Path -LiteralPath $rootKey
$hasRootCert = Test-Path -LiteralPath $rootCert
if ($hasRootKey -ne $hasRootCert) { throw 'Local CA is incomplete. Restore its matching key/certificate pair from backup.' }
function Invoke-OpenSsl([string[]]$Arguments) {
& $openssl @Arguments
if ($LASTEXITCODE -ne 0) { throw "OpenSSL failed: $($Arguments[0])" }
}
function New-RandomHex([int]$Bytes) {
$buffer = [byte[]]::new($Bytes)
$generator = [System.Security.Cryptography.RandomNumberGenerator]::Create()
try { $generator.GetBytes($buffer) } finally { $generator.Dispose() }
return ([BitConverter]::ToString($buffer).Replace('-', '').ToLowerInvariant())
}
function Save-Secret([string]$Name,[string]$Value) {
$path = Join-Path $secretRoot $Name
if (-not (Test-Path -LiteralPath $path)) { Set-Content -LiteralPath $path -Value $Value -NoNewline -Encoding ascii }
}
$postgresPassword = New-RandomHex 32
Save-Secret 'postgres_password' $postgresPassword
Save-Secret 'database_url' "postgresql+psycopg://postgres:${postgresPassword}@db:5432/messenger?sslmode=verify-full&sslrootcert=/run/secrets/internal-ca.crt"
Save-Secret 's3_root_access_key_id' (New-RandomHex 20)
Save-Secret 's3_root_secret_access_key' (New-RandomHex 32)
Save-Secret 's3_access_key_id' (New-RandomHex 20)
Save-Secret 's3_secret_access_key' (New-RandomHex 32)
Save-Secret 's3_worker_access_key_id' (New-RandomHex 20)
Save-Secret 's3_worker_secret_access_key' (New-RandomHex 32)
Save-Secret 'redis_api_password' (New-RandomHex 32)
Save-Secret 'redis_dispatcher_password' (New-RandomHex 32)
Save-Secret 'redis_worker_password' (New-RandomHex 32)
Save-Secret 'grafana_admin_password' (New-RandomHex 32)
$acl = @(
'user default off',
"user api on >$(Get-Content (Join-Path $secretRoot 'redis_api_password') -Raw) ~session:v1:* ~login:v1:* +ping +get +set +del +eval +incr +expire +ttl",
"user messenger-dispatcher on >$(Get-Content (Join-Path $secretRoot 'redis_dispatcher_password') -Raw) ~messenger:attachment-jobs:v1* ~lab5:failpoint:* +ping +set +xadd",
"user messenger-worker on >$(Get-Content (Join-Path $secretRoot 'redis_worker_password') -Raw) ~messenger:attachment-jobs:v1* ~lab5:failpoint:* ~lab6:failpoint:* +ping +get +set +xadd +xgroup +xreadgroup +xack +xautoclaim"
)
Set-Content -LiteralPath (Join-Path $secretRoot 'redis-users.acl') -Value $acl -Encoding ascii
if (-not $hasRootKey) {
Invoke-OpenSsl @('req','-x509','-newkey','rsa:4096','-sha256','-nodes','-days','3650',
'-keyout',$rootKey,'-out',$rootCert,'-subj','/CN=MTUSI-Lab7-Local-Root',
'-addext','basicConstraints=critical,CA:TRUE,pathlen:1',
'-addext','keyUsage=critical,keyCertSign,cRLSign')
}
function New-Leaf([string]$Name,[string]$CommonName,[string]$Usage,[string[]]$DnsNames,[string[]]$IpNames=@()) {
$key = Join-Path $pkiRoot "$Name.key.pem"
$csr = Join-Path $pkiRoot "$Name.csr.pem"
$cert = Join-Path $pkiRoot "$Name.crt"
$ext = Join-Path $pkiRoot "$Name.ext"
$hasKey = Test-Path -LiteralPath $key
$hasCert = Test-Path -LiteralPath $cert
if ($hasKey -and $hasCert) { return }
if ($hasKey -or $hasCert) { throw "Leaf $Name is incomplete. Restore its matching key/certificate pair or remove both and regenerate." }
$san = @($DnsNames | ForEach-Object { "DNS:$_" }) + @($IpNames | ForEach-Object { "IP:$_" })
@(
'basicConstraints=critical,CA:FALSE',
'keyUsage=critical,digitalSignature,keyEncipherment',
"extendedKeyUsage=$Usage",
"subjectAltName=$($san -join ',')"
) | Set-Content -LiteralPath $ext -Encoding ascii
Invoke-OpenSsl @('req','-new','-newkey','rsa:2048','-sha256','-nodes','-keyout',$key,'-out',$csr,'-subj',"/CN=$CommonName")
Invoke-OpenSsl @('x509','-req','-sha256','-in',$csr,'-CA',$rootCert,'-CAkey',$rootKey,'-CAcreateserial','-days','90','-extfile',$ext,'-out',$cert)
Remove-Item -LiteralPath $csr,$ext -Force
}
# Only OpenBao's listener certificate is bootstrapped by the offline CA.
# Internal leaves are issued by OpenBao's intermediate during its bootstrap.
New-Leaf 'openbao-server' 'openbao' 'serverAuth' @('openbao','localhost') @('127.0.0.1')
# Nginx enables CRL checking for the whole client certificate chain. Publish an
# empty root CRL as well as OpenBao's intermediate CRL so the chain can be
# checked without treating the absence of a root CRL as an authentication error.
$rootCrlState = Join-Path $pkiRoot 'root-crl-state'
New-Item -ItemType Directory -Force -Path $rootCrlState | Out-Null
$rootCrlIndex = Join-Path $rootCrlState 'index.txt'
$rootCrlNumber = Join-Path $rootCrlState 'crlnumber'
$rootCrlConfig = Join-Path $rootCrlState 'openssl.cnf'
$rootCrl = Join-Path $pkiRoot 'root-ca.crl.pem'
if (-not (Test-Path -LiteralPath $rootCrlIndex)) { Set-Content -LiteralPath $rootCrlIndex -Value '' -NoNewline -Encoding ascii }
if (-not (Test-Path -LiteralPath $rootCrlNumber)) { Set-Content -LiteralPath $rootCrlNumber -Value '01' -Encoding ascii }
$rootCertConfigPath = ([System.IO.Path]::GetFullPath($rootCert)).Replace('\','/')
$rootKeyConfigPath = ([System.IO.Path]::GetFullPath($rootKey)).Replace('\','/')
$rootIndexConfigPath = ([System.IO.Path]::GetFullPath($rootCrlIndex)).Replace('\','/')
$rootNumberConfigPath = ([System.IO.Path]::GetFullPath($rootCrlNumber)).Replace('\','/')
$rootCrlConfigText = @(
'[ ca ]',
'default_ca = CA_default',
'[ CA_default ]',
"database = `"$rootIndexConfigPath`"",
"certificate = `"$rootCertConfigPath`"",
"private_key = `"$rootKeyConfigPath`"",
"crlnumber = `"$rootNumberConfigPath`"",
'default_md = sha256',
'default_days = 365',
'default_crl_days = 365'
)
Set-Content -LiteralPath $rootCrlConfig -Value $rootCrlConfigText -Encoding ascii
Invoke-OpenSsl @('ca','-batch','-config',$rootCrlConfig,'-gencrl','-out',$rootCrl)
# Compose needs the source path to exist before the first OpenBao bootstrap.
# The operator bootstrap replaces this marker with the signed issuer CRL before
# any API container is started; an invalid placeholder therefore fails closed.
$crlPath = Join-Path $pkiRoot 'pki-int.crl.pem'
if (-not (Test-Path -LiteralPath $crlPath)) {
Set-Content -LiteralPath $crlPath -Value '# OpenBao bootstrap must replace this placeholder with a signed CRL.' -Encoding ascii
}
# Test-only identity: correct LB CN, deliberately signed by a separate CA.
$foreignCaKey = Join-Path $pkiRoot 'negative-test-ca.key.pem'
$foreignCaCert = Join-Path $pkiRoot 'negative-test-ca.crt'
$foreignClientKey = Join-Path $pkiRoot 'negative-test-client.key'
$foreignClientCsr = Join-Path $pkiRoot 'negative-test-client.csr'
$foreignClientCert = Join-Path $pkiRoot 'negative-test-client.crt'
if (-not ((Test-Path -LiteralPath $foreignCaKey) -and (Test-Path -LiteralPath $foreignCaCert) -and (Test-Path -LiteralPath $foreignClientKey) -and (Test-Path -LiteralPath $foreignClientCert))) {
Invoke-OpenSsl @('req','-x509','-newkey','rsa:2048','-sha256','-nodes','-days','7',
'-keyout',$foreignCaKey,'-out',$foreignCaCert,'-subj','/CN=MTUSI-Lab7-Negative-Test-CA',
'-addext','basicConstraints=critical,CA:TRUE,pathlen:0',
'-addext','keyUsage=critical,keyCertSign,cRLSign')
Invoke-OpenSsl @('req','-new','-newkey','rsa:2048','-sha256','-nodes',
'-keyout',$foreignClientKey,'-out',$foreignClientCsr,'-subj','/CN=messenger-lb')
@('basicConstraints=critical,CA:FALSE','keyUsage=critical,digitalSignature,keyEncipherment','extendedKeyUsage=clientAuth') |
Set-Content -LiteralPath (Join-Path $pkiRoot 'negative-test-client.ext') -Encoding ascii
Invoke-OpenSsl @('x509','-req','-sha256','-in',$foreignClientCsr,'-CA',$foreignCaCert,'-CAkey',$foreignCaKey,
'-CAcreateserial','-days','7','-extfile',(Join-Path $pkiRoot 'negative-test-client.ext'),'-out',$foreignClientCert)
Remove-Item -LiteralPath $foreignClientCsr,(Join-Path $pkiRoot 'negative-test-client.ext') -Force
}
Write-Host 'Local PKI created under secrets/pki. Private keys are excluded from Git; keep the CA key with the operator.'
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""Issue a short-lived LB client certificate for the expiry security probe."""
from __future__ import annotations
import getpass
import os
from pathlib import Path
import tempfile
from bao_bootstrap import Bao, CLIENT_CERTS, PKI
def main() -> None:
role = "lb-client"
common_name = CLIENT_CERTS[role]
token = getpass.getpass("OpenBao operator root token (not saved): ")
if not token:
raise SystemExit("An operator token is required")
try:
data = Bao(token).request("POST", f"pki_int/issue/{role}", {
"common_name": common_name,
"ttl": "2m",
}).get("data", {})
certificate = data.get("certificate")
private_key = data.get("private_key")
if not certificate or not private_key:
raise RuntimeError("OpenBao did not issue the short-lived probe certificate")
chain = data.get("ca_chain") or []
cert_bytes = (certificate.rstrip() + "\n" + "\n".join(item.rstrip() for item in chain) + "\n").encode("ascii")
key_bytes = (private_key.rstrip() + "\n").encode("ascii")
target = Path("secrets/revocation-probe")
target.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="expiry-probe-", dir=target) as temp_dir:
temp = Path(temp_dir)
cert_tmp = temp / "lb-client.expiry.crt"
key_tmp = temp / "lb-client.expiry.key"
cert_tmp.write_bytes(cert_bytes)
key_tmp.write_bytes(key_bytes)
os.replace(cert_tmp, target / "lb-client.expiry.crt")
os.replace(key_tmp, target / "lb-client.expiry.key")
except (OSError, RuntimeError) as exc:
raise SystemExit(f"Expiry probe issuance failed ({type(exc).__name__}): {exc}") from None
print("Issued a two-minute LB identity for the expiry probe; private key was not displayed.")
print("Run security-probe now, then again after the certificate expires (allow about 150 seconds).")
if __name__ == "__main__":
main()
+32
View File
@@ -0,0 +1,32 @@
#!/bin/sh
set -eu
# Safe to run during fresh initialization or after an interrupted initdb.
# Application roles have no passwords: pg_ident maps their client certificate
# subjects, and pg_hba rejects every non-TLS network connection.
export LAB7_POSTGRES_PASSWORD="$(cat "$POSTGRES_PASSWORD_FILE")"
psql --username "$POSTGRES_USER" --dbname postgres --set=ON_ERROR_STOP=1 <<'SQL'
\getenv lab7_database POSTGRES_DB
\getenv lab7_owner POSTGRES_USER
\getenv lab7_password LAB7_POSTGRES_PASSWORD
SELECT format('CREATE DATABASE %I OWNER %I', :'lab7_database', :'lab7_owner')
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = :'lab7_database')
\gexec
ALTER ROLE :"lab7_owner" WITH PASSWORD :'lab7_password';
SQL
psql --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" --set=ON_ERROR_STOP=1 <<'SQL'
DO $$
BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'messenger_api') THEN
CREATE ROLE messenger_api LOGIN;
END IF;
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'messenger_dispatcher') THEN
CREATE ROLE messenger_dispatcher LOGIN;
END IF;
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'messenger_worker') THEN
CREATE ROLE messenger_worker LOGIN;
END IF;
END
$$;
SQL
+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()
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env sh
set -eu
cd "$(dirname "$0")/.."
# OpenBao stays running and unsealed; app secrets are fetched again on startup.
# No named volumes are removed or re-created.
if ! docker compose exec -T \
-e BAO_ADDR=https://127.0.0.1:8200 \
-e BAO_CACERT=/run/secrets/internal-ca.crt \
openbao bao status 2>/dev/null | grep -Eq '^Sealed[[:space:]]+false$'; then
echo 'OpenBao is sealed or unreachable; unseal it before restarting application services. Nothing was stopped.' >&2
exit 1
fi
docker compose stop lb api dispatcher worker
docker compose restart db redis broker s3
attempt=0
until docker compose exec -T db pg_isready -U postgres -d messenger >/dev/null 2>&1 \
&& docker compose exec -T redis sh -ec 'REDISCLI_AUTH="$(cat /run/secrets/redis_api_password)" redis-cli --tls --cacert /run/secrets/internal-ca.crt --cert /run/secrets/api-client.crt --key /run/secrets/api-client.key --user api ping | grep -q PONG' >/dev/null 2>&1 \
&& docker compose exec -T broker sh -ec 'REDISCLI_AUTH="$(cat /run/secrets/redis_dispatcher_password)" redis-cli --tls --cacert /run/secrets/internal-ca.crt --cert /run/secrets/dispatcher-client.crt --key /run/secrets/dispatcher-client.key --user messenger-dispatcher ping | grep -q PONG' >/dev/null 2>&1 \
&& docker compose exec -T s3 curl --fail --silent --resolve s3:9000:127.0.0.1 --cacert /run/secrets/internal-ca.crt https://s3:9000/health/ready >/dev/null 2>&1; do
attempt=$((attempt + 1))
if [ "$attempt" -ge 60 ]; then
echo 'Database, cache, broker, or object store did not become ready within 60 seconds.' >&2
exit 1
fi
sleep 1
done
docker compose run --rm --no-deps s3-bootstrap
docker compose run --rm --no-deps migrate
# All dependencies were checked or bootstrapped above. Do not let Compose
# restart OpenBao here: a restarted OpenBao seals and makes workloads fail.
docker compose up -d --no-deps dispatcher worker
docker compose up -d --no-deps --scale api=2 api lb
+215
View File
@@ -0,0 +1,215 @@
#!/usr/bin/env python3
"""Prepare or activate a new OpenBao intermediate while the old CA remains trusted."""
from __future__ import annotations
import argparse
import getpass
import os
from pathlib import Path
import subprocess
import tempfile
from bao_bootstrap import BAO_ADDR, Bao, CLIENT_CERTS, OPENSSL, PKI, SERVER_CERTS
ROOT = Path(__file__).resolve().parents[1]
SECRETS = ROOT / "secrets"
MOUNT = "pki_rollover"
ROLE = "lb-client"
def openssl(args: list[str], step: str) -> bytes:
try:
result = subprocess.run([OPENSSL, *args], check=True, capture_output=True, text=True)
return result.stdout.encode("ascii")
except (OSError, subprocess.CalledProcessError) as exc:
detail = ""
if isinstance(exc, subprocess.CalledProcessError) and exc.stderr:
lines = exc.stderr.strip().splitlines()
if lines:
detail = ": " + lines[-1][:240]
raise RuntimeError(f"OpenSSL {step} failed{detail}") from None
def prepare_mount(bao: Bao) -> None:
mounts = bao.request("GET", "sys/mounts").get("data", {})
if MOUNT + "/" not in mounts:
bao.request("POST", "sys/mounts/" + MOUNT, {"type": "pki"})
bao.request("POST", "sys/mounts/" + MOUNT + "/tune", {"max_lease_ttl": "87600h"})
issuer = bao.request_text(MOUNT + "/ca/pem", allow_missing=True)
if not issuer:
generated = bao.request("POST", MOUNT + "/intermediate/generate/internal", {
"common_name": "MTUSI Lab7 Rollover 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 rollover intermediate CSR")
with tempfile.TemporaryDirectory(prefix="pki-rollover-", dir=PKI) as tmp:
tmp_path = Path(tmp)
csr_path = tmp_path / "rollover.csr"
cert_path = tmp_path / "rollover.crt"
ext_path = tmp_path / "rollover.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",
)
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),
], "offline-root signing of rollover intermediate")
bao.request("POST", MOUNT + "/intermediate/set-signed", {
"certificate": cert_path.read_text(encoding="ascii"),
})
issuer = bao.request_text(MOUNT + "/ca/pem")
if not issuer.startswith("-----BEGIN CERTIFICATE-----"):
raise RuntimeError("OpenBao returned an invalid rollover intermediate")
(PKI / "pki-rollover.crt").write_text(issuer.rstrip() + "\n", encoding="ascii")
bao.request("POST", MOUNT + "/config/urls", {
"issuing_certificates": f"{BAO_ADDR}/v1/{MOUNT}/ca",
"crl_distribution_points": f"{BAO_ADDR}/v1/{MOUNT}/crl",
})
def configure_roles(bao: Bao) -> None:
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():
server = kind == "server"
bao.request("POST", f"{MOUNT}/roles/{role}", {
"allowed_domains": sorted(set([common_name, *dns_names])),
"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": server,
"client_flag": not server,
"key_usage": ["DigitalSignature", "KeyEncipherment"],
"ext_key_usage": ["ServerAuth"] if server else ["ClientAuth"],
})
def publish_overlap_crl(bao: Bao) -> None:
root_crl_path = PKI / "root-ca.crl.pem"
old_ca = PKI / "pki-int.crt"
new_ca = PKI / "pki-rollover.crt"
if not root_crl_path.is_file() or not old_ca.is_file() or not new_ca.is_file():
raise RuntimeError("Root or intermediate CA material is missing")
crls = [
(root_crl_path.read_text(encoding="ascii"), PKI / "internal-ca.crt", "root"),
(bao.request_text("pki_int/crl/pem"), old_ca, "current intermediate"),
(bao.request_text(MOUNT + "/crl/pem"), new_ca, "rollover intermediate"),
]
with tempfile.TemporaryDirectory(prefix="crl-overlap-", dir=PKI) as tmp:
pieces: list[bytes] = []
for index, (pem, issuer, label) in enumerate(crls):
if not pem.startswith("-----BEGIN X509 CRL-----"):
raise RuntimeError(f"OpenBao returned an invalid {label} CRL")
path = Path(tmp) / f"crl-{index}.pem"
path.write_text(pem.rstrip() + "\n", encoding="ascii")
openssl(["crl", "-in", str(path), "-CAfile", str(issuer), "-verify", "-noout"], f"{label} CRL signature verification")
pieces.append(path.read_bytes().rstrip())
candidate = Path(tmp) / "combined.crl.pem"
candidate.write_bytes(b"\n".join(pieces) + b"\n")
os.replace(candidate, PKI / "pki-int.crl.pem")
def stage_lb_leaf(bao: Bao) -> None:
issued = bao.request("POST", f"{MOUNT}/issue/{ROLE}", {
"common_name": CLIENT_CERTS[ROLE],
"ttl": "6h",
}).get("data", {})
certificate, private_key = issued.get("certificate"), issued.get("private_key")
if not certificate or not private_key:
raise RuntimeError("OpenBao did not issue a rollover LB certificate")
chain = issued.get("ca_chain") or []
combined = certificate.rstrip() + "\n" + "\n".join(item.rstrip() for item in chain) + "\n"
rollover_dir = PKI / "rollover"
rollover_dir.mkdir(parents=True, exist_ok=True)
probe_dir = SECRETS / "revocation-probe"
probe_dir.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="rollover-leaf-", dir=rollover_dir) as tmp:
tmp_path = Path(tmp)
cert = tmp_path / "lb-client.crt"
key = tmp_path / "lb-client.key"
cert.write_text(combined, encoding="ascii")
key.write_text(private_key.rstrip() + "\n", encoding="ascii")
openssl([
"verify", "-purpose", "sslclient", "-CAfile", str(PKI / "internal-ca.crt"),
"-untrusted", str(PKI / "pki-rollover.crt"), str(cert),
], "rollover leaf chain verification")
openssl(["x509", "-in", str(cert), "-noout", "-checkhost", CLIENT_CERTS[ROLE]], "rollover leaf identity verification")
cert_target = rollover_dir / "lb-client.crt"
key_target = rollover_dir / "lb-client.key"
os.replace(cert, cert_target)
os.replace(key, key_target)
(probe_dir / "lb-client.rollover.crt").write_bytes((rollover_dir / "lb-client.crt").read_bytes())
(probe_dir / "lb-client.rollover.key").write_bytes((rollover_dir / "lb-client.key").read_bytes())
def activate_lb_leaf() -> None:
rollover_dir = PKI / "rollover"
source_cert = rollover_dir / "lb-client.crt"
source_key = rollover_dir / "lb-client.key"
current_cert = PKI / "lb-client.crt"
current_key = PKI / "lb-client.key"
if not source_cert.is_file() or not source_key.is_file() or not current_cert.is_file() or not current_key.is_file():
raise RuntimeError("Staged rollover leaf or current LB pair is missing; run prepare first")
if current_cert.read_bytes() == source_cert.read_bytes() and current_key.read_bytes() == source_key.read_bytes():
raise RuntimeError("Staged rollover leaf is already active; refusing to overwrite the saved previous pair")
(PKI / "lb-client.previous.crt").write_bytes(current_cert.read_bytes())
(PKI / "lb-client.previous.key").write_bytes(current_key.read_bytes())
with tempfile.TemporaryDirectory(prefix="activate-rollover-", dir=PKI) as tmp:
tmp_path = Path(tmp)
cert_tmp = tmp_path / "lb-client.crt"
key_tmp = tmp_path / "lb-client.key"
cert_tmp.write_bytes(source_cert.read_bytes())
key_tmp.write_bytes(source_key.read_bytes())
os.replace(cert_tmp, current_cert)
os.replace(key_tmp, current_key)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("prepare", "activate"))
args = parser.parse_args()
if not (PKI / "internal-ca.crt").is_file() or not (PKI / "internal-ca.key.pem").is_file():
raise SystemExit("Run scripts/bootstrap-local.ps1 first")
try:
if args.action == "prepare":
token = getpass.getpass("OpenBao operator root token (not saved): ")
if not token:
raise SystemExit("An operator token is required")
bao = Bao(token)
prepare_mount(bao)
configure_roles(bao)
publish_overlap_crl(bao)
stage_lb_leaf(bao)
print("Prepared a new offline-root-signed intermediate and a staged LB leaf.")
print("Recreate API first to load both intermediate CRLs; security-probe should accept old and staged LB identities.")
print("Then run action 'activate', recreate LB, revoke saved previous leaf, and recreate API.")
else:
activate_lb_leaf()
print("Activated the staged rollover LB leaf; the previous LB pair remains saved for revocation.")
print("Recreate LB before revoking the saved previous leaf.")
except (OSError, RuntimeError, subprocess.CalledProcessError) as exc:
raise SystemExit(f"Intermediate rollover stopped ({type(exc).__name__}): {exc}") from None
if __name__ == "__main__":
main()
+39
View File
@@ -0,0 +1,39 @@
$ErrorActionPreference = 'Stop'
$repo = Split-Path -Parent $PSScriptRoot
$trivy = Get-Command trivy -ErrorAction SilentlyContinue
if (-not $trivy) { throw 'Install Trivy and ensure it is on PATH before running this scan.' }
Push-Location $repo
try {
docker compose build api db bao-renew openbao redis s3 lb grafana
$images = @(
'mtusi-messenger-lab7-api:local',
'mtusi-messenger-lab7-bao-renew:local',
'mtusi-messenger-lab7-openbao:local',
'mtusi-messenger-lab7-postgres:local',
'mtusi-messenger-lab7-redis:local',
'mtusi-messenger-lab7-rustfs:local',
'mtusi-messenger-lab7-nginx:local',
'otel/opentelemetry-collector-contrib:0.166.0',
'prom/prometheus:v3.16.0',
'grafana/loki:3.6.23',
'grafana/tempo:2.10.10',
'mtusi-messenger-lab7-grafana:local'
)
New-Item -ItemType Directory -Force evidence | Out-Null
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
foreach ($image in $images) {
$safe = $image -replace '[^A-Za-z0-9._-]', '_'
$output = Join-Path 'evidence' "trivy-$stamp-$safe.json"
& $trivy.Source image --scanners vuln --severity HIGH,CRITICAL --ignorefile .trivyignore.yaml --show-suppressed --format json --output $output $image
if ($LASTEXITCODE -ne 0) { throw "Trivy could not scan image $image" }
Write-Host "Saved scan: $output"
}
$fsOutput = Join-Path 'evidence' "trivy-$stamp-filesystem.json"
# Dockerfile.example is an intentionally non-runnable teaching outline.
& $trivy.Source fs --scanners vuln,misconfig,secret --skip-dirs .git,.venv,secrets --skip-files Dockerfile.example --format json --output $fsOutput .
if ($LASTEXITCODE -ne 0) { throw 'Trivy could not scan the repository filesystem.' }
Write-Host "Saved scan: $fsOutput"
} finally {
Pop-Location
}
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""Run from the Compose security-test profile; never prints credential material."""
from __future__ import annotations
import socket
import ssl
from pathlib import Path
import time
SECRETS = Path("/run/secrets")
def request(host: str, server_name: str, context: ssl.SSLContext, cert: str | None = None, key: str | None = None, *, method: str = "GET", path: str = "/health/ready") -> bytes:
if cert and key:
cert_path = Path(cert)
key_path = Path(key)
context.load_cert_chain(
str(cert_path if cert_path.is_absolute() else SECRETS / cert_path),
str(key_path if key_path.is_absolute() else SECRETS / key_path),
)
with socket.create_connection((host, 8443), timeout=3) as raw:
with context.wrap_socket(raw, server_hostname=server_name) as tls:
tls.sendall(f"{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nContent-Length: 0\r\n\r\n".encode("ascii"))
chunks = []
while True:
chunk = tls.recv(4096)
if not chunk:
break
chunks.append(chunk)
response = b"".join(chunks)
return response
def status_code(response: bytes) -> int:
status = response.split(b"\r\n", 1)[0].split()
if len(status) < 2:
raise RuntimeError("peer returned no HTTP status")
return int(status[1])
def expect_tls_rejection(host: str, server_name: str, *, trusted_ca: bool = False) -> None:
if trusted_ca:
context = ssl.create_default_context(cafile=str(SECRETS / "internal-ca.crt"))
else:
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
try:
request(host, server_name, context)
except (ssl.SSLError, OSError):
return
raise AssertionError("untrusted TLS server was accepted")
def expect_client_certificate_rejection(cert: str | None = None, key: str | None = None) -> int | None:
context = ssl.create_default_context(cafile=str(SECRETS / "internal-ca.crt"))
try:
return status_code(request("api", "api", context, cert, key))
except (ssl.SSLError, OSError):
return None
def main() -> None:
ca = ssl.create_default_context(cafile=str(SECRETS / "internal-ca.crt"))
public_status = status_code(request("lb", "localhost", ca))
assert public_status == 200, f"trusted public TLS ingress failed with HTTP {public_status}"
expect_tls_rejection("lb", "localhost")
expect_tls_rejection("lb", "wrong-host.invalid", trusted_ca=True)
no_certificate_status = expect_client_certificate_rejection()
# Nginx may complete TLS and reject the HTTP request with its standard
# 400 response when ssl_verify_client is on. A TLS alert (None) is also a
# valid rejection; a successful or unrelated HTTP response is not.
assert no_certificate_status in (None, 400), (
f"API did not reject a request without a client certificate (HTTP {no_certificate_status})"
)
foreign_ca_status = expect_client_certificate_rejection(
"negative-test-client.crt", "negative-test-client.key"
)
assert foreign_ca_status in (None, 400), (
"API did not reject a correct-CN certificate from a foreign CA "
f"(HTTP {foreign_ca_status})"
)
wrong_identity = expect_client_certificate_rejection("prometheus-client.crt", "prometheus-client.key")
assert wrong_identity == 403, f"trusted but unauthorized identity returned {wrong_identity}"
assert expect_client_certificate_rejection("lb-client.crt", "lb-client.key") == 200, "authorized LB identity failed"
previous_cert = Path("/revocation/lb-client.previous.crt")
previous_key = Path("/revocation/lb-client.previous.key")
if previous_cert.is_file() and previous_key.is_file():
previous_status = expect_client_certificate_rejection(str(previous_cert), str(previous_key))
assert previous_status in (None, 400), (
"API accepted the revoked previous LB certificate "
f"(HTTP {previous_status}); verify the mounted CRL and recreate API"
)
expiry_cert = Path("/revocation/lb-client.expiry.crt")
expiry_key = Path("/revocation/lb-client.expiry.key")
if expiry_cert.is_file() and expiry_key.is_file():
cert_info = ssl._ssl._test_decode_cert(str(expiry_cert))
still_valid = ssl.cert_time_to_seconds(cert_info["notAfter"]) > time.time()
expiry_status = expect_client_certificate_rejection(str(expiry_cert), str(expiry_key))
if still_valid:
assert expiry_status == 200, f"short-lived LB certificate failed before expiry (HTTP {expiry_status})"
print("PASS: short-lived LB certificate accepted before expiry")
else:
assert expiry_status in (None, 400), (
f"API accepted the expired LB certificate (HTTP {expiry_status})"
)
assert expect_client_certificate_rejection("lb-client.crt", "lb-client.key") == 200, (
"valid replacement LB identity did not recover after the expiry rejection"
)
print("PASS: expired LB certificate rejected; current LB identity remains accepted")
rollover_cert = Path("/revocation/lb-client.rollover.crt")
rollover_key = Path("/revocation/lb-client.rollover.key")
if rollover_cert.is_file() and rollover_key.is_file():
rollover_status = expect_client_certificate_rejection(str(rollover_cert), str(rollover_key))
assert rollover_status == 200, (
f"new-intermediate LB identity was not accepted during overlap (HTTP {rollover_status})"
)
print("PASS: LB identities signed by old and rollover intermediates are accepted during overlap")
throttled = []
for _ in range(20):
throttled.append(request("lb", "localhost", ca, method="POST", path="/api/v1/auth/sessions"))
limited = [response for response in throttled if status_code(response) == 429]
assert limited, "login requests did not reach the 429 rate limit"
assert any(b"retry-after:" in response.lower() for response in limited), "429 response lacks Retry-After"
if previous_cert.is_file() and previous_key.is_file():
print("PASS: TLS trust, API client CA/identity, revoked prior LB certificate, login 429 and Retry-After")
else:
print("PASS: TLS trust, API client CA/identity, login 429 and Retry-After (no prior revoked LB cert staged)")
if __name__ == "__main__":
main()
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}"
for container_id in $(docker compose ps -q api); do
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container_id")
instance_id=$(printf '%s' "$hostname" | sha256sum | cut -c1-12)
if [[ "$instance_id" == "$TARGET_INSTANCE_ID" ]]; then
docker stop --time 6 "$container_id" >/dev/null
exit 0
fi
done
printf 'No running API container matches TARGET_INSTANCE_ID.\n' >&2
exit 1