Files
mtusi2026lab7/student-tests/tls.py
T
gamayunov2004 9fb7dde29b
Skeleton contracts / contracts (pull_request) Canceled after 0s
ЛР 7: TLS, mTLS, OpenBao и безопасность — на 3
2026-11-22 06:03:17 +03:00

62 lines
2.7 KiB
Python

"""Verify names, mTLS handshake and peer authorization at each API replica."""
import http.client
import json
import socket
import ssl
from pathlib import Path
CA = Path("/run/ca")
CERT = Path("/run/probe")
def probe(host, port, hostname, cafile, identity=None, tls12=False):
ctx = ssl.create_default_context(cafile=str(CA / cafile))
if tls12:
ctx.maximum_version = ssl.TLSVersion.TLSv1_2
if identity:
ctx.load_cert_chain(CERT / identity / "client.crt", CERT / identity / "client.key")
with socket.create_connection((host, port), timeout=4) as wire:
stage = "TLS handshake"
try:
with ctx.wrap_socket(wire, server_hostname=hostname) as tls:
stage = "HTTP after TLS handshake"
tls.sendall(b"GET /health/ready HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
response = http.client.HTTPResponse(tls)
response.begin()
assert response.status == 200, response.status
return tls.version()
except OSError as exc:
exc.rejection_stage = stage
raise
def accepted(case, *args):
print(json.dumps({"case": case, "status": "PASS", "protocol": probe(*args)}))
def rejected(case, errors, stage, *args):
try:
probe(*args)
except errors as exc:
assert getattr(exc, "rejection_stage", None) == stage, (case, stage, type(exc).__name__)
reason = getattr(exc, "verify_message", None) or getattr(exc, "reason", None) or type(exc).__name__
print(json.dumps({"case": case, "status": "PASS", "stage": stage, "rejection": reason}))
else:
raise AssertionError(f"Accepted a rejected identity: {case}")
if __name__ == "__main__":
handshake = "TLS handshake"
accepted("trusted localhost", "localhost", 8443, "localhost", "public.crt")
rejected("foreign CA", ssl.SSLCertVerificationError, handshake, "localhost", 8443, "localhost", "unrelated.crt")
rejected("wrong hostname", ssl.SSLCertVerificationError, handshake, "localhost", 8443, "wrong.test", "public.crt")
for api in ("api1", "api2"):
backend = (api, 8444, api, "server.crt")
accepted(f"{api}: matching LB DNS SAN", *backend, "correct")
accepted(f"{api}: matching LB DNS SAN, TLS 1.2 control", *backend, "correct", True)
rejected(f"{api}: no client certificate", ssl.SSLError, handshake, *backend, None, True)
rejected(f"{api}: unrelated client CA", ssl.SSLError, handshake, *backend, "wrong-ca", True)
rejected(f"{api}: trusted issuer, disallowed DNS SAN",
(http.client.RemoteDisconnected, ConnectionResetError, ssl.SSLEOFError),
"HTTP after TLS handshake", *backend, "wrong-san")