Skip to content
Myr

config.py

This file

Path

http3/config.py

241 lines · 7.7 KiB · Python

Last changed by

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

History of this file

Take it

1import asyncio2import os3import ssl4import typing56import certifi78from .__version__ import __version__910CertTypes = 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"]131415USER_AGENT = f"python-http3/{__version__}"1617DEFAULT_CIPHERS = ":".join(18    [19        "ECDHE+AESGCM",20        "ECDHE+CHACHA20",21        "DHE+AESGCM",22        "DHE+CHACHA20",23        "ECDH+AESGCM",24        "DH+AESGCM",25        "ECDH+AES",26        "DH+AES",27        "RSA+AESGCM",28        "RSA+AES",29        "!aNULL",30        "!eNULL",31        "!MD5",32        "!DSS",33    ]34)353637class SSLConfig:38    """39    SSL Configuration.40    """4142    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.cert52            and self.verify == other.verify53        )5455    def __repr__(self) -> str:56        class_name = self.__class__.__name__57        return f"{class_name}(cert={self.cert}, verify={self.verify})"5859    def with_overrides(60        self, cert: CertTypes = None, verify: VerifyTypes = None61    ) -> "SSLConfig":62        cert = self.cert if cert is None else cert63        verify = self.verify if verify is None else verify64        if (cert == self.cert) and (verify == self.verify):65            return self66        return SSLConfig(cert=cert, verify=verify)6768    async def load_ssl_context(self) -> ssl.SSLContext: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.74                loop = asyncio.get_event_loop()75                self.ssl_context = await loop.run_in_executor(76                    None, self.load_ssl_context_verify77                )7879        return self.ssl_context8081    def load_ssl_context_no_verify(self) -> ssl.SSLContext:82        """83        Return an SSL context for unverified connections.84        """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        """92        Return an SSL context for verified connections.93        """94        if isinstance(self.verify, bool):95            ca_bundle_path = DEFAULT_CA_BUNDLE_PATH96        elif os.path.exists(self.verify):97            ca_bundle_path = self.verify98        else:99            raise IOError(100                "Could not find a suitable TLS CA certificate bundle, "101                "invalid path: {}".format(self.verify)102            )103104        context = self._create_default_ssl_context()105        context.verify_mode = ssl.CERT_REQUIRED106        context.check_hostname = True107108        # 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            pass114115        # 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            pass121122        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)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    """162163    def __init__(164        self,165        timeout: TimeoutTypes = None,166        *,167        connect_timeout: float = None,168        read_timeout: float = None,169        write_timeout: float = None,170    ):171        if timeout is None:172            self.connect_timeout = connect_timeout173            self.read_timeout = read_timeout174            self.write_timeout = write_timeout175        else:176            # Specified as a single timeout value177            assert connect_timeout is None178            assert read_timeout is None179            assert write_timeout is None180            if isinstance(timeout, TimeoutConfig):181                self.connect_timeout = timeout.connect_timeout182                self.read_timeout = timeout.read_timeout183                self.write_timeout = timeout.write_timeout184            elif isinstance(timeout, tuple):185                self.connect_timeout = timeout[0]186                self.read_timeout = timeout[1]187                self.write_timeout = timeout[2]188            else:189                self.connect_timeout = timeout190                self.read_timeout = timeout191                self.write_timeout = timeout192193    def __eq__(self, other: typing.Any) -> bool:194        return (195            isinstance(other, self.__class__)196            and self.connect_timeout == other.connect_timeout197            and self.read_timeout == other.read_timeout198            and self.write_timeout == other.write_timeout199        )200201    def __repr__(self) -> str:202        class_name = self.__class__.__name__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})"206207208class PoolLimits:209    """210    Limits on the number of connections in a connection pool.211    """212213    def __init__(214        self,215        *,216        soft_limit: int = None,217        hard_limit: int = None,218        pool_timeout: float = None,219    ):220        self.soft_limit = soft_limit221        self.hard_limit = hard_limit222        self.pool_timeout = pool_timeout223224    def __eq__(self, other: typing.Any) -> bool:225        return (226            isinstance(other, self.__class__)227            and self.soft_limit == other.soft_limit228            and self.hard_limit == other.hard_limit229            and self.pool_timeout == other.pool_timeout230        )231232    def __repr__(self) -> str:233        class_name = self.__class__.__name__234        return f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit}, pool_timeout={self.pool_timeout})"235236237DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)238DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)239DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100, pool_timeout=5.0)240DEFAULT_CA_BUNDLE_PATH = certifi.where()241DEFAULT_MAX_REDIRECTS = 20