Support client cert passwords, new TLS options (#118)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Support client cert passwords, new TLS options * Update test_config.py * Switch to try-except for post_handshake_auth=True SSLContext.post_handshake_auth raises AttributeError if the property is available but cannot be written to (needs OpenSSL 1.1.1+) * Also try-except for hostname_checks_common_name=False * Custom implementation of trustme.CA() that emits encrypted PKs * lint * Split name of test * Updates from review comments * Don't load default CAs yet
authored by Seth Michael Larson · committed by Tom Christie · parent 5442006 · Browse files · 4 files·+130 added−35 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+130 added−35 removed
- tests:+84 added−15 removed
- other:+46 added−20 removed
Provenance
- Commit
ba83e29- Tree
5f5adcf- Author
Seth Michael Larson <sethmichaellarson@gmail.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
5442006
4 files changed+130 added−35 removed
modified:http3/config.py+45 added-20 removed
5 unmodified lines6 import certifi7 8 from .__version__ import __version__9 10-CertTypes = typing.Union[str, typing.Tuple[str, str]]10+CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]11 VerifyTypes = typing.Union[str, bool]12 TimeoutTypes = typing.Union[float, typing.Tuple[float, float, float], "TimeoutConfig"]13 14 27 unmodified lines42 def __init__(self, *, cert: CertTypes = None, verify: VerifyTypes = True):43 self.cert = cert44 self.verify = verify45 46+ self.ssl_context: typing.Optional[ssl.SSLContext] = None47+48 def __eq__(self, other: typing.Any) -> bool:49 return (50 isinstance(other, self.__class__)51 and self.cert == other.cert13 unmodified lines65 return self66 return SSLConfig(cert=cert, verify=verify)67 68 async def load_ssl_context(self) -> ssl.SSLContext:67- if not hasattr(self, "ssl_context"):69+ if self.ssl_context is None:70 if not self.verify:71 self.ssl_context = self.load_ssl_context_no_verify()72 else:73 # Run the SSL loading in a threadpool, since it makes disk accesses.7 unmodified lines81 def load_ssl_context_no_verify(self) -> ssl.SSLContext:82 """83 Return an SSL context for unverified connections.84 """83- context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)84- context.options |= ssl.OP_NO_SSLv285- context.options |= ssl.OP_NO_SSLv386- context.options |= ssl.OP_NO_COMPRESSION87- context.set_default_verify_paths()85+ context = self._create_default_ssl_context()86+ context.verify_mode = ssl.CERT_NONE87+ context.check_hostname = False88 return context89 90 def load_ssl_context_verify(self) -> ssl.SSLContext:91 """8 unmodified lines100 "Could not find a suitable TLS CA certificate bundle, "101 "invalid path: {}".format(self.verify)102 )103 104- context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)105-104+ context = self._create_default_ssl_context()105 context.verify_mode = ssl.CERT_REQUIRED106+ context.check_hostname = True107 108- context.options |= ssl.OP_NO_SSLv2109- context.options |= ssl.OP_NO_SSLv3110- context.options |= ssl.OP_NO_COMPRESSION108+ # Signal to server support for PHA in TLS 1.3. Raises an109+ # AttributeError if only read-only access is implemented.110+ try:111+ context.post_handshake_auth = True112+ except AttributeError:113+ pass114 112- context.set_ciphers(DEFAULT_CIPHERS)115+ # Disable using 'commonName' for SSLContext.check_hostname116+ # when the 'subjectAltName' extension isn't available.117+ try:118+ context.hostname_checks_common_name = False119+ except AttributeError:120+ pass121 114- if ssl.HAS_ALPN:115- context.set_alpn_protocols(["h2", "http/1.1"])116- if ssl.HAS_NPN:117- context.set_npn_protocols(["h2", "http/1.1"])118-122 if os.path.isfile(ca_bundle_path):123 context.load_verify_locations(cafile=ca_bundle_path)124 elif os.path.isdir(ca_bundle_path):125 context.load_verify_locations(capath=ca_bundle_path)126 127 if self.cert is not None:128 if isinstance(self.cert, str):129 context.load_cert_chain(certfile=self.cert)127- else:130+ elif isinstance(self.cert, tuple) and len(self.cert) == 2:131 context.load_cert_chain(certfile=self.cert[0], keyfile=self.cert[1])132+ else:133+ context.load_cert_chain(134+ certfile=self.cert[0], keyfile=self.cert[1], password=self.cert[2]135+ )136 137 return context138 139+ def _create_default_ssl_context(self) -> ssl.SSLContext:140+ """141+ Creates the default SSLContext object that's used for both verified142+ and unverified connections.143+ """144+ context = ssl.SSLContext(ssl.PROTOCOL_TLS)145+ context.options |= ssl.OP_NO_SSLv2146+ context.options |= ssl.OP_NO_SSLv3147+ context.options |= ssl.OP_NO_COMPRESSION148+ context.set_ciphers(DEFAULT_CIPHERS)149 150+ if ssl.HAS_ALPN:151+ context.set_alpn_protocols(["h2", "http/1.1"])152+ if ssl.HAS_NPN:153+ context.set_npn_protocols(["h2", "http/1.1"])154+155+ return context156+157+158 class TimeoutConfig:159 """160 Timeout values.161 """37 unmodified lines199 )200 201 def __repr__(self) -> str:202 class_name = self.__class__.__name__178- if len(set([self.connect_timeout, self.read_timeout, self.write_timeout])) == 1:203+ if len({self.connect_timeout, self.read_timeout, self.write_timeout}) == 1:204 return f"{class_name}(timeout={self.connect_timeout})"205 return f"{class_name}(connect_timeout={self.connect_timeout}, read_timeout={self.read_timeout}, write_timeout={self.write_timeout})"206 207 34 unmodified linesmodified:tests/conftest.py+48 added-7 removed
1 import asyncio2 3 import pytest4 import trustme5+from cryptography.hazmat.primitives.serialization import (6+ BestAvailableEncryption,7+ Encoding,8+ PrivateFormat,9+)10 from uvicorn.config import Config11 from uvicorn.main import Server12 13 62 unmodified lines76 )77 await send({"type": "http.response.body", "body": body})78 79 80+class CAWithPKEncryption(trustme.CA):81+ """Implementation of trustme.CA() that can emit82+ private keys that are encrypted with a password.83+ """84+85+ @property86+ def encrypted_private_key_pem(self):87+ return trustme.Blob(88+ self._private_key.private_bytes(89+ Encoding.PEM,90+ PrivateFormat.TraditionalOpenSSL,91+ BestAvailableEncryption(password=b"password"),92+ )93+ )94+95+96 @pytest.fixture76-def cert_and_key_paths():77- ca = trustme.CA()97+def example_cert():98+ ca = CAWithPKEncryption()99 ca.issue_cert("example.org")79- with ca.cert_pem.tempfile() as cert_temp_path, ca.private_key_pem.tempfile() as key_temp_path:80- yield cert_temp_path, key_temp_path100+ return ca101 102 103 @pytest.fixture104+def cert_pem_file(example_cert):105+ with example_cert.cert_pem.tempfile() as tmp:106+ yield tmp107+108+109+@pytest.fixture110+def cert_private_key_file(example_cert):111+ with example_cert.private_key_pem.tempfile() as tmp:112+ yield tmp113+114+115+@pytest.fixture116+def cert_encrypted_private_key_file(example_cert):117+ with example_cert.encrypted_private_key_pem.tempfile() as tmp:118+ yield tmp119+120+121+@pytest.fixture122 async def server():123 config = Config(app=app, lifespan="off")124 server = Server(config=config)125 task = asyncio.ensure_future(server.serve())6 unmodified lines132 await task133 134 135 @pytest.fixture98-async def https_server(cert_and_key_paths):99- cert_path, key_path = cert_and_key_paths136+async def https_server(cert_pem_file, cert_private_key_file):137 config = Config(101- app=app, lifespan="off", ssl_certfile=cert_path, ssl_keyfile=key_path, port=8001138+ app=app,139+ lifespan="off",140+ ssl_certfile=cert_pem_file,141+ ssl_keyfile=cert_private_key_file,142+ port=8001,143 )144 server = Server(config=config)145 task = asyncio.ensure_future(server.serve())146 try:6 unmodified linesmodified:tests/test_config.py+36 added-8 removed
9 unmodified lines10 async def test_load_ssl_config():11 ssl_config = http3.SSLConfig()12 context = await ssl_config.load_ssl_context()13 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED14+ assert context.check_hostname is True15 16 17 @pytest.mark.asyncio18 async def test_load_ssl_config_verify_non_existing_path():6 unmodified lines25 async def test_load_ssl_config_verify_existing_file():26 ssl_config = http3.SSLConfig(verify=http3.config.DEFAULT_CA_BUNDLE_PATH)27 context = await ssl_config.load_ssl_context()28 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED29+ assert context.check_hostname is True30 31 32 @pytest.mark.asyncio33 async def test_load_ssl_config_verify_directory():34 path = os.path.dirname(http3.config.DEFAULT_CA_BUNDLE_PATH)35 ssl_config = http3.SSLConfig(verify=path)36 context = await ssl_config.load_ssl_context()37 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED38+ assert context.check_hostname is True39 40 41 @pytest.mark.asyncio39-async def test_load_ssl_config_cert_and_key(cert_and_key_paths):40- cert_path, key_path = cert_and_key_paths41- ssl_config = http3.SSLConfig(cert=(cert_path, key_path))42+async def test_load_ssl_config_cert_and_key(cert_pem_file, cert_private_key_file):43+ ssl_config = http3.SSLConfig(cert=(cert_pem_file, cert_private_key_file))44 context = await ssl_config.load_ssl_context()45 assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED46+ assert context.check_hostname is True47 48 49 @pytest.mark.asyncio47-async def test_load_ssl_config_cert_without_key_raises(cert_and_key_paths):48- cert_path, _ = cert_and_key_paths49- ssl_config = http3.SSLConfig(cert=cert_path)50+@pytest.mark.parametrize("password", [b"password", "password"])51+async def test_load_ssl_config_cert_and_encrypted_key(52+ cert_pem_file, cert_encrypted_private_key_file, password53+):54+ ssl_config = http3.SSLConfig(55+ cert=(cert_pem_file, cert_encrypted_private_key_file, password)56+ )57+ context = await ssl_config.load_ssl_context()58+ assert context.verify_mode == ssl.VerifyMode.CERT_REQUIRED59+ assert context.check_hostname is True60+61+62+@pytest.mark.asyncio63+async def test_load_ssl_config_cert_and_key_invalid_password(64+ cert_pem_file, cert_encrypted_private_key_file65+):66+ ssl_config = http3.SSLConfig(67+ cert=(cert_pem_file, cert_encrypted_private_key_file, "password1")68+ )69+70 with pytest.raises(ssl.SSLError):71 await ssl_config.load_ssl_context()72 73 74 @pytest.mark.asyncio55-async def test_load_ssl_config_no_verify(verify=False):75+async def test_load_ssl_config_cert_without_key_raises(cert_pem_file):76+ ssl_config = http3.SSLConfig(cert=cert_pem_file)77+ with pytest.raises(ssl.SSLError):78+ await ssl_config.load_ssl_context()79+80+81+@pytest.mark.asyncio82+async def test_load_ssl_config_no_verify():83 ssl_config = http3.SSLConfig(verify=False)84 context = await ssl_config.load_ssl_context()85 assert context.verify_mode == ssl.VerifyMode.CERT_NONE86+ assert context.check_hostname is False87 88 89 def test_ssl_repr():90 ssl = http3.SSLConfig(verify=False)38 unmodified lines129 assert timeout == http3.TimeoutConfig(timeout=5.0)130 131 132 def test_timeout_from_config_instance():105- timeout = http3.TimeoutConfig(timeout=(5.0))133+ timeout = http3.TimeoutConfig(timeout=5.0)134 assert http3.TimeoutConfig(timeout) == http3.TimeoutConfig(timeout=5.0)modified:requirements.txt+1 added
13 unmodified lines14 15 # Testing16 autoflake17 black18+cryptography19 isort20 mypy21 pytest22 pytest-asyncio3 unmodified lines