blob: 89b9ff3621f7b7e19879d8a80547960cb96e27c9 [file] [log] [blame]
Antoine Pitrou9e7d6e52011-01-02 22:39:10 +00001:mod:`ssl` --- TLS/SSL wrapper for socket objects
2=================================================
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00003
4.. module:: ssl
Antoine Pitrou9e7d6e52011-01-02 22:39:10 +00005 :synopsis: TLS/SSL wrapper for socket objects
Bill Janssen426ea0a2007-08-29 22:35:05 +00006
7.. moduleauthor:: Bill Janssen <bill.janssen@gmail.com>
Bill Janssen426ea0a2007-08-29 22:35:05 +00008.. sectionauthor:: Bill Janssen <bill.janssen@gmail.com>
9
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000010
Bill Janssen98d19da2007-09-10 21:51:02 +000011.. index:: single: OpenSSL; (use in module ssl)
12
13.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
14
Éric Araujo29a0b572011-08-19 02:14:03 +020015.. versionadded:: 2.6
16
17**Source code:** :source:`Lib/ssl.py`
18
19--------------
20
Georg Brandla50d20a2009-09-16 15:57:46 +000021This module provides access to Transport Layer Security (often known as "Secure
22Sockets Layer") encryption and peer authentication facilities for network
23sockets, both client-side and server-side. This module uses the OpenSSL
24library. It is available on all modern Unix systems, Windows, Mac OS X, and
25probably additional platforms, as long as OpenSSL is installed on that platform.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000026
27.. note::
28
Georg Brandla50d20a2009-09-16 15:57:46 +000029 Some behavior may be platform dependent, since calls are made to the
30 operating system socket APIs. The installed version of OpenSSL may also
Benjamin Petersondaeb9252014-08-20 14:14:50 -050031 cause variations in behavior. For example, TLSv1.1 and TLSv1.2 come with
32 openssl version 1.0.1.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000033
Christian Heimes88b22202013-10-29 21:08:56 +010034.. warning::
Benjamin Petersondaeb9252014-08-20 14:14:50 -050035 Don't use this module without reading the :ref:`ssl-security`. Doing so
36 may lead to a false sense of security, as the default settings of the
37 ssl module are not necessarily appropriate for your application.
Antoine Pitrouf7a52472013-11-17 15:42:58 +010038
Christian Heimes88b22202013-10-29 21:08:56 +010039
Georg Brandla50d20a2009-09-16 15:57:46 +000040This section documents the objects and functions in the ``ssl`` module; for more
41general information about TLS, SSL, and certificates, the reader is referred to
42the documents in the "See Also" section at the bottom.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000043
Georg Brandla50d20a2009-09-16 15:57:46 +000044This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
45:class:`socket.socket` type, and provides a socket-like wrapper that also
46encrypts and decrypts the data going over the socket with SSL. It supports
Benjamin Petersondaeb9252014-08-20 14:14:50 -050047additional methods such as :meth:`getpeercert`, which retrieves the
48certificate of the other side of the connection, and :meth:`cipher`,which
49retrieves the cipher being used for the secure connection.
50
51For more sophisticated applications, the :class:`ssl.SSLContext` class
52helps manage settings and certificates, which can then be inherited
53by SSL sockets created through the :meth:`SSLContext.wrap_socket` method.
54
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000055
Bill Janssen93bf9ce2007-09-11 02:42:07 +000056Functions, Constants, and Exceptions
57------------------------------------
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000058
Bill Janssen93bf9ce2007-09-11 02:42:07 +000059.. exception:: SSLError
60
Benjamin Petersondaeb9252014-08-20 14:14:50 -050061 Raised to signal an error from the underlying SSL implementation (currently
62 provided by the OpenSSL library). This signifies some problem in the
63 higher-level encryption and authentication layer that's superimposed on the
64 underlying network connection. This error is a subtype of
65 :exc:`socket.error`, which in turn is a subtype of :exc:`IOError`. The
66 error code and message of :exc:`SSLError` instances are provided by the
67 OpenSSL library.
Bill Janssen93bf9ce2007-09-11 02:42:07 +000068
Benjamin Petersondaeb9252014-08-20 14:14:50 -050069 .. attribute:: library
70
71 A string mnemonic designating the OpenSSL submodule in which the error
72 occurred, such as ``SSL``, ``PEM`` or ``X509``. The range of possible
73 values depends on the OpenSSL version.
74
75 .. versionadded:: 2.7.9
76
77 .. attribute:: reason
78
79 A string mnemonic designating the reason this error occurred, for
80 example ``CERTIFICATE_VERIFY_FAILED``. The range of possible
81 values depends on the OpenSSL version.
82
83 .. versionadded:: 2.7.9
84
85.. exception:: SSLZeroReturnError
86
87 A subclass of :exc:`SSLError` raised when trying to read or write and
88 the SSL connection has been closed cleanly. Note that this doesn't
89 mean that the underlying transport (read TCP) has been closed.
90
91 .. versionadded:: 2.7.9
92
93.. exception:: SSLWantReadError
94
95 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
96 <ssl-nonblocking>` when trying to read or write data, but more data needs
97 to be received on the underlying TCP transport before the request can be
98 fulfilled.
99
100 .. versionadded:: 2.7.9
101
102.. exception:: SSLWantWriteError
103
104 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
105 <ssl-nonblocking>` when trying to read or write data, but more data needs
106 to be sent on the underlying TCP transport before the request can be
107 fulfilled.
108
109 .. versionadded:: 2.7.9
110
111.. exception:: SSLSyscallError
112
113 A subclass of :exc:`SSLError` raised when a system error was encountered
114 while trying to fulfill an operation on a SSL socket. Unfortunately,
115 there is no easy way to inspect the original errno number.
116
117 .. versionadded:: 2.7.9
118
119.. exception:: SSLEOFError
120
121 A subclass of :exc:`SSLError` raised when the SSL connection has been
122 terminated abruptly. Generally, you shouldn't try to reuse the underlying
123 transport when this error is encountered.
124
125 .. versionadded:: 2.7.9
126
127.. exception:: CertificateError
128
129 Raised to signal an error with a certificate (such as mismatching
130 hostname). Certificate errors detected by OpenSSL, though, raise
131 an :exc:`SSLError`.
132
133
134Socket creation
135^^^^^^^^^^^^^^^
136
137The following function allows for standalone socket creation. Starting from
138Python 2.7.9, it can be more flexible to use :meth:`SSLContext.wrap_socket`
139instead.
140
141.. function:: wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None)
Bill Janssen98d19da2007-09-10 21:51:02 +0000142
Georg Brandla50d20a2009-09-16 15:57:46 +0000143 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
144 of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
Antoine Pitrou63cc99d2013-12-28 17:26:33 +0100145 the underlying socket in an SSL context. ``sock`` must be a
146 :data:`~socket.SOCK_STREAM` socket; other socket types are unsupported.
147
148 For client-side sockets, the context construction is lazy; if the
149 underlying socket isn't connected yet, the context construction will be
150 performed after :meth:`connect` is called on the socket. For
151 server-side sockets, if the socket has no remote peer, it is assumed
152 to be a listening socket, and the server-side SSL wrapping is
153 automatically performed on client connections accepted via the
154 :meth:`accept` method. :func:`wrap_socket` may raise :exc:`SSLError`.
Bill Janssen98d19da2007-09-10 21:51:02 +0000155
Georg Brandla50d20a2009-09-16 15:57:46 +0000156 The ``keyfile`` and ``certfile`` parameters specify optional files which
157 contain a certificate to be used to identify the local side of the
158 connection. See the discussion of :ref:`ssl-certificates` for more
159 information on how the certificate is stored in the ``certfile``.
Bill Janssen98d19da2007-09-10 21:51:02 +0000160
Georg Brandla50d20a2009-09-16 15:57:46 +0000161 The parameter ``server_side`` is a boolean which identifies whether
162 server-side or client-side behavior is desired from this socket.
Bill Janssen98d19da2007-09-10 21:51:02 +0000163
Georg Brandla50d20a2009-09-16 15:57:46 +0000164 The parameter ``cert_reqs`` specifies whether a certificate is required from
165 the other side of the connection, and whether it will be validated if
166 provided. It must be one of the three values :const:`CERT_NONE`
167 (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
168 if provided), or :const:`CERT_REQUIRED` (required and validated). If the
169 value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
170 parameter must point to a file of CA certificates.
Bill Janssen98d19da2007-09-10 21:51:02 +0000171
Georg Brandla50d20a2009-09-16 15:57:46 +0000172 The ``ca_certs`` file contains a set of concatenated "certification
173 authority" certificates, which are used to validate certificates passed from
174 the other end of the connection. See the discussion of
175 :ref:`ssl-certificates` for more information about how to arrange the
176 certificates in this file.
Bill Janssen98d19da2007-09-10 21:51:02 +0000177
Georg Brandla50d20a2009-09-16 15:57:46 +0000178 The parameter ``ssl_version`` specifies which version of the SSL protocol to
179 use. Typically, the server chooses a particular protocol version, and the
180 client must adapt to the server's choice. Most of the versions are not
Antoine Pitrou4a7e0c892012-01-09 21:35:11 +0100181 interoperable with the other versions. If not specified, the default is
182 :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other
Georg Brandla50d20a2009-09-16 15:57:46 +0000183 versions.
Bill Janssen98d19da2007-09-10 21:51:02 +0000184
Georg Brandla50d20a2009-09-16 15:57:46 +0000185 Here's a table showing which versions in a client (down the side) can connect
186 to which versions in a server (along the top):
Bill Janssen98d19da2007-09-10 21:51:02 +0000187
188 .. table::
189
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500190 ======================== ========= ========= ========== ========= =========== ===========
191 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1** **TLSv1.1** **TLSv1.2**
192 ------------------------ --------- --------- ---------- --------- ----------- -----------
193 *SSLv2* yes no yes no no no
194 *SSLv3* no yes yes no no no
Christian Heimesb9a860f2017-09-07 22:31:17 -0700195 *SSLv23* [1]_ no yes yes yes yes yes
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500196 *TLSv1* no no yes yes no no
197 *TLSv1.1* no no yes no yes no
198 *TLSv1.2* no no yes no no yes
199 ======================== ========= ========= ========== ========= =========== ===========
Bill Janssen98d19da2007-09-10 21:51:02 +0000200
Christian Heimesb9a860f2017-09-07 22:31:17 -0700201 .. rubric:: Footnotes
202 .. [1] TLS 1.3 protocol will be available with :data:`PROTOCOL_SSLv23` in
203 OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for just
204 TLS 1.3.
205
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000206 .. note::
207
Andrew M. Kuchling3ded4212010-04-30 00:52:31 +0000208 Which connections succeed will vary depending on the version of
Antoine Pitroubf9eb352014-12-03 20:00:56 +0100209 OpenSSL. For example, before OpenSSL 1.0.0, an SSLv23 client
210 would always attempt SSLv2 connections.
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000211
Andrew M. Kuchling3ded4212010-04-30 00:52:31 +0000212 The *ciphers* parameter sets the available ciphers for this SSL object.
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000213 It should be a string in the `OpenSSL cipher list format
Christian Heimes5b6452d2017-09-20 22:23:09 +0200214 <https://wiki.openssl.org/index.php/Manual:Ciphers(1)#CIPHER_LIST_FORMAT>`_.
Bill Janssen98d19da2007-09-10 21:51:02 +0000215
Bill Janssen934b16d2008-06-28 22:19:33 +0000216 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
217 handshake automatically after doing a :meth:`socket.connect`, or whether the
Georg Brandla50d20a2009-09-16 15:57:46 +0000218 application program will call it explicitly, by invoking the
219 :meth:`SSLSocket.do_handshake` method. Calling
220 :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
221 blocking behavior of the socket I/O involved in the handshake.
Bill Janssen934b16d2008-06-28 22:19:33 +0000222
Georg Brandla50d20a2009-09-16 15:57:46 +0000223 The parameter ``suppress_ragged_eofs`` specifies how the
224 :meth:`SSLSocket.read` method should signal unexpected EOF from the other end
225 of the connection. If specified as :const:`True` (the default), it returns a
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500226 normal EOF (an empty bytes object) in response to unexpected EOF errors
227 raised from the underlying socket; if :const:`False`, it will raise the
228 exceptions back to the caller.
Bill Janssen934b16d2008-06-28 22:19:33 +0000229
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000230 .. versionchanged:: 2.7
231 New optional argument *ciphers*.
232
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500233
234Context creation
235^^^^^^^^^^^^^^^^
236
237A convenience function helps create :class:`SSLContext` objects for common
238purposes.
239
240.. function:: create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None)
241
242 Return a new :class:`SSLContext` object with default settings for
243 the given *purpose*. The settings are chosen by the :mod:`ssl` module,
244 and usually represent a higher security level than when calling the
245 :class:`SSLContext` constructor directly.
246
247 *cafile*, *capath*, *cadata* represent optional CA certificates to
248 trust for certificate verification, as in
249 :meth:`SSLContext.load_verify_locations`. If all three are
250 :const:`None`, this function can choose to trust the system's default
251 CA certificates instead.
252
Benjamin Peterson51518382015-03-16 12:43:38 -0500253 The settings are: :data:`PROTOCOL_SSLv23`, :data:`OP_NO_SSLv2`, and
254 :data:`OP_NO_SSLv3` with high encryption cipher suites without RC4 and
255 without unauthenticated cipher suites. Passing :data:`~Purpose.SERVER_AUTH`
256 as *purpose* sets :data:`~SSLContext.verify_mode` to :data:`CERT_REQUIRED`
257 and either loads CA certificates (when at least one of *cafile*, *capath* or
258 *cadata* is given) or uses :meth:`SSLContext.load_default_certs` to load
259 default CA certificates.
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500260
261 .. note::
262 The protocol, options, cipher and other settings may change to more
263 restrictive values anytime without prior deprecation. The values
264 represent a fair balance between compatibility and security.
265
266 If your application needs specific settings, you should create a
267 :class:`SSLContext` and apply the settings yourself.
268
269 .. note::
270 If you find that when certain older clients or servers attempt to connect
Benjamin Petersonce29e872015-04-08 11:11:00 -0400271 with a :class:`SSLContext` created by this function that they get an error
272 stating "Protocol or cipher suite mismatch", it may be that they only
273 support SSL3.0 which this function excludes using the
274 :data:`OP_NO_SSLv3`. SSL3.0 is widely considered to be `completely broken
275 <https://en.wikipedia.org/wiki/POODLE>`_. If you still wish to continue to
276 use this function but still allow SSL 3.0 connections you can re-enable
277 them using::
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500278
279 ctx = ssl.create_default_context(Purpose.CLIENT_AUTH)
280 ctx.options &= ~ssl.OP_NO_SSLv3
281
282 .. versionadded:: 2.7.9
283
Benjamin Peterson51518382015-03-16 12:43:38 -0500284 .. versionchanged:: 2.7.10
285
286 RC4 was dropped from the default cipher string.
287
Christian Heimesd988f422016-09-06 20:06:47 +0200288 .. versionchanged:: 2.7.13
289
290 ChaCha20/Poly1305 was added to the default cipher string.
291
292 3DES was dropped from the default cipher string.
293
Christian Heimesb9a860f2017-09-07 22:31:17 -0700294 .. versionchanged:: 2.7.15
295
296 TLS 1.3 cipher suites TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384,
297 and TLS_CHACHA20_POLY1305_SHA256 were added to the default cipher string.
298
Nick Coghlandbcd4572016-03-20 22:39:15 +1000299.. function:: _https_verify_certificates(enable=True)
300
301 Specifies whether or not server certificates are verified when creating
302 client HTTPS connections without specifying a particular SSL context.
303
304 Starting with Python 2.7.9, :mod:`httplib` and modules which use it, such as
305 :mod:`urllib2` and :mod:`xmlrpclib`, default to verifying remote server
306 certificates received when establishing client HTTPS connections. This
307 default verification checks that the certificate is signed by a Certificate
308 Authority in the system trust store and that the Common Name (or Subject
309 Alternate Name) on the presented certificate matches the requested host.
310
311 Setting *enable* to :const:`True` ensures this default behaviour is in
312 effect.
313
314 Setting *enable* to :const:`False` reverts the default HTTPS certificate
315 handling to that of Python 2.7.8 and earlier, allowing connections to
316 servers using self-signed certificates, servers using certificates signed
317 by a Certicate Authority not present in the system trust store, and servers
318 where the hostname does not match the presented server certificate.
319
320 The leading underscore on this function denotes that it intentionally does
321 not exist in any implementation of Python 3 and may not be present in all
322 Python 2.7 implementations. The portable approach to bypassing certificate
323 checks or the system trust store when necessary is for tools to enable that
324 on a case-by-case basis by explicitly passing in a suitably configured SSL
325 context, rather than reverting the default behaviour of the standard library
326 client modules.
327
328 .. versionadded:: 2.7.12
329
330 .. seealso::
331
332 * `CVE-2014-9365 <http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-9365>`_
333 -- HTTPS man-in-the-middle attack against Python clients using default settings
334 * :pep:`476` -- Enabling certificate verification by default for HTTPS
335 * :pep:`493` -- HTTPS verification migration tools for Python 2.7
336
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500337
338Random generation
339^^^^^^^^^^^^^^^^^
340
Christian Heimes4e64c2c2016-09-06 23:41:37 +0200341 .. deprecated:: 2.7.13
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200342
Christian Heimes4e64c2c2016-09-06 23:41:37 +0200343 OpenSSL has deprecated :func:`ssl.RAND_pseudo_bytes`, use
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200344 :func:`ssl.RAND_bytes` instead.
345
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200346
Bill Janssen98d19da2007-09-10 21:51:02 +0000347.. function:: RAND_status()
348
Benjamin Peterson721c86e2015-04-11 07:42:42 -0400349 Return ``True`` if the SSL pseudo-random number generator has been seeded
350 with 'enough' randomness, and ``False`` otherwise. You can use
351 :func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness of
352 the pseudo-random number generator.
Bill Janssen98d19da2007-09-10 21:51:02 +0000353
354.. function:: RAND_egd(path)
355
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500356 If you are running an entropy-gathering daemon (EGD) somewhere, and *path*
Georg Brandla50d20a2009-09-16 15:57:46 +0000357 is the pathname of a socket connection open to it, this will read 256 bytes
358 of randomness from the socket, and add it to the SSL pseudo-random number
359 generator to increase the security of generated secret keys. This is
360 typically only necessary on systems without better sources of randomness.
Bill Janssen98d19da2007-09-10 21:51:02 +0000361
Georg Brandla50d20a2009-09-16 15:57:46 +0000362 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
363 of entropy-gathering daemons.
Bill Janssen98d19da2007-09-10 21:51:02 +0000364
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200365 Availability: not available with LibreSSL and OpenSSL > 1.1.0
Victor Stinner7c906672015-01-06 13:53:37 +0100366
Bill Janssen98d19da2007-09-10 21:51:02 +0000367.. function:: RAND_add(bytes, entropy)
368
Benjamin Peterson721c86e2015-04-11 07:42:42 -0400369 Mix the given *bytes* into the SSL pseudo-random number generator. The
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500370 parameter *entropy* (a float) is a lower bound on the entropy contained in
Georg Brandla50d20a2009-09-16 15:57:46 +0000371 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
372 information on sources of entropy.
Bill Janssen98d19da2007-09-10 21:51:02 +0000373
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500374Certificate handling
375^^^^^^^^^^^^^^^^^^^^
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000376
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500377.. function:: match_hostname(cert, hostname)
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000378
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500379 Verify that *cert* (in decoded format as returned by
380 :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules
381 applied are those for checking the identity of HTTPS servers as outlined
382 in :rfc:`2818` and :rfc:`6125`, except that IP addresses are not currently
383 supported. In addition to HTTPS, this function should be suitable for
384 checking the identity of servers in various SSL-based protocols such as
385 FTPS, IMAPS, POPS and others.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000386
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500387 :exc:`CertificateError` is raised on failure. On success, the function
388 returns nothing::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000389
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500390 >>> cert = {'subject': ((('commonName', 'example.com'),),)}
391 >>> ssl.match_hostname(cert, "example.com")
392 >>> ssl.match_hostname(cert, "example.org")
393 Traceback (most recent call last):
394 File "<stdin>", line 1, in <module>
395 File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
396 ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'
397
398 .. versionadded:: 2.7.9
399
400
401.. function:: cert_time_to_seconds(cert_time)
402
403 Return the time in seconds since the Epoch, given the ``cert_time``
404 string representing the "notBefore" or "notAfter" date from a
405 certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C
406 locale).
407
408 Here's an example:
409
410 .. doctest:: newcontext
411
412 >>> import ssl
413 >>> timestamp = ssl.cert_time_to_seconds("Jan 5 09:34:43 2018 GMT")
414 >>> timestamp
415 1515144883
416 >>> from datetime import datetime
417 >>> print(datetime.utcfromtimestamp(timestamp))
418 2018-01-05 09:34:43
419
420 "notBefore" or "notAfter" dates must use GMT (:rfc:`5280`).
421
422 .. versionchanged:: 2.7.9
423 Interpret the input time as a time in UTC as specified by 'GMT'
424 timezone in the input string. Local timezone was used
425 previously. Return an integer (no fractions of a second in the
426 input format)
427
428.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None)
Bill Janssen296a59d2007-09-16 22:06:00 +0000429
Georg Brandla50d20a2009-09-16 15:57:46 +0000430 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
431 *port-number*) pair, fetches the server's certificate, and returns it as a
432 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
433 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
434 specified, it should be a file containing a list of root certificates, the
435 same format as used for the same parameter in :func:`wrap_socket`. The call
436 will attempt to validate the server certificate against that set of root
Bill Janssen296a59d2007-09-16 22:06:00 +0000437 certificates, and will fail if the validation attempt fails.
438
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500439 .. versionchanged:: 2.7.9
440
441 This function is now IPv6-compatible, and the default *ssl_version* is
442 changed from :data:`PROTOCOL_SSLv3` to :data:`PROTOCOL_SSLv23` for
443 maximum compatibility with modern servers.
444
445.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Bill Janssen296a59d2007-09-16 22:06:00 +0000446
447 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
448 string version of the same certificate.
449
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500450.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Bill Janssen296a59d2007-09-16 22:06:00 +0000451
Georg Brandla50d20a2009-09-16 15:57:46 +0000452 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
453 bytes for that same certificate.
Bill Janssen296a59d2007-09-16 22:06:00 +0000454
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500455.. function:: get_default_verify_paths()
456
457 Returns a named tuple with paths to OpenSSL's default cafile and capath.
458 The paths are the same as used by
459 :meth:`SSLContext.set_default_verify_paths`. The return value is a
460 :term:`named tuple` ``DefaultVerifyPaths``:
461
Serhiy Storchakaad13f332016-10-19 16:29:10 +0300462 * :attr:`cafile` - resolved path to cafile or ``None`` if the file doesn't exist,
463 * :attr:`capath` - resolved path to capath or ``None`` if the directory doesn't exist,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500464 * :attr:`openssl_cafile_env` - OpenSSL's environment key that points to a cafile,
465 * :attr:`openssl_cafile` - hard coded path to a cafile,
466 * :attr:`openssl_capath_env` - OpenSSL's environment key that points to a capath,
467 * :attr:`openssl_capath` - hard coded path to a capath directory
468
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200469 Availability: LibreSSL ignores the environment vars
470 :attr:`openssl_cafile_env` and :attr:`openssl_capath_env`
471
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500472 .. versionadded:: 2.7.9
473
474.. function:: enum_certificates(store_name)
475
476 Retrieve certificates from Windows' system cert store. *store_name* may be
477 one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert
478 stores, too.
479
480 The function returns a list of (cert_bytes, encoding_type, trust) tuples.
481 The encoding_type specifies the encoding of cert_bytes. It is either
482 :const:`x509_asn` for X.509 ASN.1 data or :const:`pkcs_7_asn` for
483 PKCS#7 ASN.1 data. Trust specifies the purpose of the certificate as a set
484 of OIDS or exactly ``True`` if the certificate is trustworthy for all
485 purposes.
486
487 Example::
488
489 >>> ssl.enum_certificates("CA")
490 [(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}),
491 (b'data...', 'x509_asn', True)]
492
493 Availability: Windows.
494
495 .. versionadded:: 2.7.9
496
497.. function:: enum_crls(store_name)
498
499 Retrieve CRLs from Windows' system cert store. *store_name* may be
500 one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert
501 stores, too.
502
503 The function returns a list of (cert_bytes, encoding_type, trust) tuples.
504 The encoding_type specifies the encoding of cert_bytes. It is either
505 :const:`x509_asn` for X.509 ASN.1 data or :const:`pkcs_7_asn` for
506 PKCS#7 ASN.1 data.
507
508 Availability: Windows.
509
510 .. versionadded:: 2.7.9
511
512
513Constants
514^^^^^^^^^
515
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000516.. data:: CERT_NONE
517
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500518 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
519 parameter to :func:`wrap_socket`. In this mode (the default), no
520 certificates will be required from the other side of the socket connection.
521 If a certificate is received from the other end, no attempt to validate it
522 is made.
523
524 See the discussion of :ref:`ssl-security` below.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000525
526.. data:: CERT_OPTIONAL
527
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500528 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
529 parameter to :func:`wrap_socket`. In this mode no certificates will be
530 required from the other side of the socket connection; but if they
531 are provided, validation will be attempted and an :class:`SSLError`
532 will be raised on failure.
533
534 Use of this setting requires a valid set of CA certificates to
535 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
536 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000537
538.. data:: CERT_REQUIRED
539
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500540 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
541 parameter to :func:`wrap_socket`. In this mode, certificates are
542 required from the other side of the socket connection; an :class:`SSLError`
543 will be raised if no certificate is provided, or if its validation fails.
544
545 Use of this setting requires a valid set of CA certificates to
546 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
547 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
548
549.. data:: VERIFY_DEFAULT
550
Benjamin Peterson72ef9612015-03-04 22:49:41 -0500551 Possible value for :attr:`SSLContext.verify_flags`. In this mode, certificate
552 revocation lists (CRLs) are not checked. By default OpenSSL does neither
553 require nor verify CRLs.
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500554
555 .. versionadded:: 2.7.9
556
557.. data:: VERIFY_CRL_CHECK_LEAF
558
559 Possible value for :attr:`SSLContext.verify_flags`. In this mode, only the
560 peer cert is check but non of the intermediate CA certificates. The mode
561 requires a valid CRL that is signed by the peer cert's issuer (its direct
562 ancestor CA). If no proper has been loaded
563 :attr:`SSLContext.load_verify_locations`, validation will fail.
564
565 .. versionadded:: 2.7.9
566
567.. data:: VERIFY_CRL_CHECK_CHAIN
568
569 Possible value for :attr:`SSLContext.verify_flags`. In this mode, CRLs of
570 all certificates in the peer cert chain are checked.
571
572 .. versionadded:: 2.7.9
573
574.. data:: VERIFY_X509_STRICT
575
576 Possible value for :attr:`SSLContext.verify_flags` to disable workarounds
577 for broken X.509 certificates.
578
579 .. versionadded:: 2.7.9
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000580
Benjamin Peterson72ef9612015-03-04 22:49:41 -0500581.. data:: VERIFY_X509_TRUSTED_FIRST
582
583 Possible value for :attr:`SSLContext.verify_flags`. It instructs OpenSSL to
584 prefer trusted certificates when building the trust chain to validate a
585 certificate. This flag is enabled by default.
586
587 .. versionadded:: 2.7.10
588
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200589.. data:: PROTOCOL_TLS
Antoine Pitrou9e4a9332014-10-21 00:14:39 +0200590
591 Selects the highest protocol version that both the client and server support.
592 Despite the name, this option can select "TLS" protocols as well as "SSL".
593
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200594 .. versionadded:: 2.7.13
595
596.. data:: PROTOCOL_SSLv23
597
598 Alias for ``PROTOCOL_TLS``.
599
600 .. deprecated:: 2.7.13 Use ``PROTOCOL_TLS`` instead.
601
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000602.. data:: PROTOCOL_SSLv2
603
604 Selects SSL version 2 as the channel encryption protocol.
605
Benjamin Petersonfd0c92f2014-12-06 11:36:32 -0500606 This protocol is not available if OpenSSL is compiled with the
607 ``OPENSSL_NO_SSL2`` flag.
Victor Stinnerb1241f92011-05-10 01:52:03 +0200608
Antoine Pitrou308c2af2010-05-16 14:16:56 +0000609 .. warning::
610
611 SSL version 2 is insecure. Its use is highly discouraged.
612
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200613 .. deprecated:: 2.7.13 OpenSSL has removed support for SSLv2.
614
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000615.. data:: PROTOCOL_SSLv3
616
Antoine Pitrou9e4a9332014-10-21 00:14:39 +0200617 Selects SSL version 3 as the channel encryption protocol.
618
Benjamin Petersonfd0c92f2014-12-06 11:36:32 -0500619 This protocol is not be available if OpenSSL is compiled with the
620 ``OPENSSL_NO_SSLv3`` flag.
621
Antoine Pitrou9e4a9332014-10-21 00:14:39 +0200622 .. warning::
623
624 SSL version 3 is insecure. Its use is highly discouraged.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000625
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200626 .. deprecated:: 2.7.13
627
628 OpenSSL has deprecated all version specific protocols. Use the default
629 protocol with flags like ``OP_NO_SSLv3`` instead.
630
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000631.. data:: PROTOCOL_TLSv1
632
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500633 Selects TLS version 1.0 as the channel encryption protocol.
634
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200635 .. deprecated:: 2.7.13
636
637 OpenSSL has deprecated all version specific protocols. Use the default
638 protocol with flags like ``OP_NO_SSLv3`` instead.
639
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500640.. data:: PROTOCOL_TLSv1_1
641
642 Selects TLS version 1.1 as the channel encryption protocol.
643 Available only with openssl version 1.0.1+.
644
645 .. versionadded:: 2.7.9
646
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200647 .. deprecated:: 2.7.13
648
649 OpenSSL has deprecated all version specific protocols. Use the default
650 protocol with flags like ``OP_NO_SSLv3`` instead.
651
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500652.. data:: PROTOCOL_TLSv1_2
653
Antoine Pitrou9e4a9332014-10-21 00:14:39 +0200654 Selects TLS version 1.2 as the channel encryption protocol. This is the
655 most modern version, and probably the best choice for maximum protection,
656 if both sides can speak it. Available only with openssl version 1.0.1+.
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500657
658 .. versionadded:: 2.7.9
659
Christian Heimesc2fc7c42016-09-05 23:37:13 +0200660 .. deprecated:: 2.7.13
661
662 OpenSSL has deprecated all version specific protocols. Use the default
663 protocol with flags like ``OP_NO_SSLv3`` instead.
664
665
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500666.. data:: OP_ALL
667
668 Enables workarounds for various bugs present in other SSL implementations.
669 This option is set by default. It does not necessarily set the same
670 flags as OpenSSL's ``SSL_OP_ALL`` constant.
671
672 .. versionadded:: 2.7.9
673
674.. data:: OP_NO_SSLv2
675
676 Prevents an SSLv2 connection. This option is only applicable in
677 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
678 choosing SSLv2 as the protocol version.
679
680 .. versionadded:: 2.7.9
681
682.. data:: OP_NO_SSLv3
683
684 Prevents an SSLv3 connection. This option is only applicable in
685 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
686 choosing SSLv3 as the protocol version.
687
688 .. versionadded:: 2.7.9
689
690.. data:: OP_NO_TLSv1
691
692 Prevents a TLSv1 connection. This option is only applicable in
693 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
694 choosing TLSv1 as the protocol version.
695
696 .. versionadded:: 2.7.9
697
698.. data:: OP_NO_TLSv1_1
699
700 Prevents a TLSv1.1 connection. This option is only applicable in conjunction
701 with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.1 as
702 the protocol version. Available only with openssl version 1.0.1+.
703
704 .. versionadded:: 2.7.9
705
706.. data:: OP_NO_TLSv1_2
707
708 Prevents a TLSv1.2 connection. This option is only applicable in conjunction
709 with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.2 as
710 the protocol version. Available only with openssl version 1.0.1+.
711
712 .. versionadded:: 2.7.9
713
Christian Heimesb9a860f2017-09-07 22:31:17 -0700714.. data:: OP_NO_TLSv1_3
715
716 Prevents a TLSv1.3 connection. This option is only applicable in conjunction
717 with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.3 as
718 the protocol version. TLS 1.3 is available with OpenSSL 1.1.1 or later.
719 When Python has been compiled against an older version of OpenSSL, the
720 flag defaults to *0*.
721
722 .. versionadded:: 2.7.15
723
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500724.. data:: OP_CIPHER_SERVER_PREFERENCE
725
726 Use the server's cipher ordering preference, rather than the client's.
727 This option has no effect on client sockets and SSLv2 server sockets.
728
729 .. versionadded:: 2.7.9
730
731.. data:: OP_SINGLE_DH_USE
732
733 Prevents re-use of the same DH key for distinct SSL sessions. This
734 improves forward secrecy but requires more computational resources.
735 This option only applies to server sockets.
736
737 .. versionadded:: 2.7.9
738
739.. data:: OP_SINGLE_ECDH_USE
740
741 Prevents re-use of the same ECDH key for distinct SSL sessions. This
742 improves forward secrecy but requires more computational resources.
743 This option only applies to server sockets.
744
745 .. versionadded:: 2.7.9
746
747.. data:: OP_NO_COMPRESSION
748
749 Disable compression on the SSL channel. This is useful if the application
750 protocol supports its own compression scheme.
751
752 This option is only available with OpenSSL 1.0.0 and later.
753
754 .. versionadded:: 2.7.9
755
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500756.. data:: HAS_ALPN
757
758 Whether the OpenSSL library has built-in support for the *Application-Layer
759 Protocol Negotiation* TLS extension as described in :rfc:`7301`.
760
Benjamin Peterson65aa2612015-01-23 16:47:52 -0500761 .. versionadded:: 2.7.10
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500762
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500763.. data:: HAS_ECDH
764
765 Whether the OpenSSL library has built-in support for Elliptic Curve-based
766 Diffie-Hellman key exchange. This should be true unless the feature was
767 explicitly disabled by the distributor.
768
769 .. versionadded:: 2.7.9
770
771.. data:: HAS_SNI
772
773 Whether the OpenSSL library has built-in support for the *Server Name
Benjamin Peterson31aa69e2014-11-23 20:13:31 -0600774 Indication* extension (as defined in :rfc:`4366`).
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500775
776 .. versionadded:: 2.7.9
777
778.. data:: HAS_NPN
779
780 Whether the OpenSSL library has built-in support for *Next Protocol
781 Negotiation* as described in the `NPN draft specification
Georg Brandl6e0b44e2016-02-26 19:37:12 +0100782 <https://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. When true,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500783 you can use the :meth:`SSLContext.set_npn_protocols` method to advertise
784 which protocols you want to support.
785
786 .. versionadded:: 2.7.9
787
Christian Heimesb9a860f2017-09-07 22:31:17 -0700788.. data:: HAS_TLSv1_3
789
790 Whether the OpenSSL library has built-in support for the TLS 1.3 protocol.
791
792 .. versionadded:: 2.7.15
793
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500794.. data:: CHANNEL_BINDING_TYPES
795
796 List of supported TLS channel binding types. Strings in this list
797 can be used as arguments to :meth:`SSLSocket.get_channel_binding`.
798
799 .. versionadded:: 2.7.9
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000800
Antoine Pitrouf9de5342010-04-05 21:35:07 +0000801.. data:: OPENSSL_VERSION
802
803 The version string of the OpenSSL library loaded by the interpreter::
804
805 >>> ssl.OPENSSL_VERSION
806 'OpenSSL 0.9.8k 25 Mar 2009'
807
808 .. versionadded:: 2.7
809
810.. data:: OPENSSL_VERSION_INFO
811
812 A tuple of five integers representing version information about the
813 OpenSSL library::
814
815 >>> ssl.OPENSSL_VERSION_INFO
816 (0, 9, 8, 11, 15)
817
818 .. versionadded:: 2.7
819
820.. data:: OPENSSL_VERSION_NUMBER
821
822 The raw version number of the OpenSSL library, as a single integer::
823
824 >>> ssl.OPENSSL_VERSION_NUMBER
825 9470143L
826 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
827 '0x9080bfL'
828
829 .. versionadded:: 2.7
830
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500831.. data:: ALERT_DESCRIPTION_HANDSHAKE_FAILURE
832 ALERT_DESCRIPTION_INTERNAL_ERROR
833 ALERT_DESCRIPTION_*
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000834
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500835 Alert Descriptions from :rfc:`5246` and others. The `IANA TLS Alert Registry
Serhiy Storchakab4905ef2016-05-07 10:50:12 +0300836 <https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6>`_
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500837 contains this list and references to the RFCs where their meaning is defined.
838
839 Used as the return value of the callback function in
840 :meth:`SSLContext.set_servername_callback`.
841
842 .. versionadded:: 2.7.9
843
844.. data:: Purpose.SERVER_AUTH
845
846 Option for :func:`create_default_context` and
847 :meth:`SSLContext.load_default_certs`. This value indicates that the
848 context may be used to authenticate Web servers (therefore, it will
849 be used to create client-side sockets).
850
851 .. versionadded:: 2.7.9
852
853.. data:: Purpose.CLIENT_AUTH
854
855 Option for :func:`create_default_context` and
856 :meth:`SSLContext.load_default_certs`. This value indicates that the
857 context may be used to authenticate Web clients (therefore, it will
858 be used to create server-side sockets).
859
860 .. versionadded:: 2.7.9
861
862
863SSL Sockets
864-----------
Bill Janssen98d19da2007-09-10 21:51:02 +0000865
Giampaolo Rodola'76794132013-04-06 03:46:47 +0200866SSL sockets provide the following methods of :ref:`socket-objects`:
Bill Janssen98d19da2007-09-10 21:51:02 +0000867
Giampaolo Rodola'76794132013-04-06 03:46:47 +0200868- :meth:`~socket.socket.accept()`
869- :meth:`~socket.socket.bind()`
870- :meth:`~socket.socket.close()`
871- :meth:`~socket.socket.connect()`
872- :meth:`~socket.socket.fileno()`
873- :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`
874- :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`
875- :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`,
876 :meth:`~socket.socket.setblocking()`
877- :meth:`~socket.socket.listen()`
878- :meth:`~socket.socket.makefile()`
879- :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()`
880 (but passing a non-zero ``flags`` argument is not allowed)
881- :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with
882 the same limitation)
883- :meth:`~socket.socket.shutdown()`
Bill Janssen98d19da2007-09-10 21:51:02 +0000884
Giampaolo Rodola'76794132013-04-06 03:46:47 +0200885However, since the SSL (and TLS) protocol has its own framing atop
886of TCP, the SSL sockets abstraction can, in certain respects, diverge from
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500887the specification of normal, OS-level sockets. See especially the
888:ref:`notes on non-blocking sockets <ssl-nonblocking>`.
Bill Janssen98d19da2007-09-10 21:51:02 +0000889
Giampaolo Rodola'76794132013-04-06 03:46:47 +0200890SSL sockets also have the following additional methods and attributes:
Bill Janssen98d19da2007-09-10 21:51:02 +0000891
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500892.. method:: SSLSocket.do_handshake()
893
894 Perform the SSL setup handshake.
895
896 .. versionchanged:: 2.7.9
897
898 The handshake method also performs :func:`match_hostname` when the
899 :attr:`~SSLContext.check_hostname` attribute of the socket's
900 :attr:`~SSLSocket.context` is true.
901
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000902.. method:: SSLSocket.getpeercert(binary_form=False)
Bill Janssen98d19da2007-09-10 21:51:02 +0000903
Georg Brandla50d20a2009-09-16 15:57:46 +0000904 If there is no certificate for the peer on the other end of the connection,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500905 return ``None``. If the SSL handshake hasn't been done yet, raise
906 :exc:`ValueError`.
Bill Janssen98d19da2007-09-10 21:51:02 +0000907
Antoine Pitrouf12f3912013-04-16 20:27:17 +0200908 If the ``binary_form`` parameter is :const:`False`, and a certificate was
Georg Brandla50d20a2009-09-16 15:57:46 +0000909 received from the peer, this method returns a :class:`dict` instance. If the
910 certificate was not validated, the dict is empty. If the certificate was
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500911 validated, it returns a dict with several keys, amongst them ``subject``
912 (the principal for which the certificate was issued) and ``issuer``
913 (the principal issuing the certificate). If a certificate contains an
914 instance of the *Subject Alternative Name* extension (see :rfc:`3280`),
915 there will also be a ``subjectAltName`` key in the dictionary.
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000916
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500917 The ``subject`` and ``issuer`` fields are tuples containing the sequence
918 of relative distinguished names (RDNs) given in the certificate's data
919 structure for the respective fields, and each RDN is a sequence of
920 name-value pairs. Here is a real-world example::
Bill Janssen98d19da2007-09-10 21:51:02 +0000921
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500922 {'issuer': ((('countryName', 'IL'),),
923 (('organizationName', 'StartCom Ltd.'),),
924 (('organizationalUnitName',
925 'Secure Digital Certificate Signing'),),
926 (('commonName',
927 'StartCom Class 2 Primary Intermediate Server CA'),)),
928 'notAfter': 'Nov 22 08:15:19 2013 GMT',
929 'notBefore': 'Nov 21 03:09:52 2011 GMT',
930 'serialNumber': '95F0',
931 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
932 (('countryName', 'US'),),
933 (('stateOrProvinceName', 'California'),),
934 (('localityName', 'San Francisco'),),
935 (('organizationName', 'Electronic Frontier Foundation, Inc.'),),
936 (('commonName', '*.eff.org'),),
937 (('emailAddress', 'hostmaster@eff.org'),)),
938 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
939 'version': 3}
940
941 .. note::
942
943 To validate a certificate for a particular service, you can use the
944 :func:`match_hostname` function.
Bill Janssen98d19da2007-09-10 21:51:02 +0000945
Georg Brandla50d20a2009-09-16 15:57:46 +0000946 If the ``binary_form`` parameter is :const:`True`, and a certificate was
947 provided, this method returns the DER-encoded form of the entire certificate
948 as a sequence of bytes, or :const:`None` if the peer did not provide a
Antoine Pitrouf12f3912013-04-16 20:27:17 +0200949 certificate. Whether the peer provides a certificate depends on the SSL
950 socket's role:
951
952 * for a client SSL socket, the server will always provide a certificate,
953 regardless of whether validation was required;
954
955 * for a server SSL socket, the client will only provide a certificate
956 when requested by the server; therefore :meth:`getpeercert` will return
957 :const:`None` if you used :const:`CERT_NONE` (rather than
958 :const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`).
Bill Janssen98d19da2007-09-10 21:51:02 +0000959
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500960 .. versionchanged:: 2.7.9
961 The returned dictionary includes additional items such as ``issuer`` and
962 ``notBefore``. Additionall :exc:`ValueError` is raised when the handshake
963 isn't done. The returned dictionary includes additional X509v3 extension
964 items such as ``crlDistributionPoints``, ``caIssuers`` and ``OCSP`` URIs.
965
Bill Janssen98d19da2007-09-10 21:51:02 +0000966.. method:: SSLSocket.cipher()
967
Georg Brandla50d20a2009-09-16 15:57:46 +0000968 Returns a three-value tuple containing the name of the cipher being used, the
969 version of the SSL protocol that defines its use, and the number of secret
970 bits being used. If no connection has been established, returns ``None``.
Bill Janssen98d19da2007-09-10 21:51:02 +0000971
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500972.. method:: SSLSocket.compression()
Bill Janssen934b16d2008-06-28 22:19:33 +0000973
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500974 Return the compression algorithm being used as a string, or ``None``
975 if the connection isn't compressed.
Bill Janssen934b16d2008-06-28 22:19:33 +0000976
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500977 If the higher-level protocol supports its own compression mechanism,
978 you can use :data:`OP_NO_COMPRESSION` to disable SSL-level compression.
979
980 .. versionadded:: 2.7.9
981
982.. method:: SSLSocket.get_channel_binding(cb_type="tls-unique")
983
984 Get channel binding data for current connection, as a bytes object. Returns
985 ``None`` if not connected or the handshake has not been completed.
986
987 The *cb_type* parameter allow selection of the desired channel binding
988 type. Valid channel binding types are listed in the
989 :data:`CHANNEL_BINDING_TYPES` list. Currently only the 'tls-unique' channel
990 binding, defined by :rfc:`5929`, is supported. :exc:`ValueError` will be
991 raised if an unsupported channel binding type is requested.
992
993 .. versionadded:: 2.7.9
994
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -0500995.. method:: SSLSocket.selected_alpn_protocol()
996
997 Return the protocol that was selected during the TLS handshake. If
998 :meth:`SSLContext.set_alpn_protocols` was not called, if the other party does
Benjamin Petersonaa707582015-01-23 17:30:26 -0500999 not support ALPN, if this socket does not support any of the client's
1000 proposed protocols, or if the handshake has not happened yet, ``None`` is
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001001 returned.
1002
Benjamin Peterson65aa2612015-01-23 16:47:52 -05001003 .. versionadded:: 2.7.10
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001004
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001005.. method:: SSLSocket.selected_npn_protocol()
1006
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001007 Return the higher-level protocol that was selected during the TLS/SSL
Alex Gaynore98205d2014-09-04 13:33:22 -07001008 handshake. If :meth:`SSLContext.set_npn_protocols` was not called, or
1009 if the other party does not support NPN, or if the handshake has not yet
1010 happened, this will return ``None``.
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001011
1012 .. versionadded:: 2.7.9
Bill Janssen98d19da2007-09-10 21:51:02 +00001013
Bill Janssen5bfbd762008-08-12 17:09:57 +00001014.. method:: SSLSocket.unwrap()
1015
Georg Brandla50d20a2009-09-16 15:57:46 +00001016 Performs the SSL shutdown handshake, which removes the TLS layer from the
1017 underlying socket, and returns the underlying socket object. This can be
1018 used to go from encrypted operation over a connection to unencrypted. The
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001019 returned socket should always be used for further communication with the
1020 other side of the connection, rather than the original socket.
1021
Alex Gaynore98205d2014-09-04 13:33:22 -07001022.. method:: SSLSocket.version()
1023
1024 Return the actual SSL protocol version negotiated by the connection
1025 as a string, or ``None`` is no secure connection is established.
1026 As of this writing, possible return values include ``"SSLv2"``,
1027 ``"SSLv3"``, ``"TLSv1"``, ``"TLSv1.1"`` and ``"TLSv1.2"``.
1028 Recent OpenSSL versions may define more return values.
1029
Alex Gaynor162126d2014-09-04 13:37:07 -07001030 .. versionadded:: 2.7.9
Alex Gaynore98205d2014-09-04 13:33:22 -07001031
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001032.. attribute:: SSLSocket.context
1033
1034 The :class:`SSLContext` object this SSL socket is tied to. If the SSL
1035 socket was created using the top-level :func:`wrap_socket` function
1036 (rather than :meth:`SSLContext.wrap_socket`), this is a custom context
1037 object created for this SSL socket.
1038
1039 .. versionadded:: 2.7.9
1040
1041
1042SSL Contexts
1043------------
1044
1045.. versionadded:: 2.7.9
1046
1047An SSL context holds various data longer-lived than single SSL connections,
1048such as SSL configuration options, certificate(s) and private key(s).
1049It also manages a cache of SSL sessions for server-side sockets, in order
1050to speed up repeated connections from the same clients.
1051
1052.. class:: SSLContext(protocol)
1053
1054 Create a new SSL context. You must pass *protocol* which must be one
1055 of the ``PROTOCOL_*`` constants defined in this module.
1056 :data:`PROTOCOL_SSLv23` is currently recommended for maximum
1057 interoperability.
1058
1059 .. seealso::
1060 :func:`create_default_context` lets the :mod:`ssl` module choose
1061 security settings for a given purpose.
1062
1063
1064:class:`SSLContext` objects have the following methods and attributes:
1065
1066.. method:: SSLContext.cert_store_stats()
1067
1068 Get statistics about quantities of loaded X.509 certificates, count of
1069 X.509 certificates flagged as CA certificates and certificate revocation
1070 lists as dictionary.
1071
1072 Example for a context with one CA cert and one other cert::
1073
1074 >>> context.cert_store_stats()
1075 {'crl': 0, 'x509_ca': 1, 'x509': 2}
1076
1077
1078.. method:: SSLContext.load_cert_chain(certfile, keyfile=None, password=None)
1079
1080 Load a private key and the corresponding certificate. The *certfile*
1081 string must be the path to a single file in PEM format containing the
1082 certificate as well as any number of CA certificates needed to establish
1083 the certificate's authenticity. The *keyfile* string, if present, must
1084 point to a file containing the private key in. Otherwise the private
1085 key will be taken from *certfile* as well. See the discussion of
1086 :ref:`ssl-certificates` for more information on how the certificate
1087 is stored in the *certfile*.
1088
1089 The *password* argument may be a function to call to get the password for
1090 decrypting the private key. It will only be called if the private key is
1091 encrypted and a password is necessary. It will be called with no arguments,
1092 and it should return a string, bytes, or bytearray. If the return value is
1093 a string it will be encoded as UTF-8 before using it to decrypt the key.
1094 Alternatively a string, bytes, or bytearray value may be supplied directly
1095 as the *password* argument. It will be ignored if the private key is not
1096 encrypted and no password is needed.
1097
1098 If the *password* argument is not specified and a password is required,
1099 OpenSSL's built-in password prompting mechanism will be used to
1100 interactively prompt the user for a password.
1101
1102 An :class:`SSLError` is raised if the private key doesn't
1103 match with the certificate.
1104
1105.. method:: SSLContext.load_default_certs(purpose=Purpose.SERVER_AUTH)
1106
1107 Load a set of default "certification authority" (CA) certificates from
1108 default locations. On Windows it loads CA certs from the ``CA`` and
1109 ``ROOT`` system stores. On other systems it calls
1110 :meth:`SSLContext.set_default_verify_paths`. In the future the method may
1111 load CA certificates from other locations, too.
1112
1113 The *purpose* flag specifies what kind of CA certificates are loaded. The
1114 default settings :data:`Purpose.SERVER_AUTH` loads certificates, that are
1115 flagged and trusted for TLS web server authentication (client side
1116 sockets). :data:`Purpose.CLIENT_AUTH` loads CA certificates for client
1117 certificate verification on the server side.
1118
1119.. method:: SSLContext.load_verify_locations(cafile=None, capath=None, cadata=None)
1120
1121 Load a set of "certification authority" (CA) certificates used to validate
1122 other peers' certificates when :data:`verify_mode` is other than
1123 :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified.
1124
1125 This method can also load certification revocation lists (CRLs) in PEM or
1126 DER format. In order to make use of CRLs, :attr:`SSLContext.verify_flags`
1127 must be configured properly.
1128
1129 The *cafile* string, if present, is the path to a file of concatenated
1130 CA certificates in PEM format. See the discussion of
1131 :ref:`ssl-certificates` for more information about how to arrange the
1132 certificates in this file.
1133
1134 The *capath* string, if present, is
1135 the path to a directory containing several CA certificates in PEM format,
1136 following an `OpenSSL specific layout
Miss Islington (bot)3ff488c2017-12-13 04:45:13 -08001137 <https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_load_verify_locations.html>`_.
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001138
1139 The *cadata* object, if present, is either an ASCII string of one or more
1140 PEM-encoded certificates or a bytes-like object of DER-encoded
1141 certificates. Like with *capath* extra lines around PEM-encoded
1142 certificates are ignored but at least one certificate must be present.
1143
1144.. method:: SSLContext.get_ca_certs(binary_form=False)
1145
1146 Get a list of loaded "certification authority" (CA) certificates. If the
1147 ``binary_form`` parameter is :const:`False` each list
1148 entry is a dict like the output of :meth:`SSLSocket.getpeercert`. Otherwise
1149 the method returns a list of DER-encoded certificates. The returned list
1150 does not contain certificates from *capath* unless a certificate was
1151 requested and loaded by a SSL connection.
1152
Xiang Zhangc4f91ba2016-12-23 11:10:19 +08001153 .. note::
1154 Certificates in a capath directory aren't loaded unless they have
1155 been used at least once.
1156
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001157.. method:: SSLContext.set_default_verify_paths()
1158
1159 Load a set of default "certification authority" (CA) certificates from
1160 a filesystem path defined when building the OpenSSL library. Unfortunately,
1161 there's no easy way to know whether this method succeeds: no error is
1162 returned if no certificates are to be found. When the OpenSSL library is
1163 provided as part of the operating system, though, it is likely to be
1164 configured properly.
1165
1166.. method:: SSLContext.set_ciphers(ciphers)
1167
1168 Set the available ciphers for sockets created with this context.
1169 It should be a string in the `OpenSSL cipher list format
Christian Heimes5b6452d2017-09-20 22:23:09 +02001170 <https://wiki.openssl.org/index.php/Manual:Ciphers(1)#CIPHER_LIST_FORMAT>`_.
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001171 If no cipher can be selected (because compile-time options or other
1172 configuration forbids use of all the specified ciphers), an
1173 :class:`SSLError` will be raised.
1174
1175 .. note::
1176 when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
1177 give the currently selected cipher.
1178
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001179.. method:: SSLContext.set_alpn_protocols(protocols)
1180
1181 Specify which protocols the socket should advertise during the SSL/TLS
1182 handshake. It should be a list of ASCII strings, like ``['http/1.1',
1183 'spdy/2']``, ordered by preference. The selection of a protocol will happen
1184 during the handshake, and will play out according to :rfc:`7301`. After a
1185 successful handshake, the :meth:`SSLSocket.selected_alpn_protocol` method will
1186 return the agreed-upon protocol.
1187
1188 This method will raise :exc:`NotImplementedError` if :data:`HAS_ALPN` is
1189 False.
1190
Christian Heimes05b7d9c2017-08-15 10:55:03 +02001191 OpenSSL 1.1.0 to 1.1.0e will abort the handshake and raise :exc:`SSLError`
1192 when both sides support ALPN but cannot agree on a protocol. 1.1.0f+
1193 behaves like 1.0.2, :meth:`SSLSocket.selected_alpn_protocol` returns None.
Christian Heimesc2fc7c42016-09-05 23:37:13 +02001194
Benjamin Peterson65aa2612015-01-23 16:47:52 -05001195 .. versionadded:: 2.7.10
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001196
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001197.. method:: SSLContext.set_npn_protocols(protocols)
1198
1199 Specify which protocols the socket should advertise during the SSL/TLS
1200 handshake. It should be a list of strings, like ``['http/1.1', 'spdy/2']``,
1201 ordered by preference. The selection of a protocol will happen during the
1202 handshake, and will play out according to the `NPN draft specification
Georg Brandl6e0b44e2016-02-26 19:37:12 +01001203 <https://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. After a
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001204 successful handshake, the :meth:`SSLSocket.selected_npn_protocol` method will
1205 return the agreed-upon protocol.
1206
1207 This method will raise :exc:`NotImplementedError` if :data:`HAS_NPN` is
1208 False.
1209
1210.. method:: SSLContext.set_servername_callback(server_name_callback)
1211
1212 Register a callback function that will be called after the TLS Client Hello
1213 handshake message has been received by the SSL/TLS server when the TLS client
1214 specifies a server name indication. The server name indication mechanism
1215 is specified in :rfc:`6066` section 3 - Server Name Indication.
1216
1217 Only one callback can be set per ``SSLContext``. If *server_name_callback*
1218 is ``None`` then the callback is disabled. Calling this function a
1219 subsequent time will disable the previously registered callback.
1220
1221 The callback function, *server_name_callback*, will be called with three
1222 arguments; the first being the :class:`ssl.SSLSocket`, the second is a string
1223 that represents the server name that the client is intending to communicate
1224 (or :const:`None` if the TLS Client Hello does not contain a server name)
1225 and the third argument is the original :class:`SSLContext`. The server name
1226 argument is the IDNA decoded server name.
1227
1228 A typical use of this callback is to change the :class:`ssl.SSLSocket`'s
1229 :attr:`SSLSocket.context` attribute to a new object of type
1230 :class:`SSLContext` representing a certificate chain that matches the server
1231 name.
1232
1233 Due to the early negotiation phase of the TLS connection, only limited
1234 methods and attributes are usable like
Benjamin Petersonb10bfbe2015-01-23 16:35:37 -05001235 :meth:`SSLSocket.selected_alpn_protocol` and :attr:`SSLSocket.context`.
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001236 :meth:`SSLSocket.getpeercert`, :meth:`SSLSocket.getpeercert`,
1237 :meth:`SSLSocket.cipher` and :meth:`SSLSocket.compress` methods require that
1238 the TLS connection has progressed beyond the TLS Client Hello and therefore
1239 will not contain return meaningful values nor can they be called safely.
1240
1241 The *server_name_callback* function must return ``None`` to allow the
1242 TLS negotiation to continue. If a TLS failure is required, a constant
1243 :const:`ALERT_DESCRIPTION_* <ALERT_DESCRIPTION_INTERNAL_ERROR>` can be
1244 returned. Other return values will result in a TLS fatal error with
1245 :const:`ALERT_DESCRIPTION_INTERNAL_ERROR`.
1246
1247 If there is an IDNA decoding error on the server name, the TLS connection
1248 will terminate with an :const:`ALERT_DESCRIPTION_INTERNAL_ERROR` fatal TLS
1249 alert message to the client.
1250
1251 If an exception is raised from the *server_name_callback* function the TLS
1252 connection will terminate with a fatal TLS alert message
1253 :const:`ALERT_DESCRIPTION_HANDSHAKE_FAILURE`.
1254
1255 This method will raise :exc:`NotImplementedError` if the OpenSSL library
1256 had OPENSSL_NO_TLSEXT defined when it was built.
1257
1258.. method:: SSLContext.load_dh_params(dhfile)
1259
1260 Load the key generation parameters for Diffie-Helman (DH) key exchange.
1261 Using DH key exchange improves forward secrecy at the expense of
1262 computational resources (both on the server and on the client).
1263 The *dhfile* parameter should be the path to a file containing DH
1264 parameters in PEM format.
1265
1266 This setting doesn't apply to client sockets. You can also use the
1267 :data:`OP_SINGLE_DH_USE` option to further improve security.
1268
1269.. method:: SSLContext.set_ecdh_curve(curve_name)
1270
1271 Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key
1272 exchange. ECDH is significantly faster than regular DH while arguably
1273 as secure. The *curve_name* parameter should be a string describing
1274 a well-known elliptic curve, for example ``prime256v1`` for a widely
1275 supported curve.
1276
1277 This setting doesn't apply to client sockets. You can also use the
1278 :data:`OP_SINGLE_ECDH_USE` option to further improve security.
1279
Serhiy Storchakadc0e3a82016-10-19 18:30:16 +03001280 This method is not available if :data:`HAS_ECDH` is ``False``.
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001281
1282 .. seealso::
1283 `SSL/TLS & Perfect Forward Secrecy <http://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy.html>`_
1284 Vincent Bernat.
1285
1286.. method:: SSLContext.wrap_socket(sock, server_side=False, \
1287 do_handshake_on_connect=True, suppress_ragged_eofs=True, \
1288 server_hostname=None)
1289
1290 Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
1291 object. *sock* must be a :data:`~socket.SOCK_STREAM` socket; other socket
1292 types are unsupported.
1293
1294 The returned SSL socket is tied to the context, its settings and
1295 certificates. The parameters *server_side*, *do_handshake_on_connect*
1296 and *suppress_ragged_eofs* have the same meaning as in the top-level
1297 :func:`wrap_socket` function.
1298
1299 On client connections, the optional parameter *server_hostname* specifies
1300 the hostname of the service which we are connecting to. This allows a
1301 single server to host multiple SSL-based services with distinct certificates,
Benjamin Peterson31aa69e2014-11-23 20:13:31 -06001302 quite similarly to HTTP virtual hosts. Specifying *server_hostname* will
1303 raise a :exc:`ValueError` if *server_side* is true.
1304
Benjamin Peterson6fa40c42014-11-23 20:13:55 -06001305 .. versionchanged:: 2.7.9
Benjamin Peterson31aa69e2014-11-23 20:13:31 -06001306 Always allow a server_hostname to be passed, even if OpenSSL does not
1307 have SNI.
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001308
1309.. method:: SSLContext.session_stats()
1310
1311 Get statistics about the SSL sessions created or managed by this context.
1312 A dictionary is returned which maps the names of each `piece of information
Miss Islington (bot)3ff488c2017-12-13 04:45:13 -08001313 <https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_sess_number.html>`_ to their
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001314 numeric values. For example, here is the total number of hits and misses
1315 in the session cache since the context was created::
1316
1317 >>> stats = context.session_stats()
1318 >>> stats['hits'], stats['misses']
1319 (0, 0)
1320
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001321.. attribute:: SSLContext.check_hostname
1322
1323 Wether to match the peer cert's hostname with :func:`match_hostname` in
1324 :meth:`SSLSocket.do_handshake`. The context's
1325 :attr:`~SSLContext.verify_mode` must be set to :data:`CERT_OPTIONAL` or
1326 :data:`CERT_REQUIRED`, and you must pass *server_hostname* to
1327 :meth:`~SSLContext.wrap_socket` in order to match the hostname.
1328
1329 Example::
1330
1331 import socket, ssl
1332
Benjamin Peterson6c7edba2018-02-20 22:17:10 -08001333 context = ssl.SSLContext(ssl.PROTOCOL_TLS)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001334 context.verify_mode = ssl.CERT_REQUIRED
1335 context.check_hostname = True
1336 context.load_default_certs()
1337
1338 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1339 ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com')
1340 ssl_sock.connect(('www.verisign.com', 443))
1341
1342 .. note::
1343
1344 This features requires OpenSSL 0.9.8f or newer.
1345
1346.. attribute:: SSLContext.options
1347
1348 An integer representing the set of SSL options enabled on this context.
1349 The default value is :data:`OP_ALL`, but you can specify other options
1350 such as :data:`OP_NO_SSLv2` by ORing them together.
1351
1352 .. note::
1353 With versions of OpenSSL older than 0.9.8m, it is only possible
1354 to set options, not to clear them. Attempting to clear an option
1355 (by resetting the corresponding bits) will raise a ``ValueError``.
1356
1357.. attribute:: SSLContext.protocol
1358
1359 The protocol version chosen when constructing the context. This attribute
1360 is read-only.
1361
1362.. attribute:: SSLContext.verify_flags
1363
1364 The flags for certificate verification operations. You can set flags like
1365 :data:`VERIFY_CRL_CHECK_LEAF` by ORing them together. By default OpenSSL
1366 does neither require nor verify certificate revocation lists (CRLs).
1367 Available only with openssl version 0.9.8+.
1368
1369.. attribute:: SSLContext.verify_mode
1370
1371 Whether to try to verify other peers' certificates and how to behave
1372 if verification fails. This attribute must be one of
1373 :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.
1374
Bill Janssen5bfbd762008-08-12 17:09:57 +00001375
Bill Janssen98d19da2007-09-10 21:51:02 +00001376.. index:: single: certificates
1377
1378.. index:: single: X509 certificate
1379
Bill Janssen93bf9ce2007-09-11 02:42:07 +00001380.. _ssl-certificates:
1381
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001382Certificates
1383------------
1384
Georg Brandla50d20a2009-09-16 15:57:46 +00001385Certificates in general are part of a public-key / private-key system. In this
1386system, each *principal*, (which may be a machine, or a person, or an
1387organization) is assigned a unique two-part encryption key. One part of the key
1388is public, and is called the *public key*; the other part is kept secret, and is
1389called the *private key*. The two parts are related, in that if you encrypt a
1390message with one of the parts, you can decrypt it with the other part, and
1391**only** with the other part.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001392
Georg Brandla50d20a2009-09-16 15:57:46 +00001393A certificate contains information about two principals. It contains the name
1394of a *subject*, and the subject's public key. It also contains a statement by a
1395second principal, the *issuer*, that the subject is who he claims to be, and
1396that this is indeed the subject's public key. The issuer's statement is signed
1397with the issuer's private key, which only the issuer knows. However, anyone can
1398verify the issuer's statement by finding the issuer's public key, decrypting the
1399statement with it, and comparing it to the other information in the certificate.
1400The certificate also contains information about the time period over which it is
1401valid. This is expressed as two fields, called "notBefore" and "notAfter".
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001402
Georg Brandla50d20a2009-09-16 15:57:46 +00001403In the Python use of certificates, a client or server can use a certificate to
1404prove who they are. The other side of a network connection can also be required
1405to produce a certificate, and that certificate can be validated to the
1406satisfaction of the client or server that requires such validation. The
1407connection attempt can be set to raise an exception if the validation fails.
1408Validation is done automatically, by the underlying OpenSSL framework; the
1409application need not concern itself with its mechanics. But the application
1410does usually need to provide sets of certificates to allow this process to take
1411place.
Bill Janssen426ea0a2007-08-29 22:35:05 +00001412
Georg Brandla50d20a2009-09-16 15:57:46 +00001413Python uses files to contain certificates. They should be formatted as "PEM"
1414(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
1415and a footer line::
Bill Janssen426ea0a2007-08-29 22:35:05 +00001416
1417 -----BEGIN CERTIFICATE-----
1418 ... (certificate in base64 PEM encoding) ...
1419 -----END CERTIFICATE-----
1420
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001421Certificate chains
1422^^^^^^^^^^^^^^^^^^
1423
Georg Brandla50d20a2009-09-16 15:57:46 +00001424The Python files which contain certificates can contain a sequence of
1425certificates, sometimes called a *certificate chain*. This chain should start
1426with the specific certificate for the principal who "is" the client or server,
1427and then the certificate for the issuer of that certificate, and then the
1428certificate for the issuer of *that* certificate, and so on up the chain till
1429you get to a certificate which is *self-signed*, that is, a certificate which
1430has the same subject and issuer, sometimes called a *root certificate*. The
1431certificates should just be concatenated together in the certificate file. For
1432example, suppose we had a three certificate chain, from our server certificate
1433to the certificate of the certification authority that signed our server
1434certificate, to the root certificate of the agency which issued the
1435certification authority's certificate::
Bill Janssen426ea0a2007-08-29 22:35:05 +00001436
1437 -----BEGIN CERTIFICATE-----
1438 ... (certificate for your server)...
1439 -----END CERTIFICATE-----
1440 -----BEGIN CERTIFICATE-----
1441 ... (the certificate for the CA)...
1442 -----END CERTIFICATE-----
1443 -----BEGIN CERTIFICATE-----
1444 ... (the root certificate for the CA's issuer)...
1445 -----END CERTIFICATE-----
1446
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001447CA certificates
1448^^^^^^^^^^^^^^^
1449
Bill Janssen426ea0a2007-08-29 22:35:05 +00001450If you are going to require validation of the other side of the connection's
1451certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandla50d20a2009-09-16 15:57:46 +00001452chains for each issuer you are willing to trust. Again, this file just contains
1453these chains concatenated together. For validation, Python will use the first
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001454chain it finds in the file which matches. The platform's certificates file can
1455be used by calling :meth:`SSLContext.load_default_certs`, this is done
1456automatically with :func:`.create_default_context`.
Bill Janssen934b16d2008-06-28 22:19:33 +00001457
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001458Combined key and certificate
1459^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Bill Janssen98d19da2007-09-10 21:51:02 +00001460
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001461Often the private key is stored in the same file as the certificate; in this
1462case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain`
1463and :func:`wrap_socket` needs to be passed. If the private key is stored
1464with the certificate, it should come before the first certificate in
1465the certificate chain::
1466
1467 -----BEGIN RSA PRIVATE KEY-----
1468 ... (private key in base64 encoding) ...
1469 -----END RSA PRIVATE KEY-----
1470 -----BEGIN CERTIFICATE-----
1471 ... (certificate in base64 PEM encoding) ...
1472 -----END CERTIFICATE-----
1473
1474Self-signed certificates
1475^^^^^^^^^^^^^^^^^^^^^^^^
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001476
Georg Brandla50d20a2009-09-16 15:57:46 +00001477If you are going to create a server that provides SSL-encrypted connection
1478services, you will need to acquire a certificate for that service. There are
1479many ways of acquiring appropriate certificates, such as buying one from a
1480certification authority. Another common practice is to generate a self-signed
1481certificate. The simplest way to do this is with the OpenSSL package, using
1482something like the following::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001483
Bill Janssen98d19da2007-09-10 21:51:02 +00001484 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
1485 Generating a 1024 bit RSA private key
1486 .......++++++
1487 .............................++++++
1488 writing new private key to 'cert.pem'
1489 -----
1490 You are about to be asked to enter information that will be incorporated
1491 into your certificate request.
1492 What you are about to enter is what is called a Distinguished Name or a DN.
1493 There are quite a few fields but you can leave some blank
1494 For some fields there will be a default value,
1495 If you enter '.', the field will be left blank.
1496 -----
1497 Country Name (2 letter code) [AU]:US
1498 State or Province Name (full name) [Some-State]:MyState
1499 Locality Name (eg, city) []:Some City
1500 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
1501 Organizational Unit Name (eg, section) []:My Group
1502 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
1503 Email Address []:ops@myserver.mygroup.myorganization.com
1504 %
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001505
Georg Brandla50d20a2009-09-16 15:57:46 +00001506The disadvantage of a self-signed certificate is that it is its own root
1507certificate, and no one else will have it in their cache of known (and trusted)
1508root certificates.
Bill Janssen426ea0a2007-08-29 22:35:05 +00001509
1510
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001511Examples
1512--------
1513
Bill Janssen426ea0a2007-08-29 22:35:05 +00001514Testing for SSL support
1515^^^^^^^^^^^^^^^^^^^^^^^
1516
Georg Brandla50d20a2009-09-16 15:57:46 +00001517To test for the presence of SSL support in a Python installation, user code
1518should use the following idiom::
Bill Janssen426ea0a2007-08-29 22:35:05 +00001519
1520 try:
Georg Brandl28046022011-02-25 11:01:04 +00001521 import ssl
Bill Janssen426ea0a2007-08-29 22:35:05 +00001522 except ImportError:
Georg Brandl28046022011-02-25 11:01:04 +00001523 pass
Bill Janssen426ea0a2007-08-29 22:35:05 +00001524 else:
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001525 ... # do something that requires SSL support
Bill Janssen426ea0a2007-08-29 22:35:05 +00001526
1527Client-side operation
1528^^^^^^^^^^^^^^^^^^^^^
1529
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001530This example creates a SSL context with the recommended security settings
1531for client sockets, including automatic certificate verification::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001532
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001533 >>> context = ssl.create_default_context()
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001534
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001535If you prefer to tune security settings yourself, you might create
1536a context from scratch (but beware that you might not get the settings
1537right)::
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001538
Benjamin Peterson6c7edba2018-02-20 22:17:10 -08001539 >>> context = ssl.SSLContext(ssl.PROTOCOL_TLS)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001540 >>> context.verify_mode = ssl.CERT_REQUIRED
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001541 >>> context.check_hostname = True
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001542 >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
1543
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001544(this snippet assumes your operating system places a bundle of all CA
1545certificates in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an
1546error and have to adjust the location)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001547
1548When you use the context to connect to a server, :const:`CERT_REQUIRED`
1549validates the server certificate: it ensures that the server certificate
1550was signed with one of the CA certificates, and checks the signature for
1551correctness::
1552
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001553 >>> conn = context.wrap_socket(socket.socket(socket.AF_INET),
1554 ... server_hostname="www.python.org")
1555 >>> conn.connect(("www.python.org", 443))
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001556
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001557You may then fetch the certificate::
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001558
1559 >>> cert = conn.getpeercert()
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001560
1561Visual inspection shows that the certificate does identify the desired service
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001562(that is, the HTTPS host ``www.python.org``)::
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001563
1564 >>> pprint.pprint(cert)
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001565 {'OCSP': ('http://ocsp.digicert.com',),
1566 'caIssuers': ('http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt',),
1567 'crlDistributionPoints': ('http://crl3.digicert.com/sha2-ev-server-g1.crl',
1568 'http://crl4.digicert.com/sha2-ev-server-g1.crl'),
1569 'issuer': ((('countryName', 'US'),),
1570 (('organizationName', 'DigiCert Inc'),),
1571 (('organizationalUnitName', 'www.digicert.com'),),
1572 (('commonName', 'DigiCert SHA2 Extended Validation Server CA'),)),
1573 'notAfter': 'Sep 9 12:00:00 2016 GMT',
1574 'notBefore': 'Sep 5 00:00:00 2014 GMT',
1575 'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26',
1576 'subject': ((('businessCategory', 'Private Organization'),),
1577 (('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
1578 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
1579 (('serialNumber', '3359300'),),
1580 (('streetAddress', '16 Allen Rd'),),
1581 (('postalCode', '03894-4801'),),
1582 (('countryName', 'US'),),
1583 (('stateOrProvinceName', 'NH'),),
1584 (('localityName', 'Wolfeboro,'),),
1585 (('organizationName', 'Python Software Foundation'),),
1586 (('commonName', 'www.python.org'),)),
1587 'subjectAltName': (('DNS', 'www.python.org'),
1588 ('DNS', 'python.org'),
1589 ('DNS', 'pypi.python.org'),
1590 ('DNS', 'docs.python.org'),
1591 ('DNS', 'testpypi.python.org'),
1592 ('DNS', 'bugs.python.org'),
1593 ('DNS', 'wiki.python.org'),
1594 ('DNS', 'hg.python.org'),
1595 ('DNS', 'mail.python.org'),
1596 ('DNS', 'packaging.python.org'),
1597 ('DNS', 'pythonhosted.org'),
1598 ('DNS', 'www.pythonhosted.org'),
1599 ('DNS', 'test.pythonhosted.org'),
1600 ('DNS', 'us.pycon.org'),
1601 ('DNS', 'id.python.org')),
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001602 'version': 3}
1603
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001604Now the SSL channel is established and the certificate verified, you can
1605proceed to talk with the server::
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001606
1607 >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
1608 >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001609 [b'HTTP/1.1 200 OK',
1610 b'Date: Sat, 18 Oct 2014 18:27:20 GMT',
1611 b'Server: nginx',
1612 b'Content-Type: text/html; charset=utf-8',
1613 b'X-Frame-Options: SAMEORIGIN',
1614 b'Content-Length: 45679',
1615 b'Accept-Ranges: bytes',
1616 b'Via: 1.1 varnish',
1617 b'Age: 2188',
1618 b'X-Served-By: cache-lcy1134-LCY',
1619 b'X-Cache: HIT',
1620 b'X-Cache-Hits: 11',
1621 b'Vary: Cookie',
1622 b'Strict-Transport-Security: max-age=63072000; includeSubDomains',
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001623 b'Connection: close',
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001624 b'',
1625 b'']
1626
1627See the discussion of :ref:`ssl-security` below.
1628
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001629
Bill Janssen426ea0a2007-08-29 22:35:05 +00001630Server-side operation
1631^^^^^^^^^^^^^^^^^^^^^
1632
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001633For server operation, typically you'll need to have a server certificate, and
1634private key, each in a file. You'll first create a context holding the key
1635and the certificate, so that clients can check your authenticity. Then
1636you'll open a socket, bind it to a port, call :meth:`listen` on it, and start
1637waiting for clients to connect::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001638
Benjamin Petersona7b55a32009-02-20 03:31:23 +00001639 import socket, ssl
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001640
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001641 context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001642 context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")
1643
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001644 bindsocket = socket.socket()
1645 bindsocket.bind(('myaddr.mydomain.com', 10023))
1646 bindsocket.listen(5)
1647
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001648When a client connects, you'll call :meth:`accept` on the socket to get the
1649new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket`
1650method to create a server-side SSL socket for the connection::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001651
1652 while True:
Antoine Pitrou9e7d6e52011-01-02 22:39:10 +00001653 newsocket, fromaddr = bindsocket.accept()
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001654 connstream = context.wrap_socket(newsocket, server_side=True)
Antoine Pitrou9e7d6e52011-01-02 22:39:10 +00001655 try:
1656 deal_with_client(connstream)
1657 finally:
1658 connstream.shutdown(socket.SHUT_RDWR)
1659 connstream.close()
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001660
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001661Then you'll read data from the ``connstream`` and do something with it till you
Georg Brandla50d20a2009-09-16 15:57:46 +00001662are finished with the client (or the client is finished with you)::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001663
1664 def deal_with_client(connstream):
Georg Brandl28046022011-02-25 11:01:04 +00001665 data = connstream.read()
1666 # null data means the client is finished with us
1667 while data:
1668 if not do_something(connstream, data):
1669 # we'll assume do_something returns False
1670 # when we're finished with client
1671 break
1672 data = connstream.read()
1673 # finished with client
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001674
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001675And go back to listening for new client connections (of course, a real server
1676would probably handle each client connection in a separate thread, or put
1677the sockets in non-blocking mode and use an event loop).
1678
1679
1680.. _ssl-nonblocking:
1681
1682Notes on non-blocking sockets
1683-----------------------------
1684
1685When working with non-blocking sockets, there are several things you need
1686to be aware of:
1687
1688- Calling :func:`~select.select` tells you that the OS-level socket can be
1689 read from (or written to), but it does not imply that there is sufficient
1690 data at the upper SSL layer. For example, only part of an SSL frame might
1691 have arrived. Therefore, you must be ready to handle :meth:`SSLSocket.recv`
1692 and :meth:`SSLSocket.send` failures, and retry after another call to
1693 :func:`~select.select`.
1694
1695- Conversely, since the SSL layer has its own framing, a SSL socket may
1696 still have data available for reading without :func:`~select.select`
1697 being aware of it. Therefore, you should first call
1698 :meth:`SSLSocket.recv` to drain any potentially available data, and then
1699 only block on a :func:`~select.select` call if still necessary.
1700
1701 (of course, similar provisions apply when using other primitives such as
1702 :func:`~select.poll`, or those in the :mod:`selectors` module)
1703
1704- The SSL handshake itself will be non-blocking: the
1705 :meth:`SSLSocket.do_handshake` method has to be retried until it returns
1706 successfully. Here is a synopsis using :func:`~select.select` to wait for
1707 the socket's readiness::
1708
1709 while True:
1710 try:
1711 sock.do_handshake()
1712 break
1713 except ssl.SSLWantReadError:
1714 select.select([sock], [], [])
1715 except ssl.SSLWantWriteError:
1716 select.select([], [sock], [])
1717
1718
1719.. _ssl-security:
1720
1721Security considerations
1722-----------------------
1723
1724Best defaults
1725^^^^^^^^^^^^^
1726
1727For **client use**, if you don't have any special requirements for your
1728security policy, it is highly recommended that you use the
1729:func:`create_default_context` function to create your SSL context.
1730It will load the system's trusted CA certificates, enable certificate
1731validation and hostname checking, and try to choose reasonably secure
1732protocol and cipher settings.
1733
1734If a client certificate is needed for the connection, it can be added with
1735:meth:`SSLContext.load_cert_chain`.
1736
1737By contrast, if you create the SSL context by calling the :class:`SSLContext`
1738constructor yourself, it will not have certificate validation nor hostname
1739checking enabled by default. If you do so, please read the paragraphs below
1740to achieve a good security level.
1741
1742Manual settings
1743^^^^^^^^^^^^^^^
1744
1745Verifying certificates
1746''''''''''''''''''''''
1747
1748When calling the :class:`SSLContext` constructor directly,
1749:const:`CERT_NONE` is the default. Since it does not authenticate the other
1750peer, it can be insecure, especially in client mode where most of time you
1751would like to ensure the authenticity of the server you're talking to.
1752Therefore, when in client mode, it is highly recommended to use
1753:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also
1754have to check that the server certificate, which can be obtained by calling
1755:meth:`SSLSocket.getpeercert`, matches the desired service. For many
1756protocols and applications, the service can be identified by the hostname;
1757in this case, the :func:`match_hostname` function can be used. This common
1758check is automatically performed when :attr:`SSLContext.check_hostname` is
1759enabled.
1760
1761In server mode, if you want to authenticate your clients using the SSL layer
1762(rather than using a higher-level authentication mechanism), you'll also have
1763to specify :const:`CERT_REQUIRED` and similarly check the client certificate.
1764
1765 .. note::
1766
1767 In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are
1768 equivalent unless anonymous ciphers are enabled (they are disabled
1769 by default).
1770
1771Protocol versions
1772'''''''''''''''''
1773
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001774SSL versions 2 and 3 are considered insecure and are therefore dangerous to
1775use. If you want maximum compatibility between clients and servers, it is
1776recommended to use :const:`PROTOCOL_SSLv23` as the protocol version and then
1777disable SSLv2 and SSLv3 explicitly using the :data:`SSLContext.options`
1778attribute::
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001779
1780 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1781 context.options |= ssl.OP_NO_SSLv2
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001782 context.options |= ssl.OP_NO_SSLv3
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001783
Antoine Pitrou9e4a9332014-10-21 00:14:39 +02001784The SSL context created above will only allow TLSv1 and later (if
1785supported by your system) connections.
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001786
1787Cipher selection
1788''''''''''''''''
1789
1790If you have advanced security requirements, fine-tuning of the ciphers
1791enabled when negotiating a SSL session is possible through the
1792:meth:`SSLContext.set_ciphers` method. Starting from Python 2.7.9, the
1793ssl module disables certain weak ciphers by default, but you may want
1794to further restrict the cipher choice. Be sure to read OpenSSL's documentation
Serhiy Storchakab4905ef2016-05-07 10:50:12 +03001795about the `cipher list format <https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT>`_.
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001796If you want to check which ciphers are enabled by a given cipher list, use the
1797``openssl ciphers`` command on your system.
1798
1799Multi-processing
1800^^^^^^^^^^^^^^^^
1801
1802If using this module as part of a multi-processed application (using,
1803for example the :mod:`multiprocessing` or :mod:`concurrent.futures` modules),
1804be aware that OpenSSL's internal random number generator does not properly
1805handle forked processes. Applications must change the PRNG state of the
1806parent process if they use any SSL feature with :func:`os.fork`. Any
1807successful call of :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or
1808:func:`~ssl.RAND_pseudo_bytes` is sufficient.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00001809
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001810
Christian Heimes3d87f4c2018-02-25 10:21:03 +01001811.. ssl-libressl:
1812
1813LibreSSL support
1814----------------
1815
1816LibreSSL is a fork of OpenSSL 1.0.1. The ssl module has limited support for
1817LibreSSL. Some features are not available when the ssl module is compiled
1818with LibreSSL.
1819
1820* LibreSSL >= 2.6.1 no longer supports NPN. The methods
1821 :meth:`SSLContext.set_npn_protocols` and
1822 :meth:`SSLSocket.selected_npn_protocol` are not available.
1823* :meth:`SSLContext.set_default_verify_paths` ignores the env vars
1824 :envvar:`SSL_CERT_FILE` and :envvar:`SSL_CERT_PATH` although
1825 :func:`get_default_verify_paths` still reports them.
1826
1827
Bill Janssen98d19da2007-09-10 21:51:02 +00001828.. seealso::
Bill Janssen426ea0a2007-08-29 22:35:05 +00001829
Bill Janssen98d19da2007-09-10 21:51:02 +00001830 Class :class:`socket.socket`
Georg Brandl4e8534e2013-10-06 18:20:31 +02001831 Documentation of underlying :mod:`socket` class
Bill Janssen426ea0a2007-08-29 22:35:05 +00001832
Georg Brandl6e0b44e2016-02-26 19:37:12 +01001833 `SSL/TLS Strong Encryption: An Introduction <https://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html>`_
Georg Brandl4e8534e2013-10-06 18:20:31 +02001834 Intro from the Apache webserver documentation
Bill Janssen426ea0a2007-08-29 22:35:05 +00001835
Georg Brandl6e0b44e2016-02-26 19:37:12 +01001836 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <https://www.ietf.org/rfc/rfc1422>`_
Bill Janssen98d19da2007-09-10 21:51:02 +00001837 Steve Kent
Bill Janssen426ea0a2007-08-29 22:35:05 +00001838
Georg Brandl6e0b44e2016-02-26 19:37:12 +01001839 `RFC 1750: Randomness Recommendations for Security <https://www.ietf.org/rfc/rfc1750>`_
Bill Janssen98d19da2007-09-10 21:51:02 +00001840 D. Eastlake et. al.
Bill Janssenffe576d2007-09-05 00:46:27 +00001841
Georg Brandl6e0b44e2016-02-26 19:37:12 +01001842 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <https://www.ietf.org/rfc/rfc3280>`_
Bill Janssen98d19da2007-09-10 21:51:02 +00001843 Housley et. al.
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001844
Georg Brandl6e0b44e2016-02-26 19:37:12 +01001845 `RFC 4366: Transport Layer Security (TLS) Extensions <https://www.ietf.org/rfc/rfc4366>`_
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001846 Blake-Wilson et. al.
1847
Georg Brandl6e0b44e2016-02-26 19:37:12 +01001848 `RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2 <https://tools.ietf.org/html/rfc5246>`_
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001849 T. Dierks et. al.
1850
Georg Brandl6e0b44e2016-02-26 19:37:12 +01001851 `RFC 6066: Transport Layer Security (TLS) Extensions <https://tools.ietf.org/html/rfc6066>`_
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001852 D. Eastlake
1853
Serhiy Storchakab4905ef2016-05-07 10:50:12 +03001854 `IANA TLS: Transport Layer Security (TLS) Parameters <https://www.iana.org/assignments/tls-parameters/tls-parameters.xml>`_
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001855 IANA
Miss Islington (bot)ab4894b2017-09-06 17:31:48 -07001856
1857 `RFC 7525: Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS) <https://tools.ietf.org/html/rfc7525>`_
1858 IETF
1859
1860 `Mozilla's Server Side TLS recommendations <https://wiki.mozilla.org/Security/Server_Side_TLS>`_
1861 Mozilla