Debian Codegraph @

Doc/library/ssl.rst

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