127 lines
7.0 KiB
Python
127 lines
7.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Lab 7 TLS audit of the whole trust matrix. Runs INSIDE the backend network (see security-tests/run_in_net.sh) with ./secrets/pki mounted at /pki.
|
|
|
|
Every row is a positive or a negative probe; "rejected" means: handshake/ACL/auth error, never "server unavailable".
|
|
Exit code 0 only if every probe behaved as expected.
|
|
"""
|
|
import socket
|
|
import ssl
|
|
import sys
|
|
|
|
P = "/pki"
|
|
CA = f"{P}/ca/ca.crt"
|
|
RESULTS = []
|
|
|
|
|
|
def ctx(ca=CA, cert=None, check=True):
|
|
c = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
|
if ca:
|
|
c.load_verify_locations(ca)
|
|
c.check_hostname = check
|
|
c.verify_mode = ssl.CERT_REQUIRED
|
|
if cert:
|
|
c.load_cert_chain(f"{P}/{cert}/tls.crt", f"{P}/{cert}/tls.key")
|
|
return c
|
|
|
|
|
|
def tls_get(host, port, path="/", c=None, sni=None):
|
|
"""returns the HTTP status line, or the exception class name when the connection is refused/reset/verification fails."""
|
|
try:
|
|
with socket.create_connection((host, port), timeout=5) as raw:
|
|
with (c or ctx()).wrap_socket(raw, server_hostname=sni or host) as s:
|
|
s.sendall(f"GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n".encode())
|
|
data = s.recv(200)
|
|
return data.split(b"\r\n")[0].decode() if data else "EmptyReply" # TLS 1.3: a refused client cert shows up here
|
|
except (ssl.SSLError, OSError) as exc:
|
|
return type(exc).__name__
|
|
|
|
|
|
def plain(host, port):
|
|
"""Plain-text probe. A TLS-only server may still answer with 'HTTP/1.x 400 ... HTTPS server': that is a REFUSAL, not an accepted plaintext request."""
|
|
try:
|
|
with socket.create_connection((host, port), timeout=3) as s:
|
|
s.sendall(b"GET / HTTP/1.0\r\n\r\n")
|
|
data = s.recv(300)
|
|
if not data:
|
|
return "Closed"
|
|
if not data.startswith(b"HTTP"):
|
|
return "NoHTTP"
|
|
return "TLS_ONLY" if (b"HTTPS" in data or data.split(b"\r\n")[0].split(b" ")[1:2] == [b"400"]) else "ANSWERED"
|
|
except OSError as exc:
|
|
return type(exc).__name__
|
|
|
|
|
|
def expect(name, got, ok):
|
|
RESULTS.append((name, got, ok))
|
|
print(("PASS " if ok else "FAIL ") + f"{name}: {got}")
|
|
|
|
|
|
def accepted(r):
|
|
"""The server completed TLS and answered with any HTTP status (2xx/3xx/4xx/5xx)."""
|
|
return r.startswith("HTTP/1.") and r.split(" ")[1][:1] in "2345"
|
|
|
|
|
|
def refused(r):
|
|
"""A real refusal (handshake/verify error, reset, empty reply). DNS failures and timeouts mean 'service not reachable' and must NOT count as refusal."""
|
|
return not accepted(r) and r not in ("gaierror", "TimeoutError", "timeout")
|
|
|
|
|
|
def kafka_produce(cert):
|
|
from confluent_kafka import KafkaException, Producer
|
|
errors = []
|
|
p = Producer({"bootstrap.servers": "kafka:9092", "security.protocol": "SSL", "ssl.ca.location": CA,
|
|
"ssl.certificate.location": f"{P}/{cert}/tls.crt", "ssl.key.location": f"{P}/{cert}/tls.key",
|
|
"message.timeout.ms": 8000, "enable.idempotence": True})
|
|
try:
|
|
p.produce("attachment-jobs", b"audit-probe", on_delivery=lambda e, m: errors.append(str(e) if e else "OK"))
|
|
p.flush(10)
|
|
except KafkaException as exc: # idempotent producer: denied IdempotentWrite on the cluster surfaces here (also an authorization refusal)
|
|
return str(exc)
|
|
return errors[0] if errors else "NoDelivery"
|
|
|
|
|
|
def main():
|
|
# 1. LB -> API (mTLS + identity allowlist)
|
|
r = tls_get("api", 8443, "/health/live", ctx(cert="lb"), sni="api"); expect("api: lb identity accepted", r, accepted(r))
|
|
r = tls_get("api", 8443, "/health/live", sni="api"); expect("api: no client cert refused", r, refused(r))
|
|
r = tls_get("api", 8443, "/health/live", ctx(cert="rogue", ca=CA), sni="api"); expect("api: foreign-CA cert refused", r, refused(r))
|
|
r = tls_get("api", 8443, "/health/live", ctx(cert="outsider"), sni="api"); expect("api: same-CA, wrong identity (outsider) refused", r, refused(r))
|
|
r = tls_get("api", 8443, "/health/live", ctx(cert="worker"), sni="api"); expect("api: worker identity refused", r, refused(r))
|
|
r = tls_get("api", 8443, "/health/live", ctx(ca="/pki/rogue/rogue-ca.crt", cert="lb"), sni="api"); expect("api: client distrusting server CA fails verification", r, r == "SSLCertVerificationError")
|
|
# 2. Collector (mTLS, workload CA only)
|
|
for who in ("api", "worker", "dispatcher"):
|
|
r = tls_get("otel-collector", 4318, "/", ctx(cert=who)); expect(f"collector: {who} identity accepted", r, accepted(r))
|
|
for who in ("outsider", "grafana", "lb"):
|
|
r = tls_get("otel-collector", 4318, "/", ctx(cert=who)); expect(f"collector: {who} (same root CA, not a workload) refused", r, refused(r))
|
|
r = tls_get("otel-collector", 4318, "/"); expect("collector: no client cert refused", r, refused(r))
|
|
expect("collector: plaintext refused", plain("otel-collector", 4318), plain("otel-collector", 4318) != "ANSWERED")
|
|
# 3. Kafka (mTLS + ACL by CN)
|
|
r = kafka_produce("dispatcher"); expect("kafka: dispatcher may produce", r, r == "OK")
|
|
r = kafka_produce("worker"); expect("kafka: worker may NOT produce", r, "AUTHORIZATION" in r.upper())
|
|
r = kafka_produce("outsider"); expect("kafka: CA-signed outsider may NOT produce", r, "AUTHORIZATION" in r.upper())
|
|
r = kafka_produce("api"); expect("kafka: api identity may NOT produce", r, "AUTHORIZATION" in r.upper())
|
|
expect("kafka: plaintext refused", plain("kafka", 9092), plain("kafka", 9092) != "ANSWERED")
|
|
# 4. Stores and backends: TLS only, server verified
|
|
for host, port in (("postgres", 5432), ("redis", 6379), ("s3", 9000), ("openbao", 8200), ("prometheus", 9090), ("loki", 3100), ("tempo", 3200)):
|
|
r = tls_get(host, port, "/", ctx(ca="/pki/rogue/rogue-ca.crt")); expect(f"{host}: foreign CA -> verification error", r, r == "SSLCertVerificationError" or r.startswith("SSL"))
|
|
for host, port in (("prometheus", 9090), ("loki", 3100), ("tempo", 3200)):
|
|
r = tls_get(host, port, "/ready"); expect(f"{host}: no client cert refused (mTLS)", r, refused(r))
|
|
r = tls_get(host, port, "/", ctx(cert="grafana")); expect(f"{host}: client cert accepted", r, accepted(r))
|
|
r = tls_get("s3", 9000, "/minio/health/live"); expect("s3: TLS with verification works", r, accepted(r))
|
|
r = tls_get("openbao", 8200, "/v1/sys/health"); expect("openbao: TLS with verification works", r, accepted(r))
|
|
for host, port in (("redis", 6379), ("s3", 9000), ("openbao", 8200)):
|
|
expect(f"{host}: plaintext refused", plain(host, port), plain(host, port) != "ANSWERED")
|
|
try:
|
|
import psycopg
|
|
psycopg.connect(host="postgres", user="messenger_api", password="x", dbname="messenger", sslmode="disable", connect_timeout=3)
|
|
expect("postgres: sslmode=disable refused", "connected", False)
|
|
except Exception as exc:
|
|
expect("postgres: sslmode=disable refused (pg_hba reject)", type(exc).__name__, "pg_hba" in str(exc) or "SSL" in str(exc).upper())
|
|
bad = [n for n, _, ok in RESULTS if not ok]
|
|
print(f"\n{len(RESULTS) - len(bad)}/{len(RESULTS)} probes as expected")
|
|
sys.exit(1 if bad else 0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|