Implement Lab 7 security and 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,53 @@
|
||||
"""Internal mTLS negative/positive probes; run inside the API container."""
|
||||
import argparse
|
||||
import http.client
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
|
||||
|
||||
def probe(mode: str) -> int:
|
||||
context = ssl.create_default_context(cafile="/run/tls/ca.crt")
|
||||
headers = {"Host": "api", "X-Lab7-Client-Identity": "spiffe://lab7/ingress/nginx"}
|
||||
if mode == "positive":
|
||||
context.load_cert_chain("/run/tls/lb-client.crt", "/run/tls/lb-client.key")
|
||||
elif mode == "wrong-identity":
|
||||
context.load_cert_chain("/run/tls/lb-client.crt", "/run/tls/lb-client.key")
|
||||
headers["X-Lab7-Client-Identity"] = "spiffe://lab7/worker"
|
||||
elif mode == "foreign-ca":
|
||||
context.load_cert_chain("/tmp/foreign-client.crt", "/tmp/foreign-client.key")
|
||||
elif mode != "no-cert":
|
||||
raise ValueError(mode)
|
||||
|
||||
try:
|
||||
raw = socket.create_connection(("127.0.0.1", 8443), timeout=4)
|
||||
tls = context.wrap_socket(raw, server_hostname="api")
|
||||
request = "GET /health/live HTTP/1.1\r\n"
|
||||
request += "".join(f"{k}: {v}\r\n" for k, v in headers.items())
|
||||
request += "Connection: close\r\n\r\n"
|
||||
tls.sendall(request.encode())
|
||||
response = tls.recv(4096).decode("latin1", errors="replace")
|
||||
tls.close()
|
||||
status = int(response.split(" ", 2)[1])
|
||||
except (ssl.SSLError, OSError) as exc:
|
||||
if mode in {"no-cert", "foreign-ca"}:
|
||||
print(f"PASS: {mode} rejected during TLS handshake ({type(exc).__name__})")
|
||||
return 0
|
||||
raise
|
||||
|
||||
if mode == "positive" and status == 200:
|
||||
print("PASS: allowed ingress identity accepted")
|
||||
return 0
|
||||
if mode == "wrong-identity" and status == 403:
|
||||
print("PASS: non-ingress identity rejected by API authorization")
|
||||
return 0
|
||||
if mode in {"no-cert", "foreign-ca"}:
|
||||
raise AssertionError(f"{mode} unexpectedly reached HTTP status {status}")
|
||||
raise AssertionError(f"{mode} expected its security outcome, got HTTP {status}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("mode", choices=["no-cert", "foreign-ca", "wrong-identity", "positive"])
|
||||
args = parser.parse_args()
|
||||
sys.exit(probe(args.mode))
|
||||
Reference in New Issue
Block a user