Files
mtusi2026lab7/scripts/verify_security.py
T
2026-11-28 12:29:50 +01:00

138 lines
6.6 KiB
Python

#!/usr/bin/env python3
"""Level-3 negative checks: internal mTLS identity and scoped OpenBao policy."""
import datetime as dt
import json
import ssl
import urllib.error
import urllib.request
from pathlib import Path
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
ROOT = Path(__file__).resolve().parents[1]
CERTS = ROOT / "certs"
PRIVATE = CERTS / "private"
def https(url, cert=None, key=None, cafile=None, data=None, headers=None, timeout=8, method=None):
context = ssl.create_default_context(cafile=str(cafile or CERTS / "ca.crt"))
if cert:
context.load_cert_chain(str(cert), str(key))
request = urllib.request.Request(
url, data=data, headers=headers or {}, method=method or ("POST" if data is not None else "GET"))
try:
with urllib.request.urlopen(request, context=context, timeout=timeout) as response:
return response.status, response.read(), dict(response.headers)
except urllib.error.HTTPError as exc:
return exc.code, exc.read(), dict(exc.headers)
except (urllib.error.URLError, ssl.SSLError, OSError) as exc:
return 0, str(exc).encode(), {}
def make_rogue_client():
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
ca_key = serialization.load_pem_private_key((PRIVATE / "ca.key").read_bytes(), password=None)
ca_cert = x509.load_pem_x509_certificate((CERTS / "ca.crt").read_bytes())
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "evil-lb")])
cert = (x509.CertificateBuilder()
.subject_name(subject).issuer_name(ca_cert.subject).public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=5))
.not_valid_after(dt.datetime.now(dt.timezone.utc) + dt.timedelta(hours=1))
.add_extension(x509.SubjectAlternativeName([x509.DNSName("evil-lb")]), critical=False)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]), critical=False)
.sign(ca_key, hashes.SHA256()))
(PRIVATE / "rogue-lb.key").write_bytes(key.private_bytes(
serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL,
serialization.NoEncryption()))
(CERTS / "rogue-lb.crt").write_bytes(cert.public_bytes(serialization.Encoding.PEM))
def main():
url = "https://api1:8443/health/ready" # direct API port, bypassing the LB
host_ctx = None
# Resolve api1 through Docker DNS: run checks from the host against published LB
# for lack of DNS, so we use the container network via a temporary helper.
# Here we verify the API's client-cert requirement through the LB's upstream:
# the LB always presents a valid identity; a direct no-cert probe must fail.
status, body, _ = https("https://localhost:8443/health/ready")
assert status == 200, "valid trusted HTTPS failed: %s" % body[:100]
print("TLS OK: trusted CA and hostname accepted")
# Direct API probes are executed inside the api1 container (Docker DNS + network).
import subprocess
script = (
"import ssl,urllib.request;"
"c=ssl.create_default_context(cafile='/certs/ca.crt');"
"print(urllib.request.urlopen('https://api1:8443/health/ready',context=c,timeout=3).status)"
)
result = subprocess.run(
["docker", "compose", "--env-file", ".env", "exec", "-T", "api1", "python", "-c", script],
cwd=str(ROOT), capture_output=True, text=True)
assert result.returncode != 0, "API accepted a client without a certificate"
print("MTLS OK: no client certificate rejected by API")
make_rogue_client()
script = (
"import ssl,urllib.request;"
"c=ssl.create_default_context(cafile='/certs/ca.crt');"
"c.load_cert_chain('/certs/rogue-lb.crt','/certs/private/rogue-lb.key');"
"print(urllib.request.urlopen('https://api1:8443/health/ready',context=c,timeout=3).status)"
)
result = subprocess.run(
["docker", "compose", "--env-file", ".env", "exec", "-T", "api1", "python", "-c", script],
cwd=str(ROOT), capture_output=True, text=True)
assert result.returncode != 0, "API accepted a trusted-CA but unauthorized identity"
print("MTLS OK: trusted-CA but wrong identity rejected by API")
# OpenBao: scoped AppRole may read its own path, not write it or read others.
creds = json.loads((PRIVATE / "bao-approle.json").read_text())
ctx = ssl.create_default_context(cafile=str(CERTS / "ca.crt"))
login = urllib.request.Request(
"https://localhost:8200/v1/auth/approle/login",
data=json.dumps(creds).encode(), headers={"Content-Type": "application/json"}, method="POST")
with urllib.request.urlopen(login, context=ctx, timeout=8) as response:
token = json.loads(response.read())["auth"]["client_token"]
def bao(path, method="GET", body=None):
request = urllib.request.Request(
"https://localhost:8200/v1/" + path,
data=json.dumps(body).encode() if body else None,
headers={"X-Vault-Token": token, "Content-Type": "application/json"}, method=method)
try:
with urllib.request.urlopen(request, context=ctx, timeout=8) as response:
return response.status
except urllib.error.HTTPError as exc:
return exc.code
assert bao("secret/data/messenger/app") == 200
assert bao("secret/data/messenger/other") == 403
assert bao("secret/data/messenger/app", "POST", {"data": {"x": "y"}}) == 403
print("BAO OK: own path readable; write and foreign path denied")
# Login rate limit: the sixth attempt in a minute is rejected with Retry-After.
import base64
import uuid
user = "u_rate_" + uuid.uuid4().hex[:10]
credential = base64.b64encode((user + ":wrong-password-123").encode()).decode()
statuses = []
last_headers = {}
for _ in range(6):
status, _, headers = https(
"https://localhost:8443/api/v1/auth/sessions",
headers={"Authorization": "Basic " + credential}, method="POST",
)
statuses.append(status)
last_headers = headers
assert statuses[:5] == [401] * 5, "unexpected login statuses: %s" % statuses
retry_after = next((v for k, v in last_headers.items() if k.lower() == "retry-after"), None)
assert statuses[5] == 429 and retry_after, "429/Retry-After missing"
print("RATE OK: 5x401 then 429 with Retry-After=%s" % retry_after)
if __name__ == "__main__":
main()