feat: complete lab 7 for grade 4
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
This commit is contained in:
+210
@@ -0,0 +1,210 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator-only OpenBao bootstrap, unseal and KV operations over verified HTTPS."""
|
||||
import argparse
|
||||
import base64
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import stat
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import HTTPSHandler, Request, build_opener
|
||||
|
||||
from pki import STATE
|
||||
|
||||
BASE = os.environ.get("LAB7_OPENBAO_URL", "https://localhost:18200").rstrip("/") + "/v1/"
|
||||
OPERATOR = STATE / "operator/openbao-v2.json"
|
||||
INIT_ATTEMPT = OPERATOR.with_suffix(".init-attempted")
|
||||
STAGED_OPERATOR = OPERATOR.with_suffix(".pending")
|
||||
OPERATOR_LOCK = OPERATOR.with_suffix(".lock")
|
||||
|
||||
|
||||
def request(path, body=None, token=None, method=None, accepted=(), timeout=4):
|
||||
if not BASE.startswith("https://"):
|
||||
raise ValueError("OpenBao operator endpoint requires HTTPS")
|
||||
context = ssl.create_default_context(cafile=str(STATE / "trust/ca.crt"))
|
||||
# Existing lab roots omit Key Usage. Keep certificate and hostname
|
||||
# verification against the explicit lab CA on Python 3.13 and newer.
|
||||
context.verify_flags &= ~ssl.VERIFY_X509_STRICT
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
payload = None if body is None else json.dumps(body).encode()
|
||||
req = Request(BASE + path, data=payload, headers=headers, method=method)
|
||||
try:
|
||||
response = build_opener(HTTPSHandler(context=context)).open(req, timeout=timeout)
|
||||
except HTTPError as exc:
|
||||
if exc.code not in accepted:
|
||||
raise RuntimeError(f"OpenBao operation {path} returned {exc.code}") from None
|
||||
response = exc
|
||||
with response:
|
||||
data = response.read()
|
||||
return json.loads(data) if data else {}
|
||||
|
||||
|
||||
def status():
|
||||
return request("sys/health", accepted=(429, 501, 503))
|
||||
|
||||
|
||||
def private_operator_directory():
|
||||
directory = OPERATOR.parent
|
||||
directory.mkdir(mode=0o700, exist_ok=True)
|
||||
metadata = directory.lstat()
|
||||
if (not stat.S_ISDIR(metadata.st_mode) or stat.S_IMODE(metadata.st_mode) != 0o700
|
||||
or metadata.st_uid != os.getuid()):
|
||||
raise RuntimeError("OpenBao operator directory must be owned by this user with mode 0700")
|
||||
return directory
|
||||
|
||||
|
||||
def validate_operator(material):
|
||||
try:
|
||||
encoded_shares = material["keys_base64"]
|
||||
token = material["root_token"]
|
||||
if isinstance(encoded_shares, list) and len(encoded_shares) == 3:
|
||||
shares = [base64.b64decode(share, validate=True) for share in encoded_shares]
|
||||
if len(set(shares)) == 3 and all(shares) and isinstance(token, str) and token:
|
||||
return material
|
||||
except (KeyError, TypeError, ValueError):
|
||||
pass
|
||||
raise RuntimeError("Invalid OpenBao operator material")
|
||||
|
||||
|
||||
def operator():
|
||||
private_operator_directory()
|
||||
try:
|
||||
with os.fdopen(os.open(OPERATOR, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)) as file:
|
||||
metadata = os.fstat(file.fileno())
|
||||
if (not stat.S_ISREG(metadata.st_mode) or stat.S_IMODE(metadata.st_mode) != 0o600
|
||||
or metadata.st_uid != os.getuid()):
|
||||
raise RuntimeError("OpenBao operator file must be owned by this user with mode 0600")
|
||||
return validate_operator(json.load(file))
|
||||
except (OSError, ValueError):
|
||||
raise RuntimeError("OpenBao operator file is unavailable or unreadable; reconcile it before continuing") from None
|
||||
|
||||
|
||||
def initialize():
|
||||
directory = private_operator_directory()
|
||||
if any(os.path.lexists(path) for path in (OPERATOR, INIT_ATTEMPT, STAGED_OPERATOR)):
|
||||
raise RuntimeError("Existing OpenBao v2 operator files or init attempt require manual reconciliation")
|
||||
directory_fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
parent_fd = os.open(directory.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
os.fsync(parent_fd)
|
||||
finally:
|
||||
os.close(parent_fd)
|
||||
# Reserve one attempt even if the server responds after a client timeout.
|
||||
with os.fdopen(os.open(INIT_ATTEMPT, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") as marker:
|
||||
marker.write("OpenBao v2 initialization attempted\n")
|
||||
marker.flush()
|
||||
os.fsync(marker.fileno())
|
||||
fd = os.open(STAGED_OPERATOR, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(fd, "w+") as staged:
|
||||
os.fchmod(staged.fileno(), 0o600)
|
||||
os.fsync(directory_fd)
|
||||
material = validate_operator(request("sys/init", {"secret_shares": 3, "secret_threshold": 2},
|
||||
timeout=180))
|
||||
json.dump(material, staged)
|
||||
staged.flush()
|
||||
os.fsync(staged.fileno())
|
||||
staged.seek(0)
|
||||
if json.load(staged) != material:
|
||||
raise RuntimeError("OpenBao operator file verification failed")
|
||||
# Hard-link publication is atomic and refuses to replace an existing file.
|
||||
os.link(STAGED_OPERATOR, OPERATOR)
|
||||
os.fsync(directory_fd)
|
||||
if operator() != material:
|
||||
raise RuntimeError("Published OpenBao operator file verification failed")
|
||||
STAGED_OPERATOR.unlink()
|
||||
os.fsync(directory_fd)
|
||||
except (OSError, RuntimeError, ValueError):
|
||||
raise RuntimeError(
|
||||
"OpenBao initialization did not complete locally. Preserve the operator files and "
|
||||
"check status before manual reconciliation. Initialization will not be retried."
|
||||
) from None
|
||||
finally:
|
||||
os.close(directory_fd)
|
||||
|
||||
|
||||
def unseal():
|
||||
if status().get("sealed"):
|
||||
for share in operator()["keys_base64"]:
|
||||
result = request("sys/unseal", {"key": share})
|
||||
if not result["sealed"]:
|
||||
break
|
||||
else:
|
||||
raise RuntimeError("Unseal did not reach the configured threshold")
|
||||
|
||||
|
||||
def conninfo(role, password=None):
|
||||
value = password or (STATE / "postgres" / role).read_text().strip()
|
||||
return (f"host=postgres dbname=messenger user={role} password={value} "
|
||||
"sslmode=verify-full sslrootcert=/run/trust/ca.crt gssencmode=disable")
|
||||
|
||||
|
||||
def configure():
|
||||
api_role = os.environ.get("LAB7_API_DB_ROLE", "api_blue")
|
||||
if api_role not in ("api_blue", "api_green"):
|
||||
raise RuntimeError("LAB7_API_DB_ROLE must be api_blue or api_green")
|
||||
token = operator()["root_token"]
|
||||
if "cert/" not in request("sys/auth", token=token):
|
||||
request("sys/auth/cert", {"type": "cert"}, token)
|
||||
if "kv/" not in request("sys/mounts", token=token):
|
||||
request("sys/mounts/kv", {"type": "kv", "options": {"version": "2"}}, token)
|
||||
ca = (STATE / "trust/ca.crt").read_text()
|
||||
for role in ("api-a", "api-b", "publisher", "worker", "recovery"):
|
||||
scope = "api" if role.startswith("api-") else role
|
||||
policy = (f'path "kv/data/messenger/{scope}" {{ capabilities = ["read"] }}\n'
|
||||
'path "auth/token/renew-self" { capabilities = ["update"] }')
|
||||
policy_path = f"sys/policies/acl/{scope}"
|
||||
if not request(policy_path, token=token, accepted=(404,)).get("data"):
|
||||
request(policy_path, {"policy": policy}, token)
|
||||
cert_path = f"auth/cert/certs/{role}"
|
||||
if not request(cert_path, token=token, accepted=(404,)).get("data"):
|
||||
request(cert_path, {"certificate": ca,
|
||||
"allowed_dns_sans": [f"{role}.bao.lab"], "token_policies": [scope],
|
||||
"token_no_default_policy": True, "token_type": "service",
|
||||
"token_ttl": "20s", "token_explicit_max_ttl": "60s"}, token)
|
||||
for scope in ("api", "publisher", "worker", "recovery"):
|
||||
path = f"kv/data/messenger/{scope}"
|
||||
if request(path, token=token, accepted=(404,)).get("data"):
|
||||
continue
|
||||
data = {"database_url": conninfo(api_role if scope == "api" else scope)}
|
||||
if scope != "publisher":
|
||||
data.update(s3_user="lab-" + scope, s3_password=(STATE / "s3" / scope).read_text().strip())
|
||||
request(path, {"options": {"cas": 0}, "data": data}, token)
|
||||
|
||||
|
||||
def prepare_local_dsn():
|
||||
for role in ("migrator", "ops"):
|
||||
directory = STATE / role
|
||||
directory.mkdir(exist_ok=True)
|
||||
path = directory / "dsn"
|
||||
if not path.exists():
|
||||
path.write_text(conninfo(role))
|
||||
path.chmod(0o444)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=("bootstrap", "unseal", "status", "local-dsn"))
|
||||
action = parser.parse_args().action
|
||||
if action == "local-dsn":
|
||||
prepare_local_dsn()
|
||||
return
|
||||
if action in ("bootstrap", "unseal"):
|
||||
private_operator_directory()
|
||||
fd = os.open(OPERATOR_LOCK, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, "w") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
if action == "bootstrap" and not status()["initialized"]:
|
||||
initialize()
|
||||
unseal()
|
||||
if action == "bootstrap":
|
||||
configure()
|
||||
state = status()
|
||||
print(f"OpenBao initialized={state['initialized']} sealed={state['sealed']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
case "$#:${1:-}" in
|
||||
0:) python3 scripts/pki.py init; python3 scripts/bao.py local-dsn ;;
|
||||
1:--openbao-only) ;;
|
||||
*) echo 'Usage: scripts/bootstrap.sh [--openbao-only]' >&2; exit 2 ;;
|
||||
esac
|
||||
./scripts/compose.sh up -d openbao
|
||||
attempt=0
|
||||
until python3 scripts/bao.py status >/dev/null 2>&1; do
|
||||
attempt=$((attempt + 1))
|
||||
test "$attempt" -lt 60
|
||||
sleep 1
|
||||
done
|
||||
python3 scripts/bao.py bootstrap
|
||||
if [ "${1:-}" = --openbao-only ]; then
|
||||
exit 0
|
||||
fi
|
||||
./scripts/compose.sh up -d --build postgres s3 broker migrate \
|
||||
otel-collector otel-tls prometheus prometheus-tls loki loki-tls tempo tempo-tls grafana
|
||||
./scripts/compose.sh run --rm s3-bootstrap
|
||||
./scripts/compose.sh up -d --wait --wait-timeout 120
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check effective Compose privileges and the actual image user defaults."""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
STATEFUL = {"postgres", "broker", "openbao", "s3"}
|
||||
ROOT_BOOTSTRAP = {"postgres", "broker", "volume-init"}
|
||||
PUBLISHED = {"lb": 8443, "openbao": 8200, "grafana": 3000}
|
||||
|
||||
|
||||
def check(config, image_user):
|
||||
findings = []
|
||||
for name, service in config["services"].items():
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
findings.append(f"{name}: {message}")
|
||||
|
||||
require(not service.get("privileged") and service.get("network_mode") != "host",
|
||||
"privileged mode or host network")
|
||||
require(not service.get("pid") and not service.get("ipc") == "host", "host process or IPC namespace")
|
||||
require(all("docker.sock" not in str(mount) for mount in service.get("volumes", [])),
|
||||
"Docker socket mount")
|
||||
require("no-new-privileges:true" in service.get("security_opt", []), "no-new-privileges absent")
|
||||
require(bool(service.get("mem_limit") and service.get("cpus") and service.get("pids_limit")),
|
||||
"CPU/RAM/PID limit absent")
|
||||
for port in service.get("ports", []):
|
||||
require(port.get("host_ip") == "127.0.0.1" and port["target"] == PUBLISHED.get(name),
|
||||
"unexpected published port")
|
||||
effective = service.get("user") or image_user(service["image"])
|
||||
if name not in ROOT_BOOTSTRAP:
|
||||
require(bool(effective) and effective.split(":")[0] not in {"0", "root"}, "effective image user is root")
|
||||
if name not in STATEFUL:
|
||||
require(service.get("read_only"), "writable root filesystem")
|
||||
require("ALL" in service.get("cap_drop", []), "global capability drop absent")
|
||||
require(not service.get("cap_add") or (name == "volume-init" and service["cap_add"] == ["CHOWN"]),
|
||||
"unexpected capability grant")
|
||||
return findings
|
||||
|
||||
|
||||
def main():
|
||||
config = json.load(sys.stdin)
|
||||
|
||||
def image_user(image):
|
||||
return subprocess.check_output(
|
||||
["docker", "image", "inspect", "--format", "{{.Config.User}}", image], text=True
|
||||
).strip()
|
||||
|
||||
findings = check(config, image_user)
|
||||
if findings:
|
||||
print("\n".join(findings))
|
||||
raise SystemExit(1)
|
||||
print(f"PASS: effective Docker hardening for {len(config['services'])} services")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
if [ -d /Applications/Docker.app/Contents/Resources/bin ]; then
|
||||
export PATH="/Applications/Docker.app/Contents/Resources/bin:$PATH"
|
||||
fi
|
||||
export LAB7_STATE="${LAB7_STATE:-/private/tmp/mtusi2026lab7-$(id -u)}"
|
||||
if [ -x /Applications/Docker.app/Contents/Resources/cli-plugins/docker-compose ]; then
|
||||
exec /Applications/Docker.app/Contents/Resources/cli-plugins/docker-compose "$@"
|
||||
fi
|
||||
exec docker compose "$@"
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
python_absent() {
|
||||
for file in /run/trust/ca.crt /run/identity/client.crt /run/identity/client.key; do
|
||||
test -s "$file"
|
||||
done
|
||||
}
|
||||
python_absent
|
||||
export LAB_CA="$(cat /run/trust/ca.crt)"
|
||||
export LAB_CERT="$(cat /run/identity/client.crt)"
|
||||
export LAB_KEY="$(cat /run/identity/client.key)"
|
||||
exec /run.sh
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
#!/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()
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
./scripts/compose.sh restart openbao postgres s3 broker api-a api-b publisher worker recovery
|
||||
attempt=0
|
||||
until python3 scripts/bao.py unseal; do
|
||||
attempt=$((attempt + 1))
|
||||
test "$attempt" -lt 15
|
||||
sleep 1
|
||||
done
|
||||
@@ -0,0 +1,135 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rotate API PostgreSQL access without invalidating the published KV generation."""
|
||||
import argparse
|
||||
import fcntl
|
||||
import os
|
||||
import secrets
|
||||
import shlex
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from bao import conninfo, operator, request
|
||||
from pki import STATE
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PATH = "kv/data/messenger/api"
|
||||
ALTERNATE = {"api_blue": "api_green", "api_green": "api_blue"}
|
||||
|
||||
|
||||
def compose(*arguments, data=None):
|
||||
return subprocess.run([str(ROOT / "scripts/compose.sh"), *arguments], input=data,
|
||||
capture_output=True, text=True, timeout=15, check=True).stdout.strip()
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return compose("exec", "-T", "--user", "postgres", "postgres", "psql", "-XqAt",
|
||||
"-v", "ON_ERROR_STOP=1", "-d", "messenger", data=statement)
|
||||
|
||||
|
||||
def db_probe(info):
|
||||
code = (
|
||||
"import sys,psycopg; "
|
||||
"c=psycopg.connect(sys.stdin.read(),connect_timeout=3); "
|
||||
"print(c.execute('select session_user from pg_stat_ssl where pid=pg_backend_pid() and ssl').fetchone()[0]); "
|
||||
"c.close()"
|
||||
)
|
||||
return compose("exec", "-T", "api-a", "python", "-c", code, data=info)
|
||||
|
||||
|
||||
def read_generation(token):
|
||||
document = request(PATH, token=token)["data"]
|
||||
info = document["data"]["database_url"]
|
||||
fields = dict(field.split("=", 1) for field in shlex.split(info))
|
||||
role = fields.get("user")
|
||||
if role not in ALTERNATE or fields.get("sslmode") != "verify-full":
|
||||
raise RuntimeError("The published API credential does not match the supported roles and TLS mode")
|
||||
return document, info, role
|
||||
|
||||
|
||||
def await_active(role):
|
||||
deadline = time.monotonic() + 50
|
||||
while time.monotonic() < deadline:
|
||||
for instance in ("api-a", "api-b"):
|
||||
compose("exec", "-T", instance, "python", "/app/uds_probe.py")
|
||||
count = sql(f"SELECT count(DISTINCT client_addr) FROM pg_stat_activity WHERE usename='{role}' AND backend_type='client backend';")
|
||||
if count == "2":
|
||||
return
|
||||
time.sleep(1)
|
||||
raise RuntimeError("Both replicas have not acquired the published role; the previous credential remains enabled")
|
||||
|
||||
|
||||
def retire(token, current, info, active, old_info=None):
|
||||
previous = ALTERNATE[active]
|
||||
await_active(active)
|
||||
deadline = time.monotonic() + 25
|
||||
while sql(f"SELECT count(*) FROM pg_stat_activity WHERE usename='{previous}';") != "0":
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError("Previous sessions did not drain; both credentials remain usable")
|
||||
time.sleep(1)
|
||||
# CAS protects the publication itself. A final version check also prevents
|
||||
# retiring an identity after an unrelated change during convergence.
|
||||
latest, _, _ = read_generation(token)
|
||||
if latest["metadata"]["version"] != current["metadata"]["version"] or db_probe(info) != active:
|
||||
raise RuntimeError("KV generation changed or TLS verification failed before retirement")
|
||||
sql(f"ALTER ROLE {previous} PASSWORD NULL;")
|
||||
if sql(f"SELECT (rolpassword IS NULL)::int FROM pg_authid WHERE rolname='{previous}';") != "1":
|
||||
raise RuntimeError("Could not verify retirement of the previous password")
|
||||
if old_info is not None:
|
||||
try:
|
||||
db_probe(old_info)
|
||||
except subprocess.CalledProcessError as exc:
|
||||
if "password authentication failed" not in exc.stderr:
|
||||
raise RuntimeError("The previous password denial was not verified") from None
|
||||
else:
|
||||
raise RuntimeError("The previous password still authenticates")
|
||||
if db_probe(info) != active:
|
||||
raise RuntimeError("Published PostgreSQL credential could not be verified after retirement")
|
||||
|
||||
|
||||
def rotate(token, resume=False):
|
||||
current, old_info, active = read_generation(token)
|
||||
if db_probe(old_info) != active:
|
||||
raise RuntimeError("The published PostgreSQL credential did not pass the TLS probe")
|
||||
if resume:
|
||||
retire(token, current, old_info, active)
|
||||
return
|
||||
alternate = ALTERNATE[active]
|
||||
password = secrets.token_hex(24)
|
||||
sql("SET log_statement=none; SET log_min_error_statement=panic; "
|
||||
f"ALTER ROLE {alternate} LOGIN PASSWORD '{password}';")
|
||||
new_info = conninfo(alternate, password)
|
||||
if db_probe(new_info) != alternate:
|
||||
raise RuntimeError("The replacement PostgreSQL credential did not pass the TLS probe")
|
||||
try:
|
||||
request(PATH, {"data": dict(current["data"], database_url=new_info),
|
||||
"options": {"cas": current["metadata"]["version"]}}, token)
|
||||
except (OSError, RuntimeError, ValueError):
|
||||
# A timeout can follow a committed KV write. Neither role is retired
|
||||
# on uncertainty and blindly issuing another rotation is unsafe.
|
||||
raise RuntimeError("KV CAS outcome uncertain; both credentials remain usable. Inspect KV and use --retire-previous.") from None
|
||||
published, info, role = read_generation(token)
|
||||
if info != new_info or role != alternate:
|
||||
raise RuntimeError("OpenBao did not return the expected replacement generation")
|
||||
retire(token, published, info, role, old_info)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--retire-previous", action="store_true",
|
||||
help="verify the currently published generation and retire only the other role")
|
||||
args = parser.parse_args()
|
||||
lock = STATE / "operator/rotate-db.lock"
|
||||
with os.fdopen(os.open(lock, os.O_CREAT | os.O_WRONLY | os.O_NOFOLLOW, 0o600), "w") as file:
|
||||
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
rotate(operator()["root_token"], args.retire_previous)
|
||||
print("PASS: both API replicas use the published TLS credential; the other password is retired")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except RuntimeError as exc:
|
||||
raise SystemExit(str(exc)) from None
|
||||
except (OSError, subprocess.SubprocessError, ValueError, KeyError):
|
||||
raise SystemExit("Rotation stopped. Inspect the active KV generation before resuming; no credentials printed.") from None
|
||||
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rotate the allowlisted LB client leaf and roll the CRL across both API proxies."""
|
||||
import fcntl
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from pki import ROOT, STATE, issue, openssl, crl
|
||||
|
||||
CONFIG = "/usr/local/etc/haproxy/haproxy.cfg"
|
||||
|
||||
|
||||
def compose(*args, capture=False):
|
||||
return subprocess.run([str(ROOT / "scripts/compose.sh"), *args], check=True, timeout=45,
|
||||
capture_output=capture).stdout
|
||||
|
||||
|
||||
def reload(service):
|
||||
host_file = STATE / ("lb/client.pem" if service == "lb" else "trust/ca.crl")
|
||||
mounted_file = "/run/identity/client.pem" if service == "lb" else "/run/trust/ca.crl"
|
||||
expected = hashlib.sha256(host_file.read_bytes()).hexdigest().encode()
|
||||
for _ in range(25):
|
||||
try:
|
||||
actual = compose("exec", "-T", service, "sha256sum", mounted_file, capture=True).split()[0]
|
||||
if expected == actual:
|
||||
compose("exec", "-T", service, "haproxy", "-c", "-f", CONFIG, capture=True)
|
||||
break
|
||||
except subprocess.CalledProcessError:
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
raise RuntimeError("HAProxy cannot read or validate the newly mounted TLS file")
|
||||
before = compose("exec", "-T", service, "cat", "/proc/1/task/1/children", capture=True).split()
|
||||
compose("exec", "-T", service, "sh", "-ec",
|
||||
'tr "\\000" " " </proc/1/cmdline | grep -Eq "(^|/)haproxy .* -W |^haproxy -W "; kill -USR2 1')
|
||||
for _ in range(25):
|
||||
after = compose("exec", "-T", service, "cat", "/proc/1/task/1/children", capture=True).split()
|
||||
if set(after).difference(before):
|
||||
return
|
||||
time.sleep(0.2)
|
||||
raise RuntimeError("HAProxy did not start a replacement worker")
|
||||
|
||||
|
||||
def probe(mode):
|
||||
for attempt in range(5):
|
||||
try:
|
||||
compose("run", "--rm", "-T", "probe", mode)
|
||||
return
|
||||
except subprocess.CalledProcessError:
|
||||
if attempt == 4:
|
||||
raise
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def install(directory, name, data):
|
||||
temporary = directory / (name + ".next")
|
||||
with temporary.open("xb") as file:
|
||||
os.fchmod(file.fileno(), 0o444)
|
||||
file.write(data)
|
||||
file.flush()
|
||||
os.fsync(file.fileno())
|
||||
temporary.replace(directory / name)
|
||||
|
||||
|
||||
def rotate():
|
||||
previous = STATE / "rotation"
|
||||
lb = STATE / "lb"
|
||||
target = previous / f"candidate-{time.time_ns()}"
|
||||
issue(str(target), "client", "lb-to-api", "clientAuth", ("DNS:lb-to-api",))
|
||||
openssl("verify", "-purpose", "sslclient", "-verify_hostname", "lb-to-api",
|
||||
"-CAfile", STATE / "trust/ca.crt", target / "client.crt")
|
||||
# Prove the intended identity is in SAN as well as the CN enforced by HAProxy.
|
||||
subprocess.run(["openssl", "x509", "-in", str(target / "client.crt"), "-noout",
|
||||
"-ext", "subjectAltName"], check=True, capture_output=True).stdout.index(b"DNS:lb-to-api")
|
||||
old = (lb / "client.pem").read_bytes()
|
||||
install(previous, "old.pem", old)
|
||||
install(lb, "client.pem", (target / "client.pem").read_bytes())
|
||||
try:
|
||||
reload("lb")
|
||||
probe("leaf-current")
|
||||
except (OSError, RuntimeError, subprocess.SubprocessError):
|
||||
install(lb, "client.pem", old)
|
||||
reload("lb")
|
||||
raise
|
||||
# From here the replacement stays installed, including on partial CRL rollout.
|
||||
openssl("ca", "-config", "ca.cnf", "-revoke", previous / "old.pem")
|
||||
crl()
|
||||
for service in ("api-a-tls", "api-b-tls"):
|
||||
reload(service)
|
||||
probe("leaf-current")
|
||||
probe("leaf-revoked")
|
||||
print("PASS: new LB leaf accepted; old leaf denied on both API TLS listeners")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
lock = STATE / "operator/rotate-leaf.lock"
|
||||
with os.fdopen(os.open(lock, os.O_CREAT | os.O_WRONLY | os.O_NOFOLLOW, 0o600), "w") as file:
|
||||
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
rotate()
|
||||
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError):
|
||||
raise SystemExit("Leaf rotation stopped; inspect active certificate and CRL before rerunning.") from None
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
# Output JSON reports. Exit nonzero on scanner findings or incomplete runs.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${SCAN_OUTPUT:?Set SCAN_OUTPUT to a report directory}"
|
||||
mkdir -p "$SCAN_OUTPUT"
|
||||
out=$(cd "$SCAN_OUTPUT" && pwd -P)
|
||||
mkdir -p "${SCAN_CACHE:-$out/cache}"
|
||||
cache=$(cd "${SCAN_CACHE:-$out/cache}" && pwd -P)
|
||||
audit=${PIP_AUDIT:-pip-audit}
|
||||
scanner=aquasec/trivy:0.66.0@sha256:086971aaf400beebd94e8300fd8ea623774419597169156cec56eec5b00dfb1e
|
||||
status=0
|
||||
./scripts/compose.sh --profile operator --profile bootstrap config --format json |
|
||||
python3 scripts/check-hardening.py > "$out/hardening.txt" || status=1
|
||||
# Audit the exact installed dependency set, including transitive dependencies.
|
||||
app_image=$(./scripts/compose.sh config --format json |
|
||||
python3 -c 'import json,sys; print(json.load(sys.stdin)["services"]["migrate"]["image"])')
|
||||
docker run --rm --network none --entrypoint python "$app_image" \
|
||||
-m pip freeze > "$out/runtime-pins.txt"
|
||||
"$audit" --no-deps --disable-pip -r "$out/runtime-pins.txt" -f json -o "$out/python.json" || status=1
|
||||
"$audit" -r requirements-dev.txt -f json -o "$out/dev-python.json" || status=1
|
||||
docker run --rm --mount "type=bind,src=$PWD,dst=/project,readonly" \
|
||||
--mount "type=bind,src=$cache,dst=/cache" --mount "type=bind,src=$out,dst=/results" \
|
||||
"$scanner" --cache-dir /cache \
|
||||
config --skip-files /project/Dockerfile.example --misconfig-scanners dockerfile --exit-code 1 --format json \
|
||||
--output /results/dockerfiles.json /project || status=1
|
||||
./scripts/compose.sh --profile operator --profile bootstrap config --images | sort -u > "$out/images.txt"
|
||||
while IFS= read -r image; do
|
||||
name=$(printf '%s' "$image" | tr '/:@' '___')
|
||||
archive=$(mktemp "$out/image.XXXXXX")
|
||||
if docker save -o "$archive" "$image"; then
|
||||
docker run --rm -e "TRIVY_SKIP_DB_UPDATE=${TRIVY_SKIP_DB_UPDATE:-false}" \
|
||||
--mount "type=bind,src=$cache,dst=/cache" --mount "type=bind,src=$out,dst=/results" \
|
||||
"$scanner" --cache-dir /cache \
|
||||
image --input "/results/${archive##*/}" --scanners vuln --image-config-scanners misconfig \
|
||||
--severity HIGH,CRITICAL --exit-code 1 --format json --output "/results/$name.json" || status=1
|
||||
else
|
||||
status=1
|
||||
fi
|
||||
if [ -f "$archive" ]; then unlink "$archive"; fi
|
||||
done < "$out/images.txt"
|
||||
exit "$status"
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${TARGET_INSTANCE_ID:?target API instance required}"
|
||||
for service in api-a api-b; do
|
||||
actual=$(./scripts/compose.sh exec -T "$service" python /app/uds_probe.py live) || continue
|
||||
if [ "$actual" = "$TARGET_INSTANCE_ID" ]; then
|
||||
if [ -n "${STOP_ONE_EVIDENCE:-}" ]; then
|
||||
printf '%s\n' "$service" > "$STOP_ONE_EVIDENCE"
|
||||
fi
|
||||
exec ./scripts/compose.sh stop -t 2 "$service"
|
||||
fi
|
||||
done
|
||||
exit 1
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inventory comparable pip-audit and Trivy reports without counting duplicate paths."""
|
||||
import argparse
|
||||
from collections import Counter, defaultdict
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def surface(package):
|
||||
if package in {"pillow", "starlette", "fastapi", "opentelemetry-api"}:
|
||||
return {
|
||||
"pillow": "JPEG/PNG exposed; other codecs restricted",
|
||||
"starlette": "ASGI/HTTP used; check the affected API",
|
||||
"fastapi": "ASGI/HTTP used; check the affected API",
|
||||
"opentelemetry-api": "trace context consumed from broker",
|
||||
}[package]
|
||||
if package in {"openssl", "libssl3", "libssl3t64", "libcrypto3", "gnutls", "libgnutls30"}:
|
||||
return "TLS library present; verify process, platform and affected feature"
|
||||
if package == "stdlib" or "/" in package:
|
||||
return "Embedded Go dependency; module presence alone does not show reachable code"
|
||||
return "Image package present; process and affected feature not established"
|
||||
|
||||
|
||||
def advisory_id(aliases):
|
||||
return min(aliases, key=lambda value: (not value.startswith("CVE-"), not value.startswith("GHSA-"), value))
|
||||
|
||||
|
||||
def load(directory):
|
||||
audit = json.loads((directory / "python.json").read_text())
|
||||
images = (directory / "images.txt").read_text().splitlines()
|
||||
rows = []
|
||||
aliases = {}
|
||||
python_entries = 0
|
||||
image_counts = Counter()
|
||||
for dependency in audit["dependencies"]:
|
||||
for item in dependency.get("vulns", []):
|
||||
python_entries += 1
|
||||
group = {item["id"], *item.get("aliases", [])}
|
||||
for key in group.copy():
|
||||
group.update(aliases.get(key, ()))
|
||||
for key in group:
|
||||
aliases[key] = group
|
||||
rows.append(("Python runtime", dependency["name"], dependency["version"], item["id"],
|
||||
"not supplied", ", ".join(item["fix_versions"]), "pip-audit"))
|
||||
for image in images:
|
||||
stem = image.translate(str.maketrans("/:@", "___"))
|
||||
report = json.loads((directory / f"{stem}.json").read_text())
|
||||
if not report.get("Metadata", {}).get("ImageID"):
|
||||
raise ValueError(f"Incomplete Trivy report for {image}")
|
||||
for result in report.get("Results", []):
|
||||
for item in result.get("Vulnerabilities", []):
|
||||
image_counts[item["Severity"]] += 1
|
||||
rows.append((image, item["PkgName"], item["InstalledVersion"], item["VulnerabilityID"],
|
||||
item["Severity"], item.get("FixedVersion", ""), result["Target"]))
|
||||
grouped = defaultdict(set)
|
||||
for image, package, version, identifier, severity, fix, target in rows:
|
||||
group = aliases.get(identifier, {identifier})
|
||||
normalized = advisory_id(group)
|
||||
grouped[image, package, version, normalized, severity, fix].add(target)
|
||||
return grouped, python_entries, image_counts, aliases
|
||||
|
||||
|
||||
def family(image):
|
||||
repository = image.split("@", 1)[0].rsplit(":", 1)[0]
|
||||
if repository.startswith("mtusi2026lab7-"):
|
||||
return "local-" + repository.rsplit("-", 1)[-1]
|
||||
return repository
|
||||
|
||||
|
||||
def print_table(rows):
|
||||
print("| Image | Package | Installed | ID | Severity | Vendor fix | Targets | Applicability review |")
|
||||
print("| --- | --- | --- | --- | --- | --- | --- | --- |")
|
||||
for (image, package, version, identifier, severity, fix), targets in sorted(rows.items()):
|
||||
fields = (image, package, version, identifier, severity, fix or "not reported",
|
||||
", ".join(sorted(targets)), surface(package))
|
||||
print("| " + " | ".join(value.replace("|", "\\|").replace("\n", " ") for value in fields) + " |")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("directory", type=Path)
|
||||
parser.add_argument("--baseline", type=Path)
|
||||
args = parser.parse_args()
|
||||
grouped, python_entries, image_counts, aliases = load(args.directory)
|
||||
identities = {row[3] for row in grouped if row[0] != "Python runtime"}
|
||||
py_identities = {row[3] for row in grouped if row[0] == "Python runtime"}
|
||||
print("# Inventory")
|
||||
print()
|
||||
print(f"Python input rows: {python_entries}, distinct advisory IDs after aliases: {len(py_identities)}.")
|
||||
print(f"Image input rows: {sum(image_counts.values())} ({dict(sorted(image_counts.items()))}), "
|
||||
f"distinct advisory IDs: {len(identities)}, CVE IDs: {sum(x.startswith('CVE-') for x in identities)}.")
|
||||
if args.baseline:
|
||||
old, _, _, old_aliases = load(args.baseline)
|
||||
|
||||
def coordinate(row):
|
||||
image, package, _, identifier, _, _ = row
|
||||
related = {identifier, *aliases.get(identifier, ()), *old_aliases.get(identifier, ())}
|
||||
return family(image), package, advisory_id(related)
|
||||
|
||||
old_coordinates = {coordinate(row) for row in old}
|
||||
new_coordinates = {coordinate(row) for row in grouped}
|
||||
print("\n## Baseline findings absent from the new image or runtime\n")
|
||||
print_table({row: targets for row, targets in old.items() if coordinate(row) not in new_coordinates})
|
||||
print("\n## Newly reported placements\n")
|
||||
print_table({row: targets for row, targets in grouped.items() if coordinate(row) not in old_coordinates})
|
||||
print("\n## Grouped findings\n")
|
||||
print_table(grouped)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,19 @@
|
||||
import http.client
|
||||
import socket
|
||||
import sys
|
||||
|
||||
|
||||
class LocalConnection(http.client.HTTPConnection):
|
||||
def connect(self):
|
||||
self.sock = socket.socket(socket.AF_UNIX)
|
||||
self.sock.settimeout(3)
|
||||
self.sock.connect("/run/api/api.sock")
|
||||
|
||||
|
||||
connection = LocalConnection("localhost")
|
||||
connection.request("GET", "/health/" + ("live" if len(sys.argv) > 1 else "ready"))
|
||||
response = connection.getresponse()
|
||||
if response.status != 200:
|
||||
raise SystemExit(1)
|
||||
if len(sys.argv) > 1:
|
||||
print(response.getheader("X-Instance-Id"))
|
||||
Reference in New Issue
Block a user