#!/usr/bin/env python3 """TLS / mTLS / authorization audit of the whole trust matrix (contracts/trust-matrix.md), from INSIDE the network. Run (stand up, OpenBao unsealed for section H): docker compose run --rm --no-deps -v ./secrets/pki:/pki:ro -v ./secrets/bootstrap:/bootstrap:ro \ -v ./student-tests:/audit:ro --entrypoint python worker /audit/tls_audit.py [--only A,B,...] For every link: no client certificate / certificate of a FOREIGN CA (claims the right name) / certificate of the SAME CA with a wrong identity / the right identity. Stores additionally get allow/deny checks of the scoped rights. Credentials from /bootstrap are used only for positive probes and are never printed. Exit 1 on any mismatch. """ import argparse import asyncio import json import socket import ssl import sys import time import urllib.error import urllib.request PKI = "/pki" CA = PKI + "/ca.crt" FOREIGN_CA = PKI + "/foreign.crt" RESULTS = [] def cert(name): return (PKI + "/%s.crt" % name, PKI + "/%s.key" % name) if name else None def secret(name): with open("/bootstrap/" + name, encoding="utf-8") as handle: return handle.read().strip() def record(section, link, case, expect, observed, ok): RESULTS.append({"section": section, "link": link, "case": case, "expect": expect, "observed": observed[:160], "pass": bool(ok)}) print("%s %-2s %-26s %-44s expect=%-8s %s" % ("PASS" if ok else "FAIL", section, link, case, expect, observed[:110]), flush=True) def ctx_for(client=None, cafile=CA, alpn=None): ctx = ssl.create_default_context(cafile=cafile) if client: ctx.load_cert_chain(*cert(client)) if alpn: ctx.set_alpn_protocols(alpn) return ctx def tls_exchange(host, port, client=None, cafile=CA, server_hostname=None, payload=b"", timeout=3.0, alpn=None): """TLS connect + optional payload + read. Returns ('accepted', first bytes) or ('rejected', reason). With TLS 1.3 a missing/untrusted client certificate is reported by the server AFTER the client's handshake, so the verdict needs a read; a closed connection without data counts as rejected.""" raw = socket.create_connection((host, port), timeout=timeout) try: s = ctx_for(client, cafile, alpn).wrap_socket(raw, server_hostname=server_hostname or host) except ssl.SSLCertVerificationError as exc: raw.close() return "rejected", "server cert verify failed: " + exc.verify_message except (ssl.SSLError, OSError) as exc: raw.close() return "rejected", "handshake: " + (getattr(exc, "reason", None) or type(exc).__name__) try: if payload: s.sendall(payload) data = s.recv(64) return ("accepted", data.decode("latin-1", "replace")) if data else ("rejected", "closed without response") except socket.timeout: return "accepted", "(open, no data within %.1fs)" % timeout except (ssl.SSLError, OSError) as exc: return "rejected", "after handshake: " + (getattr(exc, "reason", None) or type(exc).__name__) finally: s.close() def http_get(host, port, path, client=None, hostname=None): payload = ("GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n" % (path, hostname or host)).encode() verdict, detail = tls_exchange(host, port, client, server_hostname=hostname, payload=payload) if verdict == "accepted" and detail.startswith("HTTP/"): return "accepted", detail.split("\r\n")[0] return verdict, detail def expect_tls(section, link, host, port, client, case, accept, path=None, payload=b"", hostname=None, alpn=None): if path: verdict, detail = http_get(host, port, path, client, hostname) else: verdict, detail = tls_exchange(host, port, client, payload=payload, server_hostname=hostname, alpn=alpn) record(section, link, case, "accept" if accept else "reject", "%s: %s" % (verdict, detail), (verdict == "accepted") == accept) def plaintext_refused(section, link, host, port, probe=b"GET / HTTP/1.0\r\n\r\n"): try: s = socket.create_connection((host, port), timeout=3) s.sendall(probe) data = s.recv(64) s.close() ok = not data.startswith((b"HTTP/1.1 200", b"AMQP", b"+PONG", b"-NOAUTH")) record(section, link, "plaintext client", "reject", "server answered %r" % data[:24], ok) except OSError as exc: record(section, link, "plaintext client", "reject", "connection failed: %s" % type(exc).__name__, True) # ---------------------------------------------------------------------------------------------- sections def a_lb_api(): for api in ("api-1", "api-2"): link = "LB -> %s:8080" % api expect_tls("A", link, api, 8080, None, "no client cert", False, "/health/ready") expect_tls("A", link, api, 8080, "foreign-client", "foreign CA (claims lb identity)", False, "/health/ready") expect_tls("A", link, api, 8080, "intruder", "same CA, identity intruder", False, "/health/ready") expect_tls("A", link, api, 8080, "worker", "same CA, identity worker", False, "/health/ready") expect_tls("A", link, api, 8080, "api", "same CA, identity api", False, "/health/ready") expect_tls("A", link, api, 8080, "lb-client", "lb.client.messenger", True, "/health/ready") plaintext_refused("A", link, api, 8080) def i_ingress(): link = "client -> nginx:8443" expect_tls("I", link, "nginx", 8443, None, "trusted CA, hostname nginx", True, "/health/live") verdict, detail = tls_exchange("nginx", 8443, cafile=FOREIGN_CA) record("I", link, "untrusted CA in client trust store", "reject", "%s: %s" % (verdict, detail), verdict == "rejected" and "verify failed" in detail) verdict, detail = tls_exchange("nginx", 8443, server_hostname="evil.example") record("I", link, "wrong hostname (evil.example)", "reject", "%s: %s" % (verdict, detail), verdict == "rejected" and "verify failed" in detail) plaintext_refused("I", link, "nginx", 8443) def b_postgres(): import psycopg link = "svc -> postgres:5432" url = lambda role, pw: "postgresql://%s:%s@postgres:5432/messenger" % (role, pw) # noqa: E731 api_pw, worker_pw = secret("db_api_password"), secret("db_worker_password") def connect(role, pw, **kw): return psycopg.connect(url(role, pw), connect_timeout=5, autocommit=True, **kw) def attempt(case, accept, **kw): try: connect("app_api", api_pw, **kw).close() record("B", link, case, "accept" if accept else "reject", "connected", accept) except psycopg.Error as exc: record("B", link, case, "accept" if accept else "reject", type(exc).__name__ + ": " + str(exc).splitlines()[0], not accept) attempt("plaintext (sslmode=disable)", False, sslmode="disable") attempt("foreign CA as root (verify-full)", False, sslmode="verify-full", sslrootcert=FOREIGN_CA) ip = socket.gethostbyname("postgres") try: psycopg.connect("postgresql://app_api:%s@%s:5432/messenger" % (api_pw, ip), sslmode="verify-full", sslrootcert=CA, connect_timeout=5).close() record("B", link, "hostname mismatch (IP, verify-full)", "reject", "connected", False) except psycopg.Error as exc: record("B", link, "hostname mismatch (IP, verify-full)", "reject", str(exc).splitlines()[0], True) attempt("TLS verify-full + app_api password", True, sslmode="verify-full", sslrootcert=CA) try: connect("app_api", "wrong-password", sslmode="verify-full", sslrootcert=CA).close() record("B", link, "wrong password", "reject", "connected", False) except psycopg.Error as exc: record("B", link, "wrong password", "reject", str(exc).splitlines()[0], True) checks = [ ("app_worker", worker_pw, "SELECT count(*) FROM users", False), ("app_worker", worker_pw, "SELECT count(*) FROM messages", False), ("app_worker", worker_pw, "SELECT count(*) FROM sessions", False), ("app_worker", worker_pw, "DELETE FROM attachments WHERE false", False), ("app_worker", worker_pw, "SELECT count(*) FROM attachment_jobs", True), ("app_api", api_pw, "SELECT count(*) FROM users", True), ("app_api", api_pw, "CREATE TABLE audit_probe (x int)", False), ("app_api", api_pw, "ALTER ROLE app_worker PASSWORD 'x'", False), ("app_api", api_pw, "SELECT count(*) FROM schema_migrations", False), ] for role, pw, query, accept in checks: try: with connect(role, pw, sslmode="verify-full", sslrootcert=CA) as conn: conn.execute(query) record("B", "%s privileges" % role, query[:44], "allow" if accept else "deny", "executed", accept) except psycopg.Error as exc: record("B", "%s privileges" % role, query[:44], "allow" if accept else "deny", type(exc).__name__, not accept) def c_s3(): import boto3 from botocore.config import Config from botocore.exceptions import ClientError, SSLError, EndpointConnectionError bucket = "messenger-attachments" def client(role, verify=CA, endpoint="https://minio:9000"): return boto3.client("s3", endpoint_url=endpoint, region_name="us-east-1", verify=verify, aws_access_key_id=secret("s3_%s_access_key" % role), aws_secret_access_key=secret("s3_%s_secret_key" % role), config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, retries={"max_attempts": 0}, connect_timeout=3, read_timeout=5)) def op(role, case, accept, fn): try: fn(client(role)) record("C", "%s S3 rights" % role, case, "allow" if accept else "deny", "ok", accept) except ClientError as exc: record("C", "%s S3 rights" % role, case, "allow" if accept else "deny", exc.response["Error"]["Code"], not accept) tag = "audit-%d" % int(time.time()) try: client("api", verify=FOREIGN_CA).list_objects_v2(Bucket=bucket, MaxKeys=1) record("C", "svc -> minio:9000", "foreign CA as trust anchor", "reject", "connected", False) except (SSLError, EndpointConnectionError, Exception) as exc: # noqa: B014 record("C", "svc -> minio:9000", "foreign CA as trust anchor", "reject", type(exc).__name__, True) try: client("api", endpoint="http://minio:9000").list_objects_v2(Bucket=bucket, MaxKeys=1) record("C", "svc -> minio:9000", "plaintext http://", "reject", "answered", False) except Exception as exc: # noqa: BLE001 record("C", "svc -> minio:9000", "plaintext http://", "reject", type(exc).__name__, True) op("worker", "PUT attachments/*", True, lambda c: c.put_object(Bucket=bucket, Key="attachments/%s/x" % tag, Body=b"x")) op("worker", "GET attachments/*", False, lambda c: c.get_object(Bucket=bucket, Key="attachments/%s/x" % tag)) op("worker", "DELETE attachments/*", False, lambda c: c.delete_object(Bucket=bucket, Key="attachments/%s/x" % tag)) op("worker", "PUT staging/*", False, lambda c: c.put_object(Bucket=bucket, Key="staging/%s" % tag, Body=b"x")) op("worker", "LIST bucket", False, lambda c: c.list_objects_v2(Bucket=bucket, MaxKeys=1)) op("worker", "PUT outside prefixes", False, lambda c: c.put_object(Bucket=bucket, Key="other/%s" % tag, Body=b"x")) op("api", "PUT staging/*", True, lambda c: c.put_object(Bucket=bucket, Key="staging/%s" % tag, Body=b"x")) op("api", "PUT attachments/* (only worker publishes)", False, lambda c: c.put_object(Bucket=bucket, Key="attachments/%s/y" % tag, Body=b"x")) op("api", "GET attachments/*", True, lambda c: c.get_object(Bucket=bucket, Key="attachments/%s/x" % tag)) op("api", "LIST bucket (reconciler)", True, lambda c: c.list_objects_v2(Bucket=bucket, MaxKeys=1)) op("api", "create bucket", False, lambda c: c.create_bucket(Bucket="audit-%s" % tag)) op("api", "cleanup audit objects", True, lambda c: (c.delete_object(Bucket=bucket, Key="staging/%s" % tag), c.delete_object(Bucket=bucket, Key="attachments/%s/x" % tag))) def d_broker(): import aio_pika from aiormq.exceptions import AMQPError link = "svc -> rabbitmq:5671" url = "amqps://rabbitmq:5671/messenger?auth=external" plaintext_refused("D", "svc -> rabbitmq:5672", "rabbitmq", 5672, b"AMQP\x00\x00\x09\x01") async def connect(client): ctx = ssl.create_default_context(cafile=CA) if client: ctx.load_cert_chain(*cert(client)) return await aio_pika.connect(url, ssl_context=ctx, timeout=5) async def run(): for client, case in ((None, "no client cert"), ("foreign-client", "foreign CA (claims worker name)"), ("intruder", "same CA, unknown identity intruder"), ("lb-client", "same CA, identity lb")): try: conn = await connect(client) await conn.close() record("D", link, case, "reject", "connected", False) except (AMQPError, ConnectionError, OSError, ssl.SSLError, asyncio.TimeoutError) as exc: record("D", link, case, "reject", type(exc).__name__ + " " + str(exc)[:60], True) async def action(client, case, accept, fn): conn = None try: conn = await connect(client) channel = await conn.channel(publisher_confirms=True) await asyncio.wait_for(fn(channel), 5) record("D", "%s AMQP rights" % client, case, "allow" if accept else "deny", "ok", accept) except (AMQPError, asyncio.TimeoutError, aio_pika.exceptions.ChannelClosed) as exc: record("D", "%s AMQP rights" % client, case, "allow" if accept else "deny", type(exc).__name__ + " " + str(exc)[:70], not accept) finally: if conn is not None: await conn.close() async def publish_unroutable(channel): ex = await channel.get_exchange("attachments", ensure=True) await ex.publish(aio_pika.Message(b"audit"), routing_key="audit.unroutable") async def consume_and_cancel(channel): q = await channel.get_queue("attachments.process", ensure=True) await channel.set_qos(prefetch_count=1) tag = await q.consume(lambda m: m.nack(requeue=True)) await q.cancel(tag) async def declare_queue(channel): await channel.declare_queue("audit-probe", auto_delete=True) async def publish_default(channel): await channel.default_exchange.publish(aio_pika.Message(b"audit"), routing_key="attachments.process") await action("api", "publish to exchange attachments", True, publish_unroutable) await action("api", "consume attachments.process", False, consume_and_cancel) await action("api", "declare a queue (configure)", False, declare_queue) await action("api", "publish via default exchange", False, publish_default) await action("worker", "consume attachments.process", True, consume_and_cancel) await action("worker", "publish to exchange attachments", False, publish_unroutable) await action("worker", "declare a queue (configure)", False, declare_queue) asyncio.run(run()) def e_collector(): link = "svc -> otel-collector:4318" body = b"POST /v1/metrics HTTP/1.1\r\nHost: otel-collector\r\nContent-Type: application/x-protobuf\r\n" \ b"Content-Length: 0\r\nConnection: close\r\n\r\n" for client, case, accept in ((None, "no client cert", False), ("foreign-client", "foreign CA", False), ("lb-client", "root CA identity lb (not ingest CA)", False), ("api", "root CA identity api (not ingest CA)", False), ("grafana-out", "telemetry CA (not ingest CA)", False), ("api-otel", "ingest CA api.otel", True), ("worker-otel", "ingest CA worker.otel", True)): verdict, detail = tls_exchange("otel-collector", 4318, client, payload=body) ok = (verdict == "accepted" and detail.startswith("HTTP/1.1 2")) if accept else verdict == "rejected" record("E", link, case, "accept" if accept else "reject", "%s: %s" % (verdict, detail.split("\r\n")[0]), ok) def f_backends(): for host, port, path in (("prometheus", 9090, "/-/ready"), ("loki", 3100, "/ready"), ("tempo", 3200, "/ready")): link = "-> %s:%d" % (host, port) for client, case, accept in ((None, "no client cert", False), ("foreign-client", "foreign CA", False), ("api", "root CA identity api", False), ("api-otel", "ingest CA (apps cannot bypass collector)", False), ("collector-out", "telemetry CA collector.out", True), ("grafana-out", "telemetry CA grafana.out", True), ("operator", "telemetry CA operator", True)): expect_tls("F", link, host, port, client, case, accept, path) link = "collector -> tempo:4317 (gRPC)" preface = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" for client, case, accept in ((None, "no client cert", False), ("api-otel", "ingest CA", False), ("collector-out", "telemetry CA collector.out", True)): expect_tls("F", link, "tempo", 4317, client, case, accept, payload=preface, alpn=["h2"]) def g_valkey(): import valkey link = "api -> valkey:6379" plaintext_refused("G", link, "valkey", 6379, b"PING\r\n") def conn(user=None, password=None, cafile=CA): return valkey.Valkey(host="valkey", port=6379, ssl=True, ssl_ca_certs=cafile, ssl_check_hostname=True, username=user, password=password, socket_timeout=3, decode_responses=True) def attempt(case, accept, fn): try: fn() record("G", link, case, "allow" if accept else "deny", "ok", accept) except Exception as exc: # noqa: BLE001 record("G", link, case, "allow" if accept else "deny", type(exc).__name__ + " " + str(exc)[:60], not accept) attempt("foreign CA as trust anchor", False, lambda: conn("api", secret("valkey_api_password"), FOREIGN_CA).ping()) attempt("no authentication (default user off)", False, lambda: conn().get("session:x")) attempt("user api, wrong password", False, lambda: conn("api", "wrong").ping()) api = lambda: conn("api", secret("valkey_api_password")) # noqa: E731 attempt("api: SET/GET session:*", True, lambda: (api().set("session:audit", "1", ex=5), api().get("session:audit"))) attempt("api: INCR ratelimit:*", True, lambda: api().incr("ratelimit:audit")) attempt("api: GET outside allowed keys", False, lambda: api().get("other:audit")) attempt("api: FLUSHALL", False, lambda: api().flushall()) attempt("api: CONFIG GET", False, lambda: api().config_get("*")) attempt("api: KEYS *", False, lambda: api().keys("*")) attempt("health: GET session:*", False, lambda: conn("health", "health").get("session:audit")) def h_openbao(): base = "https://openbao:8200" def call(path, client=None, token=None, body=None, method=None): req = urllib.request.Request(base + path, data=json.dumps(body).encode() if body is not None else None, method=method or ("POST" if body is not None else "GET")) if token: req.add_header("X-Vault-Token", token) try: with urllib.request.urlopen(req, context=ctx_for(client), timeout=5) as response: return response.status, json.loads(response.read() or b"{}") except urllib.error.HTTPError as exc: return exc.code, {} except (urllib.error.URLError, OSError) as exc: return 0, {"error": type(getattr(exc, "reason", exc)).__name__} def login(client, role): status, body = call("/v1/auth/cert/login", client, body={"name": role}) return status, (body.get("auth") or {}).get("client_token") link = "svc -> openbao:8200" for client, role, case in ((None, "worker", "no client cert"), ("intruder", "worker", "same CA, identity intruder"), ("worker", "api", "worker cert, role api"), ("api", "worker", "api cert, role worker"), ("lb-client", "api", "lb cert, role api")): status, token = login(client, role) record("H", link, "cert login: " + case, "reject", "HTTP %s token=%s" % (status, bool(token)), not token) # /v1/sys/health is public by design; what matters is that a foreign certificate never becomes an identity. status, token = login("foreign-client", "worker") record("H", link, "cert login: foreign CA (claims worker name)", "reject", "HTTP %s token=%s" % (status, bool(token)), not token) for client, role, own, other in (("worker", "worker", "worker", "api"), ("api", "api", "api", "worker")): status, token = login(client, role) record("H", link, "cert login: %s cert, role %s" % (client, role), "accept", "HTTP %s token=%s" % (status, bool(token)), bool(token)) if not token: continue lookup = call("/v1/auth/token/lookup-self", token=token)[1].get("data", {}) record("H", "%s token" % role, "policies / ttl", "scoped", "policies=%s ttl=%ss" % ( lookup.get("policies"), lookup.get("ttl")), lookup.get("policies") == ["default", "messenger-" + role] and 0 < lookup.get("ttl", 0) <= 900) status, _ = call("/v1/messenger/data/" + own, token=token) record("H", "%s token" % role, "read own messenger/%s" % own, "allow", "HTTP %s" % status, status == 200) status, _ = call("/v1/messenger/data/" + other, token=token) record("H", "%s token" % role, "read messenger/%s" % other, "deny", "HTTP %s" % status, status == 403) status, _ = call("/v1/messenger/data/" + own, token=token, body={"data": {"x": "y"}}) record("H", "%s token" % role, "write own secret", "deny", "HTTP %s" % status, status == 403) status, _ = call("/v1/sys/policies/acl/messenger-" + role, token=token, body={"policy": 'path "*" {capabilities=["sudo"]}'}, method="PUT") record("H", "%s token" % role, "write own policy", "deny", "HTTP %s" % status, status == 403) status, _ = call("/v1/sys/auth", token=token) record("H", "%s token" % role, "list auth methods (admin)", "deny", "HTTP %s" % status, status == 403) def j_operator(): link = "operator -> grafana:3000" verdict, detail = http_get("grafana", 3000, "/api/datasources") record("J", link, "HTTPS without login", "reject", "%s: %s" % (verdict, detail), "401" in detail) plaintext_refused("J", link, "grafana", 3000) def k_bypass(): """Side channels must not be reachable from the network (loopback-only or not listening at all).""" closed = [("rabbitmq", 25672, "Erlang distribution"), ("rabbitmq", 4369, "epmd"), ("rabbitmq", 15672, "management UI"), ("loki", 9096, "Loki internal gRPC"), ("tempo", 9095, "Tempo internal gRPC"), ("otel-collector", 8888, "collector self-metrics"), ("otel-collector", 13133, "collector health"), ("otel-collector", 4317, "collector OTLP/gRPC (disabled)"), ("api-1", 8081, "API loopback health"), ("api-2", 8081, "API loopback health"), ("openbao", 8201, "OpenBao cluster port"), ("minio", 9001, "MinIO console"), ("postgres", 5433, "no second PostgreSQL listener")] for host, port, what in closed: try: socket.create_connection((host, port), timeout=2).close() record("K", "%s:%d" % (host, port), what, "closed", "port OPEN from the network", False) except OSError as exc: record("K", "%s:%d" % (host, port), what, "closed", type(exc).__name__, True) SECTIONS = {"A": a_lb_api, "I": i_ingress, "B": b_postgres, "C": c_s3, "D": d_broker, "E": e_collector, "F": f_backends, "G": g_valkey, "H": h_openbao, "J": j_operator, "K": k_bypass} def main(): p = argparse.ArgumentParser() p.add_argument("--only", default=",".join(SECTIONS)) p.add_argument("--output", default="") args = p.parse_args() for key in args.only.split(","): try: SECTIONS[key]() except Exception as exc: # noqa: BLE001 a section that cannot run is a failure, not a skip record(key, "section " + key, "runs", "run", "%s: %s" % (type(exc).__name__, str(exc)[:120]), False) failed = [r for r in RESULTS if not r["pass"]] print("\n%d checks, %d failed" % (len(RESULTS), len(failed))) if args.output: with open(args.output, "w", encoding="utf-8") as handle: json.dump(RESULTS, handle, ensure_ascii=False, indent=1) sys.exit(1 if failed else 0) if __name__ == "__main__": main()