forked from mtusi2026/mtusi2026lab7
Щербацевич-БПИ2302-на 3
This commit is contained in:
@@ -0,0 +1,332 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create local CA, service certificates and passwords. Nothing here is committed."""
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SECRETS = ROOT / "secrets"
|
||||
CERTS = SECRETS / "certs"
|
||||
PASSWORDS = SECRETS / "passwords"
|
||||
OPENSSL_IMAGE = "alpine/openssl:3.3.3"
|
||||
HTTPD_IMAGE = "httpd:2.4.62-alpine"
|
||||
|
||||
SERVICES = [
|
||||
("api", "api", ["api", "localhost"], ["127.0.0.1"], "serverAuth"),
|
||||
("postgres", "postgres", ["postgres", "localhost"], ["127.0.0.1"], "serverAuth"),
|
||||
("redis", "redis", ["redis", "localhost"], ["127.0.0.1"], "serverAuth"),
|
||||
("minio", "minio", ["minio", "localhost"], ["127.0.0.1"], "serverAuth"),
|
||||
("rabbitmq", "rabbitmq", ["rabbitmq", "localhost"], ["127.0.0.1"], "serverAuth"),
|
||||
("openbao", "openbao", ["openbao", "localhost"], ["127.0.0.1"], "serverAuth"),
|
||||
("otel", "otel-collector", ["otel-collector", "localhost"], ["127.0.0.1"], "serverAuth, clientAuth"),
|
||||
("grafana", "grafana", ["grafana", "localhost"], ["127.0.0.1"], "serverAuth, clientAuth"),
|
||||
("prometheus", "prometheus", ["prometheus", "localhost"], ["127.0.0.1"], "serverAuth, clientAuth"),
|
||||
(
|
||||
"telemetry",
|
||||
"telemetry.lab.internal",
|
||||
["telemetry.lab.internal", "tempo.lab.internal", "loki.lab.internal"],
|
||||
[],
|
||||
"serverAuth",
|
||||
),
|
||||
("lb-server", "localhost", ["localhost"], ["127.0.0.1"], "serverAuth"),
|
||||
("lb-client", "lb.lab.internal", ["lb.lab.internal"], [], "clientAuth"),
|
||||
("intruder", "intruder.lab.internal", ["intruder.lab.internal"], [], "clientAuth"),
|
||||
]
|
||||
|
||||
|
||||
def docker(*args):
|
||||
subprocess.check_call(["docker", *args])
|
||||
|
||||
|
||||
def password(name: str) -> str:
|
||||
path = PASSWORDS / name
|
||||
if path.is_file() and path.read_text(encoding="utf-8").strip():
|
||||
return path.read_text(encoding="utf-8").strip()
|
||||
import secrets
|
||||
|
||||
value = secrets.token_hex(24)
|
||||
path.write_text(value + "\n", encoding="utf-8", newline="\n")
|
||||
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
|
||||
return value
|
||||
|
||||
|
||||
def write(path: Path, text: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8", newline="\n")
|
||||
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
|
||||
|
||||
|
||||
def place(src: Path, dst: Path) -> None:
|
||||
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(src, dst)
|
||||
os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
|
||||
|
||||
|
||||
def cnf(cn: str, dns_names: list[str], ips: list[str], eku: str) -> str:
|
||||
san = []
|
||||
for index, name in enumerate(dns_names, start=1):
|
||||
san.append("DNS.%s = %s" % (index, name))
|
||||
for index, ip in enumerate(ips, start=1):
|
||||
san.append("IP.%s = %s" % (index, ip))
|
||||
return (
|
||||
"[req]\n"
|
||||
"distinguished_name = dn\n"
|
||||
"prompt = no\n"
|
||||
"[dn]\n"
|
||||
"CN = %s\n"
|
||||
"[ext]\n"
|
||||
"subjectAltName = @san\n"
|
||||
"keyUsage = digitalSignature, keyEncipherment\n"
|
||||
"extendedKeyUsage = %s\n"
|
||||
"basicConstraints = CA:FALSE\n"
|
||||
"[san]\n%s\n" % (cn, eku, "\n".join(san))
|
||||
)
|
||||
|
||||
|
||||
def issue_certificates() -> None:
|
||||
if (CERTS / "ca.crt").is_file() and (CERTS / "api.crt").is_file() and (CERTS / "lb-client.crt").is_file():
|
||||
print("certificates already exist")
|
||||
return
|
||||
CERTS.mkdir(parents=True, exist_ok=True)
|
||||
script = ["#!/bin/sh", "set -eu", "cd /work"]
|
||||
script.append("openssl genrsa -out ca.key 4096")
|
||||
script.append('openssl req -x509 -new -nodes -key ca.key -sha256 -days 825 -out ca.crt -subj "/CN=lab7-local-ca"')
|
||||
script.append("openssl genrsa -out foreign-ca.key 4096")
|
||||
script.append(
|
||||
'openssl req -x509 -new -nodes -key foreign-ca.key -sha256 -days 825 -out foreign-ca.crt -subj "/CN=lab7-foreign-ca"'
|
||||
)
|
||||
script.append("issue() {")
|
||||
script.append(' name="$1"; cnf="$2"; ca_cert="$3"; ca_key="$4"')
|
||||
script.append(' openssl genrsa -out "$name.key" 2048')
|
||||
script.append(' openssl req -new -key "$name.key" -out "$name.csr" -config "$cnf"')
|
||||
script.append(
|
||||
' openssl x509 -req -in "$name.csr" -CA "$ca_cert" -CAkey "$ca_key" -CAcreateserial -out "$name.crt" -days 825 -sha256 -extfile "$cnf" -extensions ext'
|
||||
)
|
||||
script.append(' rm -f "$name.csr"')
|
||||
script.append("}")
|
||||
for name, cn, dns_names, ips, eku in SERVICES:
|
||||
write(CERTS / ("%s.cnf" % name), cnf(cn, dns_names, ips, eku))
|
||||
script.append('issue %s %s.cnf ca.crt ca.key' % (name, name))
|
||||
write(CERTS / "foreign-client.cnf", cnf("lb.lab.internal", ["lb.lab.internal"], [], "clientAuth"))
|
||||
script.append("issue foreign-client foreign-client.cnf foreign-ca.crt foreign-ca.key")
|
||||
write(CERTS / "issue.sh", "\n".join(script) + "\n")
|
||||
docker(
|
||||
"run",
|
||||
"--rm",
|
||||
"--entrypoint",
|
||||
"/bin/sh",
|
||||
"-v",
|
||||
"%s:/work" % CERTS,
|
||||
"-w",
|
||||
"/work",
|
||||
OPENSSL_IMAGE,
|
||||
"/work/issue.sh",
|
||||
)
|
||||
print("certificates created")
|
||||
|
||||
|
||||
def pem_bundle(cert: Path, key: Path, dest: Path) -> None:
|
||||
write(dest, cert.read_text(encoding="utf-8").strip() + "\n" + key.read_text(encoding="utf-8").strip() + "\n")
|
||||
|
||||
|
||||
def yaml_pem(value: str, indent: int) -> str:
|
||||
pad = " " * indent
|
||||
return "\n".join(pad + line for line in value.strip().splitlines())
|
||||
|
||||
|
||||
def grafana_datasources(prometheus_password: str) -> None:
|
||||
ca = (CERTS / "ca.crt").read_text(encoding="utf-8").strip()
|
||||
cert = (CERTS / "grafana.crt").read_text(encoding="utf-8").strip()
|
||||
key = (CERTS / "grafana.key").read_text(encoding="utf-8").strip()
|
||||
text = """apiVersion: 1
|
||||
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: https://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
basicAuth: true
|
||||
basicAuthUser: grafana
|
||||
jsonData:
|
||||
tlsAuthWithCACert: true
|
||||
serverName: prometheus
|
||||
timeInterval: 10s
|
||||
secureJsonData:
|
||||
basicAuthPassword: "%s"
|
||||
tlsCACert: |
|
||||
%s
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: https://loki.lab.internal:3100
|
||||
editable: false
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
serverName: loki.lab.internal
|
||||
derivedFields:
|
||||
- name: trace_id
|
||||
matcherRegex: "\\"trace_id\\":\\"([0-9a-f]+)\\""
|
||||
url: "$${__value.raw}"
|
||||
datasourceUid: tempo
|
||||
urlDisplayLabel: Открыть трассу
|
||||
secureJsonData:
|
||||
tlsCACert: |
|
||||
%s
|
||||
tlsClientCert: |
|
||||
%s
|
||||
tlsClientKey: |
|
||||
%s
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: https://tempo.lab.internal:3200
|
||||
editable: false
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
serverName: tempo.lab.internal
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
filterByTraceID: false
|
||||
customQuery: true
|
||||
query: '{service_name=~"messenger-.+"} | trace_id="$${__trace.traceId}"'
|
||||
tracesToMetrics:
|
||||
datasourceUid: prometheus
|
||||
serviceMap:
|
||||
datasourceUid: prometheus
|
||||
nodeGraph:
|
||||
enabled: true
|
||||
lokiSearch:
|
||||
datasourceUid: loki
|
||||
secureJsonData:
|
||||
tlsCACert: |
|
||||
%s
|
||||
tlsClientCert: |
|
||||
%s
|
||||
tlsClientKey: |
|
||||
%s
|
||||
""" % (
|
||||
prometheus_password,
|
||||
yaml_pem(ca, 8),
|
||||
yaml_pem(ca, 8),
|
||||
yaml_pem(cert, 8),
|
||||
yaml_pem(key, 8),
|
||||
yaml_pem(ca, 8),
|
||||
yaml_pem(cert, 8),
|
||||
yaml_pem(key, 8),
|
||||
)
|
||||
write(SECRETS / "grafana" / "datasources.yml", text)
|
||||
|
||||
|
||||
def prometheus_web(password: str) -> None:
|
||||
raw = subprocess.check_output(
|
||||
["docker", "run", "--rm", HTTPD_IMAGE, "htpasswd", "-nbB", "grafana", password],
|
||||
text=True,
|
||||
).strip()
|
||||
hashed = raw.split(":", 1)[1]
|
||||
write(
|
||||
SECRETS / "prometheus" / "web.yml",
|
||||
"tls_server_config:\n"
|
||||
" cert_file: /certs/prometheus.crt\n"
|
||||
" key_file: /certs/prometheus.key\n"
|
||||
"basic_auth_users:\n"
|
||||
' grafana: "%s"\n' % hashed,
|
||||
)
|
||||
|
||||
|
||||
def rabbit_definitions() -> None:
|
||||
relay = password("rabbit_relay")
|
||||
worker = password("rabbit_worker")
|
||||
pattern = "^(attachments|attachment\\\\.jobs.*)$"
|
||||
text = """{
|
||||
"vhosts": [{"name": "/"}],
|
||||
"users": [
|
||||
{"name": "relay", "password": "%s", "tags": ""},
|
||||
{"name": "worker", "password": "%s", "tags": ""}
|
||||
],
|
||||
"permissions": [
|
||||
{"user": "relay", "vhost": "/", "configure": "%s", "write": "%s", "read": "%s"},
|
||||
{"user": "worker", "vhost": "/", "configure": "%s", "write": "%s", "read": "%s"}
|
||||
]
|
||||
}
|
||||
""" % (relay, worker, pattern, pattern, pattern, pattern, pattern, pattern)
|
||||
write(SECRETS / "rabbit-definitions.json", text)
|
||||
|
||||
|
||||
def runtime_copies() -> None:
|
||||
roles = {
|
||||
"api": ["ca.crt", "api.crt", "api.key"],
|
||||
"worker": ["ca.crt"],
|
||||
"relay": ["ca.crt"],
|
||||
"gc": ["ca.crt"],
|
||||
"migrate": ["ca.crt"],
|
||||
}
|
||||
for role, names in roles.items():
|
||||
folder = SECRETS / "runtime" / role
|
||||
place(CERTS / "ca.crt", folder / "ca.crt")
|
||||
if "api.crt" in names:
|
||||
place(CERTS / "api.crt", folder / "server.crt")
|
||||
place(CERTS / "api.key", folder / "server.key")
|
||||
haproxy = SECRETS / "haproxy"
|
||||
place(CERTS / "ca.crt", haproxy / "ca.crt")
|
||||
pem_bundle(CERTS / "lb-server.crt", CERTS / "lb-server.key", haproxy / "lb-server.pem")
|
||||
pem_bundle(CERTS / "lb-client.crt", CERTS / "lb-client.key", haproxy / "lb-client.pem")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
PASSWORDS.mkdir(parents=True, exist_ok=True)
|
||||
for name in (
|
||||
"db_migrator",
|
||||
"db_api",
|
||||
"db_worker",
|
||||
"db_relay",
|
||||
"db_gc",
|
||||
"redis",
|
||||
"rabbit_operator",
|
||||
"rabbit_relay",
|
||||
"rabbit_worker",
|
||||
"minio_root_password",
|
||||
"s3_api_key",
|
||||
"s3_api_secret",
|
||||
"s3_worker_key",
|
||||
"s3_worker_secret",
|
||||
"s3_gc_key",
|
||||
"s3_gc_secret",
|
||||
"grafana_admin",
|
||||
"prometheus_grafana",
|
||||
"otel_token",
|
||||
):
|
||||
password(name)
|
||||
write(PASSWORDS / "minio_root_user", "labroot\n")
|
||||
write(PASSWORDS / "rabbit_operator_name", "operator\n")
|
||||
write(
|
||||
SECRETS / "minio.env",
|
||||
"MINIO_ROOT_USER=%s\nMINIO_ROOT_PASSWORD=%s\n" % (password("minio_root_user"), password("minio_root_password")),
|
||||
)
|
||||
write(SECRETS / "otel.env", "OTEL_INGEST_TOKEN=%s\n" % password("otel_token"))
|
||||
write(ROOT / ".env", "APP_ENV=lab\n")
|
||||
issue_certificates()
|
||||
runtime_copies()
|
||||
rabbit_definitions()
|
||||
prometheus_password = password("prometheus_grafana")
|
||||
prometheus_web(prometheus_password)
|
||||
grafana_datasources(prometheus_password)
|
||||
print("bootstrap complete")
|
||||
print("CA_FILE=%s" % (CERTS / "ca.crt"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except subprocess.CalledProcessError as exc:
|
||||
print("bootstrap command failed", file=sys.stderr)
|
||||
sys.exit(exc.returncode)
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Negative and positive probes for LB-to-API mTLS. Run inside the lab network."""
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
HOST = "api"
|
||||
PORT = 8443
|
||||
CA = Path("/certs/ca.crt")
|
||||
LB_CERT = Path("/certs/lb-client.crt")
|
||||
LB_KEY = Path("/certs/lb-client.key")
|
||||
INTRUDER_CERT = Path("/certs/intruder.crt")
|
||||
INTRUDER_KEY = Path("/certs/intruder.key")
|
||||
FOREIGN_CERT = Path("/certs/foreign-client.crt")
|
||||
FOREIGN_KEY = Path("/certs/foreign-client.key")
|
||||
FOREIGN_CA = Path("/certs/foreign-ca.crt")
|
||||
|
||||
|
||||
def ips():
|
||||
found = sorted({item[4][0] for item in socket.getaddrinfo(HOST, PORT, type=socket.SOCK_STREAM)})
|
||||
if len(found) < 2:
|
||||
raise SystemExit("expected at least two API addresses, got %s" % found)
|
||||
return found
|
||||
|
||||
|
||||
def context(ca, cert=None, key=None):
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
ctx.check_hostname = True
|
||||
ctx.verify_mode = ssl.CERT_REQUIRED
|
||||
ctx.load_verify_locations(cafile=str(ca))
|
||||
if cert and key:
|
||||
ctx.load_cert_chain(str(cert), str(key))
|
||||
return ctx
|
||||
|
||||
|
||||
def http_get(ip, ctx):
|
||||
sock = socket.create_connection((ip, PORT), timeout=5)
|
||||
try:
|
||||
tls = ctx.wrap_socket(sock, server_hostname=HOST)
|
||||
except ssl.SSLError as exc:
|
||||
return "handshake", type(exc).__name__
|
||||
try:
|
||||
tls.sendall(b"GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n")
|
||||
data = b""
|
||||
while True:
|
||||
chunk = tls.recv(4096)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
if len(data) > 65536:
|
||||
break
|
||||
except (ssl.SSLError, OSError, ConnectionError) as exc:
|
||||
return "closed", type(exc).__name__
|
||||
finally:
|
||||
try:
|
||||
tls.close()
|
||||
except OSError:
|
||||
pass
|
||||
status = data.split(b" ", 2)[1].decode("ascii", "replace") if data.startswith(b"HTTP/") and b" " in data else "none"
|
||||
return "http", status
|
||||
|
||||
|
||||
def expect(ip, label, ca, cert, key, kind):
|
||||
outcome, detail = http_get(ip, context(ca, cert, key))
|
||||
if kind == "reject-handshake" and outcome == "handshake":
|
||||
print("PASS %s %s handshake rejected (%s)" % (ip, label, detail))
|
||||
return
|
||||
if kind == "reject-http" and outcome != "http" and detail != "200":
|
||||
print("PASS %s %s rejected (%s %s)" % (ip, label, outcome, detail))
|
||||
return
|
||||
if kind == "reject-http" and outcome == "http" and detail != "200":
|
||||
print("PASS %s %s rejected status %s" % (ip, label, detail))
|
||||
return
|
||||
if kind == "allow" and outcome == "http" and detail == "200":
|
||||
print("PASS %s %s accepted" % (ip, label))
|
||||
return
|
||||
raise SystemExit("FAIL %s %s -> %s %s" % (ip, label, outcome, detail))
|
||||
|
||||
|
||||
def main():
|
||||
for ip in ips():
|
||||
expect(ip, "no-cert", CA, None, None, "reject-handshake")
|
||||
expect(ip, "foreign-ca", CA, FOREIGN_CERT, FOREIGN_KEY, "reject-handshake")
|
||||
expect(ip, "wrong-identity", CA, INTRUDER_CERT, INTRUDER_KEY, "reject-http")
|
||||
expect(ip, "lb-identity", CA, LB_CERT, LB_KEY, "allow")
|
||||
print("PASS mTLS identity checks")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as exc:
|
||||
print("FAIL %s" % type(exc).__name__, file=sys.stderr)
|
||||
raise
|
||||
@@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Init, unseal and load scoped AppRole secrets. Does not print tokens or keys."""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SECRETS = Path(os.environ.get("SECRETS_DIR", str(ROOT / "secrets")))
|
||||
POLICIES = Path(os.environ.get("POLICIES_DIR", str(ROOT / "infra" / "openbao" / "policies")))
|
||||
ADDR = os.environ.get("BAO_ADDR", "https://127.0.0.1:8200").rstrip("/")
|
||||
CA = os.environ.get("BAO_CACERT", str(SECRETS / "certs" / "ca.crt"))
|
||||
|
||||
ROLES = ("api", "worker", "relay", "gc", "migrate")
|
||||
|
||||
|
||||
def read(name: str) -> str:
|
||||
return (SECRETS / "passwords" / name).read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
def call(ctx, method, path, body=None, token=""):
|
||||
data = None if body is None else json.dumps(body).encode("utf-8")
|
||||
request = urllib.request.Request(ADDR + path, data=data, method=method)
|
||||
request.add_header("Content-Type", "application/json")
|
||||
if token:
|
||||
request.add_header("X-Vault-Token", token)
|
||||
try:
|
||||
with urllib.request.urlopen(request, context=ctx, timeout=5) as response:
|
||||
raw = response.read()
|
||||
return response.status, json.loads(raw.decode("utf-8")) if raw else {}
|
||||
except urllib.error.HTTPError as exc:
|
||||
raw = exc.read()
|
||||
try:
|
||||
payload = json.loads(raw.decode("utf-8")) if raw else {}
|
||||
except json.JSONDecodeError:
|
||||
payload = {}
|
||||
return exc.code, payload
|
||||
|
||||
|
||||
def wait_status(ctx):
|
||||
for _ in range(60):
|
||||
try:
|
||||
code, payload = call(ctx, "GET", "/v1/sys/seal-status")
|
||||
if code == 200 and isinstance(payload, dict) and "initialized" in payload:
|
||||
return payload
|
||||
except (urllib.error.URLError, TimeoutError, OSError):
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise SystemExit("openbao did not become reachable")
|
||||
|
||||
|
||||
def write_mode(path: Path, text: str, mode: int) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8", newline="\n")
|
||||
try:
|
||||
os.chmod(path, mode)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_secret_id(ctx, token, role):
|
||||
target = SECRETS / "runtime" / role / "secret_id"
|
||||
if target.is_file() and target.read_text(encoding="utf-8").strip():
|
||||
return
|
||||
code, payload = call(ctx, "POST", "/v1/auth/approle/role/%s/secret-id" % role, {}, token)
|
||||
if code != 200:
|
||||
raise SystemExit("secret-id was not issued for %s" % role)
|
||||
secret_id = payload.get("data", {}).get("secret_id", "")
|
||||
if not secret_id:
|
||||
raise SystemExit("secret-id was empty")
|
||||
write_mode(target, secret_id + "\n", 0o644)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ctx = ssl.create_default_context(cafile=CA)
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
status = wait_status(ctx)
|
||||
init_path = SECRETS / "openbao" / "init.json"
|
||||
if not status.get("initialized"):
|
||||
code, payload = call(ctx, "POST", "/v1/sys/init", {"secret_shares": 1, "secret_threshold": 1})
|
||||
if code != 200 or not payload.get("root_token") or not payload.get("keys"):
|
||||
raise SystemExit("openbao init failed")
|
||||
write_mode(init_path, json.dumps({"keys": payload["keys"], "root_token": payload["root_token"]}) + "\n", 0o600)
|
||||
print("openbao initialized")
|
||||
status = wait_status(ctx)
|
||||
saved = json.loads(init_path.read_text(encoding="utf-8"))
|
||||
if status.get("sealed"):
|
||||
code, _payload = call(ctx, "POST", "/v1/sys/unseal", {"key": saved["keys"][0]})
|
||||
if code != 200:
|
||||
raise SystemExit("openbao unseal failed")
|
||||
print("openbao unsealed")
|
||||
token = saved["root_token"]
|
||||
code, _payload = call(ctx, "POST", "/v1/sys/mounts/secret", {"type": "kv", "options": {"version": "2"}}, token)
|
||||
if code not in {200, 204, 400}:
|
||||
raise SystemExit("kv mount failed")
|
||||
code, _payload = call(ctx, "POST", "/v1/sys/auth/approle", {"type": "approle"}, token)
|
||||
if code not in {200, 204, 400}:
|
||||
raise SystemExit("approle enable failed")
|
||||
db = {
|
||||
"migrate": ("messenger", read("db_migrator")),
|
||||
"api": ("api_user", read("db_api")),
|
||||
"worker": ("worker_user", read("db_worker")),
|
||||
"relay": ("relay_user", read("db_relay")),
|
||||
"gc": ("gc_user", read("db_gc")),
|
||||
}
|
||||
secrets = {
|
||||
"migrate": {"database_url": "postgresql+asyncpg://%s:%s@postgres:5432/messenger" % db["migrate"]},
|
||||
"api": {
|
||||
"database_url": "postgresql+asyncpg://%s:%s@postgres:5432/messenger" % db["api"],
|
||||
"redis_url": "rediss://:%s@redis:6379/0" % read("redis"),
|
||||
"s3_access_key_id": read("s3_api_key"),
|
||||
"s3_secret_access_key": read("s3_api_secret"),
|
||||
"otel_token": read("otel_token"),
|
||||
},
|
||||
"worker": {
|
||||
"database_url": "postgresql+asyncpg://%s:%s@postgres:5432/messenger" % db["worker"],
|
||||
"s3_access_key_id": read("s3_worker_key"),
|
||||
"s3_secret_access_key": read("s3_worker_secret"),
|
||||
"broker_url": "amqps://worker:%s@rabbitmq:5671/%s" % (read("rabbit_worker"), "%2F"),
|
||||
"otel_token": read("otel_token"),
|
||||
},
|
||||
"relay": {
|
||||
"database_url": "postgresql+asyncpg://%s:%s@postgres:5432/messenger" % db["relay"],
|
||||
"broker_url": "amqps://relay:%s@rabbitmq:5671/%s" % (read("rabbit_relay"), "%2F"),
|
||||
"otel_token": read("otel_token"),
|
||||
},
|
||||
"gc": {
|
||||
"database_url": "postgresql+asyncpg://%s:%s@postgres:5432/messenger" % db["gc"],
|
||||
"s3_access_key_id": read("s3_gc_key"),
|
||||
"s3_secret_access_key": read("s3_gc_secret"),
|
||||
"otel_token": read("otel_token"),
|
||||
},
|
||||
}
|
||||
for role in ROLES:
|
||||
policy = (POLICIES / ("messenger-%s.hcl" % role)).read_text(encoding="utf-8")
|
||||
code, _payload = call(ctx, "PUT", "/v1/sys/policies/acl/messenger-%s" % role, {"policy": policy}, token)
|
||||
if code not in {200, 204}:
|
||||
raise SystemExit("policy write failed for %s" % role)
|
||||
code, _payload = call(
|
||||
ctx,
|
||||
"POST",
|
||||
"/v1/auth/approle/role/%s" % role,
|
||||
{
|
||||
"token_policies": ["messenger-%s" % role],
|
||||
"token_ttl": "1h",
|
||||
"token_max_ttl": "4h",
|
||||
"secret_id_ttl": "0",
|
||||
"secret_id_num_uses": 0,
|
||||
},
|
||||
token,
|
||||
)
|
||||
if code not in {200, 204}:
|
||||
raise SystemExit("approle role failed for %s" % role)
|
||||
code, payload = call(ctx, "GET", "/v1/auth/approle/role/%s/role-id" % role, token=token)
|
||||
role_id = payload.get("data", {}).get("role_id", "") if code == 200 else ""
|
||||
if not role_id:
|
||||
raise SystemExit("role-id missing for %s" % role)
|
||||
write_mode(SECRETS / "runtime" / role / "role_id", role_id + "\n", 0o644)
|
||||
ensure_secret_id(ctx, token, role)
|
||||
code, _payload = call(ctx, "POST", "/v1/secret/data/messenger/%s" % role, {"data": secrets[role]}, token)
|
||||
if code not in {200, 204}:
|
||||
raise SystemExit("kv write failed for %s" % role)
|
||||
print("openbao policies and secrets are in place")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade-3 negative checks that the public smoke does not cover."""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
CA = ROOT / "secrets" / "certs" / "ca.crt"
|
||||
BASE = os.environ.get("BASE_URL", "https://localhost:8443").rstrip("/")
|
||||
|
||||
|
||||
def compose(*args, timeout=180):
|
||||
return subprocess.run(
|
||||
["docker", "compose", "--env-file", str(ROOT / ".env"), *args],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
def trusted():
|
||||
ctx = ssl.create_default_context(cafile=str(CA))
|
||||
with urllib.request.urlopen(BASE + "/health/ready", context=ctx, timeout=10) as response:
|
||||
body = response.read()
|
||||
if response.status != 200:
|
||||
raise SystemExit("trusted HTTPS did not return 200")
|
||||
return body
|
||||
|
||||
|
||||
def untrusted():
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
ctx.verify_mode = ssl.CERT_REQUIRED
|
||||
ctx.check_hostname = True
|
||||
try:
|
||||
urllib.request.urlopen(BASE + "/health/ready", context=ctx, timeout=5).read()
|
||||
except urllib.error.URLError as exc:
|
||||
if not isinstance(exc.reason, ssl.SSLCertVerificationError):
|
||||
raise SystemExit("untrusted CA failed for a non-certificate reason")
|
||||
return
|
||||
raise SystemExit("empty trust store was accepted")
|
||||
|
||||
|
||||
def closed_port():
|
||||
import socket
|
||||
|
||||
sock = socket.socket()
|
||||
sock.settimeout(2)
|
||||
try:
|
||||
result = sock.connect_ex(("127.0.0.1", 8080))
|
||||
finally:
|
||||
sock.close()
|
||||
if result == 0:
|
||||
raise SystemExit("plaintext port 8080 is reachable on the host")
|
||||
|
||||
|
||||
def rate_limit():
|
||||
ctx = ssl.create_default_context(cafile=str(CA))
|
||||
raw = base64.b64encode(b"rate_limit_user:wrong-password-value").decode("ascii")
|
||||
saw = None
|
||||
for _ in range(12):
|
||||
request = urllib.request.Request(
|
||||
BASE + "/api/v1/auth/sessions",
|
||||
method="POST",
|
||||
headers={"Authorization": "Basic " + raw, "Accept": "application/json"},
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(request, context=ctx, timeout=20).read()
|
||||
code = 200
|
||||
headers = {}
|
||||
except urllib.error.HTTPError as exc:
|
||||
code = exc.code
|
||||
headers = exc.headers
|
||||
exc.read()
|
||||
saw = code
|
||||
if code == 429:
|
||||
if not headers.get("Retry-After"):
|
||||
raise SystemExit("429 without Retry-After")
|
||||
return
|
||||
raise SystemExit("login was not rate limited, last status %s" % saw)
|
||||
|
||||
|
||||
def oversized():
|
||||
ctx = ssl.create_default_context(cafile=str(CA))
|
||||
payload = b'{"username":"abc","display_name":"x","password":"' + (b"a" * 70000) + b'"}'
|
||||
request = urllib.request.Request(
|
||||
BASE + "/api/v1/users",
|
||||
data=payload,
|
||||
method="POST",
|
||||
headers={"Content-Type": "application/json", "Accept": "application/json"},
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(request, context=ctx, timeout=20).read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code != 413:
|
||||
raise SystemExit("oversized body returned %s" % exc.code) from None
|
||||
return
|
||||
raise SystemExit("oversized body was accepted")
|
||||
|
||||
|
||||
def openbao_deny():
|
||||
sys.path.insert(0, str(ROOT))
|
||||
os.environ["BAO_ADDR"] = "https://127.0.0.1:8200"
|
||||
os.environ["BAO_CACERT"] = str(CA)
|
||||
ctx = ssl.create_default_context(cafile=str(CA))
|
||||
role = (ROOT / "secrets" / "runtime" / "worker" / "role_id").read_text(encoding="utf-8").strip()
|
||||
secret = (ROOT / "secrets" / "runtime" / "worker" / "secret_id").read_text(encoding="utf-8").strip()
|
||||
body = json.dumps({"role_id": role, "secret_id": secret}).encode("utf-8")
|
||||
request = urllib.request.Request(
|
||||
"https://127.0.0.1:8200/v1/auth/approle/login",
|
||||
data=body,
|
||||
method="POST",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
with urllib.request.urlopen(request, context=ctx, timeout=10) as response:
|
||||
token = json.loads(response.read().decode("utf-8"))["auth"]["client_token"]
|
||||
own = urllib.request.Request(
|
||||
"https://127.0.0.1:8200/v1/secret/data/messenger/worker",
|
||||
headers={"X-Vault-Token": token},
|
||||
)
|
||||
with urllib.request.urlopen(own, context=ctx, timeout=10) as response:
|
||||
if response.status != 200:
|
||||
raise SystemExit("worker cannot read its own secret")
|
||||
foreign = urllib.request.Request(
|
||||
"https://127.0.0.1:8200/v1/secret/data/messenger/api",
|
||||
headers={"X-Vault-Token": token},
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(foreign, context=ctx, timeout=10).read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code != 403:
|
||||
raise SystemExit("worker read of api secret returned %s" % exc.code) from None
|
||||
return
|
||||
raise SystemExit("worker token read the api secret")
|
||||
|
||||
|
||||
def mtls():
|
||||
proc = compose(
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"--entrypoint",
|
||||
"python",
|
||||
"-v",
|
||||
"%s:/probe.py:ro" % (ROOT / "scripts" / "mtls_probe.py"),
|
||||
"-v",
|
||||
"%s:/certs:ro" % (ROOT / "secrets" / "certs"),
|
||||
"api",
|
||||
"/probe.py",
|
||||
)
|
||||
sys.stdout.write(proc.stdout)
|
||||
sys.stderr.write(proc.stderr)
|
||||
if proc.returncode != 0:
|
||||
raise SystemExit("mTLS probe failed")
|
||||
|
||||
|
||||
def main():
|
||||
trusted()
|
||||
print("PASS trusted HTTPS")
|
||||
untrusted()
|
||||
print("PASS untrusted CA rejected")
|
||||
closed_port()
|
||||
print("PASS host port 8080 is closed")
|
||||
rate_limit()
|
||||
print("PASS login rate limit")
|
||||
oversized()
|
||||
print("PASS request size limit")
|
||||
openbao_deny()
|
||||
print("PASS OpenBao worker policy deny")
|
||||
mtls()
|
||||
evidence = ROOT / "evidence"
|
||||
evidence.mkdir(exist_ok=True)
|
||||
(evidence / "level7.json").write_text(
|
||||
json.dumps({"result": "pass", "base_url": BASE}, indent=2) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
print("PASS level 3 security checks")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
if command -v python3 >/dev/null 2>&1; then
|
||||
PY=python3
|
||||
else
|
||||
PY=python
|
||||
fi
|
||||
docker compose --env-file .env restart postgres redis minio rabbitmq openbao
|
||||
docker compose --env-file .env restart minio-tls || true
|
||||
BAO_ADDR=https://127.0.0.1:8200 \
|
||||
BAO_CACERT="$PWD/secrets/certs/ca.crt" \
|
||||
SECRETS_DIR="$PWD/secrets" \
|
||||
"$PY" scripts/openbao_bootstrap.py
|
||||
docker compose --env-file .env restart api worker relay gc
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${TARGET_INSTANCE_ID:?missing TARGET_INSTANCE_ID}"
|
||||
ids=$(docker compose --env-file .env ps -q api)
|
||||
for id in $ids; do
|
||||
host=$(docker inspect -f '{{.Config.Hostname}}' "$id")
|
||||
if [ "$host" = "$TARGET_INSTANCE_ID" ]; then
|
||||
docker stop -t 2 "$id" >/dev/null
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
echo "api instance was not found" >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bootstrap local secrets and start the lab7 stand."""
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.check_call(["docker", "compose", "--env-file", str(ROOT / ".env"), *args], cwd=ROOT)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
subprocess.check_call([sys.executable, str(ROOT / "scripts" / "bootstrap.py")], cwd=ROOT)
|
||||
compose("up", "-d", "--build", "--scale", "api=2")
|
||||
ids = subprocess.check_output(
|
||||
["docker", "compose", "--env-file", str(ROOT / ".env"), "ps", "-q", "api"],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
).split()
|
||||
if len(ids) < 2:
|
||||
raise SystemExit("expected two API replicas, got %s" % len(ids))
|
||||
print("stand is up; wait for https://localhost:8443/health/ready")
|
||||
print("CA_FILE=%s" % (ROOT / "secrets" / "certs" / "ca.crt"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user