tlslib.tlslib

Abstract interface to TLS for Python.

  1"""Abstract interface to TLS for Python."""
  2
  3from __future__ import annotations
  4
  5import os
  6from abc import abstractmethod
  7from collections.abc import Buffer, Callable, Sequence
  8from enum import Enum, IntEnum
  9from typing import Generic, Protocol, TypeVar
 10
 11__all__ = [
 12    "TLSBuffer",
 13    "TLSServerConfiguration",
 14    "TLSClientConfiguration",
 15    "ClientContext",
 16    "ServerContext",
 17    "CipherSuite",
 18    "NextProtocol",
 19    "TLSVersion",
 20    "TLSError",
 21    "WantWriteError",
 22    "WantReadError",
 23    "RaggedEOF",
 24    "Certificate",
 25    "PrivateKey",
 26    "TLSImplementation",
 27]
 28
 29
 30class TrustStore:
 31    """
 32    The trust store that is used to verify certificate validity.
 33    """
 34
 35    __slots__ = (
 36        "_buffer",
 37        "_path",
 38        "_id",
 39    )
 40
 41    def __init__(
 42        self, buffer: bytes | None = None, path: os.PathLike | None = None, id: bytes | None = None
 43    ):
 44        """
 45        Creates a TrustStore object from a path, buffer, or ID.
 46
 47        If none of these is given, the default system trust store is used.
 48        """
 49
 50        self._buffer = buffer
 51        self._path = path
 52        self._id = id
 53
 54    @classmethod
 55    def system(cls) -> TrustStore:
 56        """
 57        Returns a TrustStore object that represents the system trust
 58        database.
 59        """
 60        return cls()
 61
 62    @classmethod
 63    def from_buffer(cls, buffer: bytes) -> TrustStore:
 64        """
 65        Initializes a trust store from a buffer of PEM-encoded certificates.
 66        """
 67        return cls(buffer=buffer)
 68
 69    @classmethod
 70    def from_file(cls, path: os.PathLike) -> TrustStore:
 71        """
 72        Initializes a trust store from a single file containing PEMs.
 73        """
 74        return cls(path=path)
 75
 76    @classmethod
 77    def from_id(cls, id: bytes) -> TrustStore:
 78        """
 79        Initializes a trust store from an arbitrary identifier.
 80        """
 81        return cls(id=id)
 82
 83
 84class Certificate:
 85    """Object representing a certificate used in TLS."""
 86
 87    __slots__ = (
 88        "_buffer",
 89        "_path",
 90        "_id",
 91    )
 92
 93    def __init__(
 94        self, buffer: bytes | None = None, path: os.PathLike | None = None, id: bytes | None = None
 95    ):
 96        """
 97        Creates a Certificate object from a path, buffer, or ID.
 98
 99        If none of these is given, an exception is raised.
100        """
101
102        if buffer is None and path is None and id is None:
103            raise ValueError("Certificate cannot be empty.")
104
105        self._buffer = buffer
106        self._path = path
107        self._id = id
108
109    @classmethod
110    def from_buffer(cls, buffer: bytes) -> Certificate:
111        """
112        Creates a Certificate object from a byte buffer. This byte buffer
113        may be either PEM-encoded or DER-encoded. If the buffer is PEM
114        encoded it *must* begin with the standard PEM preamble (a series of
115        dashes followed by the ASCII bytes "BEGIN CERTIFICATE" and another
116        series of dashes). In the absence of that preamble, the
117        implementation may assume that the certificate is DER-encoded
118        instead.
119        """
120        return cls(buffer=buffer)
121
122    @classmethod
123    def from_file(cls, path: os.PathLike) -> Certificate:
124        """
125        Creates a Certificate object from a file on disk. The file on disk
126        should contain a series of bytes corresponding to a certificate that
127        may be either PEM-encoded or DER-encoded. If the bytes are PEM encoded
128        it *must* begin with the standard PEM preamble (a series of dashes
129        followed by the ASCII bytes "BEGIN CERTIFICATE" and another series of
130        dashes). In the absence of that preamble, the implementation may
131        assume that the certificate is DER-encoded instead.
132        """
133        return cls(path=path)
134
135    @classmethod
136    def from_id(cls, id: bytes) -> Certificate:
137        """
138        Creates a Certificate object from an arbitrary identifier. This may
139        be useful for implementations that rely on system certificate stores.
140        """
141        return cls(id=id)
142
143
144class PrivateKey:
145    """Object representing a private key corresponding to a public key
146    for a certificate used in TLS."""
147
148    __slots__ = (
149        "_buffer",
150        "_path",
151        "_id",
152    )
153
154    def __init__(
155        self, buffer: bytes | None = None, path: os.PathLike | None = None, id: bytes | None = None
156    ):
157        """
158        Creates a PrivateKey object from a path, buffer, or ID.
159
160        If none of these is given, an exception is raised.
161        """
162
163        if buffer is None and path is None and id is None:
164            raise ValueError("PrivateKey cannot be empty.")
165
166        self._buffer = buffer
167        self._path = path
168        self._id = id
169
170    @classmethod
171    def from_buffer(cls, buffer: bytes) -> PrivateKey:
172        """
173        Creates a PrivateKey object from a byte buffer. This byte buffer
174        may be either PEM-encoded or DER-encoded. If the buffer is PEM
175        encoded it *must* begin with the standard PEM preamble (a series of
176        dashes followed by the ASCII bytes "BEGIN", the key type, and
177        another series of dashes). In the absence of that preamble, the
178        implementation may assume that the private key is DER-encoded
179        instead.
180        """
181        return cls(buffer=buffer)
182
183    @classmethod
184    def from_file(cls, path: os.PathLike) -> PrivateKey:
185        """
186        Creates a PrivateKey object from a file on disk. The file on disk
187        should contain a series of bytes corresponding to a certificate that
188        may be either PEM-encoded or DER-encoded. If the bytes are PEM encoded
189        it *must* begin with the standard PEM preamble (a series of dashes
190        followed by the ASCII bytes "BEGIN", the key type, and another series
191        of dashes). In the absence of that preamble, the implementation may
192        assume that the certificate is DER-encoded instead.
193        """
194        return cls(path=path)
195
196    @classmethod
197    def from_id(cls, id: bytes) -> PrivateKey:
198        """
199        Creates a PrivateKey object from an arbitrary identifier. This may
200        be useful for implementations that rely on system private key stores.
201        """
202        return cls(id=id)
203
204
205class TLSClientConfiguration:
206    """
207    An immutable TLS Configuration object for a "client" socket, i.e. a socket
208    making a connection to a server. This object has the following
209    properties:
210
211    :param certificate_chain SigningChain: A single signing chain,
212        comprising a leaf certificate including its corresponding private key
213        and optionally a list of intermediate certificates. These certificates
214        will be offered to the server during the handshake if required.
215
216    :param ciphers Sequence[CipherSuite | int] | None:
217        The available ciphers for TLS connections created with this
218        configuration, in priority order. If None is provided, the implementation
219        will choose a suitable default value (such as system recommended settings).
220
221    :param inner_protocols Sequence[NextProtocol | bytes]:
222        Protocols that connections created with this configuration should
223        advertise as supported during the TLS handshake. These may be
224        advertised using ALPN. This list of protocols should be ordered
225        by preference.
226
227    :param lowest_supported_version TLSVersion | None:
228        The minimum version of TLS that should be allowed on TLS
229        connections using this configuration.
230
231    :param highest_supported_version TLSVersion | None:
232        The maximum version of TLS that should be allowed on TLS
233        connections using this configuration.
234
235    :param trust_store TrustStore:
236        The trust store that connections using this configuration will use
237        to validate certificates. None means that the system store is used.
238    """
239
240    __slots__ = (
241        "_certificate_chain",
242        "_ciphers",
243        "_inner_protocols",
244        "_lowest_supported_version",
245        "_highest_supported_version",
246        "_trust_store",
247    )
248
249    def __init__(
250        self,
251        certificate_chain: SigningChain | None = None,
252        ciphers: Sequence[CipherSuite] | None = None,
253        inner_protocols: Sequence[NextProtocol | bytes] | None = None,
254        lowest_supported_version: TLSVersion | None = None,
255        highest_supported_version: TLSVersion | None = None,
256        trust_store: TrustStore | None = None,
257    ) -> None:
258        """Initialize TLS client configuration."""
259
260        if inner_protocols is None:
261            inner_protocols = []
262
263        self._certificate_chain = certificate_chain
264        self._ciphers = ciphers
265        self._inner_protocols = inner_protocols
266        self._lowest_supported_version = lowest_supported_version
267        self._highest_supported_version = highest_supported_version
268        self._trust_store = trust_store
269
270    @property
271    def certificate_chain(self) -> SigningChain | None:
272        """
273        The leaf certificate and corresponding private key, with optionally a list of
274        intermediate certificates. These certificates will be offered to the server
275        during the handshake if required.
276
277        """
278        return self._certificate_chain
279
280    @property
281    def ciphers(self) -> Sequence[CipherSuite | int] | None:
282        """
283        The list of available ciphers for TLS connections, in priority order.
284        None indicates that system recommended settings will be used.
285        """
286        return self._ciphers
287
288    @property
289    def inner_protocols(self) -> Sequence[NextProtocol | bytes]:
290        """Protocols that connections should advertise as supported during the TLS handshake.
291
292        These may be advertised using ALPN. This list of protocols is ordered by preference.
293        """
294        return self._inner_protocols
295
296    @property
297    def lowest_supported_version(self) -> TLSVersion | None:
298        """
299        The minimum version of TLS that is allowed on TLS connections.
300        None indicates that system recommended settings will be used.
301        """
302        return self._lowest_supported_version
303
304    @property
305    def highest_supported_version(self) -> TLSVersion | None:
306        """
307        The maximum version of TLS that will be allowed on TLS connections.
308        None indicates that system recommended settings will be used.
309        """
310        return self._highest_supported_version
311
312    @property
313    def trust_store(self) -> TrustStore | None:
314        """
315        The trust store that connections using this configuration will use
316        to validate certificates. None means that the system store is used.
317        """
318        return self._trust_store
319
320
321class TLSServerConfiguration:
322    """
323    An immutable TLS Configuration object for a "server" socket, i.e. a socket
324    making one or more connections to clients. This object has the following
325    properties:
326
327    :param certificate_chain Sequence[SigningChain]: A sequence of signing chains,
328        where each signing chain comprises a leaf certificate including
329        its corresponding private key and optionally a list of intermediate
330        certificates. These certificates will be offered to the client during
331        the handshake if required.
332
333    :param ciphers Sequence[CipherSuite | int] | None:
334        The available ciphers for TLS connections created with this
335        configuration, in priority order. If None is provided, the implementation
336        will choose a suitable default value (such as system recommended settings).
337
338    :param inner_protocols Sequence[NextProtocol | bytes]:
339        Protocols that connections created with this configuration should
340        advertise as supported during the TLS handshake. These may be
341        advertised using ALPN. This list of protocols should be ordered
342        by preference.
343
344    :param lowest_supported_version TLSVersion | None:
345        The minimum version of TLS that should be allowed on TLS
346        connections using this configuration.
347
348    :param highest_supported_version TLSVersion | None:
349        The maximum version of TLS that should be allowed on TLS
350        connections using this configuration.
351
352    :param trust_store TrustStore:
353        The trust store that connections using this configuration will use
354        to validate certificates. None means that client authentication is disabled,
355        whereas any other option enable client authentication.
356    """
357
358    __slots__ = (
359        "_certificate_chain",
360        "_ciphers",
361        "_inner_protocols",
362        "_lowest_supported_version",
363        "_highest_supported_version",
364        "_trust_store",
365    )
366
367    def __init__(
368        self,
369        certificate_chain: Sequence[SigningChain] | None = None,
370        ciphers: Sequence[CipherSuite | int] | None = None,
371        inner_protocols: Sequence[NextProtocol | bytes] | None = None,
372        lowest_supported_version: TLSVersion | None = None,
373        highest_supported_version: TLSVersion | None = None,
374        trust_store: TrustStore | None = None,
375    ) -> None:
376        """Initialize TLS server configuration."""
377
378        if inner_protocols is None:
379            inner_protocols = []
380
381        self._certificate_chain = certificate_chain
382        self._ciphers = ciphers
383        self._inner_protocols = inner_protocols
384        self._lowest_supported_version = lowest_supported_version
385        self._highest_supported_version = highest_supported_version
386        self._trust_store = trust_store
387
388    @property
389    def certificate_chain(self) -> Sequence[SigningChain] | None:
390        """
391        The set of signing chains, where each signing chain comprises a
392        leaf certificate and its corresponding private key, with optionally
393        a list of intermediate certificates. The certificates corresponding to
394        the signing chain that includes the correct certificate for the hostname
395        requested by the client will beoffered to the client during the handshake
396        if required.
397        """
398        return self._certificate_chain
399
400    @property
401    def ciphers(self) -> Sequence[CipherSuite | int] | None:
402        """
403        The list of available ciphers for TLS connections, in priority order.
404        None indicates that system recommended settings will be used.
405        """
406        return self._ciphers
407
408    @property
409    def inner_protocols(self) -> Sequence[NextProtocol | bytes]:
410        """Protocols that connections should advertise as supported during the TLS handshake.
411
412        These may be advertised using ALPN. This list of protocols is ordered by preference.
413        """
414        return self._inner_protocols
415
416    @property
417    def lowest_supported_version(self) -> TLSVersion | None:
418        """
419        The minimum version of TLS that is allowed on TLS connections.
420        None indicates that system recommended settings will be used.
421        """
422        return self._lowest_supported_version
423
424    @property
425    def highest_supported_version(self) -> TLSVersion | None:
426        """
427        The maximum version of TLS that will be allowed on TLS connections.
428        None indicates that system recommended settings will be used.
429        """
430        return self._highest_supported_version
431
432    @property
433    def trust_store(self) -> TrustStore | None:
434        """
435        The trust store that connections using this configuration will use
436        to validate certificates. None means that the system store is used.
437        """
438        return self._trust_store
439
440
441class ClientContext(Protocol):
442    """Context for setting up TLS connections for a client."""
443
444    @abstractmethod
445    def __init__(self, configuration: TLSClientConfiguration) -> None:
446        """Create a new client context object from a given TLS client configuration."""
447        ...
448
449    @property
450    @abstractmethod
451    def configuration(self) -> TLSClientConfiguration:
452        """Returns the TLS client configuration that was used to create the client context."""
453
454    @abstractmethod
455    def connect(self, address: tuple[str | None, int]) -> TLSSocket:
456        """Creates a TLSSocket that behaves like a socket.socket, and
457        contains information about the TLS exchange
458        (cipher, negotiated_protocol, negotiated_tls_version, etc.).
459        """
460
461    @abstractmethod
462    def create_buffer(self, server_hostname: str) -> TLSBuffer:
463        """Creates a TLSBuffer that acts as an in-memory channel,
464        and contains information about the TLS exchange
465        (cipher, negotiated_protocol, negotiated_tls_version, etc.)."""
466
467
468_ClientContext = TypeVar("_ClientContext", bound=ClientContext)
469
470
471class ServerContext(Protocol):
472    """Context for setting up TLS connections for a server."""
473
474    @abstractmethod
475    def __init__(self, configuration: TLSServerConfiguration) -> None:
476        """Create a new server context object from a given TLS server configuration."""
477        ...
478
479    @property
480    @abstractmethod
481    def configuration(self) -> TLSServerConfiguration:
482        """Returns the TLS server configuration that was used to create the server context."""
483
484    @abstractmethod
485    def connect(self, address: tuple[str | None, int]) -> TLSSocket:
486        """Creates a TLSSocket that behaves like a socket.socket, and
487        contains information about the TLS exchange
488        (cipher, negotiated_protocol, negotiated_tls_version, etc.).
489        """
490
491    @abstractmethod
492    def create_buffer(self) -> TLSBuffer:
493        """Creates a TLSBuffer that acts as an in-memory channel,
494        and contains information about the TLS exchange
495        (cipher, negotiated_protocol, negotiated_tls_version, etc.)."""
496
497
498_ServerContext = TypeVar("_ServerContext", bound=ServerContext)
499
500
501class TLSSocket(Protocol):
502    """This class implements a socket.socket-like object that creates an OS
503    socket, wraps it in an SSL context, and provides read and write methods
504    over that channel."""
505
506    @abstractmethod
507    def __init__(self, *args: tuple, **kwargs: tuple) -> None:
508        """TLSSockets should not be constructed by the user.
509        The implementation should implement a method to construct a TLSSocket
510        object and call it in ClientContext.connect() and
511        ServerContext.connect()."""
512
513    @abstractmethod
514    def recv(self, bufsize: int) -> bytes:
515        """Receive data from the socket. The return value is a bytes object
516        representing the data received. Should not work before the handshake
517        is completed."""
518
519    @abstractmethod
520    def send(self, bytes: bytes) -> int:
521        """Send data to the socket. The socket must be connected to a remote socket."""
522
523    @abstractmethod
524    def close(self, force: bool = False) -> None:
525        """Shuts down the connection and mark the socket closed.
526        If force is True, this method should send the close_notify alert and shut down
527        the socket without waiting for the other side.
528        If force is False, this method should send the close_notify alert and raise
529        the WantReadError exception until a corresponding close_notify alert has been
530        received from the other side.
531        In either case, this method should return WantWriteError if sending the
532        close_notify alert currently fails."""
533
534    @abstractmethod
535    def listen(self, backlog: int) -> None:
536        """Enable a server to accept connections. If backlog is specified, it
537        specifies the number of unaccepted connections that the system will allow
538        before refusing new connections."""
539
540    @abstractmethod
541    def accept(self) -> tuple[TLSSocket, tuple[str | None, int]]:
542        """Accept a connection. The socket must be bound to an address and listening
543        for connections. The return value is a pair (conn, address) where conn is a
544        new TLSSocket object usable to send and receive data on the connection, and
545        address is the address bound to the socket on the other end of the connection."""
546
547    @abstractmethod
548    def getsockname(self) -> tuple[str | None, int]:
549        """Return the local address to which the socket is connected."""
550
551    @abstractmethod
552    def getpeercert(self) -> bytes | None:
553        """
554        Return the raw DER bytes of the certificate provided by the peer
555        during the handshake, if applicable.
556        """
557
558    @abstractmethod
559    def getpeername(self) -> tuple[str | None, int]:
560        """Return the remote address to which the socket is connected."""
561
562    @property
563    @abstractmethod
564    def context(self) -> ClientContext | ServerContext:
565        """The ``Context`` object this socket is tied to."""
566
567    @abstractmethod
568    def cipher(self) -> CipherSuite | int | None:
569        """
570        Returns the CipherSuite entry for the cipher that has been negotiated on the connection.
571
572        If no connection has been negotiated, returns ``None``. If the cipher negotiated is not
573        defined in CipherSuite, returns the 16-bit integer representing that cipher directly.
574        """
575
576    @abstractmethod
577    def negotiated_protocol(self) -> NextProtocol | bytes | None:
578        """
579        Returns the protocol that was selected during the TLS handshake.
580
581        This selection may have been made using ALPN or some future
582        negotiation mechanism.
583
584        If the negotiated protocol is one of the protocols defined in the
585        ``NextProtocol`` enum, the value from that enum will be returned.
586        Otherwise, the raw bytestring of the negotiated protocol will be
587        returned.
588
589        If ``Context.set_inner_protocols()`` was not called, if the other
590        party does not support protocol negotiation, if this socket does
591        not support any of the peer's proposed protocols, or if the
592        handshake has not happened yet, ``None`` is returned.
593        """
594
595    @property
596    @abstractmethod
597    def negotiated_tls_version(self) -> TLSVersion | None:
598        """The version of TLS that has been negotiated on this connection."""
599
600
601class TLSBuffer(Protocol):
602    """This class implements an in memory-channel that creates two buffers,
603    wraps them in an SSL context, and provides read and write methods over
604    that channel."""
605
606    @abstractmethod
607    def read(self, amt: int, buffer: Buffer | None) -> bytes | int:
608        """
609        Read up to ``amt`` bytes of data from the input buffer and return
610        the result as a ``bytes`` instance. If an optional buffer is
611        provided, the result is written into the buffer and the number of
612        bytes is returned instead.
613
614        Once EOF is reached, all further calls to this method return the
615        empty byte string ``b''``.
616
617        May read "short": that is, fewer bytes may be returned than were
618        requested.
619
620        Raise ``WantReadError`` or ``WantWriteError`` if there is
621        insufficient data in either the input or output buffer and the
622        operation would have caused data to be written or read.
623
624        May raise ``RaggedEOF`` if the connection has been closed without a
625        graceful TLS shutdown. Whether this is an exception that should be
626        ignored or not is up to the specific application.
627
628        As at any time a re-negotiation is possible, a call to ``read()``
629        can also cause write operations.
630        """
631
632    @abstractmethod
633    def write(self, buf: Buffer) -> int:
634        """
635        Write ``buf`` in encrypted form to the output buffer and return the
636        number of bytes written. The ``buf`` argument must be an object
637        supporting the buffer interface.
638
639        Raise ``WantReadError`` or ``WantWriteError`` if there is
640        insufficient data in either the input or output buffer and the
641        operation would have caused data to be written or read. In either
642        case, users should endeavour to resolve that situation and then
643        re-call this method. When re-calling this method users *should*
644        re-use the exact same ``buf`` object, as some implementations require that
645        the exact same buffer be used.
646
647        This operation may write "short": that is, fewer bytes may be
648        written than were in the buffer.
649
650        As at any time a re-negotiation is possible, a call to ``write()``
651        can also cause read operations.
652        """
653
654    @abstractmethod
655    def do_handshake(self) -> None:
656        """
657        Performs the TLS handshake. Also performs certificate validation
658        and hostname verification.
659        """
660
661    @abstractmethod
662    def cipher(self) -> CipherSuite | int | None:
663        """
664        Returns the CipherSuite entry for the cipher that has been
665        negotiated on the connection. If no connection has been negotiated,
666        returns ``None``. If the cipher negotiated is not defined in
667        CipherSuite, returns the 16-bit integer representing that cipher
668        directly.
669        """
670
671    @abstractmethod
672    def negotiated_protocol(self) -> NextProtocol | bytes | None:
673        """
674        Returns the protocol that was selected during the TLS handshake.
675        This selection may have been made using ALPN, NPN, or some future
676        negotiation mechanism.
677
678        If the negotiated protocol is one of the protocols defined in the
679        ``NextProtocol`` enum, the value from that enum will be returned.
680        Otherwise, the raw bytestring of the negotiated protocol will be
681        returned.
682
683        If ``Context.set_inner_protocols()`` was not called, if the other
684        party does not support protocol negotiation, if this socket does
685        not support any of the peer's proposed protocols, or if the
686        handshake has not happened yet, ``None`` is returned.
687        """
688
689    @property
690    @abstractmethod
691    def context(self) -> ClientContext | ServerContext:
692        """
693        The ``Context`` object this buffer is tied to.
694        """
695
696    @property
697    @abstractmethod
698    def negotiated_tls_version(self) -> TLSVersion | None:
699        """
700        The version of TLS that has been negotiated on this connection.
701        """
702
703    @abstractmethod
704    def shutdown(self) -> None:
705        """
706        Performs a clean TLS shut down. This should generally be used
707        whenever possible to signal to the remote peer that the content is
708        finished.
709        """
710
711    @abstractmethod
712    def process_incoming(self, data_from_network: bytes) -> None:
713        """
714        Receives some TLS data from the network and stores it in an
715        internal buffer.
716
717        If the internal buffer is overfull, this method will raise
718        ``WantReadError`` and store no data. At this point, the user must
719        call ``read`` to remove some data from the internal buffer
720        before repeating this call.
721        """
722
723    @abstractmethod
724    def incoming_bytes_buffered(self) -> int:
725        """
726        Returns how many bytes are in the incoming buffer waiting to be processed.
727        """
728
729    @abstractmethod
730    def process_outgoing(self, amount_bytes_for_network: int) -> bytes:
731        """
732        Returns the next ``amt`` bytes of data that should be written to
733        the network from the outgoing data buffer, removing it from the
734         internal buffer.
735        """
736
737    @abstractmethod
738    def outgoing_bytes_buffered(self) -> int:
739        """
740        Returns how many bytes are in the outgoing buffer waiting to be sent.
741        """
742
743    @abstractmethod
744    def getpeercert(self) -> bytes | None:
745        """
746        Return the raw DER bytes of the certificate provided by the peer
747        during the handshake, if applicable.
748        """
749
750
751class CipherSuite(IntEnum):
752    """
753    Known cipher suites.
754
755    See: <https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml>
756    """
757
758    TLS_AES_128_GCM_SHA256 = 0x1301
759    TLS_AES_256_GCM_SHA384 = 0x1302
760    TLS_CHACHA20_POLY1305_SHA256 = 0x1303
761    TLS_AES_128_CCM_SHA256 = 0x1304
762    TLS_AES_128_CCM_8_SHA256 = 0x1305
763    TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B
764    TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C
765    TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F
766    TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030
767    TLS_ECDHE_ECDSA_WITH_AES_128_CCM = 0xC0AC
768    TLS_ECDHE_ECDSA_WITH_AES_256_CCM = 0xC0AD
769    TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 = 0xC0AE
770    TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 = 0xC0AF
771    TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA8
772    TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA9
773
774
775"""
776This default cipher list for TLS v1.2 is based on the CloudFlare recommendations,
777see: <https://developers.cloudflare.com/ssl/reference/cipher-suites/recommendations/>
778
779The default cipher list for TLS v1.3 should comprise the five fixed cipher suites
780from the TLS v1.3 specification.
781"""
782DEFAULT_CIPHER_LIST = [
783    CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
784    CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
785    CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
786    CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
787    CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
788    CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
789]
790
791
792class NextProtocol(Enum):
793    """The underlying negotiated ("next") protocol."""
794
795    H2 = b"h2"
796    H2C = b"h2c"
797    HTTP1 = b"http/1.1"
798    WEBRTC = b"webrtc"
799    C_WEBRTC = b"c-webrtc"
800    FTP = b"ftp"
801    STUN = b"stun.nat-discovery"
802    TURN = b"stun.turn"
803
804
805class TLSVersion(Enum):
806    """
807    TLS versions.
808
809    The `MINIMUM_SUPPORTED` and `MAXIMUM_SUPPORTED` variants are "open ended",
810    and refer to the "lowest mutually supported" and "highest mutually supported"
811    TLS versions, respectively.
812    """
813
814    MINIMUM_SUPPORTED = "MINIMUM_SUPPORTED"
815    TLSv1_2 = "TLSv1.2"
816    TLSv1_3 = "TLSv1.3"
817    MAXIMUM_SUPPORTED = "MAXIMUM_SUPPORTED"
818
819
820class TLSError(Exception):
821    """
822    The base exception for all TLS related errors from any implementation.
823
824    Catching this error should be sufficient to catch *all* TLS errors,
825    regardless of what implementation is used.
826    """
827
828
829class WantWriteError(TLSError):
830    """
831    A special signaling exception used only when non-blocking or buffer-only I/O is used.
832
833    This error signals that the requested
834    operation cannot complete until more data is written to the network,
835    or until the output buffer is drained.
836
837    This error is should only be raised when it is completely impossible
838    to write any data. If a partial write is achievable then this should
839    not be raised.
840    """
841
842
843class WantReadError(TLSError):
844    """
845    A special signaling exception used only when non-blocking or buffer-only I/O is used.
846
847    This error signals that the requested
848    operation cannot complete until more data is read from the network, or
849    until more data is available in the input buffer.
850
851    This error should only be raised when it is completely impossible to
852    write any data. If a partial write is achievable then this should not
853    be raised.
854    """
855
856
857class RaggedEOF(TLSError):
858    """A special signaling exception used when a TLS connection has been
859    closed gracelessly: that is, when a TLS CloseNotify was not received
860    from the peer before the underlying TCP socket reached EOF. This is a
861    so-called "ragged EOF".
862
863    This exception is not guaranteed to be raised in the face of a ragged
864    EOF: some implementations may not be able to detect or report the
865    ragged EOF.
866
867    This exception is not always a problem. Ragged EOFs are a concern only
868    when protocols are vulnerable to length truncation attacks. Any
869    protocol that can detect length truncation attacks at the application
870    layer (e.g. HTTP/1.1 and HTTP/2) is not vulnerable to this kind of
871    attack and so can ignore this exception.
872    """
873
874
875class ConfigurationError(TLSError):
876    """An special exception that implementations can use when the provided
877    configuration uses features not supported by that implementation."""
878
879
880class SigningChain:
881    """Object representing a certificate chain used in TLS."""
882
883    leaf: tuple[Certificate, PrivateKey | None]
884    chain: list[Certificate]
885
886    def __init__(
887        self,
888        leaf: tuple[Certificate, PrivateKey | None],
889        chain: Sequence[Certificate] | None = None,
890    ):
891        """Initializes a SigningChain object."""
892        self.leaf = leaf
893        if chain is None:
894            chain = []
895        self.chain = list(chain)
896
897
898class TLSImplementation(Generic[_ClientContext, _ServerContext]):
899    """An object representing the collection of classes that implement the
900    PEP 543 abstract TLS API for a specific TLS implementation.
901    """
902
903    __slots__ = (
904        "_client_context",
905        "_server_context",
906        "_validate_config",
907    )
908
909    def __init__(
910        self,
911        client_context: type[_ClientContext],
912        server_context: type[_ServerContext],
913        validate_config: Callable[[TLSClientConfiguration | TLSServerConfiguration], None],
914    ) -> None:
915        """Initializes all attributes of the implementation."""
916
917        self._client_context = client_context
918        self._server_context = server_context
919        self._validate_config = validate_config
920
921    @property
922    def client_context(self) -> type[_ClientContext]:
923        """The concrete implementation of the PEP 543 Client Context object,
924        if this TLS implementation supports being the client on a TLS connection.
925        """
926        return self._client_context
927
928    @property
929    def server_context(self) -> type[_ServerContext]:
930        """The concrete implementation of the PEP 543 Server Context object,
931        if this TLS implementation supports being a server on a TLS connection.
932        """
933        return self._server_context
934
935    @property
936    def validate_config(self) -> Callable[[TLSClientConfiguration | TLSServerConfiguration], None]:
937        """A function that reveals whether this TLS implementation supports a
938        particular TLS configuration.
939        """
940        return self._validate_config
class TLSBuffer(typing.Protocol):
602class TLSBuffer(Protocol):
603    """This class implements an in memory-channel that creates two buffers,
604    wraps them in an SSL context, and provides read and write methods over
605    that channel."""
606
607    @abstractmethod
608    def read(self, amt: int, buffer: Buffer | None) -> bytes | int:
609        """
610        Read up to ``amt`` bytes of data from the input buffer and return
611        the result as a ``bytes`` instance. If an optional buffer is
612        provided, the result is written into the buffer and the number of
613        bytes is returned instead.
614
615        Once EOF is reached, all further calls to this method return the
616        empty byte string ``b''``.
617
618        May read "short": that is, fewer bytes may be returned than were
619        requested.
620
621        Raise ``WantReadError`` or ``WantWriteError`` if there is
622        insufficient data in either the input or output buffer and the
623        operation would have caused data to be written or read.
624
625        May raise ``RaggedEOF`` if the connection has been closed without a
626        graceful TLS shutdown. Whether this is an exception that should be
627        ignored or not is up to the specific application.
628
629        As at any time a re-negotiation is possible, a call to ``read()``
630        can also cause write operations.
631        """
632
633    @abstractmethod
634    def write(self, buf: Buffer) -> int:
635        """
636        Write ``buf`` in encrypted form to the output buffer and return the
637        number of bytes written. The ``buf`` argument must be an object
638        supporting the buffer interface.
639
640        Raise ``WantReadError`` or ``WantWriteError`` if there is
641        insufficient data in either the input or output buffer and the
642        operation would have caused data to be written or read. In either
643        case, users should endeavour to resolve that situation and then
644        re-call this method. When re-calling this method users *should*
645        re-use the exact same ``buf`` object, as some implementations require that
646        the exact same buffer be used.
647
648        This operation may write "short": that is, fewer bytes may be
649        written than were in the buffer.
650
651        As at any time a re-negotiation is possible, a call to ``write()``
652        can also cause read operations.
653        """
654
655    @abstractmethod
656    def do_handshake(self) -> None:
657        """
658        Performs the TLS handshake. Also performs certificate validation
659        and hostname verification.
660        """
661
662    @abstractmethod
663    def cipher(self) -> CipherSuite | int | None:
664        """
665        Returns the CipherSuite entry for the cipher that has been
666        negotiated on the connection. If no connection has been negotiated,
667        returns ``None``. If the cipher negotiated is not defined in
668        CipherSuite, returns the 16-bit integer representing that cipher
669        directly.
670        """
671
672    @abstractmethod
673    def negotiated_protocol(self) -> NextProtocol | bytes | None:
674        """
675        Returns the protocol that was selected during the TLS handshake.
676        This selection may have been made using ALPN, NPN, or some future
677        negotiation mechanism.
678
679        If the negotiated protocol is one of the protocols defined in the
680        ``NextProtocol`` enum, the value from that enum will be returned.
681        Otherwise, the raw bytestring of the negotiated protocol will be
682        returned.
683
684        If ``Context.set_inner_protocols()`` was not called, if the other
685        party does not support protocol negotiation, if this socket does
686        not support any of the peer's proposed protocols, or if the
687        handshake has not happened yet, ``None`` is returned.
688        """
689
690    @property
691    @abstractmethod
692    def context(self) -> ClientContext | ServerContext:
693        """
694        The ``Context`` object this buffer is tied to.
695        """
696
697    @property
698    @abstractmethod
699    def negotiated_tls_version(self) -> TLSVersion | None:
700        """
701        The version of TLS that has been negotiated on this connection.
702        """
703
704    @abstractmethod
705    def shutdown(self) -> None:
706        """
707        Performs a clean TLS shut down. This should generally be used
708        whenever possible to signal to the remote peer that the content is
709        finished.
710        """
711
712    @abstractmethod
713    def process_incoming(self, data_from_network: bytes) -> None:
714        """
715        Receives some TLS data from the network and stores it in an
716        internal buffer.
717
718        If the internal buffer is overfull, this method will raise
719        ``WantReadError`` and store no data. At this point, the user must
720        call ``read`` to remove some data from the internal buffer
721        before repeating this call.
722        """
723
724    @abstractmethod
725    def incoming_bytes_buffered(self) -> int:
726        """
727        Returns how many bytes are in the incoming buffer waiting to be processed.
728        """
729
730    @abstractmethod
731    def process_outgoing(self, amount_bytes_for_network: int) -> bytes:
732        """
733        Returns the next ``amt`` bytes of data that should be written to
734        the network from the outgoing data buffer, removing it from the
735         internal buffer.
736        """
737
738    @abstractmethod
739    def outgoing_bytes_buffered(self) -> int:
740        """
741        Returns how many bytes are in the outgoing buffer waiting to be sent.
742        """
743
744    @abstractmethod
745    def getpeercert(self) -> bytes | None:
746        """
747        Return the raw DER bytes of the certificate provided by the peer
748        during the handshake, if applicable.
749        """

This class implements an in memory-channel that creates two buffers, wraps them in an SSL context, and provides read and write methods over that channel.

@abstractmethod
def read(self, amt: int, buffer: collections.abc.Buffer | None) -> bytes | int:
607    @abstractmethod
608    def read(self, amt: int, buffer: Buffer | None) -> bytes | int:
609        """
610        Read up to ``amt`` bytes of data from the input buffer and return
611        the result as a ``bytes`` instance. If an optional buffer is
612        provided, the result is written into the buffer and the number of
613        bytes is returned instead.
614
615        Once EOF is reached, all further calls to this method return the
616        empty byte string ``b''``.
617
618        May read "short": that is, fewer bytes may be returned than were
619        requested.
620
621        Raise ``WantReadError`` or ``WantWriteError`` if there is
622        insufficient data in either the input or output buffer and the
623        operation would have caused data to be written or read.
624
625        May raise ``RaggedEOF`` if the connection has been closed without a
626        graceful TLS shutdown. Whether this is an exception that should be
627        ignored or not is up to the specific application.
628
629        As at any time a re-negotiation is possible, a call to ``read()``
630        can also cause write operations.
631        """

Read up to amt bytes of data from the input buffer and return the result as a bytes instance. If an optional buffer is provided, the result is written into the buffer and the number of bytes is returned instead.

Once EOF is reached, all further calls to this method return the empty byte string b''.

May read "short": that is, fewer bytes may be returned than were requested.

Raise WantReadError or WantWriteError if there is insufficient data in either the input or output buffer and the operation would have caused data to be written or read.

May raise RaggedEOF if the connection has been closed without a graceful TLS shutdown. Whether this is an exception that should be ignored or not is up to the specific application.

As at any time a re-negotiation is possible, a call to read() can also cause write operations.

@abstractmethod
def write(self, buf: collections.abc.Buffer) -> int:
633    @abstractmethod
634    def write(self, buf: Buffer) -> int:
635        """
636        Write ``buf`` in encrypted form to the output buffer and return the
637        number of bytes written. The ``buf`` argument must be an object
638        supporting the buffer interface.
639
640        Raise ``WantReadError`` or ``WantWriteError`` if there is
641        insufficient data in either the input or output buffer and the
642        operation would have caused data to be written or read. In either
643        case, users should endeavour to resolve that situation and then
644        re-call this method. When re-calling this method users *should*
645        re-use the exact same ``buf`` object, as some implementations require that
646        the exact same buffer be used.
647
648        This operation may write "short": that is, fewer bytes may be
649        written than were in the buffer.
650
651        As at any time a re-negotiation is possible, a call to ``write()``
652        can also cause read operations.
653        """

Write buf in encrypted form to the output buffer and return the number of bytes written. The buf argument must be an object supporting the buffer interface.

Raise WantReadError or WantWriteError if there is insufficient data in either the input or output buffer and the operation would have caused data to be written or read. In either case, users should endeavour to resolve that situation and then re-call this method. When re-calling this method users should re-use the exact same buf object, as some implementations require that the exact same buffer be used.

This operation may write "short": that is, fewer bytes may be written than were in the buffer.

As at any time a re-negotiation is possible, a call to write() can also cause read operations.

@abstractmethod
def do_handshake(self) -> None:
655    @abstractmethod
656    def do_handshake(self) -> None:
657        """
658        Performs the TLS handshake. Also performs certificate validation
659        and hostname verification.
660        """

Performs the TLS handshake. Also performs certificate validation and hostname verification.

@abstractmethod
def cipher(self) -> CipherSuite | int | None:
662    @abstractmethod
663    def cipher(self) -> CipherSuite | int | None:
664        """
665        Returns the CipherSuite entry for the cipher that has been
666        negotiated on the connection. If no connection has been negotiated,
667        returns ``None``. If the cipher negotiated is not defined in
668        CipherSuite, returns the 16-bit integer representing that cipher
669        directly.
670        """

Returns the CipherSuite entry for the cipher that has been negotiated on the connection. If no connection has been negotiated, returns None. If the cipher negotiated is not defined in CipherSuite, returns the 16-bit integer representing that cipher directly.

@abstractmethod
def negotiated_protocol(self) -> NextProtocol | bytes | None:
672    @abstractmethod
673    def negotiated_protocol(self) -> NextProtocol | bytes | None:
674        """
675        Returns the protocol that was selected during the TLS handshake.
676        This selection may have been made using ALPN, NPN, or some future
677        negotiation mechanism.
678
679        If the negotiated protocol is one of the protocols defined in the
680        ``NextProtocol`` enum, the value from that enum will be returned.
681        Otherwise, the raw bytestring of the negotiated protocol will be
682        returned.
683
684        If ``Context.set_inner_protocols()`` was not called, if the other
685        party does not support protocol negotiation, if this socket does
686        not support any of the peer's proposed protocols, or if the
687        handshake has not happened yet, ``None`` is returned.
688        """

Returns the protocol that was selected during the TLS handshake. This selection may have been made using ALPN, NPN, or some future negotiation mechanism.

If the negotiated protocol is one of the protocols defined in the NextProtocol enum, the value from that enum will be returned. Otherwise, the raw bytestring of the negotiated protocol will be returned.

If Context.set_inner_protocols() was not called, if the other party does not support protocol negotiation, if this socket does not support any of the peer's proposed protocols, or if the handshake has not happened yet, None is returned.

context: ClientContext | ServerContext
690    @property
691    @abstractmethod
692    def context(self) -> ClientContext | ServerContext:
693        """
694        The ``Context`` object this buffer is tied to.
695        """

The Context object this buffer is tied to.

negotiated_tls_version: TLSVersion | None
697    @property
698    @abstractmethod
699    def negotiated_tls_version(self) -> TLSVersion | None:
700        """
701        The version of TLS that has been negotiated on this connection.
702        """

The version of TLS that has been negotiated on this connection.

@abstractmethod
def shutdown(self) -> None:
704    @abstractmethod
705    def shutdown(self) -> None:
706        """
707        Performs a clean TLS shut down. This should generally be used
708        whenever possible to signal to the remote peer that the content is
709        finished.
710        """

Performs a clean TLS shut down. This should generally be used whenever possible to signal to the remote peer that the content is finished.

@abstractmethod
def process_incoming(self, data_from_network: bytes) -> None:
712    @abstractmethod
713    def process_incoming(self, data_from_network: bytes) -> None:
714        """
715        Receives some TLS data from the network and stores it in an
716        internal buffer.
717
718        If the internal buffer is overfull, this method will raise
719        ``WantReadError`` and store no data. At this point, the user must
720        call ``read`` to remove some data from the internal buffer
721        before repeating this call.
722        """

Receives some TLS data from the network and stores it in an internal buffer.

If the internal buffer is overfull, this method will raise WantReadError and store no data. At this point, the user must call read to remove some data from the internal buffer before repeating this call.

@abstractmethod
def incoming_bytes_buffered(self) -> int:
724    @abstractmethod
725    def incoming_bytes_buffered(self) -> int:
726        """
727        Returns how many bytes are in the incoming buffer waiting to be processed.
728        """

Returns how many bytes are in the incoming buffer waiting to be processed.

@abstractmethod
def process_outgoing(self, amount_bytes_for_network: int) -> bytes:
730    @abstractmethod
731    def process_outgoing(self, amount_bytes_for_network: int) -> bytes:
732        """
733        Returns the next ``amt`` bytes of data that should be written to
734        the network from the outgoing data buffer, removing it from the
735         internal buffer.
736        """

Returns the next amt bytes of data that should be written to the network from the outgoing data buffer, removing it from the internal buffer.

@abstractmethod
def outgoing_bytes_buffered(self) -> int:
738    @abstractmethod
739    def outgoing_bytes_buffered(self) -> int:
740        """
741        Returns how many bytes are in the outgoing buffer waiting to be sent.
742        """

Returns how many bytes are in the outgoing buffer waiting to be sent.

@abstractmethod
def getpeercert(self) -> bytes | None:
744    @abstractmethod
745    def getpeercert(self) -> bytes | None:
746        """
747        Return the raw DER bytes of the certificate provided by the peer
748        during the handshake, if applicable.
749        """

Return the raw DER bytes of the certificate provided by the peer during the handshake, if applicable.

class TLSServerConfiguration:
322class TLSServerConfiguration:
323    """
324    An immutable TLS Configuration object for a "server" socket, i.e. a socket
325    making one or more connections to clients. This object has the following
326    properties:
327
328    :param certificate_chain Sequence[SigningChain]: A sequence of signing chains,
329        where each signing chain comprises a leaf certificate including
330        its corresponding private key and optionally a list of intermediate
331        certificates. These certificates will be offered to the client during
332        the handshake if required.
333
334    :param ciphers Sequence[CipherSuite | int] | None:
335        The available ciphers for TLS connections created with this
336        configuration, in priority order. If None is provided, the implementation
337        will choose a suitable default value (such as system recommended settings).
338
339    :param inner_protocols Sequence[NextProtocol | bytes]:
340        Protocols that connections created with this configuration should
341        advertise as supported during the TLS handshake. These may be
342        advertised using ALPN. This list of protocols should be ordered
343        by preference.
344
345    :param lowest_supported_version TLSVersion | None:
346        The minimum version of TLS that should be allowed on TLS
347        connections using this configuration.
348
349    :param highest_supported_version TLSVersion | None:
350        The maximum version of TLS that should be allowed on TLS
351        connections using this configuration.
352
353    :param trust_store TrustStore:
354        The trust store that connections using this configuration will use
355        to validate certificates. None means that client authentication is disabled,
356        whereas any other option enable client authentication.
357    """
358
359    __slots__ = (
360        "_certificate_chain",
361        "_ciphers",
362        "_inner_protocols",
363        "_lowest_supported_version",
364        "_highest_supported_version",
365        "_trust_store",
366    )
367
368    def __init__(
369        self,
370        certificate_chain: Sequence[SigningChain] | None = None,
371        ciphers: Sequence[CipherSuite | int] | None = None,
372        inner_protocols: Sequence[NextProtocol | bytes] | None = None,
373        lowest_supported_version: TLSVersion | None = None,
374        highest_supported_version: TLSVersion | None = None,
375        trust_store: TrustStore | None = None,
376    ) -> None:
377        """Initialize TLS server configuration."""
378
379        if inner_protocols is None:
380            inner_protocols = []
381
382        self._certificate_chain = certificate_chain
383        self._ciphers = ciphers
384        self._inner_protocols = inner_protocols
385        self._lowest_supported_version = lowest_supported_version
386        self._highest_supported_version = highest_supported_version
387        self._trust_store = trust_store
388
389    @property
390    def certificate_chain(self) -> Sequence[SigningChain] | None:
391        """
392        The set of signing chains, where each signing chain comprises a
393        leaf certificate and its corresponding private key, with optionally
394        a list of intermediate certificates. The certificates corresponding to
395        the signing chain that includes the correct certificate for the hostname
396        requested by the client will beoffered to the client during the handshake
397        if required.
398        """
399        return self._certificate_chain
400
401    @property
402    def ciphers(self) -> Sequence[CipherSuite | int] | None:
403        """
404        The list of available ciphers for TLS connections, in priority order.
405        None indicates that system recommended settings will be used.
406        """
407        return self._ciphers
408
409    @property
410    def inner_protocols(self) -> Sequence[NextProtocol | bytes]:
411        """Protocols that connections should advertise as supported during the TLS handshake.
412
413        These may be advertised using ALPN. This list of protocols is ordered by preference.
414        """
415        return self._inner_protocols
416
417    @property
418    def lowest_supported_version(self) -> TLSVersion | None:
419        """
420        The minimum version of TLS that is allowed on TLS connections.
421        None indicates that system recommended settings will be used.
422        """
423        return self._lowest_supported_version
424
425    @property
426    def highest_supported_version(self) -> TLSVersion | None:
427        """
428        The maximum version of TLS that will be allowed on TLS connections.
429        None indicates that system recommended settings will be used.
430        """
431        return self._highest_supported_version
432
433    @property
434    def trust_store(self) -> TrustStore | None:
435        """
436        The trust store that connections using this configuration will use
437        to validate certificates. None means that the system store is used.
438        """
439        return self._trust_store

An immutable TLS Configuration object for a "server" socket, i.e. a socket making one or more connections to clients. This object has the following properties:

Parameters
  • certificate_chain Sequence[SigningChain]: A sequence of signing chains, where each signing chain comprises a leaf certificate including its corresponding private key and optionally a list of intermediate certificates. These certificates will be offered to the client during the handshake if required.

  • ciphers Sequence[CipherSuite | int] | None: The available ciphers for TLS connections created with this configuration, in priority order. If None is provided, the implementation will choose a suitable default value (such as system recommended settings).

  • inner_protocols Sequence[NextProtocol | bytes]: Protocols that connections created with this configuration should advertise as supported during the TLS handshake. These may be advertised using ALPN. This list of protocols should be ordered by preference.

  • lowest_supported_version TLSVersion | None: The minimum version of TLS that should be allowed on TLS connections using this configuration.

  • highest_supported_version TLSVersion | None: The maximum version of TLS that should be allowed on TLS connections using this configuration.

  • trust_store TrustStore: The trust store that connections using this configuration will use to validate certificates. None means that client authentication is disabled, whereas any other option enable client authentication.

TLSServerConfiguration( certificate_chain: collections.abc.Sequence[tlslib.tlslib.SigningChain] | None = None, ciphers: collections.abc.Sequence[CipherSuite | int] | None = None, inner_protocols: collections.abc.Sequence[NextProtocol | bytes] | None = None, lowest_supported_version: TLSVersion | None = None, highest_supported_version: TLSVersion | None = None, trust_store: tlslib.tlslib.TrustStore | None = None)
368    def __init__(
369        self,
370        certificate_chain: Sequence[SigningChain] | None = None,
371        ciphers: Sequence[CipherSuite | int] | None = None,
372        inner_protocols: Sequence[NextProtocol | bytes] | None = None,
373        lowest_supported_version: TLSVersion | None = None,
374        highest_supported_version: TLSVersion | None = None,
375        trust_store: TrustStore | None = None,
376    ) -> None:
377        """Initialize TLS server configuration."""
378
379        if inner_protocols is None:
380            inner_protocols = []
381
382        self._certificate_chain = certificate_chain
383        self._ciphers = ciphers
384        self._inner_protocols = inner_protocols
385        self._lowest_supported_version = lowest_supported_version
386        self._highest_supported_version = highest_supported_version
387        self._trust_store = trust_store

Initialize TLS server configuration.

certificate_chain: collections.abc.Sequence[tlslib.tlslib.SigningChain] | None
389    @property
390    def certificate_chain(self) -> Sequence[SigningChain] | None:
391        """
392        The set of signing chains, where each signing chain comprises a
393        leaf certificate and its corresponding private key, with optionally
394        a list of intermediate certificates. The certificates corresponding to
395        the signing chain that includes the correct certificate for the hostname
396        requested by the client will beoffered to the client during the handshake
397        if required.
398        """
399        return self._certificate_chain

The set of signing chains, where each signing chain comprises a leaf certificate and its corresponding private key, with optionally a list of intermediate certificates. The certificates corresponding to the signing chain that includes the correct certificate for the hostname requested by the client will beoffered to the client during the handshake if required.

ciphers: collections.abc.Sequence[CipherSuite | int] | None
401    @property
402    def ciphers(self) -> Sequence[CipherSuite | int] | None:
403        """
404        The list of available ciphers for TLS connections, in priority order.
405        None indicates that system recommended settings will be used.
406        """
407        return self._ciphers

The list of available ciphers for TLS connections, in priority order. None indicates that system recommended settings will be used.

inner_protocols: collections.abc.Sequence[NextProtocol | bytes]
409    @property
410    def inner_protocols(self) -> Sequence[NextProtocol | bytes]:
411        """Protocols that connections should advertise as supported during the TLS handshake.
412
413        These may be advertised using ALPN. This list of protocols is ordered by preference.
414        """
415        return self._inner_protocols

Protocols that connections should advertise as supported during the TLS handshake.

These may be advertised using ALPN. This list of protocols is ordered by preference.

lowest_supported_version: TLSVersion | None
417    @property
418    def lowest_supported_version(self) -> TLSVersion | None:
419        """
420        The minimum version of TLS that is allowed on TLS connections.
421        None indicates that system recommended settings will be used.
422        """
423        return self._lowest_supported_version

The minimum version of TLS that is allowed on TLS connections. None indicates that system recommended settings will be used.

highest_supported_version: TLSVersion | None
425    @property
426    def highest_supported_version(self) -> TLSVersion | None:
427        """
428        The maximum version of TLS that will be allowed on TLS connections.
429        None indicates that system recommended settings will be used.
430        """
431        return self._highest_supported_version

The maximum version of TLS that will be allowed on TLS connections. None indicates that system recommended settings will be used.

trust_store: tlslib.tlslib.TrustStore | None
433    @property
434    def trust_store(self) -> TrustStore | None:
435        """
436        The trust store that connections using this configuration will use
437        to validate certificates. None means that the system store is used.
438        """
439        return self._trust_store

The trust store that connections using this configuration will use to validate certificates. None means that the system store is used.

class TLSClientConfiguration:
206class TLSClientConfiguration:
207    """
208    An immutable TLS Configuration object for a "client" socket, i.e. a socket
209    making a connection to a server. This object has the following
210    properties:
211
212    :param certificate_chain SigningChain: A single signing chain,
213        comprising a leaf certificate including its corresponding private key
214        and optionally a list of intermediate certificates. These certificates
215        will be offered to the server during the handshake if required.
216
217    :param ciphers Sequence[CipherSuite | int] | None:
218        The available ciphers for TLS connections created with this
219        configuration, in priority order. If None is provided, the implementation
220        will choose a suitable default value (such as system recommended settings).
221
222    :param inner_protocols Sequence[NextProtocol | bytes]:
223        Protocols that connections created with this configuration should
224        advertise as supported during the TLS handshake. These may be
225        advertised using ALPN. This list of protocols should be ordered
226        by preference.
227
228    :param lowest_supported_version TLSVersion | None:
229        The minimum version of TLS that should be allowed on TLS
230        connections using this configuration.
231
232    :param highest_supported_version TLSVersion | None:
233        The maximum version of TLS that should be allowed on TLS
234        connections using this configuration.
235
236    :param trust_store TrustStore:
237        The trust store that connections using this configuration will use
238        to validate certificates. None means that the system store is used.
239    """
240
241    __slots__ = (
242        "_certificate_chain",
243        "_ciphers",
244        "_inner_protocols",
245        "_lowest_supported_version",
246        "_highest_supported_version",
247        "_trust_store",
248    )
249
250    def __init__(
251        self,
252        certificate_chain: SigningChain | None = None,
253        ciphers: Sequence[CipherSuite] | None = None,
254        inner_protocols: Sequence[NextProtocol | bytes] | None = None,
255        lowest_supported_version: TLSVersion | None = None,
256        highest_supported_version: TLSVersion | None = None,
257        trust_store: TrustStore | None = None,
258    ) -> None:
259        """Initialize TLS client configuration."""
260
261        if inner_protocols is None:
262            inner_protocols = []
263
264        self._certificate_chain = certificate_chain
265        self._ciphers = ciphers
266        self._inner_protocols = inner_protocols
267        self._lowest_supported_version = lowest_supported_version
268        self._highest_supported_version = highest_supported_version
269        self._trust_store = trust_store
270
271    @property
272    def certificate_chain(self) -> SigningChain | None:
273        """
274        The leaf certificate and corresponding private key, with optionally a list of
275        intermediate certificates. These certificates will be offered to the server
276        during the handshake if required.
277
278        """
279        return self._certificate_chain
280
281    @property
282    def ciphers(self) -> Sequence[CipherSuite | int] | None:
283        """
284        The list of available ciphers for TLS connections, in priority order.
285        None indicates that system recommended settings will be used.
286        """
287        return self._ciphers
288
289    @property
290    def inner_protocols(self) -> Sequence[NextProtocol | bytes]:
291        """Protocols that connections should advertise as supported during the TLS handshake.
292
293        These may be advertised using ALPN. This list of protocols is ordered by preference.
294        """
295        return self._inner_protocols
296
297    @property
298    def lowest_supported_version(self) -> TLSVersion | None:
299        """
300        The minimum version of TLS that is allowed on TLS connections.
301        None indicates that system recommended settings will be used.
302        """
303        return self._lowest_supported_version
304
305    @property
306    def highest_supported_version(self) -> TLSVersion | None:
307        """
308        The maximum version of TLS that will be allowed on TLS connections.
309        None indicates that system recommended settings will be used.
310        """
311        return self._highest_supported_version
312
313    @property
314    def trust_store(self) -> TrustStore | None:
315        """
316        The trust store that connections using this configuration will use
317        to validate certificates. None means that the system store is used.
318        """
319        return self._trust_store

An immutable TLS Configuration object for a "client" socket, i.e. a socket making a connection to a server. This object has the following properties:

Parameters
  • certificate_chain SigningChain: A single signing chain, comprising a leaf certificate including its corresponding private key and optionally a list of intermediate certificates. These certificates will be offered to the server during the handshake if required.

  • ciphers Sequence[CipherSuite | int] | None: The available ciphers for TLS connections created with this configuration, in priority order. If None is provided, the implementation will choose a suitable default value (such as system recommended settings).

  • inner_protocols Sequence[NextProtocol | bytes]: Protocols that connections created with this configuration should advertise as supported during the TLS handshake. These may be advertised using ALPN. This list of protocols should be ordered by preference.

  • lowest_supported_version TLSVersion | None: The minimum version of TLS that should be allowed on TLS connections using this configuration.

  • highest_supported_version TLSVersion | None: The maximum version of TLS that should be allowed on TLS connections using this configuration.

  • trust_store TrustStore: The trust store that connections using this configuration will use to validate certificates. None means that the system store is used.

TLSClientConfiguration( certificate_chain: tlslib.tlslib.SigningChain | None = None, ciphers: collections.abc.Sequence[CipherSuite] | None = None, inner_protocols: collections.abc.Sequence[NextProtocol | bytes] | None = None, lowest_supported_version: TLSVersion | None = None, highest_supported_version: TLSVersion | None = None, trust_store: tlslib.tlslib.TrustStore | None = None)
250    def __init__(
251        self,
252        certificate_chain: SigningChain | None = None,
253        ciphers: Sequence[CipherSuite] | None = None,
254        inner_protocols: Sequence[NextProtocol | bytes] | None = None,
255        lowest_supported_version: TLSVersion | None = None,
256        highest_supported_version: TLSVersion | None = None,
257        trust_store: TrustStore | None = None,
258    ) -> None:
259        """Initialize TLS client configuration."""
260
261        if inner_protocols is None:
262            inner_protocols = []
263
264        self._certificate_chain = certificate_chain
265        self._ciphers = ciphers
266        self._inner_protocols = inner_protocols
267        self._lowest_supported_version = lowest_supported_version
268        self._highest_supported_version = highest_supported_version
269        self._trust_store = trust_store

Initialize TLS client configuration.

certificate_chain: tlslib.tlslib.SigningChain | None
271    @property
272    def certificate_chain(self) -> SigningChain | None:
273        """
274        The leaf certificate and corresponding private key, with optionally a list of
275        intermediate certificates. These certificates will be offered to the server
276        during the handshake if required.
277
278        """
279        return self._certificate_chain

The leaf certificate and corresponding private key, with optionally a list of intermediate certificates. These certificates will be offered to the server during the handshake if required.

ciphers: collections.abc.Sequence[CipherSuite | int] | None
281    @property
282    def ciphers(self) -> Sequence[CipherSuite | int] | None:
283        """
284        The list of available ciphers for TLS connections, in priority order.
285        None indicates that system recommended settings will be used.
286        """
287        return self._ciphers

The list of available ciphers for TLS connections, in priority order. None indicates that system recommended settings will be used.

inner_protocols: collections.abc.Sequence[NextProtocol | bytes]
289    @property
290    def inner_protocols(self) -> Sequence[NextProtocol | bytes]:
291        """Protocols that connections should advertise as supported during the TLS handshake.
292
293        These may be advertised using ALPN. This list of protocols is ordered by preference.
294        """
295        return self._inner_protocols

Protocols that connections should advertise as supported during the TLS handshake.

These may be advertised using ALPN. This list of protocols is ordered by preference.

lowest_supported_version: TLSVersion | None
297    @property
298    def lowest_supported_version(self) -> TLSVersion | None:
299        """
300        The minimum version of TLS that is allowed on TLS connections.
301        None indicates that system recommended settings will be used.
302        """
303        return self._lowest_supported_version

The minimum version of TLS that is allowed on TLS connections. None indicates that system recommended settings will be used.

highest_supported_version: TLSVersion | None
305    @property
306    def highest_supported_version(self) -> TLSVersion | None:
307        """
308        The maximum version of TLS that will be allowed on TLS connections.
309        None indicates that system recommended settings will be used.
310        """
311        return self._highest_supported_version

The maximum version of TLS that will be allowed on TLS connections. None indicates that system recommended settings will be used.

trust_store: tlslib.tlslib.TrustStore | None
313    @property
314    def trust_store(self) -> TrustStore | None:
315        """
316        The trust store that connections using this configuration will use
317        to validate certificates. None means that the system store is used.
318        """
319        return self._trust_store

The trust store that connections using this configuration will use to validate certificates. None means that the system store is used.

class ClientContext(typing.Protocol):
442class ClientContext(Protocol):
443    """Context for setting up TLS connections for a client."""
444
445    @abstractmethod
446    def __init__(self, configuration: TLSClientConfiguration) -> None:
447        """Create a new client context object from a given TLS client configuration."""
448        ...
449
450    @property
451    @abstractmethod
452    def configuration(self) -> TLSClientConfiguration:
453        """Returns the TLS client configuration that was used to create the client context."""
454
455    @abstractmethod
456    def connect(self, address: tuple[str | None, int]) -> TLSSocket:
457        """Creates a TLSSocket that behaves like a socket.socket, and
458        contains information about the TLS exchange
459        (cipher, negotiated_protocol, negotiated_tls_version, etc.).
460        """
461
462    @abstractmethod
463    def create_buffer(self, server_hostname: str) -> TLSBuffer:
464        """Creates a TLSBuffer that acts as an in-memory channel,
465        and contains information about the TLS exchange
466        (cipher, negotiated_protocol, negotiated_tls_version, etc.)."""

Context for setting up TLS connections for a client.

@abstractmethod
ClientContext(configuration: TLSClientConfiguration)
445    @abstractmethod
446    def __init__(self, configuration: TLSClientConfiguration) -> None:
447        """Create a new client context object from a given TLS client configuration."""
448        ...

Create a new client context object from a given TLS client configuration.

configuration: TLSClientConfiguration
450    @property
451    @abstractmethod
452    def configuration(self) -> TLSClientConfiguration:
453        """Returns the TLS client configuration that was used to create the client context."""

Returns the TLS client configuration that was used to create the client context.

@abstractmethod
def connect(self, address: tuple[str | None, int]) -> tlslib.tlslib.TLSSocket:
455    @abstractmethod
456    def connect(self, address: tuple[str | None, int]) -> TLSSocket:
457        """Creates a TLSSocket that behaves like a socket.socket, and
458        contains information about the TLS exchange
459        (cipher, negotiated_protocol, negotiated_tls_version, etc.).
460        """

Creates a TLSSocket that behaves like a socket.socket, and contains information about the TLS exchange (cipher, negotiated_protocol, negotiated_tls_version, etc.).

@abstractmethod
def create_buffer(self, server_hostname: str) -> TLSBuffer:
462    @abstractmethod
463    def create_buffer(self, server_hostname: str) -> TLSBuffer:
464        """Creates a TLSBuffer that acts as an in-memory channel,
465        and contains information about the TLS exchange
466        (cipher, negotiated_protocol, negotiated_tls_version, etc.)."""

Creates a TLSBuffer that acts as an in-memory channel, and contains information about the TLS exchange (cipher, negotiated_protocol, negotiated_tls_version, etc.).

class ServerContext(typing.Protocol):
472class ServerContext(Protocol):
473    """Context for setting up TLS connections for a server."""
474
475    @abstractmethod
476    def __init__(self, configuration: TLSServerConfiguration) -> None:
477        """Create a new server context object from a given TLS server configuration."""
478        ...
479
480    @property
481    @abstractmethod
482    def configuration(self) -> TLSServerConfiguration:
483        """Returns the TLS server configuration that was used to create the server context."""
484
485    @abstractmethod
486    def connect(self, address: tuple[str | None, int]) -> TLSSocket:
487        """Creates a TLSSocket that behaves like a socket.socket, and
488        contains information about the TLS exchange
489        (cipher, negotiated_protocol, negotiated_tls_version, etc.).
490        """
491
492    @abstractmethod
493    def create_buffer(self) -> TLSBuffer:
494        """Creates a TLSBuffer that acts as an in-memory channel,
495        and contains information about the TLS exchange
496        (cipher, negotiated_protocol, negotiated_tls_version, etc.)."""

Context for setting up TLS connections for a server.

@abstractmethod
ServerContext(configuration: TLSServerConfiguration)
475    @abstractmethod
476    def __init__(self, configuration: TLSServerConfiguration) -> None:
477        """Create a new server context object from a given TLS server configuration."""
478        ...

Create a new server context object from a given TLS server configuration.

configuration: TLSServerConfiguration
480    @property
481    @abstractmethod
482    def configuration(self) -> TLSServerConfiguration:
483        """Returns the TLS server configuration that was used to create the server context."""

Returns the TLS server configuration that was used to create the server context.

@abstractmethod
def connect(self, address: tuple[str | None, int]) -> tlslib.tlslib.TLSSocket:
485    @abstractmethod
486    def connect(self, address: tuple[str | None, int]) -> TLSSocket:
487        """Creates a TLSSocket that behaves like a socket.socket, and
488        contains information about the TLS exchange
489        (cipher, negotiated_protocol, negotiated_tls_version, etc.).
490        """

Creates a TLSSocket that behaves like a socket.socket, and contains information about the TLS exchange (cipher, negotiated_protocol, negotiated_tls_version, etc.).

@abstractmethod
def create_buffer(self) -> TLSBuffer:
492    @abstractmethod
493    def create_buffer(self) -> TLSBuffer:
494        """Creates a TLSBuffer that acts as an in-memory channel,
495        and contains information about the TLS exchange
496        (cipher, negotiated_protocol, negotiated_tls_version, etc.)."""

Creates a TLSBuffer that acts as an in-memory channel, and contains information about the TLS exchange (cipher, negotiated_protocol, negotiated_tls_version, etc.).

class CipherSuite(enum.IntEnum):
752class CipherSuite(IntEnum):
753    """
754    Known cipher suites.
755
756    See: <https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml>
757    """
758
759    TLS_AES_128_GCM_SHA256 = 0x1301
760    TLS_AES_256_GCM_SHA384 = 0x1302
761    TLS_CHACHA20_POLY1305_SHA256 = 0x1303
762    TLS_AES_128_CCM_SHA256 = 0x1304
763    TLS_AES_128_CCM_8_SHA256 = 0x1305
764    TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B
765    TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C
766    TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F
767    TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030
768    TLS_ECDHE_ECDSA_WITH_AES_128_CCM = 0xC0AC
769    TLS_ECDHE_ECDSA_WITH_AES_256_CCM = 0xC0AD
770    TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 = 0xC0AE
771    TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 = 0xC0AF
772    TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA8
773    TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA9
TLS_AES_128_GCM_SHA256 = <CipherSuite.TLS_AES_128_GCM_SHA256: 4865>
TLS_AES_256_GCM_SHA384 = <CipherSuite.TLS_AES_256_GCM_SHA384: 4866>
TLS_CHACHA20_POLY1305_SHA256 = <CipherSuite.TLS_CHACHA20_POLY1305_SHA256: 4867>
TLS_AES_128_CCM_SHA256 = <CipherSuite.TLS_AES_128_CCM_SHA256: 4868>
TLS_AES_128_CCM_8_SHA256 = <CipherSuite.TLS_AES_128_CCM_8_SHA256: 4869>
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = <CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: 49195>
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = <CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: 49196>
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = <CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: 49199>
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = <CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: 49200>
TLS_ECDHE_ECDSA_WITH_AES_128_CCM = <CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM: 49324>
TLS_ECDHE_ECDSA_WITH_AES_256_CCM = <CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM: 49325>
TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 = <CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: 49326>
TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 = <CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8: 49327>
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = <CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: 52392>
TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = <CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: 52393>
Inherited Members
enum.Enum
name
value
builtins.int
conjugate
bit_length
bit_count
to_bytes
from_bytes
as_integer_ratio
is_integer
real
imag
numerator
denominator
class NextProtocol(enum.Enum):
793class NextProtocol(Enum):
794    """The underlying negotiated ("next") protocol."""
795
796    H2 = b"h2"
797    H2C = b"h2c"
798    HTTP1 = b"http/1.1"
799    WEBRTC = b"webrtc"
800    C_WEBRTC = b"c-webrtc"
801    FTP = b"ftp"
802    STUN = b"stun.nat-discovery"
803    TURN = b"stun.turn"

The underlying negotiated ("next") protocol.

H2 = <NextProtocol.H2: b'h2'>
H2C = <NextProtocol.H2C: b'h2c'>
HTTP1 = <NextProtocol.HTTP1: b'http/1.1'>
WEBRTC = <NextProtocol.WEBRTC: b'webrtc'>
C_WEBRTC = <NextProtocol.C_WEBRTC: b'c-webrtc'>
FTP = <NextProtocol.FTP: b'ftp'>
STUN = <NextProtocol.STUN: b'stun.nat-discovery'>
TURN = <NextProtocol.TURN: b'stun.turn'>
Inherited Members
enum.Enum
name
value
class TLSVersion(enum.Enum):
806class TLSVersion(Enum):
807    """
808    TLS versions.
809
810    The `MINIMUM_SUPPORTED` and `MAXIMUM_SUPPORTED` variants are "open ended",
811    and refer to the "lowest mutually supported" and "highest mutually supported"
812    TLS versions, respectively.
813    """
814
815    MINIMUM_SUPPORTED = "MINIMUM_SUPPORTED"
816    TLSv1_2 = "TLSv1.2"
817    TLSv1_3 = "TLSv1.3"
818    MAXIMUM_SUPPORTED = "MAXIMUM_SUPPORTED"

TLS versions.

The MINIMUM_SUPPORTED and MAXIMUM_SUPPORTED variants are "open ended", and refer to the "lowest mutually supported" and "highest mutually supported" TLS versions, respectively.

MINIMUM_SUPPORTED = <TLSVersion.MINIMUM_SUPPORTED: 'MINIMUM_SUPPORTED'>
TLSv1_2 = <TLSVersion.TLSv1_2: 'TLSv1.2'>
TLSv1_3 = <TLSVersion.TLSv1_3: 'TLSv1.3'>
MAXIMUM_SUPPORTED = <TLSVersion.MAXIMUM_SUPPORTED: 'MAXIMUM_SUPPORTED'>
Inherited Members
enum.Enum
name
value
class TLSError(builtins.Exception):
821class TLSError(Exception):
822    """
823    The base exception for all TLS related errors from any implementation.
824
825    Catching this error should be sufficient to catch *all* TLS errors,
826    regardless of what implementation is used.
827    """

The base exception for all TLS related errors from any implementation.

Catching this error should be sufficient to catch all TLS errors, regardless of what implementation is used.

Inherited Members
builtins.Exception
Exception
builtins.BaseException
with_traceback
add_note
args
class WantWriteError(TLSError):
830class WantWriteError(TLSError):
831    """
832    A special signaling exception used only when non-blocking or buffer-only I/O is used.
833
834    This error signals that the requested
835    operation cannot complete until more data is written to the network,
836    or until the output buffer is drained.
837
838    This error is should only be raised when it is completely impossible
839    to write any data. If a partial write is achievable then this should
840    not be raised.
841    """

A special signaling exception used only when non-blocking or buffer-only I/O is used.

This error signals that the requested operation cannot complete until more data is written to the network, or until the output buffer is drained.

This error is should only be raised when it is completely impossible to write any data. If a partial write is achievable then this should not be raised.

Inherited Members
builtins.Exception
Exception
builtins.BaseException
with_traceback
add_note
args
class WantReadError(TLSError):
844class WantReadError(TLSError):
845    """
846    A special signaling exception used only when non-blocking or buffer-only I/O is used.
847
848    This error signals that the requested
849    operation cannot complete until more data is read from the network, or
850    until more data is available in the input buffer.
851
852    This error should only be raised when it is completely impossible to
853    write any data. If a partial write is achievable then this should not
854    be raised.
855    """

A special signaling exception used only when non-blocking or buffer-only I/O is used.

This error signals that the requested operation cannot complete until more data is read from the network, or until more data is available in the input buffer.

This error should only be raised when it is completely impossible to write any data. If a partial write is achievable then this should not be raised.

Inherited Members
builtins.Exception
Exception
builtins.BaseException
with_traceback
add_note
args
class RaggedEOF(TLSError):
858class RaggedEOF(TLSError):
859    """A special signaling exception used when a TLS connection has been
860    closed gracelessly: that is, when a TLS CloseNotify was not received
861    from the peer before the underlying TCP socket reached EOF. This is a
862    so-called "ragged EOF".
863
864    This exception is not guaranteed to be raised in the face of a ragged
865    EOF: some implementations may not be able to detect or report the
866    ragged EOF.
867
868    This exception is not always a problem. Ragged EOFs are a concern only
869    when protocols are vulnerable to length truncation attacks. Any
870    protocol that can detect length truncation attacks at the application
871    layer (e.g. HTTP/1.1 and HTTP/2) is not vulnerable to this kind of
872    attack and so can ignore this exception.
873    """

A special signaling exception used when a TLS connection has been closed gracelessly: that is, when a TLS CloseNotify was not received from the peer before the underlying TCP socket reached EOF. This is a so-called "ragged EOF".

This exception is not guaranteed to be raised in the face of a ragged EOF: some implementations may not be able to detect or report the ragged EOF.

This exception is not always a problem. Ragged EOFs are a concern only when protocols are vulnerable to length truncation attacks. Any protocol that can detect length truncation attacks at the application layer (e.g. HTTP/1.1 and HTTP/2) is not vulnerable to this kind of attack and so can ignore this exception.

Inherited Members
builtins.Exception
Exception
builtins.BaseException
with_traceback
add_note
args
class Certificate:
 85class Certificate:
 86    """Object representing a certificate used in TLS."""
 87
 88    __slots__ = (
 89        "_buffer",
 90        "_path",
 91        "_id",
 92    )
 93
 94    def __init__(
 95        self, buffer: bytes | None = None, path: os.PathLike | None = None, id: bytes | None = None
 96    ):
 97        """
 98        Creates a Certificate object from a path, buffer, or ID.
 99
100        If none of these is given, an exception is raised.
101        """
102
103        if buffer is None and path is None and id is None:
104            raise ValueError("Certificate cannot be empty.")
105
106        self._buffer = buffer
107        self._path = path
108        self._id = id
109
110    @classmethod
111    def from_buffer(cls, buffer: bytes) -> Certificate:
112        """
113        Creates a Certificate object from a byte buffer. This byte buffer
114        may be either PEM-encoded or DER-encoded. If the buffer is PEM
115        encoded it *must* begin with the standard PEM preamble (a series of
116        dashes followed by the ASCII bytes "BEGIN CERTIFICATE" and another
117        series of dashes). In the absence of that preamble, the
118        implementation may assume that the certificate is DER-encoded
119        instead.
120        """
121        return cls(buffer=buffer)
122
123    @classmethod
124    def from_file(cls, path: os.PathLike) -> Certificate:
125        """
126        Creates a Certificate object from a file on disk. The file on disk
127        should contain a series of bytes corresponding to a certificate that
128        may be either PEM-encoded or DER-encoded. If the bytes are PEM encoded
129        it *must* begin with the standard PEM preamble (a series of dashes
130        followed by the ASCII bytes "BEGIN CERTIFICATE" and another series of
131        dashes). In the absence of that preamble, the implementation may
132        assume that the certificate is DER-encoded instead.
133        """
134        return cls(path=path)
135
136    @classmethod
137    def from_id(cls, id: bytes) -> Certificate:
138        """
139        Creates a Certificate object from an arbitrary identifier. This may
140        be useful for implementations that rely on system certificate stores.
141        """
142        return cls(id=id)

Object representing a certificate used in TLS.

Certificate( buffer: bytes | None = None, path: os.PathLike | None = None, id: bytes | None = None)
 94    def __init__(
 95        self, buffer: bytes | None = None, path: os.PathLike | None = None, id: bytes | None = None
 96    ):
 97        """
 98        Creates a Certificate object from a path, buffer, or ID.
 99
100        If none of these is given, an exception is raised.
101        """
102
103        if buffer is None and path is None and id is None:
104            raise ValueError("Certificate cannot be empty.")
105
106        self._buffer = buffer
107        self._path = path
108        self._id = id

Creates a Certificate object from a path, buffer, or ID.

If none of these is given, an exception is raised.

@classmethod
def from_buffer(cls, buffer: bytes) -> Certificate:
110    @classmethod
111    def from_buffer(cls, buffer: bytes) -> Certificate:
112        """
113        Creates a Certificate object from a byte buffer. This byte buffer
114        may be either PEM-encoded or DER-encoded. If the buffer is PEM
115        encoded it *must* begin with the standard PEM preamble (a series of
116        dashes followed by the ASCII bytes "BEGIN CERTIFICATE" and another
117        series of dashes). In the absence of that preamble, the
118        implementation may assume that the certificate is DER-encoded
119        instead.
120        """
121        return cls(buffer=buffer)

Creates a Certificate object from a byte buffer. This byte buffer may be either PEM-encoded or DER-encoded. If the buffer is PEM encoded it must begin with the standard PEM preamble (a series of dashes followed by the ASCII bytes "BEGIN CERTIFICATE" and another series of dashes). In the absence of that preamble, the implementation may assume that the certificate is DER-encoded instead.

@classmethod
def from_file(cls, path: os.PathLike) -> Certificate:
123    @classmethod
124    def from_file(cls, path: os.PathLike) -> Certificate:
125        """
126        Creates a Certificate object from a file on disk. The file on disk
127        should contain a series of bytes corresponding to a certificate that
128        may be either PEM-encoded or DER-encoded. If the bytes are PEM encoded
129        it *must* begin with the standard PEM preamble (a series of dashes
130        followed by the ASCII bytes "BEGIN CERTIFICATE" and another series of
131        dashes). In the absence of that preamble, the implementation may
132        assume that the certificate is DER-encoded instead.
133        """
134        return cls(path=path)

Creates a Certificate object from a file on disk. The file on disk should contain a series of bytes corresponding to a certificate that may be either PEM-encoded or DER-encoded. If the bytes are PEM encoded it must begin with the standard PEM preamble (a series of dashes followed by the ASCII bytes "BEGIN CERTIFICATE" and another series of dashes). In the absence of that preamble, the implementation may assume that the certificate is DER-encoded instead.

@classmethod
def from_id(cls, id: bytes) -> Certificate:
136    @classmethod
137    def from_id(cls, id: bytes) -> Certificate:
138        """
139        Creates a Certificate object from an arbitrary identifier. This may
140        be useful for implementations that rely on system certificate stores.
141        """
142        return cls(id=id)

Creates a Certificate object from an arbitrary identifier. This may be useful for implementations that rely on system certificate stores.

class PrivateKey:
145class PrivateKey:
146    """Object representing a private key corresponding to a public key
147    for a certificate used in TLS."""
148
149    __slots__ = (
150        "_buffer",
151        "_path",
152        "_id",
153    )
154
155    def __init__(
156        self, buffer: bytes | None = None, path: os.PathLike | None = None, id: bytes | None = None
157    ):
158        """
159        Creates a PrivateKey object from a path, buffer, or ID.
160
161        If none of these is given, an exception is raised.
162        """
163
164        if buffer is None and path is None and id is None:
165            raise ValueError("PrivateKey cannot be empty.")
166
167        self._buffer = buffer
168        self._path = path
169        self._id = id
170
171    @classmethod
172    def from_buffer(cls, buffer: bytes) -> PrivateKey:
173        """
174        Creates a PrivateKey object from a byte buffer. This byte buffer
175        may be either PEM-encoded or DER-encoded. If the buffer is PEM
176        encoded it *must* begin with the standard PEM preamble (a series of
177        dashes followed by the ASCII bytes "BEGIN", the key type, and
178        another series of dashes). In the absence of that preamble, the
179        implementation may assume that the private key is DER-encoded
180        instead.
181        """
182        return cls(buffer=buffer)
183
184    @classmethod
185    def from_file(cls, path: os.PathLike) -> PrivateKey:
186        """
187        Creates a PrivateKey object from a file on disk. The file on disk
188        should contain a series of bytes corresponding to a certificate that
189        may be either PEM-encoded or DER-encoded. If the bytes are PEM encoded
190        it *must* begin with the standard PEM preamble (a series of dashes
191        followed by the ASCII bytes "BEGIN", the key type, and another series
192        of dashes). In the absence of that preamble, the implementation may
193        assume that the certificate is DER-encoded instead.
194        """
195        return cls(path=path)
196
197    @classmethod
198    def from_id(cls, id: bytes) -> PrivateKey:
199        """
200        Creates a PrivateKey object from an arbitrary identifier. This may
201        be useful for implementations that rely on system private key stores.
202        """
203        return cls(id=id)

Object representing a private key corresponding to a public key for a certificate used in TLS.

PrivateKey( buffer: bytes | None = None, path: os.PathLike | None = None, id: bytes | None = None)
155    def __init__(
156        self, buffer: bytes | None = None, path: os.PathLike | None = None, id: bytes | None = None
157    ):
158        """
159        Creates a PrivateKey object from a path, buffer, or ID.
160
161        If none of these is given, an exception is raised.
162        """
163
164        if buffer is None and path is None and id is None:
165            raise ValueError("PrivateKey cannot be empty.")
166
167        self._buffer = buffer
168        self._path = path
169        self._id = id

Creates a PrivateKey object from a path, buffer, or ID.

If none of these is given, an exception is raised.

@classmethod
def from_buffer(cls, buffer: bytes) -> PrivateKey:
171    @classmethod
172    def from_buffer(cls, buffer: bytes) -> PrivateKey:
173        """
174        Creates a PrivateKey object from a byte buffer. This byte buffer
175        may be either PEM-encoded or DER-encoded. If the buffer is PEM
176        encoded it *must* begin with the standard PEM preamble (a series of
177        dashes followed by the ASCII bytes "BEGIN", the key type, and
178        another series of dashes). In the absence of that preamble, the
179        implementation may assume that the private key is DER-encoded
180        instead.
181        """
182        return cls(buffer=buffer)

Creates a PrivateKey object from a byte buffer. This byte buffer may be either PEM-encoded or DER-encoded. If the buffer is PEM encoded it must begin with the standard PEM preamble (a series of dashes followed by the ASCII bytes "BEGIN", the key type, and another series of dashes). In the absence of that preamble, the implementation may assume that the private key is DER-encoded instead.

@classmethod
def from_file(cls, path: os.PathLike) -> PrivateKey:
184    @classmethod
185    def from_file(cls, path: os.PathLike) -> PrivateKey:
186        """
187        Creates a PrivateKey object from a file on disk. The file on disk
188        should contain a series of bytes corresponding to a certificate that
189        may be either PEM-encoded or DER-encoded. If the bytes are PEM encoded
190        it *must* begin with the standard PEM preamble (a series of dashes
191        followed by the ASCII bytes "BEGIN", the key type, and another series
192        of dashes). In the absence of that preamble, the implementation may
193        assume that the certificate is DER-encoded instead.
194        """
195        return cls(path=path)

Creates a PrivateKey object from a file on disk. The file on disk should contain a series of bytes corresponding to a certificate that may be either PEM-encoded or DER-encoded. If the bytes are PEM encoded it must begin with the standard PEM preamble (a series of dashes followed by the ASCII bytes "BEGIN", the key type, and another series of dashes). In the absence of that preamble, the implementation may assume that the certificate is DER-encoded instead.

@classmethod
def from_id(cls, id: bytes) -> PrivateKey:
197    @classmethod
198    def from_id(cls, id: bytes) -> PrivateKey:
199        """
200        Creates a PrivateKey object from an arbitrary identifier. This may
201        be useful for implementations that rely on system private key stores.
202        """
203        return cls(id=id)

Creates a PrivateKey object from an arbitrary identifier. This may be useful for implementations that rely on system private key stores.

class TLSImplementation(typing.Generic[~_ClientContext, ~_ServerContext]):
899class TLSImplementation(Generic[_ClientContext, _ServerContext]):
900    """An object representing the collection of classes that implement the
901    PEP 543 abstract TLS API for a specific TLS implementation.
902    """
903
904    __slots__ = (
905        "_client_context",
906        "_server_context",
907        "_validate_config",
908    )
909
910    def __init__(
911        self,
912        client_context: type[_ClientContext],
913        server_context: type[_ServerContext],
914        validate_config: Callable[[TLSClientConfiguration | TLSServerConfiguration], None],
915    ) -> None:
916        """Initializes all attributes of the implementation."""
917
918        self._client_context = client_context
919        self._server_context = server_context
920        self._validate_config = validate_config
921
922    @property
923    def client_context(self) -> type[_ClientContext]:
924        """The concrete implementation of the PEP 543 Client Context object,
925        if this TLS implementation supports being the client on a TLS connection.
926        """
927        return self._client_context
928
929    @property
930    def server_context(self) -> type[_ServerContext]:
931        """The concrete implementation of the PEP 543 Server Context object,
932        if this TLS implementation supports being a server on a TLS connection.
933        """
934        return self._server_context
935
936    @property
937    def validate_config(self) -> Callable[[TLSClientConfiguration | TLSServerConfiguration], None]:
938        """A function that reveals whether this TLS implementation supports a
939        particular TLS configuration.
940        """
941        return self._validate_config

An object representing the collection of classes that implement the PEP 543 abstract TLS API for a specific TLS implementation.

TLSImplementation( client_context: type[~_ClientContext], server_context: type[~_ServerContext], validate_config: collections.abc.Callable[[TLSClientConfiguration | TLSServerConfiguration], None])
910    def __init__(
911        self,
912        client_context: type[_ClientContext],
913        server_context: type[_ServerContext],
914        validate_config: Callable[[TLSClientConfiguration | TLSServerConfiguration], None],
915    ) -> None:
916        """Initializes all attributes of the implementation."""
917
918        self._client_context = client_context
919        self._server_context = server_context
920        self._validate_config = validate_config

Initializes all attributes of the implementation.

client_context: type[~_ClientContext]
922    @property
923    def client_context(self) -> type[_ClientContext]:
924        """The concrete implementation of the PEP 543 Client Context object,
925        if this TLS implementation supports being the client on a TLS connection.
926        """
927        return self._client_context

The concrete implementation of the PEP 543 Client Context object, if this TLS implementation supports being the client on a TLS connection.

server_context: type[~_ServerContext]
929    @property
930    def server_context(self) -> type[_ServerContext]:
931        """The concrete implementation of the PEP 543 Server Context object,
932        if this TLS implementation supports being a server on a TLS connection.
933        """
934        return self._server_context

The concrete implementation of the PEP 543 Server Context object, if this TLS implementation supports being a server on a TLS connection.

validate_config: collections.abc.Callable[[TLSClientConfiguration | TLSServerConfiguration], None]
936    @property
937    def validate_config(self) -> Callable[[TLSClientConfiguration | TLSServerConfiguration], None]:
938        """A function that reveals whether this TLS implementation supports a
939        particular TLS configuration.
940        """
941        return self._validate_config

A function that reveals whether this TLS implementation supports a particular TLS configuration.