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