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