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