This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify the API's client-certificate and URI SAN allowlist on the TLS socket."""
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
|
||||
CA = "/run/pki/ca.crt"
|
||||
API_HOST = "api-1"
|
||||
API_TLS_NAME = "api"
|
||||
API_PORT = 8443
|
||||
|
||||
|
||||
def request(certificate=None, key=None, trust=CA):
|
||||
context = ssl.create_default_context(cafile=trust)
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
if certificate:
|
||||
context.load_cert_chain(certificate, key)
|
||||
raw_socket = socket.create_connection((API_HOST, API_PORT), timeout=5)
|
||||
with raw_socket:
|
||||
with context.wrap_socket(raw_socket, server_hostname=API_TLS_NAME) as tls:
|
||||
tls.sendall(
|
||||
b"GET /health/live HTTP/1.1\r\n"
|
||||
b"Host: api\r\n"
|
||||
b"Connection: close\r\n\r\n"
|
||||
)
|
||||
response = bytearray()
|
||||
while True:
|
||||
chunk = tls.recv(4096)
|
||||
if not chunk:
|
||||
break
|
||||
response.extend(chunk)
|
||||
status_line = bytes(response).split(b"\r\n", 1)[0]
|
||||
if not status_line:
|
||||
raise ConnectionError("server closed connection before returning HTTP")
|
||||
return int(status_line.split()[1])
|
||||
|
||||
|
||||
def must_fail_handshake(label, certificate=None, key=None, trust=CA):
|
||||
try:
|
||||
request(certificate, key, trust)
|
||||
except (ssl.SSLError, ConnectionError, OSError):
|
||||
print(f"PASS: {label} rejected before receiving an HTTP response")
|
||||
return
|
||||
raise AssertionError(f"{label} unexpectedly completed TLS handshake")
|
||||
|
||||
|
||||
def main():
|
||||
must_fail_handshake("missing client certificate")
|
||||
must_fail_handshake(
|
||||
"client certificate from an untrusted CA",
|
||||
"/run/pki/foreign-client.crt",
|
||||
"/run/pki/foreign-client.key",
|
||||
)
|
||||
wrong_identity_status = request(
|
||||
"/run/pki/worker-client.crt", "/run/pki/worker-client.key"
|
||||
)
|
||||
if wrong_identity_status != 401:
|
||||
raise AssertionError(
|
||||
f"trusted but unauthorized SAN returned HTTP {wrong_identity_status}, expected 401"
|
||||
)
|
||||
print("PASS: trusted client certificate with wrong URI SAN rejected by API")
|
||||
|
||||
allowed_status = request("/run/pki/lb-client.crt", "/run/pki/lb-client.key")
|
||||
if allowed_status != 200:
|
||||
raise AssertionError(
|
||||
f"allowlisted load-balancer identity returned HTTP {allowed_status}, expected 200"
|
||||
)
|
||||
print("PASS: allowlisted load-balancer URI SAN accepted")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (AssertionError, OSError, ssl.SSLError, ValueError) as exc:
|
||||
print(f"FAIL: {exc}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
Reference in New Issue
Block a user