#!/usr/bin/env python3 """Verify OpenBao rejects mismatched certificate identities.""" import json import ssl import sys import urllib.error import urllib.request from pathlib import Path PKI = Path.home() / ".local/share/mtusi2026lab7/pki" URL = "https://localhost:8200/v1" CASES = ( ("api1", "lab7-worker"), ("api2", "lab7-api1"), ("worker", "lab7-api2"), ) def verify(source, claimed_identity): tls = ssl.create_default_context( cafile=str(PKI / "ca.crt") ) tls.load_cert_chain( certfile=str( PKI / "openbao-clients" / f"{source}.crt" ), keyfile=str( PKI / "openbao-clients" / f"{source}.key" ), ) body = json.dumps({ "name": claimed_identity, }).encode("utf-8") req = urllib.request.Request( URL + "/auth/cert/login", data=body, headers={"Content-Type": "application/json"}, method="POST", ) try: with urllib.request.urlopen( req, context=tls, timeout=15, ) as response: data = json.load(response) except urllib.error.HTTPError as exc: if exc.code in (400, 403): print( f"PASS: {source} cannot authenticate " f"as {claimed_identity}" ) return raise RuntimeError( f"Unexpected authentication HTTP {exc.code}" ) from None # Defensive cleanup if an unexpected login succeeded. token = data.get("auth", {}).get("client_token") if token: revoke = urllib.request.Request( URL + "/auth/token/revoke-self", data=b"{}", headers={ "Content-Type": "application/json", "X-Vault-Token": token, }, method="POST", ) try: with urllib.request.urlopen( revoke, context=tls, timeout=15, ): pass except Exception: print( "WARNING: unexpected token revocation failed", file=sys.stderr, ) raise RuntimeError( f"Certificate identity substitution accepted: {source}" ) def main(): for source, claimed_identity in CASES: verify(source, claimed_identity) print("PASS: all certificate identity substitutions rejected") print("PASS: no credentials or tokens printed") if __name__ == "__main__": try: main() except Exception as exc: print( "FAIL: certificate identity test:", type(exc).__name__, file=sys.stderr, ) raise SystemExit(1)