Files
mtusi2026lab7/scripts/mtls_check.py

123 lines
6.1 KiB
Python

#!/usr/bin/env python3
"""Negative/positive proof of the LB -> API mTLS, against EVERY API replica directly (no LB).
Runs inside the compose network `edge` (the LB's network), as the tools service `mtls-check`:
docker compose run --rm mtls-check (wrappers: make mtls-check, scripts/mtls_check.cmd)
For every IP of the DNS name `api` (one per running replica) it opens fresh connections that
always verify the SERVER (internal CA, hostname `api`) and present, as the client:
1. no certificate -> refused in the TLS handshake
2. certificate of a foreign CA, SAN `lb` (right name) -> refused in the TLS handshake (unknown CA)
3. certificate of OUR CA, SAN `worker` (wrong role) -> handshake OK, connection closed by the
API before any HTTP response (allowlist)
4. certificate of OUR CA, SAN `lb` (the LB identity) -> HTTP 200 from GET /health/ready
plus two bypass probes: plaintext HTTP to the mTLS port and the loopback health port from another
container (both must fail). Case 4 on the same address proves the refusals are not "network down".
Which check refused: the API logs `mtls_identity_rejected` (with the client SAN) ONLY for the
allowlist (case 3); cases 1-2 never reach the application - the TLS layer drops them. The wrapper
scripts/mtls_check.sh prints those log lines after the run.
Exit 0 only if every expectation holds. Prints no key material. Test-only: this container mounts the
LB's client key (to prove the positive case) and the worker's certificate (a trusted but wrong role).
"""
from __future__ import annotations
import os
import socket
import ssl
import sys
PORT = int(os.environ.get("API_PORT", "8443"))
HEALTH_PORT = int(os.environ.get("API_HEALTH_PORT", "8081"))
CA = os.environ.get("INTERNAL_CA", "/run/secrets/internal-ca.crt")
CERTS = {
"none": None,
"foreign-ca SAN=lb": ("/run/secrets/foreign-lb.crt", "/run/secrets/foreign-lb.key"),
"internal-ca SAN=worker": ("/run/secrets/worker.crt", "/run/secrets/worker.key"),
"internal-ca SAN=lb": ("/run/secrets/lb.crt", "/run/secrets/lb.key"),
}
EXPECT = {"none": "refused", "foreign-ca SAN=lb": "refused", "internal-ca SAN=worker": "refused",
"internal-ca SAN=lb": "200"}
REQUEST = b"GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n"
def attempt(ip: str, cert, version: ssl.TLSVersion) -> tuple[str, str]:
"""(outcome, detail): outcome is the HTTP status code, or 'refused'/'error'.
TLS 1.3: the client finishes its side of the handshake BEFORE the server has checked the client
certificate, so a refusal shows up as an alert/EOF on the first read. TLS 1.2: the server
checks the client certificate inside the handshake, so the alert names the reason
(certificate required / unknown CA). Both versions must refuse; the identity allowlist always
acts after a successful handshake (the chain is fine there).
"""
ctx = ssl.create_default_context(cafile=CA) # server verification is ALWAYS on
ctx.check_hostname = True
ctx.minimum_version = ctx.maximum_version = version
if cert:
ctx.load_cert_chain(*cert)
stage = "tcp"
try:
with socket.create_connection((ip, PORT), timeout=5) as raw:
stage = "handshake"
with ctx.wrap_socket(raw, server_hostname="api") as tls:
stage = "http"
tls.sendall(REQUEST)
data = tls.recv(4096)
if not data:
return "refused", "closed by the server after the handshake (no HTTP response)"
status = data.split(b" ", 2)[1].decode("ascii", "replace")
return status, f"HTTP {status}; server cert SAN api verified"
except ssl.SSLCertVerificationError as exc:
return "error", f"SERVER certificate not trusted: {exc.verify_message}"
except ssl.SSLError as exc:
if exc.reason == "UNEXPECTED_EOF_WHILE_READING":
return "refused", f"server closed the connection during the {stage} (no HTTP response)"
return "refused", f"TLS alert at {stage}: {exc.reason or exc}"
except (ConnectionResetError, BrokenPipeError, ConnectionAbortedError) as exc:
return "refused", f"connection reset at {stage}: {type(exc).__name__}"
except OSError as exc:
return "error", f"{stage}: {type(exc).__name__}: {exc}" # unreachable etc. is NOT a refusal
def plaintext(ip: str, port: int) -> tuple[bool, str]:
"""True if a plaintext HTTP request got an HTTP answer (= a bypass)."""
try:
with socket.create_connection((ip, port), timeout=3) as s:
s.sendall(REQUEST)
data = s.recv(64)
if data.startswith(b"HTTP/"):
return True, "answered plaintext HTTP: " + data.split(b"\r\n")[0].decode("latin-1")
return False, "no HTTP answer (TLS-only listener)"
except OSError as exc:
return False, f"{type(exc).__name__}"
def main() -> int:
ips = sorted({info[4][0] for info in socket.getaddrinfo("api", PORT, socket.AF_INET, socket.SOCK_STREAM)})
print(f"API replicas behind DNS name `api`: {len(ips)}")
failures = 0
for ip in ips:
print(f"\nreplica {ip}:{PORT}")
for version in (ssl.TLSVersion.TLSv1_3, ssl.TLSVersion.TLSv1_2):
tag = "1.3" if version == ssl.TLSVersion.TLSv1_3 else "1.2"
for label, cert in CERTS.items():
outcome, detail = attempt(ip, cert, version)
good = outcome == EXPECT[label]
failures += not good
print(f" {'PASS' if good else 'FAIL'} TLS {tag} client cert {label:24s} -> {outcome:8s} {detail}")
for port, what in ((PORT, "plaintext HTTP to the mTLS port"), (HEALTH_PORT, "loopback health port from outside")):
bypass, detail = plaintext(ip, port)
failures += bypass
print(f" {'FAIL' if bypass else 'PASS'} {what:51s} -> {detail}")
if not ips:
failures += 1
print(f"\n{'PASS' if failures == 0 else 'FAIL'}: mTLS LB->API, {len(ips)} replica(s), {failures} failure(s)")
return 0 if failures == 0 else 1
if __name__ == "__main__":
sys.exit(main())