blob: aa5a52f62fdf74535c892af2d59f6b8b400d2d10 [file] [log] [blame]
Antoine Pitroue1bc8982011-01-02 22:12:22 +00001:mod:`ssl` --- TLS/SSL wrapper for socket objects
2=================================================
Thomas Woutersed03b412007-08-28 21:37:11 +00003
4.. module:: ssl
Antoine Pitroue1bc8982011-01-02 22:12:22 +00005 :synopsis: TLS/SSL wrapper for socket objects
Thomas Wouters47b49bf2007-08-30 22:15:33 +00006
7.. moduleauthor:: Bill Janssen <bill.janssen@gmail.com>
Thomas Wouters47b49bf2007-08-30 22:15:33 +00008.. sectionauthor:: Bill Janssen <bill.janssen@gmail.com>
9
Thomas Woutersed03b412007-08-28 21:37:11 +000010
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011.. index:: single: OpenSSL; (use in module ssl)
12
13.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
14
Raymond Hettinger469271d2011-01-27 20:38:46 +000015**Source code:** :source:`Lib/ssl.py`
16
17--------------
18
Georg Brandl7f01a132009-09-16 15:58:14 +000019This module provides access to Transport Layer Security (often known as "Secure
20Sockets Layer") encryption and peer authentication facilities for network
21sockets, both client-side and server-side. This module uses the OpenSSL
22library. It is available on all modern Unix systems, Windows, Mac OS X, and
23probably additional platforms, as long as OpenSSL is installed on that platform.
Thomas Woutersed03b412007-08-28 21:37:11 +000024
25.. note::
26
Georg Brandl7f01a132009-09-16 15:58:14 +000027 Some behavior may be platform dependent, since calls are made to the
28 operating system socket APIs. The installed version of OpenSSL may also
29 cause variations in behavior.
Thomas Woutersed03b412007-08-28 21:37:11 +000030
Christian Heimes3046fe42013-10-29 21:08:56 +010031.. warning::
Antoine Pitrou9eefe912013-11-17 15:35:33 +010032 Don't use this module without reading the :ref:`ssl-security`. Doing so
33 may lead to a false sense of security, as the default settings of the
34 ssl module are not necessarily appropriate for your application.
Christian Heimes3046fe42013-10-29 21:08:56 +010035
Christian Heimes3046fe42013-10-29 21:08:56 +010036
Georg Brandl7f01a132009-09-16 15:58:14 +000037This section documents the objects and functions in the ``ssl`` module; for more
38general information about TLS, SSL, and certificates, the reader is referred to
39the documents in the "See Also" section at the bottom.
Thomas Woutersed03b412007-08-28 21:37:11 +000040
Georg Brandl7f01a132009-09-16 15:58:14 +000041This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
42:class:`socket.socket` type, and provides a socket-like wrapper that also
43encrypts and decrypts the data going over the socket with SSL. It supports
Antoine Pitroudab64262010-09-19 13:31:06 +000044additional methods such as :meth:`getpeercert`, which retrieves the
45certificate of the other side of the connection, and :meth:`cipher`,which
46retrieves the cipher being used for the secure connection.
Thomas Woutersed03b412007-08-28 21:37:11 +000047
Antoine Pitrou152efa22010-05-16 18:19:27 +000048For more sophisticated applications, the :class:`ssl.SSLContext` class
49helps manage settings and certificates, which can then be inherited
50by SSL sockets created through the :meth:`SSLContext.wrap_socket` method.
51
52
Thomas Wouters1b7f8912007-09-19 03:06:30 +000053Functions, Constants, and Exceptions
54------------------------------------
55
56.. exception:: SSLError
57
Antoine Pitrou59fdd672010-10-08 10:37:08 +000058 Raised to signal an error from the underlying SSL implementation
59 (currently provided by the OpenSSL library). This signifies some
60 problem in the higher-level encryption and authentication layer that's
61 superimposed on the underlying network connection. This error
Antoine Pitrou5574c302011-10-12 17:53:43 +020062 is a subtype of :exc:`OSError`. The error code and message of
63 :exc:`SSLError` instances are provided by the OpenSSL library.
64
65 .. versionchanged:: 3.3
66 :exc:`SSLError` used to be a subtype of :exc:`socket.error`.
Antoine Pitrou59fdd672010-10-08 10:37:08 +000067
Antoine Pitrou3b36fb12012-06-22 21:11:52 +020068 .. attribute:: library
69
70 A string mnemonic designating the OpenSSL submodule in which the error
71 occurred, such as ``SSL``, ``PEM`` or ``X509``. The range of possible
72 values depends on the OpenSSL version.
73
74 .. versionadded:: 3.3
75
76 .. attribute:: reason
77
78 A string mnemonic designating the reason this error occurred, for
79 example ``CERTIFICATE_VERIFY_FAILED``. The range of possible
80 values depends on the OpenSSL version.
81
82 .. versionadded:: 3.3
83
Antoine Pitrou41032a62011-10-27 23:56:55 +020084.. exception:: SSLZeroReturnError
85
86 A subclass of :exc:`SSLError` raised when trying to read or write and
87 the SSL connection has been closed cleanly. Note that this doesn't
88 mean that the underlying transport (read TCP) has been closed.
89
90 .. versionadded:: 3.3
91
92.. exception:: SSLWantReadError
93
94 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
95 <ssl-nonblocking>` when trying to read or write data, but more data needs
96 to be received on the underlying TCP transport before the request can be
97 fulfilled.
98
99 .. versionadded:: 3.3
100
101.. exception:: SSLWantWriteError
102
103 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
104 <ssl-nonblocking>` when trying to read or write data, but more data needs
105 to be sent on the underlying TCP transport before the request can be
106 fulfilled.
107
108 .. versionadded:: 3.3
109
110.. exception:: SSLSyscallError
111
112 A subclass of :exc:`SSLError` raised when a system error was encountered
113 while trying to fulfill an operation on a SSL socket. Unfortunately,
114 there is no easy way to inspect the original errno number.
115
116 .. versionadded:: 3.3
117
118.. exception:: SSLEOFError
119
120 A subclass of :exc:`SSLError` raised when the SSL connection has been
Antoine Pitrouf3dc2d72011-10-28 00:01:03 +0200121 terminated abruptly. Generally, you shouldn't try to reuse the underlying
Antoine Pitrou41032a62011-10-27 23:56:55 +0200122 transport when this error is encountered.
123
124 .. versionadded:: 3.3
125
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000126.. exception:: CertificateError
127
128 Raised to signal an error with a certificate (such as mismatching
129 hostname). Certificate errors detected by OpenSSL, though, raise
130 an :exc:`SSLError`.
131
132
133Socket creation
134^^^^^^^^^^^^^^^
135
136The following function allows for standalone socket creation. Starting from
137Python 3.2, it can be more flexible to use :meth:`SSLContext.wrap_socket`
138instead.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000139
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000140.. 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)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000141
Georg Brandl7f01a132009-09-16 15:58:14 +0000142 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
143 of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100144 the underlying socket in an SSL context. ``sock`` must be a
145 :data:`~socket.SOCK_STREAM` socket; other socket types are unsupported.
146
147 For client-side sockets, the context construction is lazy; if the
148 underlying socket isn't connected yet, the context construction will be
149 performed after :meth:`connect` is called on the socket. For
150 server-side sockets, if the socket has no remote peer, it is assumed
151 to be a listening socket, and the server-side SSL wrapping is
152 automatically performed on client connections accepted via the
153 :meth:`accept` method. :func:`wrap_socket` may raise :exc:`SSLError`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000154
Georg Brandl7f01a132009-09-16 15:58:14 +0000155 The ``keyfile`` and ``certfile`` parameters specify optional files which
156 contain a certificate to be used to identify the local side of the
157 connection. See the discussion of :ref:`ssl-certificates` for more
158 information on how the certificate is stored in the ``certfile``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000159
Georg Brandl7f01a132009-09-16 15:58:14 +0000160 The parameter ``server_side`` is a boolean which identifies whether
161 server-side or client-side behavior is desired from this socket.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000162
Georg Brandl7f01a132009-09-16 15:58:14 +0000163 The parameter ``cert_reqs`` specifies whether a certificate is required from
164 the other side of the connection, and whether it will be validated if
165 provided. It must be one of the three values :const:`CERT_NONE`
166 (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
167 if provided), or :const:`CERT_REQUIRED` (required and validated). If the
168 value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
169 parameter must point to a file of CA certificates.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000170
Georg Brandl7f01a132009-09-16 15:58:14 +0000171 The ``ca_certs`` file contains a set of concatenated "certification
172 authority" certificates, which are used to validate certificates passed from
173 the other end of the connection. See the discussion of
174 :ref:`ssl-certificates` for more information about how to arrange the
175 certificates in this file.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000176
Georg Brandl7f01a132009-09-16 15:58:14 +0000177 The parameter ``ssl_version`` specifies which version of the SSL protocol to
178 use. Typically, the server chooses a particular protocol version, and the
179 client must adapt to the server's choice. Most of the versions are not
Antoine Pitrou84a2edc2012-01-09 21:35:11 +0100180 interoperable with the other versions. If not specified, the default is
181 :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other
Georg Brandl7f01a132009-09-16 15:58:14 +0000182 versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000183
Georg Brandl7f01a132009-09-16 15:58:14 +0000184 Here's a table showing which versions in a client (down the side) can connect
185 to which versions in a server (along the top):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000186
187 .. table::
188
189 ======================== ========= ========= ========== =========
190 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1**
Christian Heimes255f53b2007-12-08 15:33:56 +0000191 ------------------------ --------- --------- ---------- ---------
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000192 *SSLv2* yes no yes no
Antoine Pitrouac8bfca2012-01-09 21:43:18 +0100193 *SSLv3* no yes yes no
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000194 *SSLv23* yes no yes no
195 *TLSv1* no no yes yes
196 ======================== ========= ========= ========== =========
197
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000198 .. note::
199
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000200 Which connections succeed will vary depending on the version of
201 OpenSSL. For instance, in some older versions of OpenSSL (such
202 as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an
203 SSLv23 server. Another example: beginning with OpenSSL 1.0.0,
204 an SSLv23 client will not actually attempt SSLv2 connections
205 unless you explicitly enable SSLv2 ciphers; for example, you
206 might specify ``"ALL"`` or ``"SSLv2"`` as the *ciphers* parameter
207 to enable them.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000208
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000209 The *ciphers* parameter sets the available ciphers for this SSL object.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000210 It should be a string in the `OpenSSL cipher list format
211 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000212
Bill Janssen48dc27c2007-12-05 03:38:10 +0000213 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
214 handshake automatically after doing a :meth:`socket.connect`, or whether the
Georg Brandl7f01a132009-09-16 15:58:14 +0000215 application program will call it explicitly, by invoking the
216 :meth:`SSLSocket.do_handshake` method. Calling
217 :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
218 blocking behavior of the socket I/O involved in the handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000219
Georg Brandl7f01a132009-09-16 15:58:14 +0000220 The parameter ``suppress_ragged_eofs`` specifies how the
Antoine Pitroudab64262010-09-19 13:31:06 +0000221 :meth:`SSLSocket.recv` method should signal unexpected EOF from the other end
Georg Brandl7f01a132009-09-16 15:58:14 +0000222 of the connection. If specified as :const:`True` (the default), it returns a
Antoine Pitroudab64262010-09-19 13:31:06 +0000223 normal EOF (an empty bytes object) in response to unexpected EOF errors
224 raised from the underlying socket; if :const:`False`, it will raise the
225 exceptions back to the caller.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000226
Ezio Melotti4d5195b2010-04-20 10:57:44 +0000227 .. versionchanged:: 3.2
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000228 New optional argument *ciphers*.
229
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000230Random generation
231^^^^^^^^^^^^^^^^^
232
Victor Stinner99c8b162011-05-24 12:05:19 +0200233.. function:: RAND_bytes(num)
234
Victor Stinnera6752062011-05-25 11:27:40 +0200235 Returns *num* cryptographically strong pseudo-random bytes. Raises an
236 :class:`SSLError` if the PRNG has not been seeded with enough data or if the
237 operation is not supported by the current RAND method. :func:`RAND_status`
238 can be used to check the status of the PRNG and :func:`RAND_add` can be used
239 to seed the PRNG.
Victor Stinner99c8b162011-05-24 12:05:19 +0200240
Victor Stinner19fb53c2011-05-24 21:32:40 +0200241 Read the Wikipedia article, `Cryptographically secure pseudorandom number
Victor Stinnera6752062011-05-25 11:27:40 +0200242 generator (CSPRNG)
Victor Stinner19fb53c2011-05-24 21:32:40 +0200243 <http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator>`_,
244 to get the requirements of a cryptographically generator.
245
Victor Stinner99c8b162011-05-24 12:05:19 +0200246 .. versionadded:: 3.3
247
248.. function:: RAND_pseudo_bytes(num)
249
250 Returns (bytes, is_cryptographic): bytes are *num* pseudo-random bytes,
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200251 is_cryptographic is ``True`` if the bytes generated are cryptographically
Victor Stinnera6752062011-05-25 11:27:40 +0200252 strong. Raises an :class:`SSLError` if the operation is not supported by the
253 current RAND method.
Victor Stinner99c8b162011-05-24 12:05:19 +0200254
Victor Stinner19fb53c2011-05-24 21:32:40 +0200255 Generated pseudo-random byte sequences will be unique if they are of
256 sufficient length, but are not necessarily unpredictable. They can be used
257 for non-cryptographic purposes and for certain purposes in cryptographic
258 protocols, but usually not for key generation etc.
259
Victor Stinner99c8b162011-05-24 12:05:19 +0200260 .. versionadded:: 3.3
261
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000262.. function:: RAND_status()
263
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200264 Returns ``True`` if the SSL pseudo-random number generator has been seeded with
265 'enough' randomness, and ``False`` otherwise. You can use :func:`ssl.RAND_egd`
Georg Brandl7f01a132009-09-16 15:58:14 +0000266 and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
267 number generator.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000268
269.. function:: RAND_egd(path)
270
Victor Stinner99c8b162011-05-24 12:05:19 +0200271 If you are running an entropy-gathering daemon (EGD) somewhere, and *path*
Georg Brandl7f01a132009-09-16 15:58:14 +0000272 is the pathname of a socket connection open to it, this will read 256 bytes
273 of randomness from the socket, and add it to the SSL pseudo-random number
274 generator to increase the security of generated secret keys. This is
275 typically only necessary on systems without better sources of randomness.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000276
Georg Brandl7f01a132009-09-16 15:58:14 +0000277 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
278 of entropy-gathering daemons.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000279
280.. function:: RAND_add(bytes, entropy)
281
Victor Stinner99c8b162011-05-24 12:05:19 +0200282 Mixes the given *bytes* into the SSL pseudo-random number generator. The
283 parameter *entropy* (a float) is a lower bound on the entropy contained in
Georg Brandl7f01a132009-09-16 15:58:14 +0000284 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
285 information on sources of entropy.
Thomas Woutersed03b412007-08-28 21:37:11 +0000286
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000287Certificate handling
288^^^^^^^^^^^^^^^^^^^^
289
290.. function:: match_hostname(cert, hostname)
291
292 Verify that *cert* (in decoded format as returned by
293 :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules
294 applied are those for checking the identity of HTTPS servers as outlined
Georg Brandl72c98d32013-10-27 07:16:53 +0100295 in :rfc:`2818` and :rfc:`6125`, except that IP addresses are not currently
296 supported. In addition to HTTPS, this function should be suitable for
297 checking the identity of servers in various SSL-based protocols such as
298 FTPS, IMAPS, POPS and others.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000299
300 :exc:`CertificateError` is raised on failure. On success, the function
301 returns nothing::
302
303 >>> cert = {'subject': ((('commonName', 'example.com'),),)}
304 >>> ssl.match_hostname(cert, "example.com")
305 >>> ssl.match_hostname(cert, "example.org")
306 Traceback (most recent call last):
307 File "<stdin>", line 1, in <module>
308 File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
309 ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'
310
311 .. versionadded:: 3.2
312
Georg Brandl72c98d32013-10-27 07:16:53 +0100313 .. versionchanged:: 3.3.3
314 The function now follows :rfc:`6125`, section 6.4.3 and does neither
315 match multiple wildcards (e.g. ``*.*.com`` or ``*a*.example.org``) nor
316 a wildcard inside an internationalized domain names (IDN) fragment.
317 IDN A-labels such as ``www*.xn--pthon-kva.org`` are still supported,
318 but ``x*.python.org`` no longer matches ``xn--tda.python.org``.
319
Thomas Woutersed03b412007-08-28 21:37:11 +0000320.. function:: cert_time_to_seconds(timestring)
321
Georg Brandl7f01a132009-09-16 15:58:14 +0000322 Returns a floating-point value containing a normal seconds-after-the-epoch
323 time value, given the time-string representing the "notBefore" or "notAfter"
324 date from a certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000325
326 Here's an example::
327
328 >>> import ssl
329 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
330 1178694000.0
331 >>> import time
332 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
333 'Wed May 9 00:00:00 2007'
Thomas Woutersed03b412007-08-28 21:37:11 +0000334
Georg Brandl7f01a132009-09-16 15:58:14 +0000335.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000336
Georg Brandl7f01a132009-09-16 15:58:14 +0000337 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
338 *port-number*) pair, fetches the server's certificate, and returns it as a
339 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
340 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
341 specified, it should be a file containing a list of root certificates, the
342 same format as used for the same parameter in :func:`wrap_socket`. The call
343 will attempt to validate the server certificate against that set of root
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000344 certificates, and will fail if the validation attempt fails.
345
Antoine Pitrou15399c32011-04-28 19:23:55 +0200346 .. versionchanged:: 3.3
347 This function is now IPv6-compatible.
348
Georg Brandl7f01a132009-09-16 15:58:14 +0000349.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000350
351 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
352 string version of the same certificate.
353
Georg Brandl7f01a132009-09-16 15:58:14 +0000354.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000355
Georg Brandl7f01a132009-09-16 15:58:14 +0000356 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
357 bytes for that same certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000358
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000359Constants
360^^^^^^^^^
361
Thomas Woutersed03b412007-08-28 21:37:11 +0000362.. data:: CERT_NONE
363
Antoine Pitrou152efa22010-05-16 18:19:27 +0000364 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
365 parameter to :func:`wrap_socket`. In this mode (the default), no
366 certificates will be required from the other side of the socket connection.
367 If a certificate is received from the other end, no attempt to validate it
368 is made.
369
370 See the discussion of :ref:`ssl-security` below.
Thomas Woutersed03b412007-08-28 21:37:11 +0000371
372.. data:: CERT_OPTIONAL
373
Antoine Pitrou152efa22010-05-16 18:19:27 +0000374 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
375 parameter to :func:`wrap_socket`. In this mode no certificates will be
376 required from the other side of the socket connection; but if they
377 are provided, validation will be attempted and an :class:`SSLError`
378 will be raised on failure.
379
380 Use of this setting requires a valid set of CA certificates to
381 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
382 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000383
384.. data:: CERT_REQUIRED
385
Antoine Pitrou152efa22010-05-16 18:19:27 +0000386 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
387 parameter to :func:`wrap_socket`. In this mode, certificates are
388 required from the other side of the socket connection; an :class:`SSLError`
389 will be raised if no certificate is provided, or if its validation fails.
390
391 Use of this setting requires a valid set of CA certificates to
392 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
393 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000394
395.. data:: PROTOCOL_SSLv2
396
397 Selects SSL version 2 as the channel encryption protocol.
398
Victor Stinner3de49192011-05-09 00:42:58 +0200399 This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
400 flag.
401
Antoine Pitrou8eac60d2010-05-16 14:19:41 +0000402 .. warning::
403
404 SSL version 2 is insecure. Its use is highly discouraged.
405
Thomas Woutersed03b412007-08-28 21:37:11 +0000406.. data:: PROTOCOL_SSLv23
407
Georg Brandl7f01a132009-09-16 15:58:14 +0000408 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
409 setting to use with servers for maximum compatibility with the other end of
410 an SSL connection, but it may cause the specific ciphers chosen for the
411 encryption to be of fairly low quality.
Thomas Woutersed03b412007-08-28 21:37:11 +0000412
413.. data:: PROTOCOL_SSLv3
414
Georg Brandl7f01a132009-09-16 15:58:14 +0000415 Selects SSL version 3 as the channel encryption protocol. For clients, this
416 is the maximally compatible SSL variant.
Thomas Woutersed03b412007-08-28 21:37:11 +0000417
418.. data:: PROTOCOL_TLSv1
419
Georg Brandl7f01a132009-09-16 15:58:14 +0000420 Selects TLS version 1 as the channel encryption protocol. This is the most
421 modern version, and probably the best choice for maximum protection, if both
422 sides can speak it.
Thomas Woutersed03b412007-08-28 21:37:11 +0000423
Antoine Pitroub5218772010-05-21 09:56:06 +0000424.. data:: OP_ALL
425
426 Enables workarounds for various bugs present in other SSL implementations.
Antoine Pitrou9f6b02e2012-01-27 10:02:55 +0100427 This option is set by default. It does not necessarily set the same
428 flags as OpenSSL's ``SSL_OP_ALL`` constant.
Antoine Pitroub5218772010-05-21 09:56:06 +0000429
430 .. versionadded:: 3.2
431
432.. data:: OP_NO_SSLv2
433
434 Prevents an SSLv2 connection. This option is only applicable in
435 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
436 choosing SSLv2 as the protocol version.
437
438 .. versionadded:: 3.2
439
440.. data:: OP_NO_SSLv3
441
442 Prevents an SSLv3 connection. This option is only applicable in
443 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
444 choosing SSLv3 as the protocol version.
445
446 .. versionadded:: 3.2
447
448.. data:: OP_NO_TLSv1
449
450 Prevents a TLSv1 connection. This option is only applicable in
451 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
452 choosing TLSv1 as the protocol version.
453
454 .. versionadded:: 3.2
455
Antoine Pitrou6db49442011-12-19 13:27:11 +0100456.. data:: OP_CIPHER_SERVER_PREFERENCE
457
458 Use the server's cipher ordering preference, rather than the client's.
459 This option has no effect on client sockets and SSLv2 server sockets.
460
461 .. versionadded:: 3.3
462
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100463.. data:: OP_SINGLE_DH_USE
464
465 Prevents re-use of the same DH key for distinct SSL sessions. This
466 improves forward secrecy but requires more computational resources.
467 This option only applies to server sockets.
468
469 .. versionadded:: 3.3
470
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100471.. data:: OP_SINGLE_ECDH_USE
472
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100473 Prevents re-use of the same ECDH key for distinct SSL sessions. This
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100474 improves forward secrecy but requires more computational resources.
475 This option only applies to server sockets.
476
477 .. versionadded:: 3.3
478
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100479.. data:: OP_NO_COMPRESSION
480
481 Disable compression on the SSL channel. This is useful if the application
482 protocol supports its own compression scheme.
483
484 This option is only available with OpenSSL 1.0.0 and later.
485
486 .. versionadded:: 3.3
487
Antoine Pitrou501da612011-12-21 09:27:41 +0100488.. data:: HAS_ECDH
489
490 Whether the OpenSSL library has built-in support for Elliptic Curve-based
491 Diffie-Hellman key exchange. This should be true unless the feature was
492 explicitly disabled by the distributor.
493
494 .. versionadded:: 3.3
495
Antoine Pitroud5323212010-10-22 18:19:07 +0000496.. data:: HAS_SNI
497
498 Whether the OpenSSL library has built-in support for the *Server Name
499 Indication* extension to the SSLv3 and TLSv1 protocols (as defined in
500 :rfc:`4366`). When true, you can use the *server_hostname* argument to
501 :meth:`SSLContext.wrap_socket`.
502
503 .. versionadded:: 3.2
504
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100505.. data:: HAS_NPN
506
507 Whether the OpenSSL library has built-in support for *Next Protocol
508 Negotiation* as described in the `NPN draft specification
509 <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. When true,
510 you can use the :meth:`SSLContext.set_npn_protocols` method to advertise
511 which protocols you want to support.
512
513 .. versionadded:: 3.3
514
Antoine Pitroud6494802011-07-21 01:11:30 +0200515.. data:: CHANNEL_BINDING_TYPES
516
517 List of supported TLS channel binding types. Strings in this list
518 can be used as arguments to :meth:`SSLSocket.get_channel_binding`.
519
520 .. versionadded:: 3.3
521
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000522.. data:: OPENSSL_VERSION
523
524 The version string of the OpenSSL library loaded by the interpreter::
525
526 >>> ssl.OPENSSL_VERSION
527 'OpenSSL 0.9.8k 25 Mar 2009'
528
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000529 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000530
531.. data:: OPENSSL_VERSION_INFO
532
533 A tuple of five integers representing version information about the
534 OpenSSL library::
535
536 >>> ssl.OPENSSL_VERSION_INFO
537 (0, 9, 8, 11, 15)
538
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000539 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000540
541.. data:: OPENSSL_VERSION_NUMBER
542
543 The raw version number of the OpenSSL library, as a single integer::
544
545 >>> ssl.OPENSSL_VERSION_NUMBER
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000546 9470143
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000547 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000548 '0x9080bf'
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000549
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000550 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000551
Thomas Woutersed03b412007-08-28 21:37:11 +0000552
Antoine Pitrou152efa22010-05-16 18:19:27 +0000553SSL Sockets
554-----------
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000555
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000556SSL sockets provide the following methods of :ref:`socket-objects`:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000557
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000558- :meth:`~socket.socket.accept()`
559- :meth:`~socket.socket.bind()`
560- :meth:`~socket.socket.close()`
561- :meth:`~socket.socket.connect()`
562- :meth:`~socket.socket.detach()`
563- :meth:`~socket.socket.fileno()`
564- :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`
565- :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`
566- :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`,
567 :meth:`~socket.socket.setblocking()`
568- :meth:`~socket.socket.listen()`
569- :meth:`~socket.socket.makefile()`
570- :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()`
571 (but passing a non-zero ``flags`` argument is not allowed)
572- :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with
573 the same limitation)
574- :meth:`~socket.socket.shutdown()`
575
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +0200576However, since the SSL (and TLS) protocol has its own framing atop
577of TCP, the SSL sockets abstraction can, in certain respects, diverge from
578the specification of normal, OS-level sockets. See especially the
579:ref:`notes on non-blocking sockets <ssl-nonblocking>`.
580
581SSL sockets also have the following additional methods and attributes:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000582
Bill Janssen48dc27c2007-12-05 03:38:10 +0000583.. method:: SSLSocket.do_handshake()
584
Antoine Pitroub3593ca2011-07-11 01:39:19 +0200585 Perform the SSL setup handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000586
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000587.. method:: SSLSocket.getpeercert(binary_form=False)
588
Georg Brandl7f01a132009-09-16 15:58:14 +0000589 If there is no certificate for the peer on the other end of the connection,
590 returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000591
Antoine Pitroud34941a2013-04-16 20:27:17 +0200592 If the ``binary_form`` parameter is :const:`False`, and a certificate was
Georg Brandl7f01a132009-09-16 15:58:14 +0000593 received from the peer, this method returns a :class:`dict` instance. If the
594 certificate was not validated, the dict is empty. If the certificate was
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200595 validated, it returns a dict with several keys, amongst them ``subject``
596 (the principal for which the certificate was issued) and ``issuer``
597 (the principal issuing the certificate). If a certificate contains an
598 instance of the *Subject Alternative Name* extension (see :rfc:`3280`),
599 there will also be a ``subjectAltName`` key in the dictionary.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000600
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200601 The ``subject`` and ``issuer`` fields are tuples containing the sequence
602 of relative distinguished names (RDNs) given in the certificate's data
603 structure for the respective fields, and each RDN is a sequence of
604 name-value pairs. Here is a real-world example::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000605
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200606 {'issuer': ((('countryName', 'IL'),),
607 (('organizationName', 'StartCom Ltd.'),),
608 (('organizationalUnitName',
609 'Secure Digital Certificate Signing'),),
610 (('commonName',
611 'StartCom Class 2 Primary Intermediate Server CA'),)),
612 'notAfter': 'Nov 22 08:15:19 2013 GMT',
613 'notBefore': 'Nov 21 03:09:52 2011 GMT',
614 'serialNumber': '95F0',
615 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
616 (('countryName', 'US'),),
617 (('stateOrProvinceName', 'California'),),
618 (('localityName', 'San Francisco'),),
619 (('organizationName', 'Electronic Frontier Foundation, Inc.'),),
620 (('commonName', '*.eff.org'),),
621 (('emailAddress', 'hostmaster@eff.org'),)),
622 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
623 'version': 3}
624
625 .. note::
Éric Araujofa5e6e42014-03-12 19:51:00 -0400626
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200627 To validate a certificate for a particular service, you can use the
628 :func:`match_hostname` function.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000629
Georg Brandl7f01a132009-09-16 15:58:14 +0000630 If the ``binary_form`` parameter is :const:`True`, and a certificate was
631 provided, this method returns the DER-encoded form of the entire certificate
632 as a sequence of bytes, or :const:`None` if the peer did not provide a
Antoine Pitroud34941a2013-04-16 20:27:17 +0200633 certificate. Whether the peer provides a certificate depends on the SSL
634 socket's role:
635
636 * for a client SSL socket, the server will always provide a certificate,
637 regardless of whether validation was required;
638
639 * for a server SSL socket, the client will only provide a certificate
640 when requested by the server; therefore :meth:`getpeercert` will return
641 :const:`None` if you used :const:`CERT_NONE` (rather than
642 :const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000643
Antoine Pitroufb046912010-11-09 20:21:19 +0000644 .. versionchanged:: 3.2
645 The returned dictionary includes additional items such as ``issuer``
646 and ``notBefore``.
647
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000648.. method:: SSLSocket.cipher()
649
Georg Brandl7f01a132009-09-16 15:58:14 +0000650 Returns a three-value tuple containing the name of the cipher being used, the
651 version of the SSL protocol that defines its use, and the number of secret
652 bits being used. If no connection has been established, returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100654.. method:: SSLSocket.compression()
655
656 Return the compression algorithm being used as a string, or ``None``
657 if the connection isn't compressed.
658
659 If the higher-level protocol supports its own compression mechanism,
660 you can use :data:`OP_NO_COMPRESSION` to disable SSL-level compression.
661
662 .. versionadded:: 3.3
663
Antoine Pitroud6494802011-07-21 01:11:30 +0200664.. method:: SSLSocket.get_channel_binding(cb_type="tls-unique")
665
666 Get channel binding data for current connection, as a bytes object. Returns
667 ``None`` if not connected or the handshake has not been completed.
668
669 The *cb_type* parameter allow selection of the desired channel binding
670 type. Valid channel binding types are listed in the
671 :data:`CHANNEL_BINDING_TYPES` list. Currently only the 'tls-unique' channel
672 binding, defined by :rfc:`5929`, is supported. :exc:`ValueError` will be
673 raised if an unsupported channel binding type is requested.
674
675 .. versionadded:: 3.3
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000676
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100677.. method:: SSLSocket.selected_npn_protocol()
678
679 Returns the protocol that was selected during the TLS/SSL handshake. If
680 :meth:`SSLContext.set_npn_protocols` was not called, or if the other party
681 does not support NPN, or if the handshake has not yet happened, this will
682 return ``None``.
683
684 .. versionadded:: 3.3
685
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000686.. method:: SSLSocket.unwrap()
687
Georg Brandl7f01a132009-09-16 15:58:14 +0000688 Performs the SSL shutdown handshake, which removes the TLS layer from the
689 underlying socket, and returns the underlying socket object. This can be
690 used to go from encrypted operation over a connection to unencrypted. The
691 returned socket should always be used for further communication with the
692 other side of the connection, rather than the original socket.
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000693
Antoine Pitrouec883db2010-05-24 21:20:20 +0000694.. attribute:: SSLSocket.context
695
696 The :class:`SSLContext` object this SSL socket is tied to. If the SSL
697 socket was created using the top-level :func:`wrap_socket` function
698 (rather than :meth:`SSLContext.wrap_socket`), this is a custom context
699 object created for this SSL socket.
700
701 .. versionadded:: 3.2
702
703
Antoine Pitrou152efa22010-05-16 18:19:27 +0000704SSL Contexts
705------------
706
Antoine Pitroucafaad42010-05-24 15:58:43 +0000707.. versionadded:: 3.2
708
Antoine Pitroub0182c82010-10-12 20:09:02 +0000709An SSL context holds various data longer-lived than single SSL connections,
710such as SSL configuration options, certificate(s) and private key(s).
711It also manages a cache of SSL sessions for server-side sockets, in order
712to speed up repeated connections from the same clients.
713
Antoine Pitrou152efa22010-05-16 18:19:27 +0000714.. class:: SSLContext(protocol)
715
Antoine Pitroub0182c82010-10-12 20:09:02 +0000716 Create a new SSL context. You must pass *protocol* which must be one
717 of the ``PROTOCOL_*`` constants defined in this module.
718 :data:`PROTOCOL_SSLv23` is recommended for maximum interoperability.
719
Antoine Pitrou152efa22010-05-16 18:19:27 +0000720
721:class:`SSLContext` objects have the following methods and attributes:
722
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200723.. method:: SSLContext.load_cert_chain(certfile, keyfile=None, password=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000724
725 Load a private key and the corresponding certificate. The *certfile*
726 string must be the path to a single file in PEM format containing the
727 certificate as well as any number of CA certificates needed to establish
728 the certificate's authenticity. The *keyfile* string, if present, must
729 point to a file containing the private key in. Otherwise the private
730 key will be taken from *certfile* as well. See the discussion of
731 :ref:`ssl-certificates` for more information on how the certificate
732 is stored in the *certfile*.
733
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200734 The *password* argument may be a function to call to get the password for
735 decrypting the private key. It will only be called if the private key is
736 encrypted and a password is necessary. It will be called with no arguments,
737 and it should return a string, bytes, or bytearray. If the return value is
738 a string it will be encoded as UTF-8 before using it to decrypt the key.
739 Alternatively a string, bytes, or bytearray value may be supplied directly
740 as the *password* argument. It will be ignored if the private key is not
741 encrypted and no password is needed.
742
743 If the *password* argument is not specified and a password is required,
744 OpenSSL's built-in password prompting mechanism will be used to
745 interactively prompt the user for a password.
746
Antoine Pitrou152efa22010-05-16 18:19:27 +0000747 An :class:`SSLError` is raised if the private key doesn't
748 match with the certificate.
749
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200750 .. versionchanged:: 3.3
751 New optional argument *password*.
752
Antoine Pitrou152efa22010-05-16 18:19:27 +0000753.. method:: SSLContext.load_verify_locations(cafile=None, capath=None)
754
755 Load a set of "certification authority" (CA) certificates used to validate
756 other peers' certificates when :data:`verify_mode` is other than
757 :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified.
758
759 The *cafile* string, if present, is the path to a file of concatenated
760 CA certificates in PEM format. See the discussion of
761 :ref:`ssl-certificates` for more information about how to arrange the
762 certificates in this file.
763
764 The *capath* string, if present, is
765 the path to a directory containing several CA certificates in PEM format,
766 following an `OpenSSL specific layout
767 <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
768
Antoine Pitrou664c2d12010-11-17 20:29:42 +0000769.. method:: SSLContext.set_default_verify_paths()
770
771 Load a set of default "certification authority" (CA) certificates from
772 a filesystem path defined when building the OpenSSL library. Unfortunately,
773 there's no easy way to know whether this method succeeds: no error is
774 returned if no certificates are to be found. When the OpenSSL library is
775 provided as part of the operating system, though, it is likely to be
776 configured properly.
777
Antoine Pitrou152efa22010-05-16 18:19:27 +0000778.. method:: SSLContext.set_ciphers(ciphers)
779
780 Set the available ciphers for sockets created with this context.
781 It should be a string in the `OpenSSL cipher list format
782 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
783 If no cipher can be selected (because compile-time options or other
784 configuration forbids use of all the specified ciphers), an
785 :class:`SSLError` will be raised.
786
787 .. note::
788 when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
789 give the currently selected cipher.
790
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100791.. method:: SSLContext.set_npn_protocols(protocols)
792
R David Murrayc7f75792013-06-26 15:11:12 -0400793 Specify which protocols the socket should advertise during the SSL/TLS
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100794 handshake. It should be a list of strings, like ``['http/1.1', 'spdy/2']``,
795 ordered by preference. The selection of a protocol will happen during the
796 handshake, and will play out according to the `NPN draft specification
797 <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. After a
798 successful handshake, the :meth:`SSLSocket.selected_npn_protocol` method will
799 return the agreed-upon protocol.
800
801 This method will raise :exc:`NotImplementedError` if :data:`HAS_NPN` is
802 False.
803
804 .. versionadded:: 3.3
805
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100806.. method:: SSLContext.load_dh_params(dhfile)
807
808 Load the key generation parameters for Diffie-Helman (DH) key exchange.
809 Using DH key exchange improves forward secrecy at the expense of
810 computational resources (both on the server and on the client).
811 The *dhfile* parameter should be the path to a file containing DH
812 parameters in PEM format.
813
814 This setting doesn't apply to client sockets. You can also use the
815 :data:`OP_SINGLE_DH_USE` option to further improve security.
816
817 .. versionadded:: 3.3
818
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100819.. method:: SSLContext.set_ecdh_curve(curve_name)
820
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100821 Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key
822 exchange. ECDH is significantly faster than regular DH while arguably
823 as secure. The *curve_name* parameter should be a string describing
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100824 a well-known elliptic curve, for example ``prime256v1`` for a widely
825 supported curve.
826
827 This setting doesn't apply to client sockets. You can also use the
828 :data:`OP_SINGLE_ECDH_USE` option to further improve security.
829
Antoine Pitrou501da612011-12-21 09:27:41 +0100830 This method is not available if :data:`HAS_ECDH` is False.
831
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100832 .. versionadded:: 3.3
833
834 .. seealso::
835 `SSL/TLS & Perfect Forward Secrecy <http://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy.html>`_
836 Vincent Bernat.
837
Antoine Pitroud5323212010-10-22 18:19:07 +0000838.. method:: SSLContext.wrap_socket(sock, server_side=False, \
839 do_handshake_on_connect=True, suppress_ragged_eofs=True, \
840 server_hostname=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000841
842 Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100843 object. *sock* must be a :data:`~socket.SOCK_STREAM` socket; other socket
844 types are unsupported.
845
846 The returned SSL socket is tied to the context, its settings and
Antoine Pitrou152efa22010-05-16 18:19:27 +0000847 certificates. The parameters *server_side*, *do_handshake_on_connect*
848 and *suppress_ragged_eofs* have the same meaning as in the top-level
849 :func:`wrap_socket` function.
850
Antoine Pitroud5323212010-10-22 18:19:07 +0000851 On client connections, the optional parameter *server_hostname* specifies
852 the hostname of the service which we are connecting to. This allows a
853 single server to host multiple SSL-based services with distinct certificates,
854 quite similarly to HTTP virtual hosts. Specifying *server_hostname*
855 will raise a :exc:`ValueError` if the OpenSSL library doesn't have support
856 for it (that is, if :data:`HAS_SNI` is :const:`False`). Specifying
857 *server_hostname* will also raise a :exc:`ValueError` if *server_side*
858 is true.
859
Antoine Pitroub0182c82010-10-12 20:09:02 +0000860.. method:: SSLContext.session_stats()
861
862 Get statistics about the SSL sessions created or managed by this context.
863 A dictionary is returned which maps the names of each `piece of information
864 <http://www.openssl.org/docs/ssl/SSL_CTX_sess_number.html>`_ to their
865 numeric values. For example, here is the total number of hits and misses
866 in the session cache since the context was created::
867
868 >>> stats = context.session_stats()
869 >>> stats['hits'], stats['misses']
870 (0, 0)
871
Antoine Pitroub5218772010-05-21 09:56:06 +0000872.. attribute:: SSLContext.options
873
874 An integer representing the set of SSL options enabled on this context.
875 The default value is :data:`OP_ALL`, but you can specify other options
876 such as :data:`OP_NO_SSLv2` by ORing them together.
877
878 .. note::
879 With versions of OpenSSL older than 0.9.8m, it is only possible
880 to set options, not to clear them. Attempting to clear an option
881 (by resetting the corresponding bits) will raise a ``ValueError``.
882
Antoine Pitrou152efa22010-05-16 18:19:27 +0000883.. attribute:: SSLContext.protocol
884
885 The protocol version chosen when constructing the context. This attribute
886 is read-only.
887
888.. attribute:: SSLContext.verify_mode
889
890 Whether to try to verify other peers' certificates and how to behave
891 if verification fails. This attribute must be one of
892 :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.
893
894
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000895.. index:: single: certificates
896
897.. index:: single: X509 certificate
898
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000899.. _ssl-certificates:
900
Thomas Woutersed03b412007-08-28 21:37:11 +0000901Certificates
902------------
903
Georg Brandl7f01a132009-09-16 15:58:14 +0000904Certificates in general are part of a public-key / private-key system. In this
905system, each *principal*, (which may be a machine, or a person, or an
906organization) is assigned a unique two-part encryption key. One part of the key
907is public, and is called the *public key*; the other part is kept secret, and is
908called the *private key*. The two parts are related, in that if you encrypt a
909message with one of the parts, you can decrypt it with the other part, and
910**only** with the other part.
Thomas Woutersed03b412007-08-28 21:37:11 +0000911
Georg Brandl7f01a132009-09-16 15:58:14 +0000912A certificate contains information about two principals. It contains the name
913of a *subject*, and the subject's public key. It also contains a statement by a
914second principal, the *issuer*, that the subject is who he claims to be, and
915that this is indeed the subject's public key. The issuer's statement is signed
916with the issuer's private key, which only the issuer knows. However, anyone can
917verify the issuer's statement by finding the issuer's public key, decrypting the
918statement with it, and comparing it to the other information in the certificate.
919The certificate also contains information about the time period over which it is
920valid. This is expressed as two fields, called "notBefore" and "notAfter".
Thomas Woutersed03b412007-08-28 21:37:11 +0000921
Georg Brandl7f01a132009-09-16 15:58:14 +0000922In the Python use of certificates, a client or server can use a certificate to
923prove who they are. The other side of a network connection can also be required
924to produce a certificate, and that certificate can be validated to the
925satisfaction of the client or server that requires such validation. The
926connection attempt can be set to raise an exception if the validation fails.
927Validation is done automatically, by the underlying OpenSSL framework; the
928application need not concern itself with its mechanics. But the application
929does usually need to provide sets of certificates to allow this process to take
930place.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000931
Georg Brandl7f01a132009-09-16 15:58:14 +0000932Python uses files to contain certificates. They should be formatted as "PEM"
933(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
934and a footer line::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000935
936 -----BEGIN CERTIFICATE-----
937 ... (certificate in base64 PEM encoding) ...
938 -----END CERTIFICATE-----
939
Antoine Pitrou152efa22010-05-16 18:19:27 +0000940Certificate chains
941^^^^^^^^^^^^^^^^^^
942
Georg Brandl7f01a132009-09-16 15:58:14 +0000943The Python files which contain certificates can contain a sequence of
944certificates, sometimes called a *certificate chain*. This chain should start
945with the specific certificate for the principal who "is" the client or server,
946and then the certificate for the issuer of that certificate, and then the
947certificate for the issuer of *that* certificate, and so on up the chain till
948you get to a certificate which is *self-signed*, that is, a certificate which
949has the same subject and issuer, sometimes called a *root certificate*. The
950certificates should just be concatenated together in the certificate file. For
951example, suppose we had a three certificate chain, from our server certificate
952to the certificate of the certification authority that signed our server
953certificate, to the root certificate of the agency which issued the
954certification authority's certificate::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000955
956 -----BEGIN CERTIFICATE-----
957 ... (certificate for your server)...
958 -----END CERTIFICATE-----
959 -----BEGIN CERTIFICATE-----
960 ... (the certificate for the CA)...
961 -----END CERTIFICATE-----
962 -----BEGIN CERTIFICATE-----
963 ... (the root certificate for the CA's issuer)...
964 -----END CERTIFICATE-----
965
Antoine Pitrou152efa22010-05-16 18:19:27 +0000966CA certificates
967^^^^^^^^^^^^^^^
968
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000969If you are going to require validation of the other side of the connection's
970certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandl7f01a132009-09-16 15:58:14 +0000971chains for each issuer you are willing to trust. Again, this file just contains
972these chains concatenated together. For validation, Python will use the first
973chain it finds in the file which matches. Some "standard" root certificates are
974available from various certification authorities: `CACert.org
975<http://www.cacert.org/index.php?id=3>`_, `Thawte
976<http://www.thawte.com/roots/>`_, `Verisign
977<http://www.verisign.com/support/roots.html>`_, `Positive SSL
978<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
979(used by python.org), `Equifax and GeoTrust
980<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000981
Georg Brandl7f01a132009-09-16 15:58:14 +0000982In general, if you are using SSL3 or TLS1, you don't need to put the full chain
983in your "CA certs" file; you only need the root certificates, and the remote
984peer is supposed to furnish the other certificates necessary to chain from its
985certificate to a root certificate. See :rfc:`4158` for more discussion of the
986way in which certification chains can be built.
Thomas Woutersed03b412007-08-28 21:37:11 +0000987
Antoine Pitrou152efa22010-05-16 18:19:27 +0000988Combined key and certificate
989^^^^^^^^^^^^^^^^^^^^^^^^^^^^
990
991Often the private key is stored in the same file as the certificate; in this
992case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain`
993and :func:`wrap_socket` needs to be passed. If the private key is stored
994with the certificate, it should come before the first certificate in
995the certificate chain::
996
997 -----BEGIN RSA PRIVATE KEY-----
998 ... (private key in base64 encoding) ...
999 -----END RSA PRIVATE KEY-----
1000 -----BEGIN CERTIFICATE-----
1001 ... (certificate in base64 PEM encoding) ...
1002 -----END CERTIFICATE-----
1003
1004Self-signed certificates
1005^^^^^^^^^^^^^^^^^^^^^^^^
1006
Georg Brandl7f01a132009-09-16 15:58:14 +00001007If you are going to create a server that provides SSL-encrypted connection
1008services, you will need to acquire a certificate for that service. There are
1009many ways of acquiring appropriate certificates, such as buying one from a
1010certification authority. Another common practice is to generate a self-signed
1011certificate. The simplest way to do this is with the OpenSSL package, using
1012something like the following::
Thomas Woutersed03b412007-08-28 21:37:11 +00001013
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001014 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
1015 Generating a 1024 bit RSA private key
1016 .......++++++
1017 .............................++++++
1018 writing new private key to 'cert.pem'
1019 -----
1020 You are about to be asked to enter information that will be incorporated
1021 into your certificate request.
1022 What you are about to enter is what is called a Distinguished Name or a DN.
1023 There are quite a few fields but you can leave some blank
1024 For some fields there will be a default value,
1025 If you enter '.', the field will be left blank.
1026 -----
1027 Country Name (2 letter code) [AU]:US
1028 State or Province Name (full name) [Some-State]:MyState
1029 Locality Name (eg, city) []:Some City
1030 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
1031 Organizational Unit Name (eg, section) []:My Group
1032 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
1033 Email Address []:ops@myserver.mygroup.myorganization.com
1034 %
Thomas Woutersed03b412007-08-28 21:37:11 +00001035
Georg Brandl7f01a132009-09-16 15:58:14 +00001036The disadvantage of a self-signed certificate is that it is its own root
1037certificate, and no one else will have it in their cache of known (and trusted)
1038root certificates.
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001039
1040
Thomas Woutersed03b412007-08-28 21:37:11 +00001041Examples
1042--------
1043
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001044Testing for SSL support
1045^^^^^^^^^^^^^^^^^^^^^^^
1046
Georg Brandl7f01a132009-09-16 15:58:14 +00001047To test for the presence of SSL support in a Python installation, user code
1048should use the following idiom::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001049
1050 try:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001051 import ssl
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001052 except ImportError:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001053 pass
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001054 else:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001055 ... # do something that requires SSL support
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001056
1057Client-side operation
1058^^^^^^^^^^^^^^^^^^^^^
1059
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001060This example connects to an SSL server and prints the server's certificate::
Thomas Woutersed03b412007-08-28 21:37:11 +00001061
1062 import socket, ssl, pprint
1063
1064 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001065 # require a certificate from the server
1066 ssl_sock = ssl.wrap_socket(s,
1067 ca_certs="/etc/ca_certs_file",
1068 cert_reqs=ssl.CERT_REQUIRED)
Thomas Woutersed03b412007-08-28 21:37:11 +00001069 ssl_sock.connect(('www.verisign.com', 443))
1070
Georg Brandl6911e3c2007-09-04 07:15:32 +00001071 pprint.pprint(ssl_sock.getpeercert())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001072 # note that closing the SSLSocket will also close the underlying socket
Thomas Woutersed03b412007-08-28 21:37:11 +00001073 ssl_sock.close()
1074
Antoine Pitrou441ae042012-01-06 20:06:15 +01001075As of January 6, 2012, the certificate printed by this program looks like
Georg Brandl7f01a132009-09-16 15:58:14 +00001076this::
Thomas Woutersed03b412007-08-28 21:37:11 +00001077
Antoine Pitrou441ae042012-01-06 20:06:15 +01001078 {'issuer': ((('countryName', 'US'),),
1079 (('organizationName', 'VeriSign, Inc.'),),
1080 (('organizationalUnitName', 'VeriSign Trust Network'),),
1081 (('organizationalUnitName',
1082 'Terms of use at https://www.verisign.com/rpa (c)06'),),
1083 (('commonName',
1084 'VeriSign Class 3 Extended Validation SSL SGC CA'),)),
1085 'notAfter': 'May 25 23:59:59 2012 GMT',
1086 'notBefore': 'May 26 00:00:00 2010 GMT',
1087 'serialNumber': '53D2BEF924A7245E83CA01E46CAA2477',
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001088 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
1089 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
1090 (('businessCategory', 'V1.0, Clause 5.(b)'),),
1091 (('serialNumber', '2497886'),),
1092 (('countryName', 'US'),),
1093 (('postalCode', '94043'),),
1094 (('stateOrProvinceName', 'California'),),
1095 (('localityName', 'Mountain View'),),
1096 (('streetAddress', '487 East Middlefield Road'),),
1097 (('organizationName', 'VeriSign, Inc.'),),
1098 (('organizationalUnitName', ' Production Security Services'),),
Antoine Pitrou441ae042012-01-06 20:06:15 +01001099 (('commonName', 'www.verisign.com'),)),
1100 'subjectAltName': (('DNS', 'www.verisign.com'),
1101 ('DNS', 'verisign.com'),
1102 ('DNS', 'www.verisign.net'),
1103 ('DNS', 'verisign.net'),
1104 ('DNS', 'www.verisign.mobi'),
1105 ('DNS', 'verisign.mobi'),
1106 ('DNS', 'www.verisign.eu'),
1107 ('DNS', 'verisign.eu')),
1108 'version': 3}
Thomas Woutersed03b412007-08-28 21:37:11 +00001109
Antoine Pitrou152efa22010-05-16 18:19:27 +00001110This other example first creates an SSL context, instructs it to verify
1111certificates sent by peers, and feeds it a set of recognized certificate
1112authorities (CA)::
1113
1114 >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001115 >>> context.verify_mode = ssl.CERT_REQUIRED
Antoine Pitrou152efa22010-05-16 18:19:27 +00001116 >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
1117
1118(it is assumed your operating system places a bundle of all CA certificates
1119in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have
1120to adjust the location)
1121
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001122When you use the context to connect to a server, :const:`CERT_REQUIRED`
Antoine Pitrou152efa22010-05-16 18:19:27 +00001123validates the server certificate: it ensures that the server certificate
1124was signed with one of the CA certificates, and checks the signature for
1125correctness::
1126
1127 >>> conn = context.wrap_socket(socket.socket(socket.AF_INET))
1128 >>> conn.connect(("linuxfr.org", 443))
1129
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001130You should then fetch the certificate and check its fields for conformity::
Antoine Pitrou152efa22010-05-16 18:19:27 +00001131
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001132 >>> cert = conn.getpeercert()
1133 >>> ssl.match_hostname(cert, "linuxfr.org")
1134
1135Visual inspection shows that the certificate does identify the desired service
1136(that is, the HTTPS host ``linuxfr.org``)::
1137
1138 >>> pprint.pprint(cert)
Antoine Pitrou441ae042012-01-06 20:06:15 +01001139 {'issuer': ((('organizationName', 'CAcert Inc.'),),
1140 (('organizationalUnitName', 'http://www.CAcert.org'),),
1141 (('commonName', 'CAcert Class 3 Root'),)),
1142 'notAfter': 'Jun 7 21:02:24 2013 GMT',
1143 'notBefore': 'Jun 8 21:02:24 2011 GMT',
1144 'serialNumber': 'D3E9',
Antoine Pitrou152efa22010-05-16 18:19:27 +00001145 'subject': ((('commonName', 'linuxfr.org'),),),
Antoine Pitrou441ae042012-01-06 20:06:15 +01001146 'subjectAltName': (('DNS', 'linuxfr.org'),
1147 ('othername', '<unsupported>'),
1148 ('DNS', 'linuxfr.org'),
1149 ('othername', '<unsupported>'),
1150 ('DNS', 'dev.linuxfr.org'),
1151 ('othername', '<unsupported>'),
1152 ('DNS', 'prod.linuxfr.org'),
1153 ('othername', '<unsupported>'),
1154 ('DNS', 'alpha.linuxfr.org'),
1155 ('othername', '<unsupported>'),
1156 ('DNS', '*.linuxfr.org'),
1157 ('othername', '<unsupported>')),
1158 'version': 3}
Antoine Pitrou152efa22010-05-16 18:19:27 +00001159
1160Now that you are assured of its authenticity, you can proceed to talk with
1161the server::
1162
Antoine Pitroudab64262010-09-19 13:31:06 +00001163 >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
1164 >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
Antoine Pitrou152efa22010-05-16 18:19:27 +00001165 [b'HTTP/1.1 302 Found',
1166 b'Date: Sun, 16 May 2010 13:43:28 GMT',
1167 b'Server: Apache/2.2',
1168 b'Location: https://linuxfr.org/pub/',
1169 b'Vary: Accept-Encoding',
1170 b'Connection: close',
1171 b'Content-Type: text/html; charset=iso-8859-1',
1172 b'',
1173 b'']
1174
Antoine Pitrou152efa22010-05-16 18:19:27 +00001175See the discussion of :ref:`ssl-security` below.
1176
1177
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001178Server-side operation
1179^^^^^^^^^^^^^^^^^^^^^
1180
Antoine Pitrou152efa22010-05-16 18:19:27 +00001181For server operation, typically you'll need to have a server certificate, and
1182private key, each in a file. You'll first create a context holding the key
1183and the certificate, so that clients can check your authenticity. Then
1184you'll open a socket, bind it to a port, call :meth:`listen` on it, and start
1185waiting for clients to connect::
Thomas Woutersed03b412007-08-28 21:37:11 +00001186
1187 import socket, ssl
1188
Antoine Pitrou152efa22010-05-16 18:19:27 +00001189 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1190 context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")
1191
Thomas Woutersed03b412007-08-28 21:37:11 +00001192 bindsocket = socket.socket()
1193 bindsocket.bind(('myaddr.mydomain.com', 10023))
1194 bindsocket.listen(5)
1195
Antoine Pitrou152efa22010-05-16 18:19:27 +00001196When a client connects, you'll call :meth:`accept` on the socket to get the
1197new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket`
1198method to create a server-side SSL socket for the connection::
Thomas Woutersed03b412007-08-28 21:37:11 +00001199
1200 while True:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001201 newsocket, fromaddr = bindsocket.accept()
1202 connstream = context.wrap_socket(newsocket, server_side=True)
1203 try:
1204 deal_with_client(connstream)
1205 finally:
Antoine Pitroub205d582011-01-02 22:09:27 +00001206 connstream.shutdown(socket.SHUT_RDWR)
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001207 connstream.close()
Thomas Woutersed03b412007-08-28 21:37:11 +00001208
Antoine Pitrou152efa22010-05-16 18:19:27 +00001209Then you'll read data from the ``connstream`` and do something with it till you
Georg Brandl7f01a132009-09-16 15:58:14 +00001210are finished with the client (or the client is finished with you)::
Thomas Woutersed03b412007-08-28 21:37:11 +00001211
1212 def deal_with_client(connstream):
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001213 data = connstream.recv(1024)
1214 # empty data means the client is finished with us
1215 while data:
1216 if not do_something(connstream, data):
1217 # we'll assume do_something returns False
1218 # when we're finished with client
1219 break
1220 data = connstream.recv(1024)
1221 # finished with client
Thomas Woutersed03b412007-08-28 21:37:11 +00001222
Antoine Pitrou152efa22010-05-16 18:19:27 +00001223And go back to listening for new client connections (of course, a real server
1224would probably handle each client connection in a separate thread, or put
1225the sockets in non-blocking mode and use an event loop).
1226
1227
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001228.. _ssl-nonblocking:
1229
1230Notes on non-blocking sockets
1231-----------------------------
1232
1233When working with non-blocking sockets, there are several things you need
1234to be aware of:
1235
1236- Calling :func:`~select.select` tells you that the OS-level socket can be
1237 read from (or written to), but it does not imply that there is sufficient
1238 data at the upper SSL layer. For example, only part of an SSL frame might
1239 have arrived. Therefore, you must be ready to handle :meth:`SSLSocket.recv`
1240 and :meth:`SSLSocket.send` failures, and retry after another call to
1241 :func:`~select.select`.
1242
1243 (of course, similar provisions apply when using other primitives such as
1244 :func:`~select.poll`)
1245
1246- The SSL handshake itself will be non-blocking: the
1247 :meth:`SSLSocket.do_handshake` method has to be retried until it returns
1248 successfully. Here is a synopsis using :func:`~select.select` to wait for
1249 the socket's readiness::
1250
1251 while True:
1252 try:
1253 sock.do_handshake()
1254 break
Antoine Pitrou873bf262011-10-27 23:59:03 +02001255 except ssl.SSLWantReadError:
1256 select.select([sock], [], [])
1257 except ssl.SSLWantWriteError:
1258 select.select([], [sock], [])
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001259
1260
Antoine Pitrou152efa22010-05-16 18:19:27 +00001261.. _ssl-security:
1262
1263Security considerations
1264-----------------------
1265
1266Verifying certificates
1267^^^^^^^^^^^^^^^^^^^^^^
1268
1269:const:`CERT_NONE` is the default. Since it does not authenticate the other
1270peer, it can be insecure, especially in client mode where most of time you
1271would like to ensure the authenticity of the server you're talking to.
1272Therefore, when in client mode, it is highly recommended to use
1273:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001274have to check that the server certificate, which can be obtained by calling
1275:meth:`SSLSocket.getpeercert`, matches the desired service. For many
1276protocols and applications, the service can be identified by the hostname;
1277in this case, the :func:`match_hostname` function can be used.
Antoine Pitrou152efa22010-05-16 18:19:27 +00001278
1279In server mode, if you want to authenticate your clients using the SSL layer
1280(rather than using a higher-level authentication mechanism), you'll also have
1281to specify :const:`CERT_REQUIRED` and similarly check the client certificate.
1282
1283 .. note::
1284
1285 In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are
1286 equivalent unless anonymous ciphers are enabled (they are disabled
1287 by default).
Thomas Woutersed03b412007-08-28 21:37:11 +00001288
Antoine Pitroub5218772010-05-21 09:56:06 +00001289Protocol versions
1290^^^^^^^^^^^^^^^^^
1291
1292SSL version 2 is considered insecure and is therefore dangerous to use. If
1293you want maximum compatibility between clients and servers, it is recommended
1294to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable
1295SSLv2 explicitly using the :data:`SSLContext.options` attribute::
1296
1297 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1298 context.options |= ssl.OP_NO_SSLv2
1299
1300The SSL context created above will allow SSLv3 and TLSv1 connections, but
1301not SSLv2.
1302
Antoine Pitroub7ffed82012-01-04 02:53:44 +01001303Cipher selection
1304^^^^^^^^^^^^^^^^
1305
1306If you have advanced security requirements, fine-tuning of the ciphers
1307enabled when negotiating a SSL session is possible through the
1308:meth:`SSLContext.set_ciphers` method. Starting from Python 3.2.3, the
1309ssl module disables certain weak ciphers by default, but you may want
1310to further restrict the cipher choice. For example::
1311
1312 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1313 context.set_ciphers('HIGH:!aNULL:!eNULL')
1314
1315The ``!aNULL:!eNULL`` part of the cipher spec is necessary to disable ciphers
1316which don't provide both encryption and authentication. Be sure to read
1317OpenSSL's documentation about the `cipher list
1318format <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
1319If you want to check which ciphers are enabled by a given cipher list,
1320use the ``openssl ciphers`` command on your system.
1321
Antoine Pitrou9eefe912013-11-17 15:35:33 +01001322Multi-processing
1323^^^^^^^^^^^^^^^^
1324
1325If using this module as part of a multi-processed application (using,
1326for example the :mod:`multiprocessing` or :mod:`concurrent.futures` modules),
1327be aware that OpenSSL's internal random number generator does not properly
1328handle forked processes. Applications must change the PRNG state of the
1329parent process if they use any SSL feature with :func:`os.fork`. Any
1330successful call of :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or
1331:func:`~ssl.RAND_pseudo_bytes` is sufficient.
1332
Georg Brandl48310cd2009-01-03 21:18:54 +00001333
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001334.. seealso::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001335
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001336 Class :class:`socket.socket`
Georg Brandl4a6cf6c2013-10-06 18:20:31 +02001337 Documentation of underlying :mod:`socket` class
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001338
Georg Brandl4a6cf6c2013-10-06 18:20:31 +02001339 `SSL/TLS Strong Encryption: An Introduction <http://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html>`_
1340 Intro from the Apache webserver documentation
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001341
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001342 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
1343 Steve Kent
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001344
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001345 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
1346 D. Eastlake et. al.
Thomas Wouters89d996e2007-09-08 17:39:28 +00001347
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001348 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
1349 Housley et. al.
Antoine Pitroud5323212010-10-22 18:19:07 +00001350
1351 `RFC 4366: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc4366>`_
1352 Blake-Wilson et. al.