Implement TLS identities, scoped OpenBao access and worker security study
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit operator init/unseal/configuration. Never prints credential values."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PRIVATE = ROOT / "secrets"
|
||||
OPERATOR = ROOT / "operator-private"
|
||||
|
||||
|
||||
def call(path, data=None, *, method=None, token=True):
|
||||
ctx = ssl.create_default_context(cafile=str(PRIVATE / "ca.pem"))
|
||||
ctx.load_cert_chain(PRIVATE / "pki/operator/cert.pem", PRIVATE / "pki/operator/key.pem")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = (OPERATOR / "root-token").read_text().strip()
|
||||
req = urllib.request.Request(
|
||||
os.getenv("BAO_OPERATOR_ADDR", "https://localhost:18207") + "/v1/" + path,
|
||||
data=json.dumps(data).encode() if data is not None else None,
|
||||
headers=headers,
|
||||
method=method,
|
||||
)
|
||||
with urllib.request.urlopen(req, context=ctx, timeout=5) as response:
|
||||
raw = response.read()
|
||||
return json.loads(raw) if raw else {}
|
||||
|
||||
|
||||
def unseal():
|
||||
for share in json.loads((OPERATOR / "unseal-shares.json").read_text())[:2]:
|
||||
result = call("sys/unseal", {"key": share}, token=False)
|
||||
if result["sealed"]:
|
||||
raise RuntimeError("OpenBao remained sealed")
|
||||
|
||||
|
||||
def configure():
|
||||
try:
|
||||
call("sys/mounts/secret", {"type": "kv", "options": {"version": "2"}})
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code != 400:
|
||||
raise
|
||||
try:
|
||||
call("sys/auth/cert", {"type": "cert"})
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code != 400:
|
||||
raise
|
||||
seed = json.loads((PRIVATE / "bao_seed.json").read_text())
|
||||
for role, values in seed.items():
|
||||
policy = (
|
||||
'path "secret/data/services/'
|
||||
+ role
|
||||
+ '" { capabilities = ["read"] }\npath "auth/token/lookup-self" { capabilities = ["read"] }\npath "auth/token/renew-self" { capabilities = ["update"] }\n'
|
||||
)
|
||||
call("sys/policies/acl/" + role, {"policy": policy}, method="PUT")
|
||||
call(
|
||||
"auth/cert/certs/" + role,
|
||||
{
|
||||
"display_name": role,
|
||||
"certificate": (PRIVATE / "pki" / role / "cert.pem").read_text(),
|
||||
"allowed_common_names": role,
|
||||
"token_policies": [role],
|
||||
"token_no_default_policy": True,
|
||||
"token_ttl": "30s",
|
||||
"token_max_ttl": "60s",
|
||||
},
|
||||
)
|
||||
call("secret/data/services/" + role, {"data": values})
|
||||
try:
|
||||
call("sys/audit/file", {"type": "file", "options": {"file_path": "/bao/data/audit.jsonl"}})
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code != 400:
|
||||
raise
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=["init", "unseal", "configure", "seal"])
|
||||
args = parser.parse_args()
|
||||
os.umask(0o077)
|
||||
if args.action == "init":
|
||||
for _attempt in range(30):
|
||||
try:
|
||||
status = call("sys/init", token=False)
|
||||
break
|
||||
except (OSError, urllib.error.URLError):
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise RuntimeError("OpenBao TLS endpoint unavailable")
|
||||
if not status["initialized"]:
|
||||
result = call(
|
||||
"sys/init", {"secret_shares": 3, "secret_threshold": 2}, method="PUT", token=False
|
||||
)
|
||||
(OPERATOR / "root-token").write_text(result["root_token"])
|
||||
(OPERATOR / "unseal-shares.json").write_text(json.dumps(result["keys_base64"]))
|
||||
(OPERATOR / "root-token").chmod(0o600)
|
||||
(OPERATOR / "unseal-shares.json").chmod(0o600)
|
||||
unseal()
|
||||
configure()
|
||||
elif args.action == "unseal":
|
||||
unseal()
|
||||
elif args.action == "configure":
|
||||
configure()
|
||||
else:
|
||||
call("sys/seal", {}, method="PUT")
|
||||
print("OpenBao operator action complete; credential values were not printed.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,340 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Idempotent local PKI/secrets bootstrap. Operator material never enters containers."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PRIVATE = ROOT / "secrets"
|
||||
OPERATOR = ROOT / "operator-private"
|
||||
ROLES = (
|
||||
"api",
|
||||
"worker",
|
||||
"dispatcher",
|
||||
"lb",
|
||||
"postgres",
|
||||
"storage",
|
||||
"broker",
|
||||
"cache",
|
||||
"collector",
|
||||
"prometheus",
|
||||
"loki",
|
||||
"tempo",
|
||||
"grafana",
|
||||
"openbao",
|
||||
"operator",
|
||||
)
|
||||
|
||||
|
||||
def write(path, text, mode=0o644):
|
||||
if not path.exists():
|
||||
path.write_text(text)
|
||||
path.chmod(mode)
|
||||
|
||||
|
||||
def run(*args):
|
||||
subprocess.run(
|
||||
["openssl", *args], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
|
||||
)
|
||||
|
||||
|
||||
def certificate(name, replace=False):
|
||||
dest = PRIVATE / "pki" / name
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
dest.chmod(0o755)
|
||||
if (dest / "cert.pem").exists() and not replace:
|
||||
valid = subprocess.run(
|
||||
["openssl", "x509", "-in", str(dest / "cert.pem"), "-checkend", "3600", "-noout"],
|
||||
capture_output=True,
|
||||
)
|
||||
if valid.returncode == 0:
|
||||
return
|
||||
key, csr = dest / "key.pem", OPERATOR / (name + ".csr")
|
||||
run("genpkey", "-algorithm", "EC", "-pkeyopt", "ec_paramgen_curve:P-256", "-out", str(key))
|
||||
run("req", "-new", "-key", str(key), "-subj", f"/CN={name}", "-out", str(csr))
|
||||
ext = OPERATOR / (name + ".ext")
|
||||
names = f"DNS:{name}"
|
||||
if name in {
|
||||
"lb",
|
||||
"api",
|
||||
"postgres",
|
||||
"broker",
|
||||
"cache",
|
||||
"collector",
|
||||
"prometheus",
|
||||
"loki",
|
||||
"tempo",
|
||||
"openbao",
|
||||
"grafana",
|
||||
"storage",
|
||||
}:
|
||||
names += ",DNS:localhost,IP:127.0.0.1"
|
||||
ext.write_text(
|
||||
f"subjectAltName={names}\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth,clientAuth\n"
|
||||
)
|
||||
run(
|
||||
"x509",
|
||||
"-req",
|
||||
"-in",
|
||||
str(csr),
|
||||
"-CA",
|
||||
str(OPERATOR / "ca.pem"),
|
||||
"-CAkey",
|
||||
str(OPERATOR / "ca-key.pem"),
|
||||
"-set_serial",
|
||||
str(secrets.randbits(127) or 1),
|
||||
"-days",
|
||||
"2",
|
||||
"-extfile",
|
||||
str(ext),
|
||||
"-out",
|
||||
str(dest / "cert.pem"),
|
||||
)
|
||||
key.chmod(0o644)
|
||||
(dest / "combined.pem").write_text((dest / "cert.pem").read_text() + key.read_text())
|
||||
(dest / "combined.pem").chmod(0o644)
|
||||
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
for folder in (PRIVATE, OPERATOR):
|
||||
folder.mkdir(exist_ok=True)
|
||||
folder.chmod(0o700)
|
||||
if not (OPERATOR / "ca-key.pem").exists():
|
||||
run(
|
||||
"genpkey",
|
||||
"-algorithm",
|
||||
"EC",
|
||||
"-pkeyopt",
|
||||
"ec_paramgen_curve:P-256",
|
||||
"-out",
|
||||
str(OPERATOR / "ca-key.pem"),
|
||||
)
|
||||
run(
|
||||
"req",
|
||||
"-x509",
|
||||
"-new",
|
||||
"-key",
|
||||
str(OPERATOR / "ca-key.pem"),
|
||||
"-subj",
|
||||
"/CN=MTUSI Lab7 local CA",
|
||||
"-days",
|
||||
"365",
|
||||
"-addext",
|
||||
"basicConstraints=critical,CA:TRUE",
|
||||
"-addext",
|
||||
"keyUsage=critical,keyCertSign,cRLSign",
|
||||
"-out",
|
||||
str(OPERATOR / "ca.pem"),
|
||||
)
|
||||
(PRIVATE / "ca.pem").write_text((OPERATOR / "ca.pem").read_text())
|
||||
(PRIVATE / "ca.pem").chmod(0o644)
|
||||
(PRIVATE / "pki").mkdir(exist_ok=True)
|
||||
(PRIVATE / "pki").chmod(0o755)
|
||||
for name in ROLES:
|
||||
certificate(name)
|
||||
write(PRIVATE / "revoked.json", "[]")
|
||||
for name in (
|
||||
"postgres_password",
|
||||
"api_db_password",
|
||||
"worker_db_password",
|
||||
"dispatcher_db_password",
|
||||
"cache_password",
|
||||
"cache_worker_password",
|
||||
"cache_dispatcher_password",
|
||||
"broker_worker_password",
|
||||
"broker_dispatcher_password",
|
||||
"broker_admin_password",
|
||||
"grafana_password",
|
||||
):
|
||||
write(PRIVATE / name, secrets.token_urlsafe(32))
|
||||
for role in ("api", "worker", "admin", "study_wide"):
|
||||
write(PRIVATE / (role + "_s3_access"), role + "-" + secrets.token_hex(12))
|
||||
write(PRIVATE / (role + "_s3_secret"), secrets.token_urlsafe(32))
|
||||
|
||||
def value(name):
|
||||
return (PRIVATE / name).read_text().strip()
|
||||
|
||||
identities = []
|
||||
for role in ("api", "worker", "admin", "study_wide"):
|
||||
identities.append(
|
||||
{
|
||||
"name": role,
|
||||
"credentials": [
|
||||
{
|
||||
"accessKey": value(role + "_s3_access"),
|
||||
"secretKey": value(role + "_s3_secret"),
|
||||
}
|
||||
],
|
||||
"actions": ["Admin", "Read", "Write", "List"]
|
||||
if role == "admin"
|
||||
else (["Read:security-study", "Write:security-study", "List:security-study"] if role == "study_wide" else ["Read:messenger", "Write:messenger", "List:messenger"]),
|
||||
}
|
||||
)
|
||||
(PRIVATE / "s3_config").write_text(json.dumps({"identities": identities}))
|
||||
(PRIVATE / "s3_config").chmod(0o644)
|
||||
write(
|
||||
PRIVATE / "cache_config",
|
||||
'bind 127.0.0.1\nport 6379\nprotected-mode yes\nsave ""\nmaxmemory 64mb\nmaxmemory-policy allkeys-lru\nuser default off\nuser api on >'
|
||||
+ value("cache_password")
|
||||
+ " ~user:v1:* +get +setex +ping +hello +client|setinfo\nuser worker on >"
|
||||
+ value("cache_worker_password")
|
||||
+ " +ping +hello +client|setinfo\nuser dispatcher on >"
|
||||
+ value("cache_dispatcher_password")
|
||||
+ " +ping +hello +client|setinfo\n",
|
||||
)
|
||||
write(
|
||||
PRIVATE / "broker_config",
|
||||
'bind 127.0.0.1\nport 6379\nprotected-mode yes\nappendonly yes\nappendfsync always\nsave ""\ndir /data\nmaxmemory 128mb\nmaxmemory-policy noeviction\nuser default off\nuser operator on >'
|
||||
+ value("broker_admin_password")
|
||||
+ " ~* &* +@all\nuser dispatcher on >"
|
||||
+ value("broker_dispatcher_password")
|
||||
+ " ~attachment-jobs:v1 +xadd +ping +hello +client|setinfo\nuser worker on >"
|
||||
+ value("broker_worker_password")
|
||||
+ " ~attachment-jobs:v1 +xgroup|create +xreadgroup +xautoclaim +xack +xdel +ping +hello +client|setinfo\n",
|
||||
)
|
||||
pg = "postgresql://{role}:{password}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/tls/ca.pem"
|
||||
values = {}
|
||||
for role in ("api", "worker", "dispatcher"):
|
||||
values[role] = {
|
||||
"DATABASE_URL": pg.format(role=role, password=value(role + "_db_password")),
|
||||
"CACHE_URL": "rediss://"
|
||||
+ role
|
||||
+ ":"
|
||||
+ value("cache_password" if role == "api" else "cache_" + role + "_password")
|
||||
+ "@cache:6380/0?ssl_cert_reqs=required&ssl_ca_certs=/run/tls/ca.pem&ssl_certfile=/run/tls/identity/cert.pem&ssl_keyfile=/run/tls/identity/key.pem",
|
||||
}
|
||||
if role in {"worker", "dispatcher"}:
|
||||
values[role]["BROKER_URL"] = (
|
||||
"rediss://"
|
||||
+ role
|
||||
+ ":"
|
||||
+ value("broker_" + role + "_password")
|
||||
+ "@broker:6380/0?ssl_cert_reqs=required&ssl_ca_certs=/run/tls/ca.pem&ssl_certfile=/run/tls/identity/cert.pem&ssl_keyfile=/run/tls/identity/key.pem"
|
||||
)
|
||||
if role in {"api", "worker"}:
|
||||
values[role].update(
|
||||
S3_ACCESS_KEY=value(role + "_s3_access"), S3_SECRET_KEY=value(role + "_s3_secret")
|
||||
)
|
||||
write(PRIVATE / "bao_seed.json", json.dumps(values))
|
||||
write(
|
||||
PRIVATE / "admin_database_url",
|
||||
pg.format(role="messenger", password=value("postgres_password")),
|
||||
)
|
||||
write(PRIVATE / "admin_s3_access_key", value("admin_s3_access"))
|
||||
write(PRIVATE / "admin_s3_secret_key", value("admin_s3_secret"))
|
||||
write(
|
||||
PRIVATE / "db_roles.sql",
|
||||
"\n".join(
|
||||
f"CREATE ROLE {role} LOGIN PASSWORD '{value(role + '_db_password')}';"
|
||||
for role in ("api", "worker", "dispatcher")
|
||||
),
|
||||
)
|
||||
gateways = {
|
||||
"api": {"port": 9443, "upstream": 8080, "allowed": ["lb"]},
|
||||
"broker": {
|
||||
"port": 6380,
|
||||
"upstream": 6379,
|
||||
"allowed": ["worker", "dispatcher", "operator"],
|
||||
},
|
||||
"cache": {
|
||||
"port": 6380,
|
||||
"upstream": 6379,
|
||||
"allowed": ["api", "worker", "dispatcher", "operator"],
|
||||
},
|
||||
"storage": {
|
||||
"port": 8443,
|
||||
"upstream": 8333,
|
||||
"allowed": ["api", "worker", "operator"],
|
||||
"http": True,
|
||||
"s3": True,
|
||||
},
|
||||
"collector": [
|
||||
{
|
||||
"port": 4318,
|
||||
"upstream": 14318,
|
||||
"allowed": ["api", "worker", "dispatcher", "operator"],
|
||||
},
|
||||
{"port": 9464, "upstream": 19464, "allowed": ["prometheus", "operator"]},
|
||||
{"port": 8888, "upstream": 18888, "allowed": ["prometheus", "operator"]},
|
||||
],
|
||||
"prometheus": {
|
||||
"http": True,
|
||||
"backend": "prometheus",
|
||||
"port": 9443,
|
||||
"upstream": 9090,
|
||||
"allowed": ["grafana", "operator"],
|
||||
},
|
||||
"loki": {
|
||||
"http": True,
|
||||
"backend": "loki",
|
||||
"port": 9443,
|
||||
"upstream": 3100,
|
||||
"allowed": ["collector", "grafana", "operator"],
|
||||
},
|
||||
"tempo": [
|
||||
{
|
||||
"port": 9443,
|
||||
"upstream": 3200,
|
||||
"allowed": ["grafana", "operator"],
|
||||
"http": True,
|
||||
"backend": "tempo",
|
||||
},
|
||||
{"port": 44318, "upstream": 4318, "allowed": ["collector", "operator"]},
|
||||
],
|
||||
}
|
||||
for role, configs in gateways.items():
|
||||
for item in configs if isinstance(configs, list) else [configs]:
|
||||
item.update(
|
||||
cert="/run/tls/identity/cert.pem",
|
||||
key="/run/tls/identity/key.pem",
|
||||
ca="/run/tls/ca.pem",
|
||||
)
|
||||
(PRIVATE / (role + "_gateway.json")).write_text(json.dumps(configs))
|
||||
(PRIVATE / (role + "_gateway.json")).chmod(0o644)
|
||||
provisioning = PRIVATE / "grafana-provisioning" / "datasources"
|
||||
provisioning.mkdir(parents=True, exist_ok=True)
|
||||
provisioning.parent.chmod(0o755)
|
||||
provisioning.chmod(0o755)
|
||||
datasources = []
|
||||
for name in ("prometheus", "loki", "tempo"):
|
||||
item = {
|
||||
"name": name.title(),
|
||||
"uid": name,
|
||||
"type": name,
|
||||
"access": "proxy",
|
||||
"url": f"https://{name}:9443",
|
||||
"editable": False,
|
||||
"jsonData": {"tlsAuth": True, "tlsAuthWithCACert": True, "serverName": name},
|
||||
"secureJsonData": {
|
||||
"tlsCACert": (PRIVATE / "ca.pem").read_text(),
|
||||
"tlsClientCert": (PRIVATE / "pki/grafana/cert.pem").read_text(),
|
||||
"tlsClientKey": (PRIVATE / "pki/grafana/key.pem").read_text(),
|
||||
},
|
||||
}
|
||||
if name == "prometheus":
|
||||
item["isDefault"] = True
|
||||
if name == "loki":
|
||||
item["jsonData"]["derivedFields"] = [
|
||||
{
|
||||
"datasourceUid": "tempo",
|
||||
"matcherRegex": '"trace_id": "([a-f0-9]{32})"',
|
||||
"name": "TraceID",
|
||||
"url": "$${__value.raw}",
|
||||
}
|
||||
]
|
||||
datasources.append(item)
|
||||
(provisioning / "datasources.yaml").write_text(
|
||||
json.dumps({"apiVersion": 1, "datasources": datasources})
|
||||
)
|
||||
(provisioning / "datasources.yaml").chmod(0o644)
|
||||
if not (ROOT / ".env").exists():
|
||||
(ROOT / ".env").write_text("PUBLIC_PORT=8447\nSESSION_TTL_SECONDS=3600\n")
|
||||
print("Local PKI and scoped credential material ready; operator CA stays outside containers.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
# Namespace-sharing gateways are stopped before their backing services restart.
|
||||
# Unseal is an explicit operator action; shares never enter application containers.
|
||||
docker compose stop
|
||||
docker compose up -d postgres openbao cache cache-tls broker broker-tls storage s3 storage-tls
|
||||
python3 scripts/bao_operator.py unseal
|
||||
docker compose up -d --wait
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator-driven worker revoke/cert renewal and DB credential rotation, no rebuild."""
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import secrets
|
||||
import ssl
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
spec = importlib.util.spec_from_file_location("bootstrap", ROOT / "scripts/bootstrap.py")
|
||||
bootstrap = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(bootstrap)
|
||||
old = ROOT / "secrets/pki/worker"
|
||||
cert = ssl._ssl._test_decode_cert(str(old / "cert.pem"))
|
||||
snapshot = ROOT / "operator-private/revoked-worker"
|
||||
snapshot.mkdir(exist_ok=True, mode=0o700)
|
||||
for name in ("cert.pem", "key.pem"):
|
||||
(snapshot / name).write_bytes((old / name).read_bytes())
|
||||
(snapshot / name).chmod(0o600)
|
||||
seed_before = json.loads((ROOT / "secrets/bao_seed.json").read_text())
|
||||
(snapshot / "material.json").write_text(json.dumps(seed_before["worker"]))
|
||||
(snapshot / "material.json").chmod(0o644)
|
||||
# The containing operator-private directory stays 0700 on the host. This
|
||||
# disposable old-material mount is used only by the explicit negative probe.
|
||||
for name in ("cert.pem", "key.pem"):
|
||||
(snapshot / name).chmod(0o644)
|
||||
snapshot.chmod(0o755)
|
||||
revoked = ROOT / "secrets/revoked.json"
|
||||
serials = json.loads(revoked.read_text())
|
||||
serials.append(cert["serialNumber"].lstrip("0").lower())
|
||||
revoked.write_text(json.dumps(sorted(set(serials))))
|
||||
subprocess.run(
|
||||
["docker", "compose", "stop", "worker"], cwd=ROOT, check=True, capture_output=True
|
||||
)
|
||||
bootstrap.certificate("worker", replace=True)
|
||||
password = secrets.token_urlsafe(32)
|
||||
# psql receives SQL through stdin, never a process argument/output containing
|
||||
# credentials. The operator/admin role is confined to this explicit command.
|
||||
sql = f"ALTER ROLE worker PASSWORD '{password}'; SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='worker' AND pid<>pg_backend_pid();"
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-U",
|
||||
"messenger",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
],
|
||||
cwd=ROOT,
|
||||
input=sql,
|
||||
text=True,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
path = ROOT / "secrets/worker_db_password"
|
||||
path.write_text(password)
|
||||
seed_path = ROOT / "secrets/bao_seed.json"
|
||||
seed = json.loads(seed_path.read_text())
|
||||
seed["worker"]["DATABASE_URL"] = (
|
||||
"postgresql://worker:"
|
||||
+ password
|
||||
+ "@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/tls/ca.pem"
|
||||
)
|
||||
seed_path.write_text(json.dumps(seed))
|
||||
subprocess.run(
|
||||
["python3", "scripts/bao_operator.py", "configure"],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
subprocess.run(
|
||||
["docker", "compose", "start", "worker"], cwd=ROOT, check=True, capture_output=True
|
||||
)
|
||||
print(
|
||||
"Worker identity revoked and replaced; database credential rotated; worker resumed without image rebuild."
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit operator probes; test identities never become application mounts."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def run(args, *, output=None):
|
||||
result = subprocess.run(args, cwd=ROOT, check=True, capture_output=True, text=True)
|
||||
if output:
|
||||
(ROOT / "evidence" / output).write_text(result.stdout)
|
||||
else:
|
||||
print(result.stdout, end="")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def foreign_certificate():
|
||||
path = ROOT / "secrets/pki/foreign"
|
||||
path.mkdir(exist_ok=True, mode=0o755)
|
||||
run(
|
||||
[
|
||||
"openssl",
|
||||
"req",
|
||||
"-x509",
|
||||
"-newkey",
|
||||
"ec",
|
||||
"-pkeyopt",
|
||||
"ec_paramgen_curve:P-256",
|
||||
"-nodes",
|
||||
"-keyout",
|
||||
str(path / "key.pem"),
|
||||
"-out",
|
||||
str(path / "cert.pem"),
|
||||
"-days",
|
||||
"1",
|
||||
"-subj",
|
||||
"/CN=foreign",
|
||||
"-addext",
|
||||
"subjectAltName=DNS:lb,DNS:worker,DNS:api",
|
||||
]
|
||||
)
|
||||
for item in path.iterdir():
|
||||
item.chmod(0o644)
|
||||
|
||||
|
||||
def audit_container(module, *, material=False):
|
||||
command = [
|
||||
"docker",
|
||||
"compose",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-e",
|
||||
"BAO_ROLE=",
|
||||
"-e",
|
||||
"OTEL_ENABLED=0",
|
||||
"-v",
|
||||
str(ROOT / "secrets/pki") + ":/run/audit-identities:ro",
|
||||
]
|
||||
if material:
|
||||
# Only selected synthetic/admin S3 credential files, never Bao root/shares.
|
||||
path = ROOT / "operator-private/s3-study-material"
|
||||
path.mkdir(exist_ok=True, mode=0o755)
|
||||
for name in (
|
||||
"admin_s3_access",
|
||||
"admin_s3_secret",
|
||||
"study_wide_s3_access",
|
||||
"study_wide_s3_secret",
|
||||
"worker_s3_access",
|
||||
"worker_s3_secret",
|
||||
):
|
||||
(path / name).write_bytes((ROOT / "secrets" / name).read_bytes())
|
||||
(path / name).chmod(0o644)
|
||||
command += ["-v", str(path) + ":/run/audit-material:ro"]
|
||||
command += ["api", "python", "-m", module]
|
||||
return command
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("probe", choices=["transport", "policies", "baseline", "revoked", "kdf"])
|
||||
args = parser.parse_args()
|
||||
os.umask(0o077)
|
||||
if args.probe == "transport":
|
||||
foreign_certificate()
|
||||
run(audit_container("messenger.transport_probe"), output="transport-matrix.json")
|
||||
elif args.probe == "policies":
|
||||
run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"worker",
|
||||
"python",
|
||||
"-m",
|
||||
"messenger.security_probe",
|
||||
],
|
||||
output="worker-policy-final.json",
|
||||
)
|
||||
elif args.probe == "baseline":
|
||||
run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"migrate",
|
||||
"python",
|
||||
"-m",
|
||||
"messenger.baseline_db_probe",
|
||||
],
|
||||
output="baseline-db.json",
|
||||
)
|
||||
run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"broker",
|
||||
"valkey-server",
|
||||
"--port",
|
||||
"6378",
|
||||
"--bind",
|
||||
"127.0.0.1",
|
||||
"--save",
|
||||
"",
|
||||
"--appendonly",
|
||||
"no",
|
||||
"--daemonize",
|
||||
"yes",
|
||||
"--pidfile",
|
||||
"/tmp/security-study.pid",
|
||||
"--logfile",
|
||||
"/tmp/security-study.log",
|
||||
]
|
||||
)
|
||||
broker = run(["docker", "compose", "ps", "-q", "broker"]).strip()
|
||||
config = json.loads(
|
||||
subprocess.check_output(
|
||||
["docker", "compose", "config", "--format", "json"], cwd=ROOT, text=True
|
||||
)
|
||||
)
|
||||
app_image = config["services"]["api"]["image"]
|
||||
run(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"--network",
|
||||
"container:" + broker,
|
||||
"--read-only",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--security-opt",
|
||||
"no-new-privileges",
|
||||
"--memory",
|
||||
"128m",
|
||||
"--cpus",
|
||||
"0.5",
|
||||
app_image,
|
||||
"python",
|
||||
"-m",
|
||||
"messenger.baseline_queue_probe",
|
||||
],
|
||||
output="baseline-queue.json",
|
||||
)
|
||||
run(
|
||||
audit_container("messenger.baseline_s3_probe", material=True), output="baseline-s3.json"
|
||||
)
|
||||
elif args.probe == "revoked":
|
||||
run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-v",
|
||||
str(ROOT / "operator-private/revoked-worker") + ":/run/old-worker:ro",
|
||||
"worker",
|
||||
"python",
|
||||
"-m",
|
||||
"messenger.revoked_probe",
|
||||
],
|
||||
output="revoked-identity.json",
|
||||
)
|
||||
else:
|
||||
run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-e",
|
||||
"OTEL_ENABLED=0",
|
||||
"worker",
|
||||
"python",
|
||||
"-m",
|
||||
"messenger.kdf_probe",
|
||||
],
|
||||
output="argon2-budget.json",
|
||||
)
|
||||
print(json.dumps({"probe": args.probe, "passed": True}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
python3 scripts/stop_one.py
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Map a process alias to its real container, then leave exactly it stopped."""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
wanted = os.environ["TARGET_INSTANCE_ID"]
|
||||
ids = subprocess.check_output(["docker", "compose", "ps", "-q", "api"], text=True).split()
|
||||
for cid in ids:
|
||||
result = subprocess.run(
|
||||
["docker", "exec", cid, "python", "-c",
|
||||
"import urllib.request; r=urllib.request.urlopen('http://127.0.0.1:8080/health/live'); print(r.headers['X-Instance-Id'])"],
|
||||
text=True, capture_output=True, check=False,
|
||||
)
|
||||
if result.returncode == 0 and result.stdout.strip() == wanted:
|
||||
subprocess.run(["docker", "stop", "--time", "8", cid], check=True, stdout=subprocess.DEVNULL)
|
||||
receipt = {"stopped_container": cid, "instance_id": wanted}
|
||||
Path("evidence/last-stopped.json").write_text(json.dumps(receipt))
|
||||
print(json.dumps(receipt))
|
||||
break
|
||||
else:
|
||||
raise SystemExit("Target instance not found among this project's API containers")
|
||||
Reference in New Issue
Block a user