1:mod:`ssl` --- TLS/SSL wrapper for socket objects 2================================================= 3 4.. module:: ssl 5 :synopsis: TLS/SSL wrapper for socket objects 6 7.. moduleauthor:: Bill Janssen <[email protected]> 8.. sectionauthor:: Bill Janssen <[email protected]> 9 10**Source code:** :source:`Lib/ssl.py` 11 12.. index:: single: OpenSSL; (use in module ssl) 13 14.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer 15 16-------------- 17 18This module provides access to Transport Layer Security (often known as "Secure 19Sockets Layer") encryption and peer authentication facilities for network 20sockets, both client-side and server-side. This module uses the OpenSSL 21library. It is available on all modern Unix systems, Windows, macOS, and 22probably additional platforms, as long as OpenSSL is installed on that platform. 23 24.. note:: 25 26 Some behavior may be platform dependent, since calls are made to the 27 operating system socket APIs. The installed version of OpenSSL may also 28 cause variations in behavior. For example, TLSv1.3 with OpenSSL version 29 1.1.1. 30 31.. warning:: 32 Don't use this module without reading the :ref:`ssl-security`. Doing so 33 may lead to a false sense of security, as the default settings of the 34 ssl module are not necessarily appropriate for your application. 35 36.. include:: ../includes/wasm-notavail.rst 37 38This section documents the objects and functions in the ``ssl`` module; for more 39general information about TLS, SSL, and certificates, the reader is referred to 40the documents in the "See Also" section at the bottom. 41 42This module provides a class, :class:`ssl.SSLSocket`, which is derived from the 43:class:`socket.socket` type, and provides a socket-like wrapper that also 44encrypts and decrypts the data going over the socket with SSL. It supports 45additional methods such as :meth:`getpeercert`, which retrieves the 46certificate of the other side of the connection, and :meth:`cipher`, which 47retrieves the cipher being used for the secure connection. 48 49For more sophisticated applications, the :class:`ssl.SSLContext` class 50helps manage settings and certificates, which can then be inherited 51by SSL sockets created through the :meth:`SSLContext.wrap_socket` method. 52 53.. versionchanged:: 3.5.3 54 Updated to support linking with OpenSSL 1.1.0 55 56.. versionchanged:: 3.6 57 58 OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported. 59 In the future the ssl module will require at least OpenSSL 1.0.2 or 60 1.1.0. 61 62.. versionchanged:: 3.10 63 64 :pep:`644` has been implemented. The ssl module requires OpenSSL 1.1.1 65 or newer. 66 67 Use of deprecated constants and functions result in deprecation warnings. 68 69 70Functions, Constants, and Exceptions 71------------------------------------ 72 73 74Socket creation 75^^^^^^^^^^^^^^^ 76 77Since Python 3.2 and 2.7.9, it is recommended to use the 78:meth:`SSLContext.wrap_socket` of an :class:`SSLContext` instance to wrap 79sockets as :class:`SSLSocket` objects. The helper functions 80:func:`create_default_context` returns a new context with secure default 81settings. The old :func:`wrap_socket` function is deprecated since it is 82both inefficient and has no support for server name indication (SNI) and 83hostname matching. 84 85Client socket example with default context and IPv4/IPv6 dual stack:: 86 87 import socket 88 import ssl 89 90 hostname = 'www.python.org' 91 context = ssl.create_default_context() 92 93 with socket.create_connection((hostname, 443)) as sock: 94 with context.wrap_socket(sock, server_hostname=hostname) as ssock: 95 print(ssock.version()) 96 97 98Client socket example with custom context and IPv4:: 99 100 hostname = 'www.python.org' 101 # PROTOCOL_TLS_CLIENT requires valid cert chain and hostname 102 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) 103 context.load_verify_locations('path/to/cabundle.pem') 104 105 with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock: 106 with context.wrap_socket(sock, server_hostname=hostname) as ssock: 107 print(ssock.version()) 108 109 110Server socket example listening on localhost IPv4:: 111 112 context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) 113 context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key') 114 115 with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock: 116 sock.bind(('127.0.0.1', 8443)) 117 sock.listen(5) 118 with context.wrap_socket(sock, server_side=True) as ssock: 119 conn, addr = ssock.accept() 120 ... 121 122 123Context creation 124^^^^^^^^^^^^^^^^ 125 126A convenience function helps create :class:`SSLContext` objects for common 127purposes. 128 129.. function:: create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None) 130 131 Return a new :class:`SSLContext` object with default settings for 132 the given *purpose*. The settings are chosen by the :mod:`ssl` module, 133 and usually represent a higher security level than when calling the 134 :class:`SSLContext` constructor directly. 135 136 *cafile*, *capath*, *cadata* represent optional CA certificates to 137 trust for certificate verification, as in 138 :meth:`SSLContext.load_verify_locations`. If all three are 139 :const:`None`, this function can choose to trust the system's default 140 CA certificates instead. 141 142 The settings are: :data:`PROTOCOL_TLS_CLIENT` or 143 :data:`PROTOCOL_TLS_SERVER`, :data:`OP_NO_SSLv2`, and :data:`OP_NO_SSLv3` 144 with high encryption cipher suites without RC4 and 145 without unauthenticated cipher suites. Passing :data:`~Purpose.SERVER_AUTH` 146 as *purpose* sets :data:`~SSLContext.verify_mode` to :data:`CERT_REQUIRED` 147 and either loads CA certificates (when at least one of *cafile*, *capath* or 148 *cadata* is given) or uses :meth:`SSLContext.load_default_certs` to load 149 default CA certificates. 150 151 When :attr:`~SSLContext.keylog_filename` is supported and the environment 152 variable :envvar:`SSLKEYLOGFILE` is set, :func:`create_default_context` 153 enables key logging. 154 155 .. note:: 156 The protocol, options, cipher and other settings may change to more 157 restrictive values anytime without prior deprecation. The values 158 represent a fair balance between compatibility and security. 159 160 If your application needs specific settings, you should create a 161 :class:`SSLContext` and apply the settings yourself. 162 163 .. note:: 164 If you find that when certain older clients or servers attempt to connect 165 with a :class:`SSLContext` created by this function that they get an error 166 stating "Protocol or cipher suite mismatch", it may be that they only 167 support SSL3.0 which this function excludes using the 168 :data:`OP_NO_SSLv3`. SSL3.0 is widely considered to be `completely broken 169 <https://en.wikipedia.org/wiki/POODLE>`_. If you still wish to continue to 170 use this function but still allow SSL 3.0 connections you can re-enable 171 them using:: 172 173 ctx = ssl.create_default_context(Purpose.CLIENT_AUTH) 174 ctx.options &= ~ssl.OP_NO_SSLv3 175 176 .. versionadded:: 3.4 177 178 .. versionchanged:: 3.4.4 179 180 RC4 was dropped from the default cipher string. 181 182 .. versionchanged:: 3.6 183 184 ChaCha20/Poly1305 was added to the default cipher string. 185 186 3DES was dropped from the default cipher string. 187 188 .. versionchanged:: 3.8 189 190 Support for key logging to :envvar:`SSLKEYLOGFILE` was added. 191 192 .. versionchanged:: 3.10 193 194 The context now uses :data:`PROTOCOL_TLS_CLIENT` or 195 :data:`PROTOCOL_TLS_SERVER` protocol instead of generic 196 :data:`PROTOCOL_TLS`. 197 198 199Exceptions 200^^^^^^^^^^ 201 202.. exception:: SSLError 203 204 Raised to signal an error from the underlying SSL implementation 205 (currently provided by the OpenSSL library). This signifies some 206 problem in the higher-level encryption and authentication layer that's 207 superimposed on the underlying network connection. This error 208 is a subtype of :exc:`OSError`. The error code and message of 209 :exc:`SSLError` instances are provided by the OpenSSL library. 210 211 .. versionchanged:: 3.3 212 :exc:`SSLError` used to be a subtype of :exc:`socket.error`. 213 214 .. attribute:: library 215 216 A string mnemonic designating the OpenSSL submodule in which the error 217 occurred, such as ``SSL``, ``PEM`` or ``X509``. The range of possible 218 values depends on the OpenSSL version. 219 220 .. versionadded:: 3.3 221 222 .. attribute:: reason 223 224 A string mnemonic designating the reason this error occurred, for 225 example ``CERTIFICATE_VERIFY_FAILED``. The range of possible 226 values depends on the OpenSSL version. 227 228 .. versionadded:: 3.3 229 230.. exception:: SSLZeroReturnError 231 232 A subclass of :exc:`SSLError` raised when trying to read or write and 233 the SSL connection has been closed cleanly. Note that this doesn't 234 mean that the underlying transport (read TCP) has been closed. 235 236 .. versionadded:: 3.3 237 238.. exception:: SSLWantReadError 239 240 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket 241 <ssl-nonblocking>` when trying to read or write data, but more data needs 242 to be received on the underlying TCP transport before the request can be 243 fulfilled. 244 245 .. versionadded:: 3.3 246 247.. exception:: SSLWantWriteError 248 249 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket 250 <ssl-nonblocking>` when trying to read or write data, but more data needs 251 to be sent on the underlying TCP transport before the request can be 252 fulfilled. 253 254 .. versionadded:: 3.3 255 256.. exception:: SSLSyscallError 257 258 A subclass of :exc:`SSLError` raised when a system error was encountered 259 while trying to fulfill an operation on a SSL socket. Unfortunately, 260 there is no easy way to inspect the original errno number. 261 262 .. versionadded:: 3.3 263 264.. exception:: SSLEOFError 265 266 A subclass of :exc:`SSLError` raised when the SSL connection has been 267 terminated abruptly. Generally, you shouldn't try to reuse the underlying 268 transport when this error is encountered. 269 270 .. versionadded:: 3.3 271 272.. exception:: SSLCertVerificationError 273 274 A subclass of :exc:`SSLError` raised when certificate validation has 275 failed. 276 277 .. versionadded:: 3.7 278 279 .. attribute:: verify_code 280 281 A numeric error number that denotes the verification error. 282 283 .. attribute:: verify_message 284 285 A human readable string of the verification error. 286 287.. exception:: CertificateError 288 289 An alias for :exc:`SSLCertVerificationError`. 290 291 .. versionchanged:: 3.7 292 The exception is now an alias for :exc:`SSLCertVerificationError`. 293 294 295Random generation 296^^^^^^^^^^^^^^^^^ 297 298.. function:: RAND_bytes(num) 299 300 Return *num* cryptographically strong pseudo-random bytes. Raises an 301 :class:`SSLError` if the PRNG has not been seeded with enough data or if the 302 operation is not supported by the current RAND method. :func:`RAND_status` 303 can be used to check the status of the PRNG and :func:`RAND_add` can be used 304 to seed the PRNG. 305 306 For almost all applications :func:`os.urandom` is preferable. 307 308 Read the Wikipedia article, `Cryptographically secure pseudorandom number 309 generator (CSPRNG) 310 <https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator>`_, 311 to get the requirements of a cryptographically strong generator. 312 313 .. versionadded:: 3.3 314 315.. function:: RAND_pseudo_bytes(num) 316 317 Return (bytes, is_cryptographic): bytes are *num* pseudo-random bytes, 318 is_cryptographic is ``True`` if the bytes generated are cryptographically 319 strong. Raises an :class:`SSLError` if the operation is not supported by the 320 current RAND method. 321 322 Generated pseudo-random byte sequences will be unique if they are of 323 sufficient length, but are not necessarily unpredictable. They can be used 324 for non-cryptographic purposes and for certain purposes in cryptographic 325 protocols, but usually not for key generation etc. 326 327 For almost all applications :func:`os.urandom` is preferable. 328 329 .. versionadded:: 3.3 330 331 .. deprecated:: 3.6 332 333 OpenSSL has deprecated :func:`ssl.RAND_pseudo_bytes`, use 334 :func:`ssl.RAND_bytes` instead. 335 336.. function:: RAND_status() 337 338 Return ``True`` if the SSL pseudo-random number generator has been seeded 339 with 'enough' randomness, and ``False`` otherwise. You can use 340 :func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness of 341 the pseudo-random number generator. 342 343.. function:: RAND_add(bytes, entropy) 344 345 Mix the given *bytes* into the SSL pseudo-random number generator. The 346 parameter *entropy* (a float) is a lower bound on the entropy contained in 347 string (so you can always use :const:`0.0`). See :rfc:`1750` for more 348 information on sources of entropy. 349 350 .. versionchanged:: 3.5 351 Writable :term:`bytes-like object` is now accepted. 352 353Certificate handling 354^^^^^^^^^^^^^^^^^^^^ 355 356.. testsetup:: 357 358 import ssl 359 360.. function:: match_hostname(cert, hostname) 361 362 Verify that *cert* (in decoded format as returned by 363 :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules 364 applied are those for checking the identity of HTTPS servers as outlined 365 in :rfc:`2818`, :rfc:`5280` and :rfc:`6125`. In addition to HTTPS, this 366 function should be suitable for checking the identity of servers in 367 various SSL-based protocols such as FTPS, IMAPS, POPS and others. 368 369 :exc:`CertificateError` is raised on failure. On success, the function 370 returns nothing:: 371 372 >>> cert = {'subject': ((('commonName', 'example.com'),),)} 373 >>> ssl.match_hostname(cert, "example.com") 374 >>> ssl.match_hostname(cert, "example.org") 375 Traceback (most recent call last): 376 File "<stdin>", line 1, in <module> 377 File "/home/py3k/Lib/ssl.py", line 130, in match_hostname 378 ssl.CertificateError: hostname 'example.org' doesn't match 'example.com' 379 380 .. versionadded:: 3.2 381 382 .. versionchanged:: 3.3.3 383 The function now follows :rfc:`6125`, section 6.4.3 and does neither 384 match multiple wildcards (e.g. ``*.*.com`` or ``*a*.example.org``) nor 385 a wildcard inside an internationalized domain names (IDN) fragment. 386 IDN A-labels such as ``www*.xn--pthon-kva.org`` are still supported, 387 but ``x*.python.org`` no longer matches ``xn--tda.python.org``. 388 389 .. versionchanged:: 3.5 390 Matching of IP addresses, when present in the subjectAltName field 391 of the certificate, is now supported. 392 393 .. versionchanged:: 3.7 394 The function is no longer used to TLS connections. Hostname matching 395 is now performed by OpenSSL. 396 397 Allow wildcard when it is the leftmost and the only character 398 in that segment. Partial wildcards like ``www*.example.com`` are no 399 longer supported. 400 401 .. deprecated:: 3.7 402 403.. function:: cert_time_to_seconds(cert_time) 404 405 Return the time in seconds since the Epoch, given the ``cert_time`` 406 string representing the "notBefore" or "notAfter" date from a 407 certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C 408 locale). 409 410 Here's an example: 411 412 .. doctest:: newcontext 413 414 >>> import ssl 415 >>> timestamp = ssl.cert_time_to_seconds("Jan 5 09:34:43 2018 GMT") 416 >>> timestamp # doctest: +SKIP 417 1515144883 418 >>> from datetime import datetime 419 >>> print(datetime.utcfromtimestamp(timestamp)) # doctest: +SKIP 420 2018-01-05 09:34:43 421 422 "notBefore" or "notAfter" dates must use GMT (:rfc:`5280`). 423 424 .. versionchanged:: 3.5 425 Interpret the input time as a time in UTC as specified by 'GMT' 426 timezone in the input string. Local timezone was used 427 previously. Return an integer (no fractions of a second in the 428 input format) 429 430.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_TLS_CLIENT, \ 431 ca_certs=None[, timeout]) 432 433 Given the address ``addr`` of an SSL-protected server, as a (*hostname*, 434 *port-number*) pair, fetches the server's certificate, and returns it as a 435 PEM-encoded string. If ``ssl_version`` is specified, uses that version of 436 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is 437 specified, it should be a file containing a list of root certificates, the 438 same format as used for the same parameter in 439 :meth:`SSLContext.wrap_socket`. The call will attempt to validate the 440 server certificate against that set of root certificates, and will fail 441 if the validation attempt fails. A timeout can be specified with the 442 ``timeout`` parameter. 443 444 .. versionchanged:: 3.3 445 This function is now IPv6-compatible. 446 447 .. versionchanged:: 3.5 448 The default *ssl_version* is changed from :data:`PROTOCOL_SSLv3` to 449 :data:`PROTOCOL_TLS` for maximum compatibility with modern servers. 450 451 .. versionchanged:: 3.10 452 The *timeout* parameter was added. 453 454.. function:: DER_cert_to_PEM_cert(DER_cert_bytes) 455 456 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded 457 string version of the same certificate. 458 459.. function:: PEM_cert_to_DER_cert(PEM_cert_string) 460 461 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of 462 bytes for that same certificate. 463 464.. function:: get_default_verify_paths() 465 466 Returns a named tuple with paths to OpenSSL's default cafile and capath. 467 The paths are the same as used by 468 :meth:`SSLContext.set_default_verify_paths`. The return value is a 469 :term:`named tuple` ``DefaultVerifyPaths``: 470 471 * :attr:`cafile` - resolved path to cafile or ``None`` if the file doesn't exist, 472 * :attr:`capath` - resolved path to capath or ``None`` if the directory doesn't exist, 473 * :attr:`openssl_cafile_env` - OpenSSL's environment key that points to a cafile, 474 * :attr:`openssl_cafile` - hard coded path to a cafile, 475 * :attr:`openssl_capath_env` - OpenSSL's environment key that points to a capath, 476 * :attr:`openssl_capath` - hard coded path to a capath directory 477 478 .. versionadded:: 3.4 479 480.. function:: enum_certificates(store_name) 481 482 Retrieve certificates from Windows' system cert store. *store_name* may be 483 one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert 484 stores, too. 485 486 The function returns a list of (cert_bytes, encoding_type, trust) tuples. 487 The encoding_type specifies the encoding of cert_bytes. It is either 488 :const:`x509_asn` for X.509 ASN.1 data or :const:`pkcs_7_asn` for 489 PKCS#7 ASN.1 data. Trust specifies the purpose of the certificate as a set 490 of OIDS or exactly ``True`` if the certificate is trustworthy for all 491 purposes. 492 493 Example:: 494 495 >>> ssl.enum_certificates("CA") 496 [(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}), 497 (b'data...', 'x509_asn', True)] 498 499 .. availability:: Windows. 500 501 .. versionadded:: 3.4 502 503.. function:: enum_crls(store_name) 504 505 Retrieve CRLs from Windows' system cert store. *store_name* may be 506 one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert 507 stores, too. 508 509 The function returns a list of (cert_bytes, encoding_type, trust) tuples. 510 The encoding_type specifies the encoding of cert_bytes. It is either 511 :const:`x509_asn` for X.509 ASN.1 data or :const:`pkcs_7_asn` for 512 PKCS#7 ASN.1 data. 513 514 .. availability:: Windows. 515 516 .. versionadded:: 3.4 517 518.. function:: wrap_socket(sock, keyfile=None, certfile=None, \ 519 server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_TLS, \ 520 ca_certs=None, do_handshake_on_connect=True, \ 521 suppress_ragged_eofs=True, ciphers=None) 522 523 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance 524 of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps 525 the underlying socket in an SSL context. ``sock`` must be a 526 :data:`~socket.SOCK_STREAM` socket; other socket types are unsupported. 527 528 Internally, function creates a :class:`SSLContext` with protocol 529 *ssl_version* and :attr:`SSLContext.options` set to *cert_reqs*. If 530 parameters *keyfile*, *certfile*, *ca_certs* or *ciphers* are set, then 531 the values are passed to :meth:`SSLContext.load_cert_chain`, 532 :meth:`SSLContext.load_verify_locations`, and 533 :meth:`SSLContext.set_ciphers`. 534 535 The arguments *server_side*, *do_handshake_on_connect*, and 536 *suppress_ragged_eofs* have the same meaning as 537 :meth:`SSLContext.wrap_socket`. 538 539 .. deprecated:: 3.7 540 541 Since Python 3.2 and 2.7.9, it is recommended to use the 542 :meth:`SSLContext.wrap_socket` instead of :func:`wrap_socket`. The 543 top-level function is limited and creates an insecure client socket 544 without server name indication or hostname matching. 545 546Constants 547^^^^^^^^^ 548 549 All constants are now :class:`enum.IntEnum` or :class:`enum.IntFlag` collections. 550 551 .. versionadded:: 3.6 552 553.. data:: CERT_NONE 554 555 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` 556 parameter to :func:`wrap_socket`. Except for :const:`PROTOCOL_TLS_CLIENT`, 557 it is the default mode. With client-side sockets, just about any 558 cert is accepted. Validation errors, such as untrusted or expired cert, 559 are ignored and do not abort the TLS/SSL handshake. 560 561 In server mode, no certificate is requested from the client, so the client 562 does not send any for client cert authentication. 563 564 See the discussion of :ref:`ssl-security` below. 565 566.. data:: CERT_OPTIONAL 567 568 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` 569 parameter to :func:`wrap_socket`. In client mode, :const:`CERT_OPTIONAL` 570 has the same meaning as :const:`CERT_REQUIRED`. It is recommended to 571 use :const:`CERT_REQUIRED` for client-side sockets instead. 572 573 In server mode, a client certificate request is sent to the client. The 574 client may either ignore the request or send a certificate in order 575 perform TLS client cert authentication. If the client chooses to send 576 a certificate, it is verified. Any verification error immediately aborts 577 the TLS handshake. 578 579 Use of this setting requires a valid set of CA certificates to 580 be passed, either to :meth:`SSLContext.load_verify_locations` or as a 581 value of the ``ca_certs`` parameter to :func:`wrap_socket`. 582 583.. data:: CERT_REQUIRED 584 585 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` 586 parameter to :func:`wrap_socket`. In this mode, certificates are 587 required from the other side of the socket connection; an :class:`SSLError` 588 will be raised if no certificate is provided, or if its validation fails. 589 This mode is **not** sufficient to verify a certificate in client mode as 590 it does not match hostnames. :attr:`~SSLContext.check_hostname` must be 591 enabled as well to verify the authenticity of a cert. 592 :const:`PROTOCOL_TLS_CLIENT` uses :const:`CERT_REQUIRED` and 593 enables :attr:`~SSLContext.check_hostname` by default. 594 595 With server socket, this mode provides mandatory TLS client cert 596 authentication. A client certificate request is sent to the client and 597 the client must provide a valid and trusted certificate. 598 599 Use of this setting requires a valid set of CA certificates to 600 be passed, either to :meth:`SSLContext.load_verify_locations` or as a 601 value of the ``ca_certs`` parameter to :func:`wrap_socket`. 602 603.. class:: VerifyMode 604 605 :class:`enum.IntEnum` collection of CERT_* constants. 606 607 .. versionadded:: 3.6 608 609.. data:: VERIFY_DEFAULT 610 611 Possible value for :attr:`SSLContext.verify_flags`. In this mode, certificate 612 revocation lists (CRLs) are not checked. By default OpenSSL does neither 613 require nor verify CRLs. 614 615 .. versionadded:: 3.4 616 617.. data:: VERIFY_CRL_CHECK_LEAF 618 619 Possible value for :attr:`SSLContext.verify_flags`. In this mode, only the 620 peer cert is checked but none of the intermediate CA certificates. The mode 621 requires a valid CRL that is signed by the peer cert's issuer (its direct 622 ancestor CA). If no proper CRL has been loaded with 623 :attr:`SSLContext.load_verify_locations`, validation will fail. 624 625 .. versionadded:: 3.4 626 627.. data:: VERIFY_CRL_CHECK_CHAIN 628 629 Possible value for :attr:`SSLContext.verify_flags`. In this mode, CRLs of 630 all certificates in the peer cert chain are checked. 631 632 .. versionadded:: 3.4 633 634.. data:: VERIFY_X509_STRICT 635 636 Possible value for :attr:`SSLContext.verify_flags` to disable workarounds 637 for broken X.509 certificates. 638 639 .. versionadded:: 3.4 640 641.. data:: VERIFY_ALLOW_PROXY_CERTS 642 643 Possible value for :attr:`SSLContext.verify_flags` to enables proxy 644 certificate verification. 645 646 .. versionadded:: 3.10 647 648.. data:: VERIFY_X509_TRUSTED_FIRST 649 650 Possible value for :attr:`SSLContext.verify_flags`. It instructs OpenSSL to 651 prefer trusted certificates when building the trust chain to validate a 652 certificate. This flag is enabled by default. 653 654 .. versionadded:: 3.4.4 655 656.. data:: VERIFY_X509_PARTIAL_CHAIN 657 658 Possible value for :attr:`SSLContext.verify_flags`. It instructs OpenSSL to 659 accept intermediate CAs in the trust store to be treated as trust-anchors, 660 in the same way as the self-signed root CA certificates. This makes it 661 possible to trust certificates issued by an intermediate CA without having 662 to trust its ancestor root CA. 663 664 .. versionadded:: 3.10 665 666 667.. class:: VerifyFlags 668 669 :class:`enum.IntFlag` collection of VERIFY_* constants. 670 671 .. versionadded:: 3.6 672 673.. data:: PROTOCOL_TLS 674 675 Selects the highest protocol version that both the client and server support. 676 Despite the name, this option can select both "SSL" and "TLS" protocols. 677 678 .. versionadded:: 3.6 679 680 .. deprecated:: 3.10 681 682 TLS clients and servers require different default settings for secure 683 communication. The generic TLS protocol constant is deprecated in 684 favor of :data:`PROTOCOL_TLS_CLIENT` and :data:`PROTOCOL_TLS_SERVER`. 685 686.. data:: PROTOCOL_TLS_CLIENT 687 688 Auto-negotiate the highest protocol version that both the client and 689 server support, and configure the context client-side connections. The 690 protocol enables :data:`CERT_REQUIRED` and 691 :attr:`~SSLContext.check_hostname` by default. 692 693 .. versionadded:: 3.6 694 695.. data:: PROTOCOL_TLS_SERVER 696 697 Auto-negotiate the highest protocol version that both the client and 698 server support, and configure the context server-side connections. 699 700 .. versionadded:: 3.6 701 702.. data:: PROTOCOL_SSLv23 703 704 Alias for :data:`PROTOCOL_TLS`. 705 706 .. deprecated:: 3.6 707 708 Use :data:`PROTOCOL_TLS` instead. 709 710.. data:: PROTOCOL_SSLv2 711 712 Selects SSL version 2 as the channel encryption protocol. 713 714 This protocol is not available if OpenSSL is compiled with the 715 ``no-ssl2`` option. 716 717 .. warning:: 718 719 SSL version 2 is insecure. Its use is highly discouraged. 720 721 .. deprecated:: 3.6 722 723 OpenSSL has removed support for SSLv2. 724 725.. data:: PROTOCOL_SSLv3 726 727 Selects SSL version 3 as the channel encryption protocol. 728 729 This protocol is not available if OpenSSL is compiled with the 730 ``no-ssl3`` option. 731 732 .. warning:: 733 734 SSL version 3 is insecure. Its use is highly discouraged. 735 736 .. deprecated:: 3.6 737 738 OpenSSL has deprecated all version specific protocols. Use the default 739 protocol :data:`PROTOCOL_TLS_SERVER` or :data:`PROTOCOL_TLS_CLIENT` 740 with :attr:`SSLContext.minimum_version` and 741 :attr:`SSLContext.maximum_version` instead. 742 743 744.. data:: PROTOCOL_TLSv1 745 746 Selects TLS version 1.0 as the channel encryption protocol. 747 748 .. deprecated:: 3.6 749 750 OpenSSL has deprecated all version specific protocols. 751 752.. data:: PROTOCOL_TLSv1_1 753 754 Selects TLS version 1.1 as the channel encryption protocol. 755 Available only with openssl version 1.0.1+. 756 757 .. versionadded:: 3.4 758 759 .. deprecated:: 3.6 760 761 OpenSSL has deprecated all version specific protocols. 762 763.. data:: PROTOCOL_TLSv1_2 764 765 Selects TLS version 1.2 as the channel encryption protocol. 766 Available only with openssl version 1.0.1+. 767 768 .. versionadded:: 3.4 769 770 .. deprecated:: 3.6 771 772 OpenSSL has deprecated all version specific protocols. 773 774.. data:: OP_ALL 775 776 Enables workarounds for various bugs present in other SSL implementations. 777 This option is set by default. It does not necessarily set the same 778 flags as OpenSSL's ``SSL_OP_ALL`` constant. 779 780 .. versionadded:: 3.2 781 782.. data:: OP_NO_SSLv2 783 784 Prevents an SSLv2 connection. This option is only applicable in 785 conjunction with :const:`PROTOCOL_TLS`. It prevents the peers from 786 choosing SSLv2 as the protocol version. 787 788 .. versionadded:: 3.2 789 790 .. deprecated:: 3.6 791 792 SSLv2 is deprecated 793 794.. data:: OP_NO_SSLv3 795 796 Prevents an SSLv3 connection. This option is only applicable in 797 conjunction with :const:`PROTOCOL_TLS`. It prevents the peers from 798 choosing SSLv3 as the protocol version. 799 800 .. versionadded:: 3.2 801 802 .. deprecated:: 3.6 803 804 SSLv3 is deprecated 805 806.. data:: OP_NO_TLSv1 807 808 Prevents a TLSv1 connection. This option is only applicable in 809 conjunction with :const:`PROTOCOL_TLS`. It prevents the peers from 810 choosing TLSv1 as the protocol version. 811 812 .. versionadded:: 3.2 813 814 .. deprecated:: 3.7 815 The option is deprecated since OpenSSL 1.1.0, use the new 816 :attr:`SSLContext.minimum_version` and 817 :attr:`SSLContext.maximum_version` instead. 818 819.. data:: OP_NO_TLSv1_1 820 821 Prevents a TLSv1.1 connection. This option is only applicable in conjunction 822 with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.1 as 823 the protocol version. Available only with openssl version 1.0.1+. 824 825 .. versionadded:: 3.4 826 827 .. deprecated:: 3.7 828 The option is deprecated since OpenSSL 1.1.0. 829 830.. data:: OP_NO_TLSv1_2 831 832 Prevents a TLSv1.2 connection. This option is only applicable in conjunction 833 with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.2 as 834 the protocol version. Available only with openssl version 1.0.1+. 835 836 .. versionadded:: 3.4 837 838 .. deprecated:: 3.7 839 The option is deprecated since OpenSSL 1.1.0. 840 841.. data:: OP_NO_TLSv1_3 842 843 Prevents a TLSv1.3 connection. This option is only applicable in conjunction 844 with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.3 as 845 the protocol version. TLS 1.3 is available with OpenSSL 1.1.1 or later. 846 When Python has been compiled against an older version of OpenSSL, the 847 flag defaults to *0*. 848 849 .. versionadded:: 3.7 850 851 .. deprecated:: 3.7 852 The option is deprecated since OpenSSL 1.1.0. It was added to 2.7.15, 853 3.6.3 and 3.7.0 for backwards compatibility with OpenSSL 1.0.2. 854 855.. data:: OP_NO_RENEGOTIATION 856 857 Disable all renegotiation in TLSv1.2 and earlier. Do not send 858 HelloRequest messages, and ignore renegotiation requests via ClientHello. 859 860 This option is only available with OpenSSL 1.1.0h and later. 861 862 .. versionadded:: 3.7 863 864.. data:: OP_CIPHER_SERVER_PREFERENCE 865 866 Use the server's cipher ordering preference, rather than the client's. 867 This option has no effect on client sockets and SSLv2 server sockets. 868 869 .. versionadded:: 3.3 870 871.. data:: OP_SINGLE_DH_USE 872 873 Prevents re-use of the same DH key for distinct SSL sessions. This 874 improves forward secrecy but requires more computational resources. 875 This option only applies to server sockets. 876 877 .. versionadded:: 3.3 878 879.. data:: OP_SINGLE_ECDH_USE 880 881 Prevents re-use of the same ECDH key for distinct SSL sessions. This 882 improves forward secrecy but requires more computational resources. 883 This option only applies to server sockets. 884 885 .. versionadded:: 3.3 886 887.. data:: OP_ENABLE_MIDDLEBOX_COMPAT 888 889 Send dummy Change Cipher Spec (CCS) messages in TLS 1.3 handshake to make 890 a TLS 1.3 connection look more like a TLS 1.2 connection. 891 892 This option is only available with OpenSSL 1.1.1 and later. 893 894 .. versionadded:: 3.8 895 896.. data:: OP_NO_COMPRESSION 897 898 Disable compression on the SSL channel. This is useful if the application 899 protocol supports its own compression scheme. 900 901 .. versionadded:: 3.3 902 903.. class:: Options 904 905 :class:`enum.IntFlag` collection of OP_* constants. 906 907.. data:: OP_NO_TICKET 908 909 Prevent client side from requesting a session ticket. 910 911 .. versionadded:: 3.6 912 913.. data:: OP_IGNORE_UNEXPECTED_EOF 914 915 Ignore unexpected shutdown of TLS connections. 916 917 This option is only available with OpenSSL 3.0.0 and later. 918 919 .. versionadded:: 3.10 920 921.. data:: HAS_ALPN 922 923 Whether the OpenSSL library has built-in support for the *Application-Layer 924 Protocol Negotiation* TLS extension as described in :rfc:`7301`. 925 926 .. versionadded:: 3.5 927 928.. data:: HAS_NEVER_CHECK_COMMON_NAME 929 930 Whether the OpenSSL library has built-in support not checking subject 931 common name and :attr:`SSLContext.hostname_checks_common_name` is 932 writeable. 933 934 .. versionadded:: 3.7 935 936.. data:: HAS_ECDH 937 938 Whether the OpenSSL library has built-in support for the Elliptic Curve-based 939 Diffie-Hellman key exchange. This should be true unless the feature was 940 explicitly disabled by the distributor. 941 942 .. versionadded:: 3.3 943 944.. data:: HAS_SNI 945 946 Whether the OpenSSL library has built-in support for the *Server Name 947 Indication* extension (as defined in :rfc:`6066`). 948 949 .. versionadded:: 3.2 950 951.. data:: HAS_NPN 952 953 Whether the OpenSSL library has built-in support for the *Next Protocol 954 Negotiation* as described in the `Application Layer Protocol 955 Negotiation <https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation>`_. 956 When true, you can use the :meth:`SSLContext.set_npn_protocols` method to advertise 957 which protocols you want to support. 958 959 .. versionadded:: 3.3 960 961.. data:: HAS_SSLv2 962 963 Whether the OpenSSL library has built-in support for the SSL 2.0 protocol. 964 965 .. versionadded:: 3.7 966 967.. data:: HAS_SSLv3 968 969 Whether the OpenSSL library has built-in support for the SSL 3.0 protocol. 970 971 .. versionadded:: 3.7 972 973.. data:: HAS_TLSv1 974 975 Whether the OpenSSL library has built-in support for the TLS 1.0 protocol. 976 977 .. versionadded:: 3.7 978 979.. data:: HAS_TLSv1_1 980 981 Whether the OpenSSL library has built-in support for the TLS 1.1 protocol. 982 983 .. versionadded:: 3.7 984 985.. data:: HAS_TLSv1_2 986 987 Whether the OpenSSL library has built-in support for the TLS 1.2 protocol. 988 989 .. versionadded:: 3.7 990 991.. data:: HAS_TLSv1_3 992 993 Whether the OpenSSL library has built-in support for the TLS 1.3 protocol. 994 995 .. versionadded:: 3.7 996 997.. data:: CHANNEL_BINDING_TYPES 998 999 List of supported TLS channel binding types. Strings in this list 1000 can be used as arguments to :meth:`SSLSocket.get_channel_binding`. 1001 1002 .. versionadded:: 3.3 1003 1004.. data:: OPENSSL_VERSION 1005 1006 The version string of the OpenSSL library loaded by the interpreter:: 1007 1008 >>> ssl.OPENSSL_VERSION 1009 'OpenSSL 1.0.2k 26 Jan 2017' 1010 1011 .. versionadded:: 3.2 1012 1013.. data:: OPENSSL_VERSION_INFO 1014 1015 A tuple of five integers representing version information about the 1016 OpenSSL library:: 1017 1018 >>> ssl.OPENSSL_VERSION_INFO 1019 (1, 0, 2, 11, 15) 1020 1021 .. versionadded:: 3.2 1022 1023.. data:: OPENSSL_VERSION_NUMBER 1024 1025 The raw version number of the OpenSSL library, as a single integer:: 1026 1027 >>> ssl.OPENSSL_VERSION_NUMBER 1028 268443839 1029 >>> hex(ssl.OPENSSL_VERSION_NUMBER) 1030 '0x100020bf' 1031 1032 .. versionadded:: 3.2 1033 1034.. data:: ALERT_DESCRIPTION_HANDSHAKE_FAILURE 1035 ALERT_DESCRIPTION_INTERNAL_ERROR 1036 ALERT_DESCRIPTION_* 1037 1038 Alert Descriptions from :rfc:`5246` and others. The `IANA TLS Alert Registry 1039 <https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6>`_ 1040 contains this list and references to the RFCs where their meaning is defined. 1041 1042 Used as the return value of the callback function in 1043 :meth:`SSLContext.set_servername_callback`. 1044 1045 .. versionadded:: 3.4 1046 1047.. class:: AlertDescription 1048 1049 :class:`enum.IntEnum` collection of ALERT_DESCRIPTION_* constants. 1050 1051 .. versionadded:: 3.6 1052 1053.. data:: Purpose.SERVER_AUTH 1054 1055 Option for :func:`create_default_context` and 1056 :meth:`SSLContext.load_default_certs`. This value indicates that the 1057 context may be used to authenticate web servers (therefore, it will 1058 be used to create client-side sockets). 1059 1060 .. versionadded:: 3.4 1061 1062.. data:: Purpose.CLIENT_AUTH 1063 1064 Option for :func:`create_default_context` and 1065 :meth:`SSLContext.load_default_certs`. This value indicates that the 1066 context may be used to authenticate web clients (therefore, it will 1067 be used to create server-side sockets). 1068 1069 .. versionadded:: 3.4 1070 1071.. class:: SSLErrorNumber 1072 1073 :class:`enum.IntEnum` collection of SSL_ERROR_* constants. 1074 1075 .. versionadded:: 3.6 1076 1077.. class:: TLSVersion 1078 1079 :class:`enum.IntEnum` collection of SSL and TLS versions for 1080 :attr:`SSLContext.maximum_version` and :attr:`SSLContext.minimum_version`. 1081 1082 .. versionadded:: 3.7 1083 1084.. attribute:: TLSVersion.MINIMUM_SUPPORTED 1085.. attribute:: TLSVersion.MAXIMUM_SUPPORTED 1086 1087 The minimum or maximum supported SSL or TLS version. These are magic 1088 constants. Their values don't reflect the lowest and highest available 1089 TLS/SSL versions. 1090 1091.. attribute:: TLSVersion.SSLv3 1092.. attribute:: TLSVersion.TLSv1 1093.. attribute:: TLSVersion.TLSv1_1 1094.. attribute:: TLSVersion.TLSv1_2 1095.. attribute:: TLSVersion.TLSv1_3 1096 1097 SSL 3.0 to TLS 1.3. 1098 1099 .. deprecated:: 3.10 1100 1101 All :class:`TLSVersion` members except :attr:`TLSVersion.TLSv1_2` and 1102 :attr:`TLSVersion.TLSv1_3` are deprecated. 1103 1104 1105SSL Sockets 1106----------- 1107 1108.. class:: SSLSocket(socket.socket) 1109 1110 SSL sockets provide the following methods of :ref:`socket-objects`: 1111 1112 - :meth:`~socket.socket.accept()` 1113 - :meth:`~socket.socket.bind()` 1114 - :meth:`~socket.socket.close()` 1115 - :meth:`~socket.socket.connect()` 1116 - :meth:`~socket.socket.detach()` 1117 - :meth:`~socket.socket.fileno()` 1118 - :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()` 1119 - :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()` 1120 - :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`, 1121 :meth:`~socket.socket.setblocking()` 1122 - :meth:`~socket.socket.listen()` 1123 - :meth:`~socket.socket.makefile()` 1124 - :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()` 1125 (but passing a non-zero ``flags`` argument is not allowed) 1126 - :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with 1127 the same limitation) 1128 - :meth:`~socket.socket.sendfile()` (but :mod:`os.sendfile` will be used 1129 for plain-text sockets only, else :meth:`~socket.socket.send()` will be used) 1130 - :meth:`~socket.socket.shutdown()` 1131 1132 However, since the SSL (and TLS) protocol has its own framing atop 1133 of TCP, the SSL sockets abstraction can, in certain respects, diverge from 1134 the specification of normal, OS-level sockets. See especially the 1135 :ref:`notes on non-blocking sockets <ssl-nonblocking>`. 1136 1137 Instances of :class:`SSLSocket` must be created using the 1138 :meth:`SSLContext.wrap_socket` method. 1139 1140 .. versionchanged:: 3.5 1141 The :meth:`sendfile` method was added. 1142 1143 .. versionchanged:: 3.5 1144 The :meth:`shutdown` does not reset the socket timeout each time bytes 1145 are received or sent. The socket timeout is now the maximum total duration 1146 of the shutdown. 1147 1148 .. deprecated:: 3.6 1149 It is deprecated to create a :class:`SSLSocket` instance directly, use 1150 :meth:`SSLContext.wrap_socket` to wrap a socket. 1151 1152 .. versionchanged:: 3.7 1153 :class:`SSLSocket` instances must to created with 1154 :meth:`~SSLContext.wrap_socket`. In earlier versions, it was possible 1155 to create instances directly. This was never documented or officially 1156 supported. 1157 1158 .. versionchanged:: 3.10 1159 Python now uses ``SSL_read_ex`` and ``SSL_write_ex`` internally. The 1160 functions support reading and writing of data larger than 2 GB. Writing 1161 zero-length data no longer fails with a protocol violation error. 1162 1163SSL sockets also have the following additional methods and attributes: 1164 1165.. method:: SSLSocket.read(len=1024, buffer=None) 1166 1167 Read up to *len* bytes of data from the SSL socket and return the result as 1168 a ``bytes`` instance. If *buffer* is specified, then read into the buffer 1169 instead, and return the number of bytes read. 1170 1171 Raise :exc:`SSLWantReadError` or :exc:`SSLWantWriteError` if the socket is 1172 :ref:`non-blocking <ssl-nonblocking>` and the read would block. 1173 1174 As at any time a re-negotiation is possible, a call to :meth:`read` can also 1175 cause write operations. 1176 1177 .. versionchanged:: 3.5 1178 The socket timeout is no longer reset each time bytes are received or sent. 1179 The socket timeout is now the maximum total duration to read up to *len* 1180 bytes. 1181 1182 .. deprecated:: 3.6 1183 Use :meth:`~SSLSocket.recv` instead of :meth:`~SSLSocket.read`. 1184 1185.. method:: SSLSocket.write(buf) 1186 1187 Write *buf* to the SSL socket and return the number of bytes written. The 1188 *buf* argument must be an object supporting the buffer interface. 1189 1190 Raise :exc:`SSLWantReadError` or :exc:`SSLWantWriteError` if the socket is 1191 :ref:`non-blocking <ssl-nonblocking>` and the write would block. 1192 1193 As at any time a re-negotiation is possible, a call to :meth:`write` can 1194 also cause read operations. 1195 1196 .. versionchanged:: 3.5 1197 The socket timeout is no longer reset each time bytes are received or sent. 1198 The socket timeout is now the maximum total duration to write *buf*. 1199 1200 .. deprecated:: 3.6 1201 Use :meth:`~SSLSocket.send` instead of :meth:`~SSLSocket.write`. 1202 1203.. note:: 1204 1205 The :meth:`~SSLSocket.read` and :meth:`~SSLSocket.write` methods are the 1206 low-level methods that read and write unencrypted, application-level data 1207 and decrypt/encrypt it to encrypted, wire-level data. These methods 1208 require an active SSL connection, i.e. the handshake was completed and 1209 :meth:`SSLSocket.unwrap` was not called. 1210 1211 Normally you should use the socket API methods like 1212 :meth:`~socket.socket.recv` and :meth:`~socket.socket.send` instead of these 1213 methods. 1214 1215.. method:: SSLSocket.do_handshake() 1216 1217 Perform the SSL setup handshake. 1218 1219 .. versionchanged:: 3.4 1220 The handshake method also performs :func:`match_hostname` when the 1221 :attr:`~SSLContext.check_hostname` attribute of the socket's 1222 :attr:`~SSLSocket.context` is true. 1223 1224 .. versionchanged:: 3.5 1225 The socket timeout is no longer reset each time bytes are received or sent. 1226 The socket timeout is now the maximum total duration of the handshake. 1227 1228 .. versionchanged:: 3.7 1229 Hostname or IP address is matched by OpenSSL during handshake. The 1230 function :func:`match_hostname` is no longer used. In case OpenSSL 1231 refuses a hostname or IP address, the handshake is aborted early and 1232 a TLS alert message is sent to the peer. 1233 1234.. method:: SSLSocket.getpeercert(binary_form=False) 1235 1236 If there is no certificate for the peer on the other end of the connection, 1237 return ``None``. If the SSL handshake hasn't been done yet, raise 1238 :exc:`ValueError`. 1239 1240 If the ``binary_form`` parameter is :const:`False`, and a certificate was 1241 received from the peer, this method returns a :class:`dict` instance. If the 1242 certificate was not validated, the dict is empty. If the certificate was 1243 validated, it returns a dict with several keys, amongst them ``subject`` 1244 (the principal for which the certificate was issued) and ``issuer`` 1245 (the principal issuing the certificate). If a certificate contains an 1246 instance of the *Subject Alternative Name* extension (see :rfc:`3280`), 1247 there will also be a ``subjectAltName`` key in the dictionary. 1248 1249 The ``subject`` and ``issuer`` fields are tuples containing the sequence 1250 of relative distinguished names (RDNs) given in the certificate's data 1251 structure for the respective fields, and each RDN is a sequence of 1252 name-value pairs. Here is a real-world example:: 1253 1254 {'issuer': ((('countryName', 'IL'),), 1255 (('organizationName', 'StartCom Ltd.'),), 1256 (('organizationalUnitName', 1257 'Secure Digital Certificate Signing'),), 1258 (('commonName', 1259 'StartCom Class 2 Primary Intermediate Server CA'),)), 1260 'notAfter': 'Nov 22 08:15:19 2013 GMT', 1261 'notBefore': 'Nov 21 03:09:52 2011 GMT', 1262 'serialNumber': '95F0', 1263 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),), 1264 (('countryName', 'US'),), 1265 (('stateOrProvinceName', 'California'),), 1266 (('localityName', 'San Francisco'),), 1267 (('organizationName', 'Electronic Frontier Foundation, Inc.'),), 1268 (('commonName', '*.eff.org'),), 1269 (('emailAddress', '[email protected]'),)), 1270 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')), 1271 'version': 3} 1272 1273 .. note:: 1274 1275 To validate a certificate for a particular service, you can use the 1276 :func:`match_hostname` function. 1277 1278 If the ``binary_form`` parameter is :const:`True`, and a certificate was 1279 provided, this method returns the DER-encoded form of the entire certificate 1280 as a sequence of bytes, or :const:`None` if the peer did not provide a 1281 certificate. Whether the peer provides a certificate depends on the SSL 1282 socket's role: 1283 1284 * for a client SSL socket, the server will always provide a certificate, 1285 regardless of whether validation was required; 1286 1287 * for a server SSL socket, the client will only provide a certificate 1288 when requested by the server; therefore :meth:`getpeercert` will return 1289 :const:`None` if you used :const:`CERT_NONE` (rather than 1290 :const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`). 1291 1292 .. versionchanged:: 3.2 1293 The returned dictionary includes additional items such as ``issuer`` 1294 and ``notBefore``. 1295 1296 .. versionchanged:: 3.4 1297 :exc:`ValueError` is raised when the handshake isn't done. 1298 The returned dictionary includes additional X509v3 extension items 1299 such as ``crlDistributionPoints``, ``caIssuers`` and ``OCSP`` URIs. 1300 1301 .. versionchanged:: 3.9 1302 IPv6 address strings no longer have a trailing new line. 1303 1304.. method:: SSLSocket.cipher() 1305 1306 Returns a three-value tuple containing the name of the cipher being used, the 1307 version of the SSL protocol that defines its use, and the number of secret 1308 bits being used. If no connection has been established, returns ``None``. 1309 1310.. method:: SSLSocket.shared_ciphers() 1311 1312 Return the list of ciphers available in both the client and server. Each 1313 entry of the returned list is a three-value tuple containing the name of the 1314 cipher, the version of the SSL protocol that defines its use, and the number 1315 of secret bits the cipher uses. :meth:`~SSLSocket.shared_ciphers` returns 1316 ``None`` if no connection has been established or the socket is a client 1317 socket. 1318 1319 .. versionadded:: 3.5 1320 1321.. method:: SSLSocket.compression() 1322 1323 Return the compression algorithm being used as a string, or ``None`` 1324 if the connection isn't compressed. 1325 1326 If the higher-level protocol supports its own compression mechanism, 1327 you can use :data:`OP_NO_COMPRESSION` to disable SSL-level compression. 1328 1329 .. versionadded:: 3.3 1330 1331.. method:: SSLSocket.get_channel_binding(cb_type="tls-unique") 1332 1333 Get channel binding data for current connection, as a bytes object. Returns 1334 ``None`` if not connected or the handshake has not been completed. 1335 1336 The *cb_type* parameter allow selection of the desired channel binding 1337 type. Valid channel binding types are listed in the 1338 :data:`CHANNEL_BINDING_TYPES` list. Currently only the 'tls-unique' channel 1339 binding, defined by :rfc:`5929`, is supported. :exc:`ValueError` will be 1340 raised if an unsupported channel binding type is requested. 1341 1342 .. versionadded:: 3.3 1343 1344.. method:: SSLSocket.selected_alpn_protocol() 1345 1346 Return the protocol that was selected during the TLS handshake. If 1347 :meth:`SSLContext.set_alpn_protocols` was not called, if the other party does 1348 not support ALPN, if this socket does not support any of the client's 1349 proposed protocols, or if the handshake has not happened yet, ``None`` is 1350 returned. 1351 1352 .. versionadded:: 3.5 1353 1354.. method:: SSLSocket.selected_npn_protocol() 1355 1356 Return the higher-level protocol that was selected during the TLS/SSL 1357 handshake. If :meth:`SSLContext.set_npn_protocols` was not called, or 1358 if the other party does not support NPN, or if the handshake has not yet 1359 happened, this will return ``None``. 1360 1361 .. versionadded:: 3.3 1362 1363 .. deprecated:: 3.10 1364 1365 NPN has been superseded by ALPN 1366 1367.. method:: SSLSocket.unwrap() 1368 1369 Performs the SSL shutdown handshake, which removes the TLS layer from the 1370 underlying socket, and returns the underlying socket object. This can be 1371 used to go from encrypted operation over a connection to unencrypted. The 1372 returned socket should always be used for further communication with the 1373 other side of the connection, rather than the original socket. 1374 1375.. method:: SSLSocket.verify_client_post_handshake() 1376 1377 Requests post-handshake authentication (PHA) from a TLS 1.3 client. PHA 1378 can only be initiated for a TLS 1.3 connection from a server-side socket, 1379 after the initial TLS handshake and with PHA enabled on both sides, see 1380 :attr:`SSLContext.post_handshake_auth`. 1381 1382 The method does not perform a cert exchange immediately. The server-side 1383 sends a CertificateRequest during the next write event and expects the 1384 client to respond with a certificate on the next read event. 1385 1386 If any precondition isn't met (e.g. not TLS 1.3, PHA not enabled), an 1387 :exc:`SSLError` is raised. 1388 1389 .. note:: 1390 Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 1391 support, the method raises :exc:`NotImplementedError`. 1392 1393 .. versionadded:: 3.8 1394 1395.. method:: SSLSocket.version() 1396 1397 Return the actual SSL protocol version negotiated by the connection 1398 as a string, or ``None`` if no secure connection is established. 1399 As of this writing, possible return values include ``"SSLv2"``, 1400 ``"SSLv3"``, ``"TLSv1"``, ``"TLSv1.1"`` and ``"TLSv1.2"``. 1401 Recent OpenSSL versions may define more return values. 1402 1403 .. versionadded:: 3.5 1404 1405.. method:: SSLSocket.pending() 1406 1407 Returns the number of already decrypted bytes available for read, pending on 1408 the connection. 1409 1410.. attribute:: SSLSocket.context 1411 1412 The :class:`SSLContext` object this SSL socket is tied to. If the SSL 1413 socket was created using the deprecated :func:`wrap_socket` function 1414 (rather than :meth:`SSLContext.wrap_socket`), this is a custom context 1415 object created for this SSL socket. 1416 1417 .. versionadded:: 3.2 1418 1419.. attribute:: SSLSocket.server_side 1420 1421 A boolean which is ``True`` for server-side sockets and ``False`` for 1422 client-side sockets. 1423 1424 .. versionadded:: 3.2 1425 1426.. attribute:: SSLSocket.server_hostname 1427 1428 Hostname of the server: :class:`str` type, or ``None`` for server-side 1429 socket or if the hostname was not specified in the constructor. 1430 1431 .. versionadded:: 3.2 1432 1433 .. versionchanged:: 3.7 1434 The attribute is now always ASCII text. When ``server_hostname`` is 1435 an internationalized domain name (IDN), this attribute now stores the 1436 A-label form (``"xn--pythn-mua.org"``), rather than the U-label form 1437 (``"pythön.org"``). 1438 1439.. attribute:: SSLSocket.session 1440 1441 The :class:`SSLSession` for this SSL connection. The session is available 1442 for client and server side sockets after the TLS handshake has been 1443 performed. For client sockets the session can be set before 1444 :meth:`~SSLSocket.do_handshake` has been called to reuse a session. 1445 1446 .. versionadded:: 3.6 1447 1448.. attribute:: SSLSocket.session_reused 1449 1450 .. versionadded:: 3.6 1451 1452 1453SSL Contexts 1454------------ 1455 1456.. versionadded:: 3.2 1457 1458An SSL context holds various data longer-lived than single SSL connections, 1459such as SSL configuration options, certificate(s) and private key(s). 1460It also manages a cache of SSL sessions for server-side sockets, in order 1461to speed up repeated connections from the same clients. 1462 1463.. class:: SSLContext(protocol=None) 1464 1465 Create a new SSL context. You may pass *protocol* which must be one 1466 of the ``PROTOCOL_*`` constants defined in this module. The parameter 1467 specifies which version of the SSL protocol to use. Typically, the 1468 server chooses a particular protocol version, and the client must adapt 1469 to the server's choice. Most of the versions are not interoperable 1470 with the other versions. If not specified, the default is 1471 :data:`PROTOCOL_TLS`; it provides the most compatibility with other 1472 versions. 1473 1474 Here's a table showing which versions in a client (down the side) can connect 1475 to which versions in a server (along the top): 1476 1477 .. table:: 1478 1479 ======================== ============ ============ ============= ========= =========== =========== 1480 *client* / **server** **SSLv2** **SSLv3** **TLS** [3]_ **TLSv1** **TLSv1.1** **TLSv1.2** 1481 ------------------------ ------------ ------------ ------------- --------- ----------- ----------- 1482 *SSLv2* yes no no [1]_ no no no 1483 *SSLv3* no yes no [2]_ no no no 1484 *TLS* (*SSLv23*) [3]_ no [1]_ no [2]_ yes yes yes yes 1485 *TLSv1* no no yes yes no no 1486 *TLSv1.1* no no yes no yes no 1487 *TLSv1.2* no no yes no no yes 1488 ======================== ============ ============ ============= ========= =========== =========== 1489 1490 .. rubric:: Footnotes 1491 .. [1] :class:`SSLContext` disables SSLv2 with :data:`OP_NO_SSLv2` by default. 1492 .. [2] :class:`SSLContext` disables SSLv3 with :data:`OP_NO_SSLv3` by default. 1493 .. [3] TLS 1.3 protocol will be available with :data:`PROTOCOL_TLS` in 1494 OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for just 1495 TLS 1.3. 1496 1497 .. seealso:: 1498 :func:`create_default_context` lets the :mod:`ssl` module choose 1499 security settings for a given purpose. 1500 1501 .. versionchanged:: 3.6 1502 1503 The context is created with secure default values. The options 1504 :data:`OP_NO_COMPRESSION`, :data:`OP_CIPHER_SERVER_PREFERENCE`, 1505 :data:`OP_SINGLE_DH_USE`, :data:`OP_SINGLE_ECDH_USE`, 1506 :data:`OP_NO_SSLv2` (except for :data:`PROTOCOL_SSLv2`), 1507 and :data:`OP_NO_SSLv3` (except for :data:`PROTOCOL_SSLv3`) are 1508 set by default. The initial cipher suite list contains only ``HIGH`` 1509 ciphers, no ``NULL`` ciphers and no ``MD5`` ciphers (except for 1510 :data:`PROTOCOL_SSLv2`). 1511 1512 .. deprecated:: 3.10 1513 1514 :class:`SSLContext` without protocol argument is deprecated. The 1515 context class will either require :data:`PROTOCOL_TLS_CLIENT` or 1516 :data:`PROTOCOL_TLS_SERVER` protocol in the future. 1517 1518 .. versionchanged:: 3.10 1519 1520 The default cipher suites now include only secure AES and ChaCha20 1521 ciphers with forward secrecy and security level 2. RSA and DH keys with 1522 less than 2048 bits and ECC keys with less than 224 bits are prohibited. 1523 :data:`PROTOCOL_TLS`, :data:`PROTOCOL_TLS_CLIENT`, and 1524 :data:`PROTOCOL_TLS_SERVER` use TLS 1.2 as minimum TLS version. 1525 1526 1527:class:`SSLContext` objects have the following methods and attributes: 1528 1529.. method:: SSLContext.cert_store_stats() 1530 1531 Get statistics about quantities of loaded X.509 certificates, count of 1532 X.509 certificates flagged as CA certificates and certificate revocation 1533 lists as dictionary. 1534 1535 Example for a context with one CA cert and one other cert:: 1536 1537 >>> context.cert_store_stats() 1538 {'crl': 0, 'x509_ca': 1, 'x509': 2} 1539 1540 .. versionadded:: 3.4 1541 1542 1543.. method:: SSLContext.load_cert_chain(certfile, keyfile=None, password=None) 1544 1545 Load a private key and the corresponding certificate. The *certfile* 1546 string must be the path to a single file in PEM format containing the 1547 certificate as well as any number of CA certificates needed to establish 1548 the certificate's authenticity. The *keyfile* string, if present, must 1549 point to a file containing the private key. Otherwise the private 1550 key will be taken from *certfile* as well. See the discussion of 1551 :ref:`ssl-certificates` for more information on how the certificate 1552 is stored in the *certfile*. 1553 1554 The *password* argument may be a function to call to get the password for 1555 decrypting the private key. It will only be called if the private key is 1556 encrypted and a password is necessary. It will be called with no arguments, 1557 and it should return a string, bytes, or bytearray. If the return value is 1558 a string it will be encoded as UTF-8 before using it to decrypt the key. 1559 Alternatively a string, bytes, or bytearray value may be supplied directly 1560 as the *password* argument. It will be ignored if the private key is not 1561 encrypted and no password is needed. 1562 1563 If the *password* argument is not specified and a password is required, 1564 OpenSSL's built-in password prompting mechanism will be used to 1565 interactively prompt the user for a password. 1566 1567 An :class:`SSLError` is raised if the private key doesn't 1568 match with the certificate. 1569 1570 .. versionchanged:: 3.3 1571 New optional argument *password*. 1572 1573.. method:: SSLContext.load_default_certs(purpose=Purpose.SERVER_AUTH) 1574 1575 Load a set of default "certification authority" (CA) certificates from 1576 default locations. On Windows it loads CA certs from the ``CA`` and 1577 ``ROOT`` system stores. On all systems it calls 1578 :meth:`SSLContext.set_default_verify_paths`. In the future the method may 1579 load CA certificates from other locations, too. 1580 1581 The *purpose* flag specifies what kind of CA certificates are loaded. The 1582 default settings :data:`Purpose.SERVER_AUTH` loads certificates, that are 1583 flagged and trusted for TLS web server authentication (client side 1584 sockets). :data:`Purpose.CLIENT_AUTH` loads CA certificates for client 1585 certificate verification on the server side. 1586 1587 .. versionadded:: 3.4 1588 1589.. method:: SSLContext.load_verify_locations(cafile=None, capath=None, cadata=None) 1590 1591 Load a set of "certification authority" (CA) certificates used to validate 1592 other peers' certificates when :data:`verify_mode` is other than 1593 :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified. 1594 1595 This method can also load certification revocation lists (CRLs) in PEM or 1596 DER format. In order to make use of CRLs, :attr:`SSLContext.verify_flags` 1597 must be configured properly. 1598 1599 The *cafile* string, if present, is the path to a file of concatenated 1600 CA certificates in PEM format. See the discussion of 1601 :ref:`ssl-certificates` for more information about how to arrange the 1602 certificates in this file. 1603 1604 The *capath* string, if present, is 1605 the path to a directory containing several CA certificates in PEM format, 1606 following an `OpenSSL specific layout 1607 <https://www.openssl.org/docs/manmaster/man3/SSL_CTX_load_verify_locations.html>`_. 1608 1609 The *cadata* object, if present, is either an ASCII string of one or more 1610 PEM-encoded certificates or a :term:`bytes-like object` of DER-encoded 1611 certificates. Like with *capath* extra lines around PEM-encoded 1612 certificates are ignored but at least one certificate must be present. 1613 1614 .. versionchanged:: 3.4 1615 New optional argument *cadata* 1616 1617.. method:: SSLContext.get_ca_certs(binary_form=False) 1618 1619 Get a list of loaded "certification authority" (CA) certificates. If the 1620 ``binary_form`` parameter is :const:`False` each list 1621 entry is a dict like the output of :meth:`SSLSocket.getpeercert`. Otherwise 1622 the method returns a list of DER-encoded certificates. The returned list 1623 does not contain certificates from *capath* unless a certificate was 1624 requested and loaded by a SSL connection. 1625 1626 .. note:: 1627 Certificates in a capath directory aren't loaded unless they have 1628 been used at least once. 1629 1630 .. versionadded:: 3.4 1631 1632.. method:: SSLContext.get_ciphers() 1633 1634 Get a list of enabled ciphers. The list is in order of cipher priority. 1635 See :meth:`SSLContext.set_ciphers`. 1636 1637 Example:: 1638 1639 >>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) 1640 >>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA') 1641 >>> ctx.get_ciphers() 1642 [{'aead': True, 1643 'alg_bits': 256, 1644 'auth': 'auth-rsa', 1645 'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA ' 1646 'Enc=AESGCM(256) Mac=AEAD', 1647 'digest': None, 1648 'id': 50380848, 1649 'kea': 'kx-ecdhe', 1650 'name': 'ECDHE-RSA-AES256-GCM-SHA384', 1651 'protocol': 'TLSv1.2', 1652 'strength_bits': 256, 1653 'symmetric': 'aes-256-gcm'}, 1654 {'aead': True, 1655 'alg_bits': 128, 1656 'auth': 'auth-rsa', 1657 'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA ' 1658 'Enc=AESGCM(128) Mac=AEAD', 1659 'digest': None, 1660 'id': 50380847, 1661 'kea': 'kx-ecdhe', 1662 'name': 'ECDHE-RSA-AES128-GCM-SHA256', 1663 'protocol': 'TLSv1.2', 1664 'strength_bits': 128, 1665 'symmetric': 'aes-128-gcm'}] 1666 1667 .. versionadded:: 3.6 1668 1669.. method:: SSLContext.set_default_verify_paths() 1670 1671 Load a set of default "certification authority" (CA) certificates from 1672 a filesystem path defined when building the OpenSSL library. Unfortunately, 1673 there's no easy way to know whether this method succeeds: no error is 1674 returned if no certificates are to be found. When the OpenSSL library is 1675 provided as part of the operating system, though, it is likely to be 1676 configured properly. 1677 1678.. method:: SSLContext.set_ciphers(ciphers) 1679 1680 Set the available ciphers for sockets created with this context. 1681 It should be a string in the `OpenSSL cipher list format 1682 <https://www.openssl.org/docs/manmaster/man1/ciphers.html>`_. 1683 If no cipher can be selected (because compile-time options or other 1684 configuration forbids use of all the specified ciphers), an 1685 :class:`SSLError` will be raised. 1686 1687 .. note:: 1688 when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will 1689 give the currently selected cipher. 1690 1691 TLS 1.3 cipher suites cannot be disabled with 1692 :meth:`~SSLContext.set_ciphers`. 1693 1694.. method:: SSLContext.set_alpn_protocols(protocols) 1695 1696 Specify which protocols the socket should advertise during the SSL/TLS 1697 handshake. It should be a list of ASCII strings, like ``['http/1.1', 1698 'spdy/2']``, ordered by preference. The selection of a protocol will happen 1699 during the handshake, and will play out according to :rfc:`7301`. After a 1700 successful handshake, the :meth:`SSLSocket.selected_alpn_protocol` method will 1701 return the agreed-upon protocol. 1702 1703 This method will raise :exc:`NotImplementedError` if :data:`HAS_ALPN` is 1704 ``False``. 1705 1706 .. versionadded:: 3.5 1707 1708.. method:: SSLContext.set_npn_protocols(protocols) 1709 1710 Specify which protocols the socket should advertise during the SSL/TLS 1711 handshake. It should be a list of strings, like ``['http/1.1', 'spdy/2']``, 1712 ordered by preference. The selection of a protocol will happen during the 1713 handshake, and will play out according to the `Application Layer Protocol Negotiation 1714 <https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation>`_. After a 1715 successful handshake, the :meth:`SSLSocket.selected_npn_protocol` method will 1716 return the agreed-upon protocol. 1717 1718 This method will raise :exc:`NotImplementedError` if :data:`HAS_NPN` is 1719 ``False``. 1720 1721 .. versionadded:: 3.3 1722 1723 .. deprecated:: 3.10 1724 1725 NPN has been superseded by ALPN 1726 1727.. attribute:: SSLContext.sni_callback 1728 1729 Register a callback function that will be called after the TLS Client Hello 1730 handshake message has been received by the SSL/TLS server when the TLS client 1731 specifies a server name indication. The server name indication mechanism 1732 is specified in :rfc:`6066` section 3 - Server Name Indication. 1733 1734 Only one callback can be set per ``SSLContext``. If *sni_callback* 1735 is set to ``None`` then the callback is disabled. Calling this function a 1736 subsequent time will disable the previously registered callback. 1737 1738 The callback function will be called with three 1739 arguments; the first being the :class:`ssl.SSLSocket`, the second is a string 1740 that represents the server name that the client is intending to communicate 1741 (or :const:`None` if the TLS Client Hello does not contain a server name) 1742 and the third argument is the original :class:`SSLContext`. The server name 1743 argument is text. For internationalized domain name, the server 1744 name is an IDN A-label (``"xn--pythn-mua.org"``). 1745 1746 A typical use of this callback is to change the :class:`ssl.SSLSocket`'s 1747 :attr:`SSLSocket.context` attribute to a new object of type 1748 :class:`SSLContext` representing a certificate chain that matches the server 1749 name. 1750 1751 Due to the early negotiation phase of the TLS connection, only limited 1752 methods and attributes are usable like 1753 :meth:`SSLSocket.selected_alpn_protocol` and :attr:`SSLSocket.context`. 1754 The :meth:`SSLSocket.getpeercert`, 1755 :meth:`SSLSocket.cipher` and :meth:`SSLSocket.compression` methods require that 1756 the TLS connection has progressed beyond the TLS Client Hello and therefore 1757 will not return meaningful values nor can they be called safely. 1758 1759 The *sni_callback* function must return ``None`` to allow the 1760 TLS negotiation to continue. If a TLS failure is required, a constant 1761 :const:`ALERT_DESCRIPTION_* <ALERT_DESCRIPTION_INTERNAL_ERROR>` can be 1762 returned. Other return values will result in a TLS fatal error with 1763 :const:`ALERT_DESCRIPTION_INTERNAL_ERROR`. 1764 1765 If an exception is raised from the *sni_callback* function the TLS 1766 connection will terminate with a fatal TLS alert message 1767 :const:`ALERT_DESCRIPTION_HANDSHAKE_FAILURE`. 1768 1769 This method will raise :exc:`NotImplementedError` if the OpenSSL library 1770 had OPENSSL_NO_TLSEXT defined when it was built. 1771 1772 .. versionadded:: 3.7 1773 1774.. attribute:: SSLContext.set_servername_callback(server_name_callback) 1775 1776 This is a legacy API retained for backwards compatibility. When possible, 1777 you should use :attr:`sni_callback` instead. The given *server_name_callback* 1778 is similar to *sni_callback*, except that when the server hostname is an 1779 IDN-encoded internationalized domain name, the *server_name_callback* 1780 receives a decoded U-label (``"pythön.org"``). 1781 1782 If there is an decoding error on the server name, the TLS connection will 1783 terminate with an :const:`ALERT_DESCRIPTION_INTERNAL_ERROR` fatal TLS 1784 alert message to the client. 1785 1786 .. versionadded:: 3.4 1787 1788.. method:: SSLContext.load_dh_params(dhfile) 1789 1790 Load the key generation parameters for Diffie-Hellman (DH) key exchange. 1791 Using DH key exchange improves forward secrecy at the expense of 1792 computational resources (both on the server and on the client). 1793 The *dhfile* parameter should be the path to a file containing DH 1794 parameters in PEM format. 1795 1796 This setting doesn't apply to client sockets. You can also use the 1797 :data:`OP_SINGLE_DH_USE` option to further improve security. 1798 1799 .. versionadded:: 3.3 1800 1801.. method:: SSLContext.set_ecdh_curve(curve_name) 1802 1803 Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key 1804 exchange. ECDH is significantly faster than regular DH while arguably 1805 as secure. The *curve_name* parameter should be a string describing 1806 a well-known elliptic curve, for example ``prime256v1`` for a widely 1807 supported curve. 1808 1809 This setting doesn't apply to client sockets. You can also use the 1810 :data:`OP_SINGLE_ECDH_USE` option to further improve security. 1811 1812 This method is not available if :data:`HAS_ECDH` is ``False``. 1813 1814 .. versionadded:: 3.3 1815 1816 .. seealso:: 1817 `SSL/TLS & Perfect Forward Secrecy <https://vincent.bernat.ch/en/blog/2011-ssl-perfect-forward-secrecy>`_ 1818 Vincent Bernat. 1819 1820.. method:: SSLContext.wrap_socket(sock, server_side=False, \ 1821 do_handshake_on_connect=True, suppress_ragged_eofs=True, \ 1822 server_hostname=None, session=None) 1823 1824 Wrap an existing Python socket *sock* and return an instance of 1825 :attr:`SSLContext.sslsocket_class` (default :class:`SSLSocket`). The 1826 returned SSL socket is tied to the context, its settings and certificates. 1827 *sock* must be a :data:`~socket.SOCK_STREAM` socket; other 1828 socket types are unsupported. 1829 1830 The parameter ``server_side`` is a boolean which identifies whether 1831 server-side or client-side behavior is desired from this socket. 1832 1833 For client-side sockets, the context construction is lazy; if the 1834 underlying socket isn't connected yet, the context construction will be 1835 performed after :meth:`connect` is called on the socket. For 1836 server-side sockets, if the socket has no remote peer, it is assumed 1837 to be a listening socket, and the server-side SSL wrapping is 1838 automatically performed on client connections accepted via the 1839 :meth:`accept` method. The method may raise :exc:`SSLError`. 1840 1841 On client connections, the optional parameter *server_hostname* specifies 1842 the hostname of the service which we are connecting to. This allows a 1843 single server to host multiple SSL-based services with distinct certificates, 1844 quite similarly to HTTP virtual hosts. Specifying *server_hostname* will 1845 raise a :exc:`ValueError` if *server_side* is true. 1846 1847 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL 1848 handshake automatically after doing a :meth:`socket.connect`, or whether the 1849 application program will call it explicitly, by invoking the 1850 :meth:`SSLSocket.do_handshake` method. Calling 1851 :meth:`SSLSocket.do_handshake` explicitly gives the program control over the 1852 blocking behavior of the socket I/O involved in the handshake. 1853 1854 The parameter ``suppress_ragged_eofs`` specifies how the 1855 :meth:`SSLSocket.recv` method should signal unexpected EOF from the other end 1856 of the connection. If specified as :const:`True` (the default), it returns a 1857 normal EOF (an empty bytes object) in response to unexpected EOF errors 1858 raised from the underlying socket; if :const:`False`, it will raise the 1859 exceptions back to the caller. 1860 1861 *session*, see :attr:`~SSLSocket.session`. 1862 1863 .. versionchanged:: 3.5 1864 Always allow a server_hostname to be passed, even if OpenSSL does not 1865 have SNI. 1866 1867 .. versionchanged:: 3.6 1868 *session* argument was added. 1869 1870 .. versionchanged:: 3.7 1871 The method returns an instance of :attr:`SSLContext.sslsocket_class` 1872 instead of hard-coded :class:`SSLSocket`. 1873 1874.. attribute:: SSLContext.sslsocket_class 1875 1876 The return type of :meth:`SSLContext.wrap_socket`, defaults to 1877 :class:`SSLSocket`. The attribute can be overridden on instance of class 1878 in order to return a custom subclass of :class:`SSLSocket`. 1879 1880 .. versionadded:: 3.7 1881 1882.. method:: SSLContext.wrap_bio(incoming, outgoing, server_side=False, \ 1883 server_hostname=None, session=None) 1884 1885 Wrap the BIO objects *incoming* and *outgoing* and return an instance of 1886 :attr:`SSLContext.sslobject_class` (default :class:`SSLObject`). The SSL 1887 routines will read input data from the incoming BIO and write data to the 1888 outgoing BIO. 1889 1890 The *server_side*, *server_hostname* and *session* parameters have the 1891 same meaning as in :meth:`SSLContext.wrap_socket`. 1892 1893 .. versionchanged:: 3.6 1894 *session* argument was added. 1895 1896 .. versionchanged:: 3.7 1897 The method returns an instance of :attr:`SSLContext.sslobject_class` 1898 instead of hard-coded :class:`SSLObject`. 1899 1900.. attribute:: SSLContext.sslobject_class 1901 1902 The return type of :meth:`SSLContext.wrap_bio`, defaults to 1903 :class:`SSLObject`. The attribute can be overridden on instance of class 1904 in order to return a custom subclass of :class:`SSLObject`. 1905 1906 .. versionadded:: 3.7 1907 1908.. method:: SSLContext.session_stats() 1909 1910 Get statistics about the SSL sessions created or managed by this context. 1911 A dictionary is returned which maps the names of each `piece of information <https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_sess_number.html>`_ to their 1912 numeric values. For example, here is the total number of hits and misses 1913 in the session cache since the context was created:: 1914 1915 >>> stats = context.session_stats() 1916 >>> stats['hits'], stats['misses'] 1917 (0, 0) 1918 1919.. attribute:: SSLContext.check_hostname 1920 1921 Whether to match the peer cert's hostname in 1922 :meth:`SSLSocket.do_handshake`. The context's 1923 :attr:`~SSLContext.verify_mode` must be set to :data:`CERT_OPTIONAL` or 1924 :data:`CERT_REQUIRED`, and you must pass *server_hostname* to 1925 :meth:`~SSLContext.wrap_socket` in order to match the hostname. Enabling 1926 hostname checking automatically sets :attr:`~SSLContext.verify_mode` from 1927 :data:`CERT_NONE` to :data:`CERT_REQUIRED`. It cannot be set back to 1928 :data:`CERT_NONE` as long as hostname checking is enabled. The 1929 :data:`PROTOCOL_TLS_CLIENT` protocol enables hostname checking by default. 1930 With other protocols, hostname checking must be enabled explicitly. 1931 1932 Example:: 1933 1934 import socket, ssl 1935 1936 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) 1937 context.verify_mode = ssl.CERT_REQUIRED 1938 context.check_hostname = True 1939 context.load_default_certs() 1940 1941 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1942 ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com') 1943 ssl_sock.connect(('www.verisign.com', 443)) 1944 1945 .. versionadded:: 3.4 1946 1947 .. versionchanged:: 3.7 1948 1949 :attr:`~SSLContext.verify_mode` is now automatically changed 1950 to :data:`CERT_REQUIRED` when hostname checking is enabled and 1951 :attr:`~SSLContext.verify_mode` is :data:`CERT_NONE`. Previously 1952 the same operation would have failed with a :exc:`ValueError`. 1953 1954.. attribute:: SSLContext.keylog_filename 1955 1956 Write TLS keys to a keylog file, whenever key material is generated or 1957 received. The keylog file is designed for debugging purposes only. The 1958 file format is specified by NSS and used by many traffic analyzers such 1959 as Wireshark. The log file is opened in append-only mode. Writes are 1960 synchronized between threads, but not between processes. 1961 1962 .. versionadded:: 3.8 1963 1964.. attribute:: SSLContext.maximum_version 1965 1966 A :class:`TLSVersion` enum member representing the highest supported 1967 TLS version. The value defaults to :attr:`TLSVersion.MAXIMUM_SUPPORTED`. 1968 The attribute is read-only for protocols other than :attr:`PROTOCOL_TLS`, 1969 :attr:`PROTOCOL_TLS_CLIENT`, and :attr:`PROTOCOL_TLS_SERVER`. 1970 1971 The attributes :attr:`~SSLContext.maximum_version`, 1972 :attr:`~SSLContext.minimum_version` and 1973 :attr:`SSLContext.options` all affect the supported SSL 1974 and TLS versions of the context. The implementation does not prevent 1975 invalid combination. For example a context with 1976 :attr:`OP_NO_TLSv1_2` in :attr:`~SSLContext.options` and 1977 :attr:`~SSLContext.maximum_version` set to :attr:`TLSVersion.TLSv1_2` 1978 will not be able to establish a TLS 1.2 connection. 1979 1980 .. versionadded:: 3.7 1981 1982.. attribute:: SSLContext.minimum_version 1983 1984 Like :attr:`SSLContext.maximum_version` except it is the lowest 1985 supported version or :attr:`TLSVersion.MINIMUM_SUPPORTED`. 1986 1987 .. versionadded:: 3.7 1988 1989.. attribute:: SSLContext.num_tickets 1990 1991 Control the number of TLS 1.3 session tickets of a 1992 :attr:`PROTOCOL_TLS_SERVER` context. The setting has no impact on TLS 1993 1.0 to 1.2 connections. 1994 1995 .. versionadded:: 3.8 1996 1997.. attribute:: SSLContext.options 1998 1999 An integer representing the set of SSL options enabled on this context. 2000 The default value is :data:`OP_ALL`, but you can specify other options 2001 such as :data:`OP_NO_SSLv2` by ORing them together. 2002 2003 .. versionchanged:: 3.6 2004 :attr:`SSLContext.options` returns :class:`Options` flags: 2005 2006 >>> ssl.create_default_context().options # doctest: +SKIP 2007 <Options.OP_ALL|OP_NO_SSLv3|OP_NO_SSLv2|OP_NO_COMPRESSION: 2197947391> 2008 2009 .. deprecated:: 3.7 2010 2011 All ``OP_NO_SSL*`` and ``OP_NO_TLS*`` options have been deprecated since 2012 Python 3.7. Use :attr:`SSLContext.minimum_version` and 2013 :attr:`SSLContext.maximum_version` instead. 2014 2015.. attribute:: SSLContext.post_handshake_auth 2016 2017 Enable TLS 1.3 post-handshake client authentication. Post-handshake auth 2018 is disabled by default and a server can only request a TLS client 2019 certificate during the initial handshake. When enabled, a server may 2020 request a TLS client certificate at any time after the handshake. 2021 2022 When enabled on client-side sockets, the client signals the server that 2023 it supports post-handshake authentication. 2024 2025 When enabled on server-side sockets, :attr:`SSLContext.verify_mode` must 2026 be set to :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`, too. The 2027 actual client cert exchange is delayed until 2028 :meth:`SSLSocket.verify_client_post_handshake` is called and some I/O is 2029 performed. 2030 2031 .. versionadded:: 3.8 2032 2033.. attribute:: SSLContext.protocol 2034 2035 The protocol version chosen when constructing the context. This attribute 2036 is read-only. 2037 2038.. attribute:: SSLContext.hostname_checks_common_name 2039 2040 Whether :attr:`~SSLContext.check_hostname` falls back to verify the cert's 2041 subject common name in the absence of a subject alternative name 2042 extension (default: true). 2043 2044 .. versionadded:: 3.7 2045 2046 .. versionchanged:: 3.10 2047 2048 The flag had no effect with OpenSSL before version 1.1.1k. Python 3.8.9, 2049 3.9.3, and 3.10 include workarounds for previous versions. 2050 2051.. attribute:: SSLContext.security_level 2052 2053 An integer representing the `security level 2054 <https://www.openssl.org/docs/manmaster/man3/SSL_CTX_get_security_level.html>`_ 2055 for the context. This attribute is read-only. 2056 2057 .. versionadded:: 3.10 2058 2059.. attribute:: SSLContext.verify_flags 2060 2061 The flags for certificate verification operations. You can set flags like 2062 :data:`VERIFY_CRL_CHECK_LEAF` by ORing them together. By default OpenSSL 2063 does neither require nor verify certificate revocation lists (CRLs). 2064 2065 .. versionadded:: 3.4 2066 2067 .. versionchanged:: 3.6 2068 :attr:`SSLContext.verify_flags` returns :class:`VerifyFlags` flags: 2069 2070 >>> ssl.create_default_context().verify_flags # doctest: +SKIP 2071 <VerifyFlags.VERIFY_X509_TRUSTED_FIRST: 32768> 2072 2073.. attribute:: SSLContext.verify_mode 2074 2075 Whether to try to verify other peers' certificates and how to behave 2076 if verification fails. This attribute must be one of 2077 :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`. 2078 2079 .. versionchanged:: 3.6 2080 :attr:`SSLContext.verify_mode` returns :class:`VerifyMode` enum: 2081 2082 >>> ssl.create_default_context().verify_mode # doctest: +SKIP 2083 <VerifyMode.CERT_REQUIRED: 2> 2084 2085.. index:: single: certificates 2086 2087.. index:: single: X509 certificate 2088 2089.. _ssl-certificates: 2090 2091Certificates 2092------------ 2093 2094Certificates in general are part of a public-key / private-key system. In this 2095system, each *principal*, (which may be a machine, or a person, or an 2096organization) is assigned a unique two-part encryption key. One part of the key 2097is public, and is called the *public key*; the other part is kept secret, and is 2098called the *private key*. The two parts are related, in that if you encrypt a 2099message with one of the parts, you can decrypt it with the other part, and 2100**only** with the other part. 2101 2102A certificate contains information about two principals. It contains the name 2103of a *subject*, and the subject's public key. It also contains a statement by a 2104second principal, the *issuer*, that the subject is who they claim to be, and 2105that this is indeed the subject's public key. The issuer's statement is signed 2106with the issuer's private key, which only the issuer knows. However, anyone can 2107verify the issuer's statement by finding the issuer's public key, decrypting the 2108statement with it, and comparing it to the other information in the certificate. 2109The certificate also contains information about the time period over which it is 2110valid. This is expressed as two fields, called "notBefore" and "notAfter". 2111 2112In the Python use of certificates, a client or server can use a certificate to 2113prove who they are. The other side of a network connection can also be required 2114to produce a certificate, and that certificate can be validated to the 2115satisfaction of the client or server that requires such validation. The 2116connection attempt can be set to raise an exception if the validation fails. 2117Validation is done automatically, by the underlying OpenSSL framework; the 2118application need not concern itself with its mechanics. But the application 2119does usually need to provide sets of certificates to allow this process to take 2120place. 2121 2122Python uses files to contain certificates. They should be formatted as "PEM" 2123(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line 2124and a footer line:: 2125 2126 -----BEGIN CERTIFICATE----- 2127 ... (certificate in base64 PEM encoding) ... 2128 -----END CERTIFICATE----- 2129 2130Certificate chains 2131^^^^^^^^^^^^^^^^^^ 2132 2133The Python files which contain certificates can contain a sequence of 2134certificates, sometimes called a *certificate chain*. This chain should start 2135with the specific certificate for the principal who "is" the client or server, 2136and then the certificate for the issuer of that certificate, and then the 2137certificate for the issuer of *that* certificate, and so on up the chain till 2138you get to a certificate which is *self-signed*, that is, a certificate which 2139has the same subject and issuer, sometimes called a *root certificate*. The 2140certificates should just be concatenated together in the certificate file. For 2141example, suppose we had a three certificate chain, from our server certificate 2142to the certificate of the certification authority that signed our server 2143certificate, to the root certificate of the agency which issued the 2144certification authority's certificate:: 2145 2146 -----BEGIN CERTIFICATE----- 2147 ... (certificate for your server)... 2148 -----END CERTIFICATE----- 2149 -----BEGIN CERTIFICATE----- 2150 ... (the certificate for the CA)... 2151 -----END CERTIFICATE----- 2152 -----BEGIN CERTIFICATE----- 2153 ... (the root certificate for the CA's issuer)... 2154 -----END CERTIFICATE----- 2155 2156CA certificates 2157^^^^^^^^^^^^^^^ 2158 2159If you are going to require validation of the other side of the connection's 2160certificate, you need to provide a "CA certs" file, filled with the certificate 2161chains for each issuer you are willing to trust. Again, this file just contains 2162these chains concatenated together. For validation, Python will use the first 2163chain it finds in the file which matches. The platform's certificates file can 2164be used by calling :meth:`SSLContext.load_default_certs`, this is done 2165automatically with :func:`.create_default_context`. 2166 2167Combined key and certificate 2168^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2169 2170Often the private key is stored in the same file as the certificate; in this 2171case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain` 2172and :func:`wrap_socket` needs to be passed. If the private key is stored 2173with the certificate, it should come before the first certificate in 2174the certificate chain:: 2175 2176 -----BEGIN RSA PRIVATE KEY----- 2177 ... (private key in base64 encoding) ... 2178 -----END RSA PRIVATE KEY----- 2179 -----BEGIN CERTIFICATE----- 2180 ... (certificate in base64 PEM encoding) ... 2181 -----END CERTIFICATE----- 2182 2183Self-signed certificates 2184^^^^^^^^^^^^^^^^^^^^^^^^ 2185 2186If you are going to create a server that provides SSL-encrypted connection 2187services, you will need to acquire a certificate for that service. There are 2188many ways of acquiring appropriate certificates, such as buying one from a 2189certification authority. Another common practice is to generate a self-signed 2190certificate. The simplest way to do this is with the OpenSSL package, using 2191something like the following:: 2192 2193 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem 2194 Generating a 1024 bit RSA private key 2195 .......++++++ 2196 .............................++++++ 2197 writing new private key to 'cert.pem' 2198 ----- 2199 You are about to be asked to enter information that will be incorporated 2200 into your certificate request. 2201 What you are about to enter is what is called a Distinguished Name or a DN. 2202 There are quite a few fields but you can leave some blank 2203 For some fields there will be a default value, 2204 If you enter '.', the field will be left blank. 2205 ----- 2206 Country Name (2 letter code) [AU]:US 2207 State or Province Name (full name) [Some-State]:MyState 2208 Locality Name (eg, city) []:Some City 2209 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc. 2210 Organizational Unit Name (eg, section) []:My Group 2211 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com 2212 Email Address []:[email protected] 2213 % 2214 2215The disadvantage of a self-signed certificate is that it is its own root 2216certificate, and no one else will have it in their cache of known (and trusted) 2217root certificates. 2218 2219 2220Examples 2221-------- 2222 2223Testing for SSL support 2224^^^^^^^^^^^^^^^^^^^^^^^ 2225 2226To test for the presence of SSL support in a Python installation, user code 2227should use the following idiom:: 2228 2229 try: 2230 import ssl 2231 except ImportError: 2232 pass 2233 else: 2234 ... # do something that requires SSL support 2235 2236Client-side operation 2237^^^^^^^^^^^^^^^^^^^^^ 2238 2239This example creates a SSL context with the recommended security settings 2240for client sockets, including automatic certificate verification:: 2241 2242 >>> context = ssl.create_default_context() 2243 2244If you prefer to tune security settings yourself, you might create 2245a context from scratch (but beware that you might not get the settings 2246right):: 2247 2248 >>> context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) 2249 >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt") 2250 2251(this snippet assumes your operating system places a bundle of all CA 2252certificates in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an 2253error and have to adjust the location) 2254 2255The :data:`PROTOCOL_TLS_CLIENT` protocol configures the context for cert 2256validation and hostname verification. :attr:`~SSLContext.verify_mode` is 2257set to :data:`CERT_REQUIRED` and :attr:`~SSLContext.check_hostname` is set 2258to ``True``. All other protocols create SSL contexts with insecure defaults. 2259 2260When you use the context to connect to a server, :const:`CERT_REQUIRED` 2261and :attr:`~SSLContext.check_hostname` validate the server certificate: it 2262ensures that the server certificate was signed with one of the CA 2263certificates, checks the signature for correctness, and verifies other 2264properties like validity and identity of the hostname:: 2265 2266 >>> conn = context.wrap_socket(socket.socket(socket.AF_INET), 2267 ... server_hostname="www.python.org") 2268 >>> conn.connect(("www.python.org", 443)) 2269 2270You may then fetch the certificate:: 2271 2272 >>> cert = conn.getpeercert() 2273 2274Visual inspection shows that the certificate does identify the desired service 2275(that is, the HTTPS host ``www.python.org``):: 2276 2277 >>> pprint.pprint(cert) 2278 {'OCSP': ('http://ocsp.digicert.com',), 2279 'caIssuers': ('http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt',), 2280 'crlDistributionPoints': ('http://crl3.digicert.com/sha2-ev-server-g1.crl', 2281 'http://crl4.digicert.com/sha2-ev-server-g1.crl'), 2282 'issuer': ((('countryName', 'US'),), 2283 (('organizationName', 'DigiCert Inc'),), 2284 (('organizationalUnitName', 'www.digicert.com'),), 2285 (('commonName', 'DigiCert SHA2 Extended Validation Server CA'),)), 2286 'notAfter': 'Sep 9 12:00:00 2016 GMT', 2287 'notBefore': 'Sep 5 00:00:00 2014 GMT', 2288 'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26', 2289 'subject': ((('businessCategory', 'Private Organization'),), 2290 (('1.3.6.1.4.1.311.60.2.1.3', 'US'),), 2291 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),), 2292 (('serialNumber', '3359300'),), 2293 (('streetAddress', '16 Allen Rd'),), 2294 (('postalCode', '03894-4801'),), 2295 (('countryName', 'US'),), 2296 (('stateOrProvinceName', 'NH'),), 2297 (('localityName', 'Wolfeboro'),), 2298 (('organizationName', 'Python Software Foundation'),), 2299 (('commonName', 'www.python.org'),)), 2300 'subjectAltName': (('DNS', 'www.python.org'), 2301 ('DNS', 'python.org'), 2302 ('DNS', 'pypi.org'), 2303 ('DNS', 'docs.python.org'), 2304 ('DNS', 'testpypi.org'), 2305 ('DNS', 'bugs.python.org'), 2306 ('DNS', 'wiki.python.org'), 2307 ('DNS', 'hg.python.org'), 2308 ('DNS', 'mail.python.org'), 2309 ('DNS', 'packaging.python.org'), 2310 ('DNS', 'pythonhosted.org'), 2311 ('DNS', 'www.pythonhosted.org'), 2312 ('DNS', 'test.pythonhosted.org'), 2313 ('DNS', 'us.pycon.org'), 2314 ('DNS', 'id.python.org')), 2315 'version': 3} 2316 2317Now the SSL channel is established and the certificate verified, you can 2318proceed to talk with the server:: 2319 2320 >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n") 2321 >>> pprint.pprint(conn.recv(1024).split(b"\r\n")) 2322 [b'HTTP/1.1 200 OK', 2323 b'Date: Sat, 18 Oct 2014 18:27:20 GMT', 2324 b'Server: nginx', 2325 b'Content-Type: text/html; charset=utf-8', 2326 b'X-Frame-Options: SAMEORIGIN', 2327 b'Content-Length: 45679', 2328 b'Accept-Ranges: bytes', 2329 b'Via: 1.1 varnish', 2330 b'Age: 2188', 2331 b'X-Served-By: cache-lcy1134-LCY', 2332 b'X-Cache: HIT', 2333 b'X-Cache-Hits: 11', 2334 b'Vary: Cookie', 2335 b'Strict-Transport-Security: max-age=63072000; includeSubDomains', 2336 b'Connection: close', 2337 b'', 2338 b''] 2339 2340See the discussion of :ref:`ssl-security` below. 2341 2342 2343Server-side operation 2344^^^^^^^^^^^^^^^^^^^^^ 2345 2346For server operation, typically you'll need to have a server certificate, and 2347private key, each in a file. You'll first create a context holding the key 2348and the certificate, so that clients can check your authenticity. Then 2349you'll open a socket, bind it to a port, call :meth:`listen` on it, and start 2350waiting for clients to connect:: 2351 2352 import socket, ssl 2353 2354 context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) 2355 context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile") 2356 2357 bindsocket = socket.socket() 2358 bindsocket.bind(('myaddr.example.com', 10023)) 2359 bindsocket.listen(5) 2360 2361When a client connects, you'll call :meth:`accept` on the socket to get the 2362new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket` 2363method to create a server-side SSL socket for the connection:: 2364 2365 while True: 2366 newsocket, fromaddr = bindsocket.accept() 2367 connstream = context.wrap_socket(newsocket, server_side=True) 2368 try: 2369 deal_with_client(connstream) 2370 finally: 2371 connstream.shutdown(socket.SHUT_RDWR) 2372 connstream.close() 2373 2374Then you'll read data from the ``connstream`` and do something with it till you 2375are finished with the client (or the client is finished with you):: 2376 2377 def deal_with_client(connstream): 2378 data = connstream.recv(1024) 2379 # empty data means the client is finished with us 2380 while data: 2381 if not do_something(connstream, data): 2382 # we'll assume do_something returns False 2383 # when we're finished with client 2384 break 2385 data = connstream.recv(1024) 2386 # finished with client 2387 2388And go back to listening for new client connections (of course, a real server 2389would probably handle each client connection in a separate thread, or put 2390the sockets in :ref:`non-blocking mode <ssl-nonblocking>` and use an event loop). 2391 2392 2393.. _ssl-nonblocking: 2394 2395Notes on non-blocking sockets 2396----------------------------- 2397 2398SSL sockets behave slightly different than regular sockets in 2399non-blocking mode. When working with non-blocking sockets, there are 2400thus several things you need to be aware of: 2401 2402- Most :class:`SSLSocket` methods will raise either 2403 :exc:`SSLWantWriteError` or :exc:`SSLWantReadError` instead of 2404 :exc:`BlockingIOError` if an I/O operation would 2405 block. :exc:`SSLWantReadError` will be raised if a read operation on 2406 the underlying socket is necessary, and :exc:`SSLWantWriteError` for 2407 a write operation on the underlying socket. Note that attempts to 2408 *write* to an SSL socket may require *reading* from the underlying 2409 socket first, and attempts to *read* from the SSL socket may require 2410 a prior *write* to the underlying socket. 2411 2412 .. versionchanged:: 3.5 2413 2414 In earlier Python versions, the :meth:`!SSLSocket.send` method 2415 returned zero instead of raising :exc:`SSLWantWriteError` or 2416 :exc:`SSLWantReadError`. 2417 2418- Calling :func:`~select.select` tells you that the OS-level socket can be 2419 read from (or written to), but it does not imply that there is sufficient 2420 data at the upper SSL layer. For example, only part of an SSL frame might 2421 have arrived. Therefore, you must be ready to handle :meth:`SSLSocket.recv` 2422 and :meth:`SSLSocket.send` failures, and retry after another call to 2423 :func:`~select.select`. 2424 2425- Conversely, since the SSL layer has its own framing, a SSL socket may 2426 still have data available for reading without :func:`~select.select` 2427 being aware of it. Therefore, you should first call 2428 :meth:`SSLSocket.recv` to drain any potentially available data, and then 2429 only block on a :func:`~select.select` call if still necessary. 2430 2431 (of course, similar provisions apply when using other primitives such as 2432 :func:`~select.poll`, or those in the :mod:`selectors` module) 2433 2434- The SSL handshake itself will be non-blocking: the 2435 :meth:`SSLSocket.do_handshake` method has to be retried until it returns 2436 successfully. Here is a synopsis using :func:`~select.select` to wait for 2437 the socket's readiness:: 2438 2439 while True: 2440 try: 2441 sock.do_handshake() 2442 break 2443 except ssl.SSLWantReadError: 2444 select.select([sock], [], []) 2445 except ssl.SSLWantWriteError: 2446 select.select([], [sock], []) 2447 2448.. seealso:: 2449 2450 The :mod:`asyncio` module supports :ref:`non-blocking SSL sockets 2451 <ssl-nonblocking>` and provides a 2452 higher level API. It polls for events using the :mod:`selectors` module and 2453 handles :exc:`SSLWantWriteError`, :exc:`SSLWantReadError` and 2454 :exc:`BlockingIOError` exceptions. It runs the SSL handshake asynchronously 2455 as well. 2456 2457 2458Memory BIO Support 2459------------------ 2460 2461.. versionadded:: 3.5 2462 2463Ever since the SSL module was introduced in Python 2.6, the :class:`SSLSocket` 2464class has provided two related but distinct areas of functionality: 2465 2466- SSL protocol handling 2467- Network IO 2468 2469The network IO API is identical to that provided by :class:`socket.socket`, 2470from which :class:`SSLSocket` also inherits. This allows an SSL socket to be 2471used as a drop-in replacement for a regular socket, making it very easy to add 2472SSL support to an existing application. 2473 2474Combining SSL protocol handling and network IO usually works well, but there 2475are some cases where it doesn't. An example is async IO frameworks that want to 2476use a different IO multiplexing model than the "select/poll on a file 2477descriptor" (readiness based) model that is assumed by :class:`socket.socket` 2478and by the internal OpenSSL socket IO routines. This is mostly relevant for 2479platforms like Windows where this model is not efficient. For this purpose, a 2480reduced scope variant of :class:`SSLSocket` called :class:`SSLObject` is 2481provided. 2482 2483.. class:: SSLObject 2484 2485 A reduced-scope variant of :class:`SSLSocket` representing an SSL protocol 2486 instance that does not contain any network IO methods. This class is 2487 typically used by framework authors that want to implement asynchronous IO 2488 for SSL through memory buffers. 2489 2490 This class implements an interface on top of a low-level SSL object as 2491 implemented by OpenSSL. This object captures the state of an SSL connection 2492 but does not provide any network IO itself. IO needs to be performed through 2493 separate "BIO" objects which are OpenSSL's IO abstraction layer. 2494 2495 This class has no public constructor. An :class:`SSLObject` instance 2496 must be created using the :meth:`~SSLContext.wrap_bio` method. This 2497 method will create the :class:`SSLObject` instance and bind it to a 2498 pair of BIOs. The *incoming* BIO is used to pass data from Python to the 2499 SSL protocol instance, while the *outgoing* BIO is used to pass data the 2500 other way around. 2501 2502 The following methods are available: 2503 2504 - :attr:`~SSLSocket.context` 2505 - :attr:`~SSLSocket.server_side` 2506 - :attr:`~SSLSocket.server_hostname` 2507 - :attr:`~SSLSocket.session` 2508 - :attr:`~SSLSocket.session_reused` 2509 - :meth:`~SSLSocket.read` 2510 - :meth:`~SSLSocket.write` 2511 - :meth:`~SSLSocket.getpeercert` 2512 - :meth:`~SSLSocket.selected_alpn_protocol` 2513 - :meth:`~SSLSocket.selected_npn_protocol` 2514 - :meth:`~SSLSocket.cipher` 2515 - :meth:`~SSLSocket.shared_ciphers` 2516 - :meth:`~SSLSocket.compression` 2517 - :meth:`~SSLSocket.pending` 2518 - :meth:`~SSLSocket.do_handshake` 2519 - :meth:`~SSLSocket.verify_client_post_handshake` 2520 - :meth:`~SSLSocket.unwrap` 2521 - :meth:`~SSLSocket.get_channel_binding` 2522 - :meth:`~SSLSocket.version` 2523 2524 When compared to :class:`SSLSocket`, this object lacks the following 2525 features: 2526 2527 - Any form of network IO; ``recv()`` and ``send()`` read and write only to 2528 the underlying :class:`MemoryBIO` buffers. 2529 2530 - There is no *do_handshake_on_connect* machinery. You must always manually 2531 call :meth:`~SSLSocket.do_handshake` to start the handshake. 2532 2533 - There is no handling of *suppress_ragged_eofs*. All end-of-file conditions 2534 that are in violation of the protocol are reported via the 2535 :exc:`SSLEOFError` exception. 2536 2537 - The method :meth:`~SSLSocket.unwrap` call does not return anything, 2538 unlike for an SSL socket where it returns the underlying socket. 2539 2540 - The *server_name_callback* callback passed to 2541 :meth:`SSLContext.set_servername_callback` will get an :class:`SSLObject` 2542 instance instead of a :class:`SSLSocket` instance as its first parameter. 2543 2544 Some notes related to the use of :class:`SSLObject`: 2545 2546 - All IO on an :class:`SSLObject` is :ref:`non-blocking <ssl-nonblocking>`. 2547 This means that for example :meth:`~SSLSocket.read` will raise an 2548 :exc:`SSLWantReadError` if it needs more data than the incoming BIO has 2549 available. 2550 2551 - There is no module-level ``wrap_bio()`` call like there is for 2552 :meth:`~SSLContext.wrap_socket`. An :class:`SSLObject` is always created 2553 via an :class:`SSLContext`. 2554 2555 .. versionchanged:: 3.7 2556 :class:`SSLObject` instances must to created with 2557 :meth:`~SSLContext.wrap_bio`. In earlier versions, it was possible to 2558 create instances directly. This was never documented or officially 2559 supported. 2560 2561An SSLObject communicates with the outside world using memory buffers. The 2562class :class:`MemoryBIO` provides a memory buffer that can be used for this 2563purpose. It wraps an OpenSSL memory BIO (Basic IO) object: 2564 2565.. class:: MemoryBIO 2566 2567 A memory buffer that can be used to pass data between Python and an SSL 2568 protocol instance. 2569 2570 .. attribute:: MemoryBIO.pending 2571 2572 Return the number of bytes currently in the memory buffer. 2573 2574 .. attribute:: MemoryBIO.eof 2575 2576 A boolean indicating whether the memory BIO is current at the end-of-file 2577 position. 2578 2579 .. method:: MemoryBIO.read(n=-1) 2580 2581 Read up to *n* bytes from the memory buffer. If *n* is not specified or 2582 negative, all bytes are returned. 2583 2584 .. method:: MemoryBIO.write(buf) 2585 2586 Write the bytes from *buf* to the memory BIO. The *buf* argument must be an 2587 object supporting the buffer protocol. 2588 2589 The return value is the number of bytes written, which is always equal to 2590 the length of *buf*. 2591 2592 .. method:: MemoryBIO.write_eof() 2593 2594 Write an EOF marker to the memory BIO. After this method has been called, it 2595 is illegal to call :meth:`~MemoryBIO.write`. The attribute :attr:`eof` will 2596 become true after all data currently in the buffer has been read. 2597 2598 2599SSL session 2600----------- 2601 2602.. versionadded:: 3.6 2603 2604.. class:: SSLSession 2605 2606 Session object used by :attr:`~SSLSocket.session`. 2607 2608 .. attribute:: id 2609 .. attribute:: time 2610 .. attribute:: timeout 2611 .. attribute:: ticket_lifetime_hint 2612 .. attribute:: has_ticket 2613 2614 2615.. _ssl-security: 2616 2617Security considerations 2618----------------------- 2619 2620Best defaults 2621^^^^^^^^^^^^^ 2622 2623For **client use**, if you don't have any special requirements for your 2624security policy, it is highly recommended that you use the 2625:func:`create_default_context` function to create your SSL context. 2626It will load the system's trusted CA certificates, enable certificate 2627validation and hostname checking, and try to choose reasonably secure 2628protocol and cipher settings. 2629 2630For example, here is how you would use the :class:`smtplib.SMTP` class to 2631create a trusted, secure connection to a SMTP server:: 2632 2633 >>> import ssl, smtplib 2634 >>> smtp = smtplib.SMTP("mail.python.org", port=587) 2635 >>> context = ssl.create_default_context() 2636 >>> smtp.starttls(context=context) 2637 (220, b'2.0.0 Ready to start TLS') 2638 2639If a client certificate is needed for the connection, it can be added with 2640:meth:`SSLContext.load_cert_chain`. 2641 2642By contrast, if you create the SSL context by calling the :class:`SSLContext` 2643constructor yourself, it will not have certificate validation nor hostname 2644checking enabled by default. If you do so, please read the paragraphs below 2645to achieve a good security level. 2646 2647Manual settings 2648^^^^^^^^^^^^^^^ 2649 2650Verifying certificates 2651'''''''''''''''''''''' 2652 2653When calling the :class:`SSLContext` constructor directly, 2654:const:`CERT_NONE` is the default. Since it does not authenticate the other 2655peer, it can be insecure, especially in client mode where most of time you 2656would like to ensure the authenticity of the server you're talking to. 2657Therefore, when in client mode, it is highly recommended to use 2658:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also 2659have to check that the server certificate, which can be obtained by calling 2660:meth:`SSLSocket.getpeercert`, matches the desired service. For many 2661protocols and applications, the service can be identified by the hostname; 2662in this case, the :func:`match_hostname` function can be used. This common 2663check is automatically performed when :attr:`SSLContext.check_hostname` is 2664enabled. 2665 2666.. versionchanged:: 3.7 2667 Hostname matchings is now performed by OpenSSL. Python no longer uses 2668 :func:`match_hostname`. 2669 2670In server mode, if you want to authenticate your clients using the SSL layer 2671(rather than using a higher-level authentication mechanism), you'll also have 2672to specify :const:`CERT_REQUIRED` and similarly check the client certificate. 2673 2674 2675Protocol versions 2676''''''''''''''''' 2677 2678SSL versions 2 and 3 are considered insecure and are therefore dangerous to 2679use. If you want maximum compatibility between clients and servers, it is 2680recommended to use :const:`PROTOCOL_TLS_CLIENT` or 2681:const:`PROTOCOL_TLS_SERVER` as the protocol version. SSLv2 and SSLv3 are 2682disabled by default. 2683 2684:: 2685 2686 >>> client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) 2687 >>> client_context.minimum_version = ssl.TLSVersion.TLSv1_3 2688 >>> client_context.maximum_version = ssl.TLSVersion.TLSv1_3 2689 2690 2691The SSL context created above will only allow TLSv1.2 and later (if 2692supported by your system) connections to a server. :const:`PROTOCOL_TLS_CLIENT` 2693implies certificate validation and hostname checks by default. You have to 2694load certificates into the context. 2695 2696 2697Cipher selection 2698'''''''''''''''' 2699 2700If you have advanced security requirements, fine-tuning of the ciphers 2701enabled when negotiating a SSL session is possible through the 2702:meth:`SSLContext.set_ciphers` method. Starting from Python 3.2.3, the 2703ssl module disables certain weak ciphers by default, but you may want 2704to further restrict the cipher choice. Be sure to read OpenSSL's documentation 2705about the `cipher list format <https://www.openssl.org/docs/man1.1.1/man1/ciphers.html#CIPHER-LIST-FORMAT>`_. 2706If you want to check which ciphers are enabled by a given cipher list, use 2707:meth:`SSLContext.get_ciphers` or the ``openssl ciphers`` command on your 2708system. 2709 2710Multi-processing 2711^^^^^^^^^^^^^^^^ 2712 2713If using this module as part of a multi-processed application (using, 2714for example the :mod:`multiprocessing` or :mod:`concurrent.futures` modules), 2715be aware that OpenSSL's internal random number generator does not properly 2716handle forked processes. Applications must change the PRNG state of the 2717parent process if they use any SSL feature with :func:`os.fork`. Any 2718successful call of :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or 2719:func:`~ssl.RAND_pseudo_bytes` is sufficient. 2720 2721 2722.. _ssl-tlsv1_3: 2723 2724TLS 1.3 2725------- 2726 2727.. versionadded:: 3.7 2728 2729The TLS 1.3 protocol behaves slightly differently than previous version 2730of TLS/SSL. Some new TLS 1.3 features are not yet available. 2731 2732- TLS 1.3 uses a disjunct set of cipher suites. All AES-GCM and 2733 ChaCha20 cipher suites are enabled by default. The method 2734 :meth:`SSLContext.set_ciphers` cannot enable or disable any TLS 1.3 2735 ciphers yet, but :meth:`SSLContext.get_ciphers` returns them. 2736- Session tickets are no longer sent as part of the initial handshake and 2737 are handled differently. :attr:`SSLSocket.session` and :class:`SSLSession` 2738 are not compatible with TLS 1.3. 2739- Client-side certificates are also no longer verified during the initial 2740 handshake. A server can request a certificate at any time. Clients 2741 process certificate requests while they send or receive application data 2742 from the server. 2743- TLS 1.3 features like early data, deferred TLS client cert request, 2744 signature algorithm configuration, and rekeying are not supported yet. 2745 2746 2747.. seealso:: 2748 2749 Class :class:`socket.socket` 2750 Documentation of underlying :mod:`socket` class 2751 2752 `SSL/TLS Strong Encryption: An Introduction <https://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html>`_ 2753 Intro from the Apache HTTP Server documentation 2754 2755 :rfc:`RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <1422>` 2756 Steve Kent 2757 2758 :rfc:`RFC 4086: Randomness Requirements for Security <4086>` 2759 Donald E., Jeffrey I. Schiller 2760 2761 :rfc:`RFC 5280: Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile <5280>` 2762 D. Cooper 2763 2764 :rfc:`RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2 <5246>` 2765 T. Dierks et. al. 2766 2767 :rfc:`RFC 6066: Transport Layer Security (TLS) Extensions <6066>` 2768 D. Eastlake 2769 2770 `IANA TLS: Transport Layer Security (TLS) Parameters <https://www.iana.org/assignments/tls-parameters/tls-parameters.xml>`_ 2771 IANA 2772 2773 :rfc:`RFC 7525: Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS) <7525>` 2774 IETF 2775 2776 `Mozilla's Server Side TLS recommendations <https://wiki.mozilla.org/Security/Server_Side_TLS>`_ 2777 Mozilla 2778