Complete lab 7 security infrastructure
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Negative/positive mTLS checks against the local per-replica Nginx sidecar."""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
|
||||
TLS_DIR = Path("/run/tls")
|
||||
TEST_DIR = Path("/test")
|
||||
HOST = "127.0.0.1"
|
||||
PORT = 8443
|
||||
SERVER_NAME = "api.internal"
|
||||
|
||||
|
||||
def request(cert: tuple[Path, Path] | None) -> str:
|
||||
context = ssl.create_default_context(cafile=str(TLS_DIR / "service-ca.crt"))
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
if cert is not None:
|
||||
context.load_cert_chain(certfile=str(cert[0]), keyfile=str(cert[1]))
|
||||
with socket.create_connection((HOST, PORT), timeout=4) as raw:
|
||||
with context.wrap_socket(raw, server_hostname=SERVER_NAME) as tls:
|
||||
tls.settimeout(4)
|
||||
tls.sendall(b"GET /health/live HTTP/1.1\r\nHost: api.internal\r\nConnection: close\r\n\r\n")
|
||||
data = tls.recv(4096)
|
||||
if not data:
|
||||
return "NO_RESPONSE"
|
||||
return data.split(b"\r\n", 1)[0].decode("ascii", errors="replace")
|
||||
|
||||
|
||||
def expect_handshake_rejected(label: str, cert: tuple[Path, Path] | None) -> None:
|
||||
try:
|
||||
status = request(cert)
|
||||
except (ssl.SSLError, OSError, TimeoutError):
|
||||
print(f"PASS: {label}: TLS handshake rejected")
|
||||
return
|
||||
raise SystemExit(f"FAIL: {label}: unexpected TLS/application response: {status}")
|
||||
|
||||
|
||||
def expect_status(label: str, cert: tuple[Path, Path], expected: str) -> None:
|
||||
status = request(cert)
|
||||
if not status.startswith(expected):
|
||||
raise SystemExit(f"FAIL: {label}: expected {expected}, received {status}")
|
||||
print(f"PASS: {label}: {status}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
expect_handshake_rejected("missing client certificate", None)
|
||||
expect_handshake_rejected(
|
||||
"certificate from foreign CA",
|
||||
(TEST_DIR / "foreign-client.crt", TEST_DIR / "foreign-client.key"),
|
||||
)
|
||||
expect_status(
|
||||
"trusted CA but wrong client identity",
|
||||
(TEST_DIR / "wrong-lb-client.crt", TEST_DIR / "wrong-lb-client.key"),
|
||||
"HTTP/1.1 403",
|
||||
)
|
||||
expect_status(
|
||||
"trusted load-balancer identity",
|
||||
(TEST_DIR / "lb-client.crt", TEST_DIR / "lb-client.key"),
|
||||
"HTTP/1.1 200",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user