Skip to content
Myr

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

4 files+130 added−35 removed

modified:http3/config.py+45 added-20 removed
5 unmodified lines
6import certifi78from .__version__ import __version__910CertTypes = typing.Union[str, typing.Tuple[str, str]]10CertTypes = typing.Union[str, typing.Tuple[str, str], typing.Tuple[str, str, str]]11VerifyTypes = typing.Union[str, bool]12TimeoutTypes = typing.Union[float, typing.Tuple[float, float, float], "TimeoutConfig"]1314
27 unmodified lines
42 def __init__(self, *, cert: CertTypes = None, verify: VerifyTypes = True):43 self.cert = cert44 self.verify = verify4546 self.ssl_context: typing.Optional[ssl.SSLContext] = None4748 def __eq__(self, other: typing.Any) -> bool:49 return (50 isinstance(other, self.__class__)51 and self.cert == other.cert
13 unmodified lines
65 return self66 return SSLConfig(cert=cert, verify=verify)6768 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 lines
81 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 context8990 def load_ssl_context_verify(self) -> ssl.SSLContext:91 """
8 unmodified lines
100 "Could not find a suitable TLS CA certificate bundle, "101 "invalid path: {}".format(self.verify)102 )103104 context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)105104 context = self._create_default_ssl_context()105 context.verify_mode = ssl.CERT_REQUIRED106 context.check_hostname = True107108 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 pass114112 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 pass121114 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"])118122 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)126127 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 )136137 return context138139 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)149150 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"])154155 return context156157158class TimeoutConfig:159 """160 Timeout values.161 """
37 unmodified lines
199 )200201 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})"206207
34 unmodified lines
modified:tests/conftest.py+48 added-7 removed
1import asyncio23import pytest4import trustme5from cryptography.hazmat.primitives.serialization import (6 BestAvailableEncryption,7 Encoding,8 PrivateFormat,9)10from uvicorn.config import Config11from uvicorn.main import Server1213
62 unmodified lines
76 )77 await send({"type": "http.response.body", "body": body})787980class CAWithPKEncryption(trustme.CA):81 """Implementation of trustme.CA() that can emit82 private keys that are encrypted with a password.83 """8485 @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 )949596@pytest.fixture76def cert_and_key_paths():77 ca = trustme.CA()97def 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 ca101102103@pytest.fixture104def cert_pem_file(example_cert):105 with example_cert.cert_pem.tempfile() as tmp:106 yield tmp107108109@pytest.fixture110def cert_private_key_file(example_cert):111 with example_cert.private_key_pem.tempfile() as tmp:112 yield tmp113114115@pytest.fixture116def cert_encrypted_private_key_file(example_cert):117 with example_cert.encrypted_private_key_pem.tempfile() as tmp:118 yield tmp119120121@pytest.fixture122async def server():123 config = Config(app=app, lifespan="off")124 server = Server(config=config)125 task = asyncio.ensure_future(server.serve())
6 unmodified lines
132 await task133134135@pytest.fixture98async def https_server(cert_and_key_paths):99 cert_path, key_path = cert_and_key_paths136async 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 lines
modified:tests/test_config.py+36 added-8 removed
9 unmodified lines
10async 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 True151617@pytest.mark.asyncio18async def test_load_ssl_config_verify_non_existing_path():
6 unmodified lines
25async 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 True303132@pytest.mark.asyncio33async 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 True394041@pytest.mark.asyncio39async 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))42async 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 True474849@pytest.mark.asyncio47async 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"])51async 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 True606162@pytest.mark.asyncio63async 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 )6970 with pytest.raises(ssl.SSLError):71 await ssl_config.load_ssl_context()727374@pytest.mark.asyncio55async def test_load_ssl_config_no_verify(verify=False):75async 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()798081@pytest.mark.asyncio82async 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 False878889def test_ssl_repr():90 ssl = http3.SSLConfig(verify=False)
38 unmodified lines
129 assert timeout == http3.TimeoutConfig(timeout=5.0)130131132def 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 lines
1415# Testing16autoflake17black18cryptography19isort20mypy21pytest22pytest-asyncio
3 unmodified lines