#!/usr/bin/env python3 """Check that certificate-profile compatibility does not disable trust/hostname checks.""" import ssl, subprocess, tempfile, threading, urllib.request, urllib.error from pathlib import Path from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from tls import application_context class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200); self.end_headers() def log_message(self,*args): pass with tempfile.TemporaryDirectory() as temp: root=Path(temp); cert=root/'cert.pem'; key=root/'key.pem' subprocess.run(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-days','1','-keyout',str(key),'-out',str(cert),'-subj','/CN=127.0.0.1','-addext','subjectAltName=IP:127.0.0.1'],check=True,capture_output=True) server=ThreadingHTTPServer(('127.0.0.1',0),Handler) context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);context.load_cert_chain(cert,key) server.socket=context.wrap_socket(server.socket,server_side=True) threading.Thread(target=server.serve_forever,daemon=True).start() try: trusted=application_context(str(cert)) with urllib.request.urlopen(f'https://127.0.0.1:{server.server_port}',context=trusted,timeout=3) as r:assert r.status==200 for host,ctx in [('localhost',trusted),('127.0.0.1',ssl.create_default_context())]: try:urllib.request.urlopen(f'https://{host}:{server.server_port}',context=ctx,timeout=3) except urllib.error.URLError as e:assert isinstance(e.reason,ssl.SSLCertVerificationError) else:raise AssertionError('Invalid certificate accepted') print('TLS passed: trusted CA accepted; wrong hostname and untrusted CA rejected') finally:server.shutdown();server.server_close()