Complete Lab 7 security and PKI track
This commit is contained in:
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run from the Compose security-test profile; never prints credential material."""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
|
||||
SECRETS = Path("/run/secrets")
|
||||
|
||||
|
||||
def request(host: str, server_name: str, context: ssl.SSLContext, cert: str | None = None, key: str | None = None, *, method: str = "GET", path: str = "/health/ready") -> bytes:
|
||||
if cert and key:
|
||||
cert_path = Path(cert)
|
||||
key_path = Path(key)
|
||||
context.load_cert_chain(
|
||||
str(cert_path if cert_path.is_absolute() else SECRETS / cert_path),
|
||||
str(key_path if key_path.is_absolute() else SECRETS / key_path),
|
||||
)
|
||||
with socket.create_connection((host, 8443), timeout=3) as raw:
|
||||
with context.wrap_socket(raw, server_hostname=server_name) as tls:
|
||||
tls.sendall(f"{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nContent-Length: 0\r\n\r\n".encode("ascii"))
|
||||
chunks = []
|
||||
while True:
|
||||
chunk = tls.recv(4096)
|
||||
if not chunk:
|
||||
break
|
||||
chunks.append(chunk)
|
||||
response = b"".join(chunks)
|
||||
return response
|
||||
|
||||
|
||||
def status_code(response: bytes) -> int:
|
||||
status = response.split(b"\r\n", 1)[0].split()
|
||||
if len(status) < 2:
|
||||
raise RuntimeError("peer returned no HTTP status")
|
||||
return int(status[1])
|
||||
|
||||
|
||||
def expect_tls_rejection(host: str, server_name: str, *, trusted_ca: bool = False) -> None:
|
||||
if trusted_ca:
|
||||
context = ssl.create_default_context(cafile=str(SECRETS / "internal-ca.crt"))
|
||||
else:
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
context.verify_mode = ssl.CERT_REQUIRED
|
||||
context.check_hostname = True
|
||||
try:
|
||||
request(host, server_name, context)
|
||||
except (ssl.SSLError, OSError):
|
||||
return
|
||||
raise AssertionError("untrusted TLS server was accepted")
|
||||
|
||||
|
||||
def expect_client_certificate_rejection(cert: str | None = None, key: str | None = None) -> int | None:
|
||||
context = ssl.create_default_context(cafile=str(SECRETS / "internal-ca.crt"))
|
||||
try:
|
||||
return status_code(request("api", "api", context, cert, key))
|
||||
except (ssl.SSLError, OSError):
|
||||
return None
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ca = ssl.create_default_context(cafile=str(SECRETS / "internal-ca.crt"))
|
||||
public_status = status_code(request("lb", "localhost", ca))
|
||||
assert public_status == 200, f"trusted public TLS ingress failed with HTTP {public_status}"
|
||||
expect_tls_rejection("lb", "localhost")
|
||||
expect_tls_rejection("lb", "wrong-host.invalid", trusted_ca=True)
|
||||
|
||||
no_certificate_status = expect_client_certificate_rejection()
|
||||
# Nginx may complete TLS and reject the HTTP request with its standard
|
||||
# 400 response when ssl_verify_client is on. A TLS alert (None) is also a
|
||||
# valid rejection; a successful or unrelated HTTP response is not.
|
||||
assert no_certificate_status in (None, 400), (
|
||||
f"API did not reject a request without a client certificate (HTTP {no_certificate_status})"
|
||||
)
|
||||
foreign_ca_status = expect_client_certificate_rejection(
|
||||
"negative-test-client.crt", "negative-test-client.key"
|
||||
)
|
||||
assert foreign_ca_status in (None, 400), (
|
||||
"API did not reject a correct-CN certificate from a foreign CA "
|
||||
f"(HTTP {foreign_ca_status})"
|
||||
)
|
||||
wrong_identity = expect_client_certificate_rejection("prometheus-client.crt", "prometheus-client.key")
|
||||
assert wrong_identity == 403, f"trusted but unauthorized identity returned {wrong_identity}"
|
||||
assert expect_client_certificate_rejection("lb-client.crt", "lb-client.key") == 200, "authorized LB identity failed"
|
||||
|
||||
previous_cert = Path("/revocation/lb-client.previous.crt")
|
||||
previous_key = Path("/revocation/lb-client.previous.key")
|
||||
if previous_cert.is_file() and previous_key.is_file():
|
||||
previous_status = expect_client_certificate_rejection(str(previous_cert), str(previous_key))
|
||||
assert previous_status in (None, 400), (
|
||||
"API accepted the revoked previous LB certificate "
|
||||
f"(HTTP {previous_status}); verify the mounted CRL and recreate API"
|
||||
)
|
||||
|
||||
expiry_cert = Path("/revocation/lb-client.expiry.crt")
|
||||
expiry_key = Path("/revocation/lb-client.expiry.key")
|
||||
if expiry_cert.is_file() and expiry_key.is_file():
|
||||
cert_info = ssl._ssl._test_decode_cert(str(expiry_cert))
|
||||
still_valid = ssl.cert_time_to_seconds(cert_info["notAfter"]) > time.time()
|
||||
expiry_status = expect_client_certificate_rejection(str(expiry_cert), str(expiry_key))
|
||||
if still_valid:
|
||||
assert expiry_status == 200, f"short-lived LB certificate failed before expiry (HTTP {expiry_status})"
|
||||
print("PASS: short-lived LB certificate accepted before expiry")
|
||||
else:
|
||||
assert expiry_status in (None, 400), (
|
||||
f"API accepted the expired LB certificate (HTTP {expiry_status})"
|
||||
)
|
||||
assert expect_client_certificate_rejection("lb-client.crt", "lb-client.key") == 200, (
|
||||
"valid replacement LB identity did not recover after the expiry rejection"
|
||||
)
|
||||
print("PASS: expired LB certificate rejected; current LB identity remains accepted")
|
||||
|
||||
rollover_cert = Path("/revocation/lb-client.rollover.crt")
|
||||
rollover_key = Path("/revocation/lb-client.rollover.key")
|
||||
if rollover_cert.is_file() and rollover_key.is_file():
|
||||
rollover_status = expect_client_certificate_rejection(str(rollover_cert), str(rollover_key))
|
||||
assert rollover_status == 200, (
|
||||
f"new-intermediate LB identity was not accepted during overlap (HTTP {rollover_status})"
|
||||
)
|
||||
print("PASS: LB identities signed by old and rollover intermediates are accepted during overlap")
|
||||
|
||||
throttled = []
|
||||
for _ in range(20):
|
||||
throttled.append(request("lb", "localhost", ca, method="POST", path="/api/v1/auth/sessions"))
|
||||
limited = [response for response in throttled if status_code(response) == 429]
|
||||
assert limited, "login requests did not reach the 429 rate limit"
|
||||
assert any(b"retry-after:" in response.lower() for response in limited), "429 response lacks Retry-After"
|
||||
if previous_cert.is_file() and previous_key.is_file():
|
||||
print("PASS: TLS trust, API client CA/identity, revoked prior LB certificate, login 429 and Retry-After")
|
||||
else:
|
||||
print("PASS: TLS trust, API client CA/identity, login 429 and Retry-After (no prior revoked LB cert staged)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user