blob: 1c5c3551601ca3c0864f164ab07f30589ed71519 [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::
32
33 OpenSSL's internal random number generator does not properly handle fork.
34 Applications must change the PRNG state of the parent process if they use
Christian Heimes47674bc2013-10-29 22:19:39 +010035 any SSL feature with :func:`os.fork`. Any successful call of
Christian Heimes3046fe42013-10-29 21:08:56 +010036 :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or
37 :func:`~ssl.RAND_pseudo_bytes` is sufficient.
38
Georg Brandl7f01a132009-09-16 15:58:14 +000039This section documents the objects and functions in the ``ssl`` module; for more
40general information about TLS, SSL, and certificates, the reader is referred to
41the documents in the "See Also" section at the bottom.
Thomas Woutersed03b412007-08-28 21:37:11 +000042
Georg Brandl7f01a132009-09-16 15:58:14 +000043This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
44:class:`socket.socket` type, and provides a socket-like wrapper that also
45encrypts and decrypts the data going over the socket with SSL. It supports
Antoine Pitroudab64262010-09-19 13:31:06 +000046additional methods such as :meth:`getpeercert`, which retrieves the
47certificate of the other side of the connection, and :meth:`cipher`,which
48retrieves the cipher being used for the secure connection.
Thomas Woutersed03b412007-08-28 21:37:11 +000049
Antoine Pitrou152efa22010-05-16 18:19:27 +000050For more sophisticated applications, the :class:`ssl.SSLContext` class
51helps manage settings and certificates, which can then be inherited
52by SSL sockets created through the :meth:`SSLContext.wrap_socket` method.
53
54
Thomas Wouters1b7f8912007-09-19 03:06:30 +000055Functions, Constants, and Exceptions
56------------------------------------
57
58.. exception:: SSLError
59
Antoine Pitrou59fdd672010-10-08 10:37:08 +000060 Raised to signal an error from the underlying SSL implementation
61 (currently provided by the OpenSSL library). This signifies some
62 problem in the higher-level encryption and authentication layer that's
63 superimposed on the underlying network connection. This error
Antoine Pitrou5574c302011-10-12 17:53:43 +020064 is a subtype of :exc:`OSError`. The error code and message of
65 :exc:`SSLError` instances are provided by the OpenSSL library.
66
67 .. versionchanged:: 3.3
68 :exc:`SSLError` used to be a subtype of :exc:`socket.error`.
Antoine Pitrou59fdd672010-10-08 10:37:08 +000069
Antoine Pitrou3b36fb12012-06-22 21:11:52 +020070 .. attribute:: library
71
72 A string mnemonic designating the OpenSSL submodule in which the error
73 occurred, such as ``SSL``, ``PEM`` or ``X509``. The range of possible
74 values depends on the OpenSSL version.
75
76 .. versionadded:: 3.3
77
78 .. attribute:: reason
79
80 A string mnemonic designating the reason this error occurred, for
81 example ``CERTIFICATE_VERIFY_FAILED``. The range of possible
82 values depends on the OpenSSL version.
83
84 .. versionadded:: 3.3
85
Antoine Pitrou41032a62011-10-27 23:56:55 +020086.. exception:: SSLZeroReturnError
87
88 A subclass of :exc:`SSLError` raised when trying to read or write and
89 the SSL connection has been closed cleanly. Note that this doesn't
90 mean that the underlying transport (read TCP) has been closed.
91
92 .. versionadded:: 3.3
93
94.. exception:: SSLWantReadError
95
96 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
97 <ssl-nonblocking>` when trying to read or write data, but more data needs
98 to be received on the underlying TCP transport before the request can be
99 fulfilled.
100
101 .. versionadded:: 3.3
102
103.. exception:: SSLWantWriteError
104
105 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
106 <ssl-nonblocking>` when trying to read or write data, but more data needs
107 to be sent on the underlying TCP transport before the request can be
108 fulfilled.
109
110 .. versionadded:: 3.3
111
112.. exception:: SSLSyscallError
113
114 A subclass of :exc:`SSLError` raised when a system error was encountered
115 while trying to fulfill an operation on a SSL socket. Unfortunately,
116 there is no easy way to inspect the original errno number.
117
118 .. versionadded:: 3.3
119
120.. exception:: SSLEOFError
121
122 A subclass of :exc:`SSLError` raised when the SSL connection has been
Antoine Pitrouf3dc2d72011-10-28 00:01:03 +0200123 terminated abruptly. Generally, you shouldn't try to reuse the underlying
Antoine Pitrou41032a62011-10-27 23:56:55 +0200124 transport when this error is encountered.
125
126 .. versionadded:: 3.3
127
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000128.. exception:: CertificateError
129
130 Raised to signal an error with a certificate (such as mismatching
131 hostname). Certificate errors detected by OpenSSL, though, raise
132 an :exc:`SSLError`.
133
134
135Socket creation
136^^^^^^^^^^^^^^^
137
138The following function allows for standalone socket creation. Starting from
139Python 3.2, it can be more flexible to use :meth:`SSLContext.wrap_socket`
140instead.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000141
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000142.. 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 +0000143
Georg Brandl7f01a132009-09-16 15:58:14 +0000144 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
145 of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
146 the underlying socket in an SSL context. For client-side sockets, the
147 context construction is lazy; if the underlying socket isn't connected yet,
148 the context construction will be performed after :meth:`connect` is called on
149 the socket. For server-side sockets, if the socket has no remote peer, it is
150 assumed to be a listening socket, and the server-side SSL wrapping is
151 automatically performed on client connections accepted via the :meth:`accept`
152 method. :func:`wrap_socket` may raise :exc:`SSLError`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000153
Georg Brandl7f01a132009-09-16 15:58:14 +0000154 The ``keyfile`` and ``certfile`` parameters specify optional files which
155 contain a certificate to be used to identify the local side of the
156 connection. See the discussion of :ref:`ssl-certificates` for more
157 information on how the certificate is stored in the ``certfile``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000158
Georg Brandl7f01a132009-09-16 15:58:14 +0000159 The parameter ``server_side`` is a boolean which identifies whether
160 server-side or client-side behavior is desired from this socket.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000161
Georg Brandl7f01a132009-09-16 15:58:14 +0000162 The parameter ``cert_reqs`` specifies whether a certificate is required from
163 the other side of the connection, and whether it will be validated if
164 provided. It must be one of the three values :const:`CERT_NONE`
165 (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
166 if provided), or :const:`CERT_REQUIRED` (required and validated). If the
167 value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
168 parameter must point to a file of CA certificates.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000169
Georg Brandl7f01a132009-09-16 15:58:14 +0000170 The ``ca_certs`` file contains a set of concatenated "certification
171 authority" certificates, which are used to validate certificates passed from
172 the other end of the connection. See the discussion of
173 :ref:`ssl-certificates` for more information about how to arrange the
174 certificates in this file.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000175
Georg Brandl7f01a132009-09-16 15:58:14 +0000176 The parameter ``ssl_version`` specifies which version of the SSL protocol to
177 use. Typically, the server chooses a particular protocol version, and the
178 client must adapt to the server's choice. Most of the versions are not
Antoine Pitrou84a2edc2012-01-09 21:35:11 +0100179 interoperable with the other versions. If not specified, the default is
180 :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other
Georg Brandl7f01a132009-09-16 15:58:14 +0000181 versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000182
Georg Brandl7f01a132009-09-16 15:58:14 +0000183 Here's a table showing which versions in a client (down the side) can connect
184 to which versions in a server (along the top):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000185
186 .. table::
187
188 ======================== ========= ========= ========== =========
189 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1**
Christian Heimes255f53b2007-12-08 15:33:56 +0000190 ------------------------ --------- --------- ---------- ---------
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000191 *SSLv2* yes no yes no
Antoine Pitrouac8bfca2012-01-09 21:43:18 +0100192 *SSLv3* no yes yes no
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000193 *SSLv23* yes no yes no
194 *TLSv1* no no yes yes
195 ======================== ========= ========= ========== =========
196
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000197 .. note::
198
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000199 Which connections succeed will vary depending on the version of
200 OpenSSL. For instance, in some older versions of OpenSSL (such
201 as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an
202 SSLv23 server. Another example: beginning with OpenSSL 1.0.0,
203 an SSLv23 client will not actually attempt SSLv2 connections
204 unless you explicitly enable SSLv2 ciphers; for example, you
205 might specify ``"ALL"`` or ``"SSLv2"`` as the *ciphers* parameter
206 to enable them.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000207
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000208 The *ciphers* parameter sets the available ciphers for this SSL object.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000209 It should be a string in the `OpenSSL cipher list format
210 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000211
Bill Janssen48dc27c2007-12-05 03:38:10 +0000212 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
213 handshake automatically after doing a :meth:`socket.connect`, or whether the
Georg Brandl7f01a132009-09-16 15:58:14 +0000214 application program will call it explicitly, by invoking the
215 :meth:`SSLSocket.do_handshake` method. Calling
216 :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
217 blocking behavior of the socket I/O involved in the handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000218
Georg Brandl7f01a132009-09-16 15:58:14 +0000219 The parameter ``suppress_ragged_eofs`` specifies how the
Antoine Pitroudab64262010-09-19 13:31:06 +0000220 :meth:`SSLSocket.recv` method should signal unexpected EOF from the other end
Georg Brandl7f01a132009-09-16 15:58:14 +0000221 of the connection. If specified as :const:`True` (the default), it returns a
Antoine Pitroudab64262010-09-19 13:31:06 +0000222 normal EOF (an empty bytes object) in response to unexpected EOF errors
223 raised from the underlying socket; if :const:`False`, it will raise the
224 exceptions back to the caller.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000225
Ezio Melotti4d5195b2010-04-20 10:57:44 +0000226 .. versionchanged:: 3.2
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000227 New optional argument *ciphers*.
228
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000229Random generation
230^^^^^^^^^^^^^^^^^
231
Victor Stinner99c8b162011-05-24 12:05:19 +0200232.. function:: RAND_bytes(num)
233
Victor Stinnera6752062011-05-25 11:27:40 +0200234 Returns *num* cryptographically strong pseudo-random bytes. Raises an
235 :class:`SSLError` if the PRNG has not been seeded with enough data or if the
236 operation is not supported by the current RAND method. :func:`RAND_status`
237 can be used to check the status of the PRNG and :func:`RAND_add` can be used
238 to seed the PRNG.
Victor Stinner99c8b162011-05-24 12:05:19 +0200239
Victor Stinner19fb53c2011-05-24 21:32:40 +0200240 Read the Wikipedia article, `Cryptographically secure pseudorandom number
Victor Stinnera6752062011-05-25 11:27:40 +0200241 generator (CSPRNG)
Victor Stinner19fb53c2011-05-24 21:32:40 +0200242 <http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator>`_,
243 to get the requirements of a cryptographically generator.
244
Victor Stinner99c8b162011-05-24 12:05:19 +0200245 .. versionadded:: 3.3
246
247.. function:: RAND_pseudo_bytes(num)
248
249 Returns (bytes, is_cryptographic): bytes are *num* pseudo-random bytes,
250 is_cryptographic is True if the bytes generated are cryptographically
Victor Stinnera6752062011-05-25 11:27:40 +0200251 strong. Raises an :class:`SSLError` if the operation is not supported by the
252 current RAND method.
Victor Stinner99c8b162011-05-24 12:05:19 +0200253
Victor Stinner19fb53c2011-05-24 21:32:40 +0200254 Generated pseudo-random byte sequences will be unique if they are of
255 sufficient length, but are not necessarily unpredictable. They can be used
256 for non-cryptographic purposes and for certain purposes in cryptographic
257 protocols, but usually not for key generation etc.
258
Victor Stinner99c8b162011-05-24 12:05:19 +0200259 .. versionadded:: 3.3
260
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000261.. function:: RAND_status()
262
Georg Brandl7f01a132009-09-16 15:58:14 +0000263 Returns True if the SSL pseudo-random number generator has been seeded with
264 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
265 and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
266 number generator.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000267
268.. function:: RAND_egd(path)
269
Victor Stinner99c8b162011-05-24 12:05:19 +0200270 If you are running an entropy-gathering daemon (EGD) somewhere, and *path*
Georg Brandl7f01a132009-09-16 15:58:14 +0000271 is the pathname of a socket connection open to it, this will read 256 bytes
272 of randomness from the socket, and add it to the SSL pseudo-random number
273 generator to increase the security of generated secret keys. This is
274 typically only necessary on systems without better sources of randomness.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000275
Georg Brandl7f01a132009-09-16 15:58:14 +0000276 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
277 of entropy-gathering daemons.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000278
279.. function:: RAND_add(bytes, entropy)
280
Victor Stinner99c8b162011-05-24 12:05:19 +0200281 Mixes the given *bytes* into the SSL pseudo-random number generator. The
282 parameter *entropy* (a float) is a lower bound on the entropy contained in
Georg Brandl7f01a132009-09-16 15:58:14 +0000283 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
284 information on sources of entropy.
Thomas Woutersed03b412007-08-28 21:37:11 +0000285
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000286Certificate handling
287^^^^^^^^^^^^^^^^^^^^
288
289.. function:: match_hostname(cert, hostname)
290
291 Verify that *cert* (in decoded format as returned by
292 :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules
293 applied are those for checking the identity of HTTPS servers as outlined
Georg Brandl72c98d32013-10-27 07:16:53 +0100294 in :rfc:`2818` and :rfc:`6125`, except that IP addresses are not currently
295 supported. In addition to HTTPS, this function should be suitable for
296 checking the identity of servers in various SSL-based protocols such as
297 FTPS, IMAPS, POPS and others.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000298
299 :exc:`CertificateError` is raised on failure. On success, the function
300 returns nothing::
301
302 >>> cert = {'subject': ((('commonName', 'example.com'),),)}
303 >>> ssl.match_hostname(cert, "example.com")
304 >>> ssl.match_hostname(cert, "example.org")
305 Traceback (most recent call last):
306 File "<stdin>", line 1, in <module>
307 File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
308 ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'
309
310 .. versionadded:: 3.2
311
Georg Brandl72c98d32013-10-27 07:16:53 +0100312 .. versionchanged:: 3.3.3
313 The function now follows :rfc:`6125`, section 6.4.3 and does neither
314 match multiple wildcards (e.g. ``*.*.com`` or ``*a*.example.org``) nor
315 a wildcard inside an internationalized domain names (IDN) fragment.
316 IDN A-labels such as ``www*.xn--pthon-kva.org`` are still supported,
317 but ``x*.python.org`` no longer matches ``xn--tda.python.org``.
318
Thomas Woutersed03b412007-08-28 21:37:11 +0000319.. function:: cert_time_to_seconds(timestring)
320
Georg Brandl7f01a132009-09-16 15:58:14 +0000321 Returns a floating-point value containing a normal seconds-after-the-epoch
322 time value, given the time-string representing the "notBefore" or "notAfter"
323 date from a certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000324
325 Here's an example::
326
327 >>> import ssl
328 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
329 1178694000.0
330 >>> import time
331 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
332 'Wed May 9 00:00:00 2007'
Thomas Woutersed03b412007-08-28 21:37:11 +0000333
Georg Brandl7f01a132009-09-16 15:58:14 +0000334.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000335
Georg Brandl7f01a132009-09-16 15:58:14 +0000336 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
337 *port-number*) pair, fetches the server's certificate, and returns it as a
338 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
339 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
340 specified, it should be a file containing a list of root certificates, the
341 same format as used for the same parameter in :func:`wrap_socket`. The call
342 will attempt to validate the server certificate against that set of root
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000343 certificates, and will fail if the validation attempt fails.
344
Antoine Pitrou15399c32011-04-28 19:23:55 +0200345 .. versionchanged:: 3.3
346 This function is now IPv6-compatible.
347
Georg Brandl7f01a132009-09-16 15:58:14 +0000348.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000349
350 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
351 string version of the same certificate.
352
Georg Brandl7f01a132009-09-16 15:58:14 +0000353.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000354
Georg Brandl7f01a132009-09-16 15:58:14 +0000355 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
356 bytes for that same certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000357
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000358Constants
359^^^^^^^^^
360
Thomas Woutersed03b412007-08-28 21:37:11 +0000361.. data:: CERT_NONE
362
Antoine Pitrou152efa22010-05-16 18:19:27 +0000363 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
364 parameter to :func:`wrap_socket`. In this mode (the default), no
365 certificates will be required from the other side of the socket connection.
366 If a certificate is received from the other end, no attempt to validate it
367 is made.
368
369 See the discussion of :ref:`ssl-security` below.
Thomas Woutersed03b412007-08-28 21:37:11 +0000370
371.. data:: CERT_OPTIONAL
372
Antoine Pitrou152efa22010-05-16 18:19:27 +0000373 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
374 parameter to :func:`wrap_socket`. In this mode no certificates will be
375 required from the other side of the socket connection; but if they
376 are provided, validation will be attempted and an :class:`SSLError`
377 will be raised on failure.
378
379 Use of this setting requires a valid set of CA certificates to
380 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
381 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000382
383.. data:: CERT_REQUIRED
384
Antoine Pitrou152efa22010-05-16 18:19:27 +0000385 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
386 parameter to :func:`wrap_socket`. In this mode, certificates are
387 required from the other side of the socket connection; an :class:`SSLError`
388 will be raised if no certificate is provided, or if its validation fails.
389
390 Use of this setting requires a valid set of CA certificates to
391 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
392 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000393
394.. data:: PROTOCOL_SSLv2
395
396 Selects SSL version 2 as the channel encryption protocol.
397
Victor Stinner3de49192011-05-09 00:42:58 +0200398 This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
399 flag.
400
Antoine Pitrou8eac60d2010-05-16 14:19:41 +0000401 .. warning::
402
403 SSL version 2 is insecure. Its use is highly discouraged.
404
Thomas Woutersed03b412007-08-28 21:37:11 +0000405.. data:: PROTOCOL_SSLv23
406
Georg Brandl7f01a132009-09-16 15:58:14 +0000407 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
408 setting to use with servers for maximum compatibility with the other end of
409 an SSL connection, but it may cause the specific ciphers chosen for the
410 encryption to be of fairly low quality.
Thomas Woutersed03b412007-08-28 21:37:11 +0000411
412.. data:: PROTOCOL_SSLv3
413
Georg Brandl7f01a132009-09-16 15:58:14 +0000414 Selects SSL version 3 as the channel encryption protocol. For clients, this
415 is the maximally compatible SSL variant.
Thomas Woutersed03b412007-08-28 21:37:11 +0000416
417.. data:: PROTOCOL_TLSv1
418
Georg Brandl7f01a132009-09-16 15:58:14 +0000419 Selects TLS version 1 as the channel encryption protocol. This is the most
420 modern version, and probably the best choice for maximum protection, if both
421 sides can speak it.
Thomas Woutersed03b412007-08-28 21:37:11 +0000422
Antoine Pitroub5218772010-05-21 09:56:06 +0000423.. data:: OP_ALL
424
425 Enables workarounds for various bugs present in other SSL implementations.
Antoine Pitrou9f6b02e2012-01-27 10:02:55 +0100426 This option is set by default. It does not necessarily set the same
427 flags as OpenSSL's ``SSL_OP_ALL`` constant.
Antoine Pitroub5218772010-05-21 09:56:06 +0000428
429 .. versionadded:: 3.2
430
431.. data:: OP_NO_SSLv2
432
433 Prevents an SSLv2 connection. This option is only applicable in
434 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
435 choosing SSLv2 as the protocol version.
436
437 .. versionadded:: 3.2
438
439.. data:: OP_NO_SSLv3
440
441 Prevents an SSLv3 connection. This option is only applicable in
442 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
443 choosing SSLv3 as the protocol version.
444
445 .. versionadded:: 3.2
446
447.. data:: OP_NO_TLSv1
448
449 Prevents a TLSv1 connection. This option is only applicable in
450 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
451 choosing TLSv1 as the protocol version.
452
453 .. versionadded:: 3.2
454
Antoine Pitrou6db49442011-12-19 13:27:11 +0100455.. data:: OP_CIPHER_SERVER_PREFERENCE
456
457 Use the server's cipher ordering preference, rather than the client's.
458 This option has no effect on client sockets and SSLv2 server sockets.
459
460 .. versionadded:: 3.3
461
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100462.. data:: OP_SINGLE_DH_USE
463
464 Prevents re-use of the same DH key for distinct SSL sessions. This
465 improves forward secrecy but requires more computational resources.
466 This option only applies to server sockets.
467
468 .. versionadded:: 3.3
469
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100470.. data:: OP_SINGLE_ECDH_USE
471
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100472 Prevents re-use of the same ECDH key for distinct SSL sessions. This
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100473 improves forward secrecy but requires more computational resources.
474 This option only applies to server sockets.
475
476 .. versionadded:: 3.3
477
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100478.. data:: OP_NO_COMPRESSION
479
480 Disable compression on the SSL channel. This is useful if the application
481 protocol supports its own compression scheme.
482
483 This option is only available with OpenSSL 1.0.0 and later.
484
485 .. versionadded:: 3.3
486
Antoine Pitrou501da612011-12-21 09:27:41 +0100487.. data:: HAS_ECDH
488
489 Whether the OpenSSL library has built-in support for Elliptic Curve-based
490 Diffie-Hellman key exchange. This should be true unless the feature was
491 explicitly disabled by the distributor.
492
493 .. versionadded:: 3.3
494
Antoine Pitroud5323212010-10-22 18:19:07 +0000495.. data:: HAS_SNI
496
497 Whether the OpenSSL library has built-in support for the *Server Name
498 Indication* extension to the SSLv3 and TLSv1 protocols (as defined in
499 :rfc:`4366`). When true, you can use the *server_hostname* argument to
500 :meth:`SSLContext.wrap_socket`.
501
502 .. versionadded:: 3.2
503
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100504.. data:: HAS_NPN
505
506 Whether the OpenSSL library has built-in support for *Next Protocol
507 Negotiation* as described in the `NPN draft specification
508 <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. When true,
509 you can use the :meth:`SSLContext.set_npn_protocols` method to advertise
510 which protocols you want to support.
511
512 .. versionadded:: 3.3
513
Antoine Pitroud6494802011-07-21 01:11:30 +0200514.. data:: CHANNEL_BINDING_TYPES
515
516 List of supported TLS channel binding types. Strings in this list
517 can be used as arguments to :meth:`SSLSocket.get_channel_binding`.
518
519 .. versionadded:: 3.3
520
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000521.. data:: OPENSSL_VERSION
522
523 The version string of the OpenSSL library loaded by the interpreter::
524
525 >>> ssl.OPENSSL_VERSION
526 'OpenSSL 0.9.8k 25 Mar 2009'
527
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000528 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000529
530.. data:: OPENSSL_VERSION_INFO
531
532 A tuple of five integers representing version information about the
533 OpenSSL library::
534
535 >>> ssl.OPENSSL_VERSION_INFO
536 (0, 9, 8, 11, 15)
537
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000538 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000539
540.. data:: OPENSSL_VERSION_NUMBER
541
542 The raw version number of the OpenSSL library, as a single integer::
543
544 >>> ssl.OPENSSL_VERSION_NUMBER
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000545 9470143
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000546 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000547 '0x9080bf'
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000548
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000549 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000550
Thomas Woutersed03b412007-08-28 21:37:11 +0000551
Antoine Pitrou152efa22010-05-16 18:19:27 +0000552SSL Sockets
553-----------
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000554
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000555SSL sockets provide the following methods of :ref:`socket-objects`:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000556
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000557- :meth:`~socket.socket.accept()`
558- :meth:`~socket.socket.bind()`
559- :meth:`~socket.socket.close()`
560- :meth:`~socket.socket.connect()`
561- :meth:`~socket.socket.detach()`
562- :meth:`~socket.socket.fileno()`
563- :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`
564- :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`
565- :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`,
566 :meth:`~socket.socket.setblocking()`
567- :meth:`~socket.socket.listen()`
568- :meth:`~socket.socket.makefile()`
569- :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()`
570 (but passing a non-zero ``flags`` argument is not allowed)
571- :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with
572 the same limitation)
573- :meth:`~socket.socket.shutdown()`
574
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +0200575However, since the SSL (and TLS) protocol has its own framing atop
576of TCP, the SSL sockets abstraction can, in certain respects, diverge from
577the specification of normal, OS-level sockets. See especially the
578:ref:`notes on non-blocking sockets <ssl-nonblocking>`.
579
580SSL sockets also have the following additional methods and attributes:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000581
Bill Janssen48dc27c2007-12-05 03:38:10 +0000582.. method:: SSLSocket.do_handshake()
583
Antoine Pitroub3593ca2011-07-11 01:39:19 +0200584 Perform the SSL setup handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000585
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000586.. method:: SSLSocket.getpeercert(binary_form=False)
587
Georg Brandl7f01a132009-09-16 15:58:14 +0000588 If there is no certificate for the peer on the other end of the connection,
589 returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000590
Antoine Pitroud34941a2013-04-16 20:27:17 +0200591 If the ``binary_form`` parameter is :const:`False`, and a certificate was
Georg Brandl7f01a132009-09-16 15:58:14 +0000592 received from the peer, this method returns a :class:`dict` instance. If the
593 certificate was not validated, the dict is empty. If the certificate was
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200594 validated, it returns a dict with several keys, amongst them ``subject``
595 (the principal for which the certificate was issued) and ``issuer``
596 (the principal issuing the certificate). If a certificate contains an
597 instance of the *Subject Alternative Name* extension (see :rfc:`3280`),
598 there will also be a ``subjectAltName`` key in the dictionary.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000599
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200600 The ``subject`` and ``issuer`` fields are tuples containing the sequence
601 of relative distinguished names (RDNs) given in the certificate's data
602 structure for the respective fields, and each RDN is a sequence of
603 name-value pairs. Here is a real-world example::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200605 {'issuer': ((('countryName', 'IL'),),
606 (('organizationName', 'StartCom Ltd.'),),
607 (('organizationalUnitName',
608 'Secure Digital Certificate Signing'),),
609 (('commonName',
610 'StartCom Class 2 Primary Intermediate Server CA'),)),
611 'notAfter': 'Nov 22 08:15:19 2013 GMT',
612 'notBefore': 'Nov 21 03:09:52 2011 GMT',
613 'serialNumber': '95F0',
614 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
615 (('countryName', 'US'),),
616 (('stateOrProvinceName', 'California'),),
617 (('localityName', 'San Francisco'),),
618 (('organizationName', 'Electronic Frontier Foundation, Inc.'),),
619 (('commonName', '*.eff.org'),),
620 (('emailAddress', 'hostmaster@eff.org'),)),
621 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
622 'version': 3}
623
624 .. note::
625 To validate a certificate for a particular service, you can use the
626 :func:`match_hostname` function.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000627
Georg Brandl7f01a132009-09-16 15:58:14 +0000628 If the ``binary_form`` parameter is :const:`True`, and a certificate was
629 provided, this method returns the DER-encoded form of the entire certificate
630 as a sequence of bytes, or :const:`None` if the peer did not provide a
Antoine Pitroud34941a2013-04-16 20:27:17 +0200631 certificate. Whether the peer provides a certificate depends on the SSL
632 socket's role:
633
634 * for a client SSL socket, the server will always provide a certificate,
635 regardless of whether validation was required;
636
637 * for a server SSL socket, the client will only provide a certificate
638 when requested by the server; therefore :meth:`getpeercert` will return
639 :const:`None` if you used :const:`CERT_NONE` (rather than
640 :const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000641
Antoine Pitroufb046912010-11-09 20:21:19 +0000642 .. versionchanged:: 3.2
643 The returned dictionary includes additional items such as ``issuer``
644 and ``notBefore``.
645
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000646.. method:: SSLSocket.cipher()
647
Georg Brandl7f01a132009-09-16 15:58:14 +0000648 Returns a three-value tuple containing the name of the cipher being used, the
649 version of the SSL protocol that defines its use, and the number of secret
650 bits being used. If no connection has been established, returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000651
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100652.. method:: SSLSocket.compression()
653
654 Return the compression algorithm being used as a string, or ``None``
655 if the connection isn't compressed.
656
657 If the higher-level protocol supports its own compression mechanism,
658 you can use :data:`OP_NO_COMPRESSION` to disable SSL-level compression.
659
660 .. versionadded:: 3.3
661
Antoine Pitroud6494802011-07-21 01:11:30 +0200662.. method:: SSLSocket.get_channel_binding(cb_type="tls-unique")
663
664 Get channel binding data for current connection, as a bytes object. Returns
665 ``None`` if not connected or the handshake has not been completed.
666
667 The *cb_type* parameter allow selection of the desired channel binding
668 type. Valid channel binding types are listed in the
669 :data:`CHANNEL_BINDING_TYPES` list. Currently only the 'tls-unique' channel
670 binding, defined by :rfc:`5929`, is supported. :exc:`ValueError` will be
671 raised if an unsupported channel binding type is requested.
672
673 .. versionadded:: 3.3
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000674
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100675.. method:: SSLSocket.selected_npn_protocol()
676
677 Returns the protocol that was selected during the TLS/SSL handshake. If
678 :meth:`SSLContext.set_npn_protocols` was not called, or if the other party
679 does not support NPN, or if the handshake has not yet happened, this will
680 return ``None``.
681
682 .. versionadded:: 3.3
683
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000684.. method:: SSLSocket.unwrap()
685
Georg Brandl7f01a132009-09-16 15:58:14 +0000686 Performs the SSL shutdown handshake, which removes the TLS layer from the
687 underlying socket, and returns the underlying socket object. This can be
688 used to go from encrypted operation over a connection to unencrypted. The
689 returned socket should always be used for further communication with the
690 other side of the connection, rather than the original socket.
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000691
Antoine Pitrouec883db2010-05-24 21:20:20 +0000692.. attribute:: SSLSocket.context
693
694 The :class:`SSLContext` object this SSL socket is tied to. If the SSL
695 socket was created using the top-level :func:`wrap_socket` function
696 (rather than :meth:`SSLContext.wrap_socket`), this is a custom context
697 object created for this SSL socket.
698
699 .. versionadded:: 3.2
700
701
Antoine Pitrou152efa22010-05-16 18:19:27 +0000702SSL Contexts
703------------
704
Antoine Pitroucafaad42010-05-24 15:58:43 +0000705.. versionadded:: 3.2
706
Antoine Pitroub0182c82010-10-12 20:09:02 +0000707An SSL context holds various data longer-lived than single SSL connections,
708such as SSL configuration options, certificate(s) and private key(s).
709It also manages a cache of SSL sessions for server-side sockets, in order
710to speed up repeated connections from the same clients.
711
Antoine Pitrou152efa22010-05-16 18:19:27 +0000712.. class:: SSLContext(protocol)
713
Antoine Pitroub0182c82010-10-12 20:09:02 +0000714 Create a new SSL context. You must pass *protocol* which must be one
715 of the ``PROTOCOL_*`` constants defined in this module.
716 :data:`PROTOCOL_SSLv23` is recommended for maximum interoperability.
717
Antoine Pitrou152efa22010-05-16 18:19:27 +0000718
719:class:`SSLContext` objects have the following methods and attributes:
720
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200721.. method:: SSLContext.load_cert_chain(certfile, keyfile=None, password=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000722
723 Load a private key and the corresponding certificate. The *certfile*
724 string must be the path to a single file in PEM format containing the
725 certificate as well as any number of CA certificates needed to establish
726 the certificate's authenticity. The *keyfile* string, if present, must
727 point to a file containing the private key in. Otherwise the private
728 key will be taken from *certfile* as well. See the discussion of
729 :ref:`ssl-certificates` for more information on how the certificate
730 is stored in the *certfile*.
731
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200732 The *password* argument may be a function to call to get the password for
733 decrypting the private key. It will only be called if the private key is
734 encrypted and a password is necessary. It will be called with no arguments,
735 and it should return a string, bytes, or bytearray. If the return value is
736 a string it will be encoded as UTF-8 before using it to decrypt the key.
737 Alternatively a string, bytes, or bytearray value may be supplied directly
738 as the *password* argument. It will be ignored if the private key is not
739 encrypted and no password is needed.
740
741 If the *password* argument is not specified and a password is required,
742 OpenSSL's built-in password prompting mechanism will be used to
743 interactively prompt the user for a password.
744
Antoine Pitrou152efa22010-05-16 18:19:27 +0000745 An :class:`SSLError` is raised if the private key doesn't
746 match with the certificate.
747
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200748 .. versionchanged:: 3.3
749 New optional argument *password*.
750
Antoine Pitrou152efa22010-05-16 18:19:27 +0000751.. method:: SSLContext.load_verify_locations(cafile=None, capath=None)
752
753 Load a set of "certification authority" (CA) certificates used to validate
754 other peers' certificates when :data:`verify_mode` is other than
755 :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified.
756
757 The *cafile* string, if present, is the path to a file of concatenated
758 CA certificates in PEM format. See the discussion of
759 :ref:`ssl-certificates` for more information about how to arrange the
760 certificates in this file.
761
762 The *capath* string, if present, is
763 the path to a directory containing several CA certificates in PEM format,
764 following an `OpenSSL specific layout
765 <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
766
Antoine Pitrou664c2d12010-11-17 20:29:42 +0000767.. method:: SSLContext.set_default_verify_paths()
768
769 Load a set of default "certification authority" (CA) certificates from
770 a filesystem path defined when building the OpenSSL library. Unfortunately,
771 there's no easy way to know whether this method succeeds: no error is
772 returned if no certificates are to be found. When the OpenSSL library is
773 provided as part of the operating system, though, it is likely to be
774 configured properly.
775
Antoine Pitrou152efa22010-05-16 18:19:27 +0000776.. method:: SSLContext.set_ciphers(ciphers)
777
778 Set the available ciphers for sockets created with this context.
779 It should be a string in the `OpenSSL cipher list format
780 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
781 If no cipher can be selected (because compile-time options or other
782 configuration forbids use of all the specified ciphers), an
783 :class:`SSLError` will be raised.
784
785 .. note::
786 when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
787 give the currently selected cipher.
788
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100789.. method:: SSLContext.set_npn_protocols(protocols)
790
R David Murrayc7f75792013-06-26 15:11:12 -0400791 Specify which protocols the socket should advertise during the SSL/TLS
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100792 handshake. It should be a list of strings, like ``['http/1.1', 'spdy/2']``,
793 ordered by preference. The selection of a protocol will happen during the
794 handshake, and will play out according to the `NPN draft specification
795 <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. After a
796 successful handshake, the :meth:`SSLSocket.selected_npn_protocol` method will
797 return the agreed-upon protocol.
798
799 This method will raise :exc:`NotImplementedError` if :data:`HAS_NPN` is
800 False.
801
802 .. versionadded:: 3.3
803
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100804.. method:: SSLContext.load_dh_params(dhfile)
805
806 Load the key generation parameters for Diffie-Helman (DH) key exchange.
807 Using DH key exchange improves forward secrecy at the expense of
808 computational resources (both on the server and on the client).
809 The *dhfile* parameter should be the path to a file containing DH
810 parameters in PEM format.
811
812 This setting doesn't apply to client sockets. You can also use the
813 :data:`OP_SINGLE_DH_USE` option to further improve security.
814
815 .. versionadded:: 3.3
816
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100817.. method:: SSLContext.set_ecdh_curve(curve_name)
818
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100819 Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key
820 exchange. ECDH is significantly faster than regular DH while arguably
821 as secure. The *curve_name* parameter should be a string describing
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100822 a well-known elliptic curve, for example ``prime256v1`` for a widely
823 supported curve.
824
825 This setting doesn't apply to client sockets. You can also use the
826 :data:`OP_SINGLE_ECDH_USE` option to further improve security.
827
Antoine Pitrou501da612011-12-21 09:27:41 +0100828 This method is not available if :data:`HAS_ECDH` is False.
829
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100830 .. versionadded:: 3.3
831
832 .. seealso::
833 `SSL/TLS & Perfect Forward Secrecy <http://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy.html>`_
834 Vincent Bernat.
835
Antoine Pitroud5323212010-10-22 18:19:07 +0000836.. method:: SSLContext.wrap_socket(sock, server_side=False, \
837 do_handshake_on_connect=True, suppress_ragged_eofs=True, \
838 server_hostname=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000839
840 Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
841 object. The SSL socket is tied to the context, its settings and
842 certificates. The parameters *server_side*, *do_handshake_on_connect*
843 and *suppress_ragged_eofs* have the same meaning as in the top-level
844 :func:`wrap_socket` function.
845
Antoine Pitroud5323212010-10-22 18:19:07 +0000846 On client connections, the optional parameter *server_hostname* specifies
847 the hostname of the service which we are connecting to. This allows a
848 single server to host multiple SSL-based services with distinct certificates,
849 quite similarly to HTTP virtual hosts. Specifying *server_hostname*
850 will raise a :exc:`ValueError` if the OpenSSL library doesn't have support
851 for it (that is, if :data:`HAS_SNI` is :const:`False`). Specifying
852 *server_hostname* will also raise a :exc:`ValueError` if *server_side*
853 is true.
854
Antoine Pitroub0182c82010-10-12 20:09:02 +0000855.. method:: SSLContext.session_stats()
856
857 Get statistics about the SSL sessions created or managed by this context.
858 A dictionary is returned which maps the names of each `piece of information
859 <http://www.openssl.org/docs/ssl/SSL_CTX_sess_number.html>`_ to their
860 numeric values. For example, here is the total number of hits and misses
861 in the session cache since the context was created::
862
863 >>> stats = context.session_stats()
864 >>> stats['hits'], stats['misses']
865 (0, 0)
866
Antoine Pitroub5218772010-05-21 09:56:06 +0000867.. attribute:: SSLContext.options
868
869 An integer representing the set of SSL options enabled on this context.
870 The default value is :data:`OP_ALL`, but you can specify other options
871 such as :data:`OP_NO_SSLv2` by ORing them together.
872
873 .. note::
874 With versions of OpenSSL older than 0.9.8m, it is only possible
875 to set options, not to clear them. Attempting to clear an option
876 (by resetting the corresponding bits) will raise a ``ValueError``.
877
Antoine Pitrou152efa22010-05-16 18:19:27 +0000878.. attribute:: SSLContext.protocol
879
880 The protocol version chosen when constructing the context. This attribute
881 is read-only.
882
883.. attribute:: SSLContext.verify_mode
884
885 Whether to try to verify other peers' certificates and how to behave
886 if verification fails. This attribute must be one of
887 :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.
888
889
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890.. index:: single: certificates
891
892.. index:: single: X509 certificate
893
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000894.. _ssl-certificates:
895
Thomas Woutersed03b412007-08-28 21:37:11 +0000896Certificates
897------------
898
Georg Brandl7f01a132009-09-16 15:58:14 +0000899Certificates in general are part of a public-key / private-key system. In this
900system, each *principal*, (which may be a machine, or a person, or an
901organization) is assigned a unique two-part encryption key. One part of the key
902is public, and is called the *public key*; the other part is kept secret, and is
903called the *private key*. The two parts are related, in that if you encrypt a
904message with one of the parts, you can decrypt it with the other part, and
905**only** with the other part.
Thomas Woutersed03b412007-08-28 21:37:11 +0000906
Georg Brandl7f01a132009-09-16 15:58:14 +0000907A certificate contains information about two principals. It contains the name
908of a *subject*, and the subject's public key. It also contains a statement by a
909second principal, the *issuer*, that the subject is who he claims to be, and
910that this is indeed the subject's public key. The issuer's statement is signed
911with the issuer's private key, which only the issuer knows. However, anyone can
912verify the issuer's statement by finding the issuer's public key, decrypting the
913statement with it, and comparing it to the other information in the certificate.
914The certificate also contains information about the time period over which it is
915valid. This is expressed as two fields, called "notBefore" and "notAfter".
Thomas Woutersed03b412007-08-28 21:37:11 +0000916
Georg Brandl7f01a132009-09-16 15:58:14 +0000917In the Python use of certificates, a client or server can use a certificate to
918prove who they are. The other side of a network connection can also be required
919to produce a certificate, and that certificate can be validated to the
920satisfaction of the client or server that requires such validation. The
921connection attempt can be set to raise an exception if the validation fails.
922Validation is done automatically, by the underlying OpenSSL framework; the
923application need not concern itself with its mechanics. But the application
924does usually need to provide sets of certificates to allow this process to take
925place.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000926
Georg Brandl7f01a132009-09-16 15:58:14 +0000927Python uses files to contain certificates. They should be formatted as "PEM"
928(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
929and a footer line::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000930
931 -----BEGIN CERTIFICATE-----
932 ... (certificate in base64 PEM encoding) ...
933 -----END CERTIFICATE-----
934
Antoine Pitrou152efa22010-05-16 18:19:27 +0000935Certificate chains
936^^^^^^^^^^^^^^^^^^
937
Georg Brandl7f01a132009-09-16 15:58:14 +0000938The Python files which contain certificates can contain a sequence of
939certificates, sometimes called a *certificate chain*. This chain should start
940with the specific certificate for the principal who "is" the client or server,
941and then the certificate for the issuer of that certificate, and then the
942certificate for the issuer of *that* certificate, and so on up the chain till
943you get to a certificate which is *self-signed*, that is, a certificate which
944has the same subject and issuer, sometimes called a *root certificate*. The
945certificates should just be concatenated together in the certificate file. For
946example, suppose we had a three certificate chain, from our server certificate
947to the certificate of the certification authority that signed our server
948certificate, to the root certificate of the agency which issued the
949certification authority's certificate::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000950
951 -----BEGIN CERTIFICATE-----
952 ... (certificate for your server)...
953 -----END CERTIFICATE-----
954 -----BEGIN CERTIFICATE-----
955 ... (the certificate for the CA)...
956 -----END CERTIFICATE-----
957 -----BEGIN CERTIFICATE-----
958 ... (the root certificate for the CA's issuer)...
959 -----END CERTIFICATE-----
960
Antoine Pitrou152efa22010-05-16 18:19:27 +0000961CA certificates
962^^^^^^^^^^^^^^^
963
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000964If you are going to require validation of the other side of the connection's
965certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandl7f01a132009-09-16 15:58:14 +0000966chains for each issuer you are willing to trust. Again, this file just contains
967these chains concatenated together. For validation, Python will use the first
968chain it finds in the file which matches. Some "standard" root certificates are
969available from various certification authorities: `CACert.org
970<http://www.cacert.org/index.php?id=3>`_, `Thawte
971<http://www.thawte.com/roots/>`_, `Verisign
972<http://www.verisign.com/support/roots.html>`_, `Positive SSL
973<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
974(used by python.org), `Equifax and GeoTrust
975<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000976
Georg Brandl7f01a132009-09-16 15:58:14 +0000977In general, if you are using SSL3 or TLS1, you don't need to put the full chain
978in your "CA certs" file; you only need the root certificates, and the remote
979peer is supposed to furnish the other certificates necessary to chain from its
980certificate to a root certificate. See :rfc:`4158` for more discussion of the
981way in which certification chains can be built.
Thomas Woutersed03b412007-08-28 21:37:11 +0000982
Antoine Pitrou152efa22010-05-16 18:19:27 +0000983Combined key and certificate
984^^^^^^^^^^^^^^^^^^^^^^^^^^^^
985
986Often the private key is stored in the same file as the certificate; in this
987case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain`
988and :func:`wrap_socket` needs to be passed. If the private key is stored
989with the certificate, it should come before the first certificate in
990the certificate chain::
991
992 -----BEGIN RSA PRIVATE KEY-----
993 ... (private key in base64 encoding) ...
994 -----END RSA PRIVATE KEY-----
995 -----BEGIN CERTIFICATE-----
996 ... (certificate in base64 PEM encoding) ...
997 -----END CERTIFICATE-----
998
999Self-signed certificates
1000^^^^^^^^^^^^^^^^^^^^^^^^
1001
Georg Brandl7f01a132009-09-16 15:58:14 +00001002If you are going to create a server that provides SSL-encrypted connection
1003services, you will need to acquire a certificate for that service. There are
1004many ways of acquiring appropriate certificates, such as buying one from a
1005certification authority. Another common practice is to generate a self-signed
1006certificate. The simplest way to do this is with the OpenSSL package, using
1007something like the following::
Thomas Woutersed03b412007-08-28 21:37:11 +00001008
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001009 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
1010 Generating a 1024 bit RSA private key
1011 .......++++++
1012 .............................++++++
1013 writing new private key to 'cert.pem'
1014 -----
1015 You are about to be asked to enter information that will be incorporated
1016 into your certificate request.
1017 What you are about to enter is what is called a Distinguished Name or a DN.
1018 There are quite a few fields but you can leave some blank
1019 For some fields there will be a default value,
1020 If you enter '.', the field will be left blank.
1021 -----
1022 Country Name (2 letter code) [AU]:US
1023 State or Province Name (full name) [Some-State]:MyState
1024 Locality Name (eg, city) []:Some City
1025 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
1026 Organizational Unit Name (eg, section) []:My Group
1027 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
1028 Email Address []:ops@myserver.mygroup.myorganization.com
1029 %
Thomas Woutersed03b412007-08-28 21:37:11 +00001030
Georg Brandl7f01a132009-09-16 15:58:14 +00001031The disadvantage of a self-signed certificate is that it is its own root
1032certificate, and no one else will have it in their cache of known (and trusted)
1033root certificates.
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001034
1035
Thomas Woutersed03b412007-08-28 21:37:11 +00001036Examples
1037--------
1038
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001039Testing for SSL support
1040^^^^^^^^^^^^^^^^^^^^^^^
1041
Georg Brandl7f01a132009-09-16 15:58:14 +00001042To test for the presence of SSL support in a Python installation, user code
1043should use the following idiom::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001044
1045 try:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001046 import ssl
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001047 except ImportError:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001048 pass
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001049 else:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001050 ... # do something that requires SSL support
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001051
1052Client-side operation
1053^^^^^^^^^^^^^^^^^^^^^
1054
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001055This example connects to an SSL server and prints the server's certificate::
Thomas Woutersed03b412007-08-28 21:37:11 +00001056
1057 import socket, ssl, pprint
1058
1059 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001060 # require a certificate from the server
1061 ssl_sock = ssl.wrap_socket(s,
1062 ca_certs="/etc/ca_certs_file",
1063 cert_reqs=ssl.CERT_REQUIRED)
Thomas Woutersed03b412007-08-28 21:37:11 +00001064 ssl_sock.connect(('www.verisign.com', 443))
1065
Georg Brandl6911e3c2007-09-04 07:15:32 +00001066 pprint.pprint(ssl_sock.getpeercert())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001067 # note that closing the SSLSocket will also close the underlying socket
Thomas Woutersed03b412007-08-28 21:37:11 +00001068 ssl_sock.close()
1069
Antoine Pitrou441ae042012-01-06 20:06:15 +01001070As of January 6, 2012, the certificate printed by this program looks like
Georg Brandl7f01a132009-09-16 15:58:14 +00001071this::
Thomas Woutersed03b412007-08-28 21:37:11 +00001072
Antoine Pitrou441ae042012-01-06 20:06:15 +01001073 {'issuer': ((('countryName', 'US'),),
1074 (('organizationName', 'VeriSign, Inc.'),),
1075 (('organizationalUnitName', 'VeriSign Trust Network'),),
1076 (('organizationalUnitName',
1077 'Terms of use at https://www.verisign.com/rpa (c)06'),),
1078 (('commonName',
1079 'VeriSign Class 3 Extended Validation SSL SGC CA'),)),
1080 'notAfter': 'May 25 23:59:59 2012 GMT',
1081 'notBefore': 'May 26 00:00:00 2010 GMT',
1082 'serialNumber': '53D2BEF924A7245E83CA01E46CAA2477',
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001083 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
1084 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
1085 (('businessCategory', 'V1.0, Clause 5.(b)'),),
1086 (('serialNumber', '2497886'),),
1087 (('countryName', 'US'),),
1088 (('postalCode', '94043'),),
1089 (('stateOrProvinceName', 'California'),),
1090 (('localityName', 'Mountain View'),),
1091 (('streetAddress', '487 East Middlefield Road'),),
1092 (('organizationName', 'VeriSign, Inc.'),),
1093 (('organizationalUnitName', ' Production Security Services'),),
Antoine Pitrou441ae042012-01-06 20:06:15 +01001094 (('commonName', 'www.verisign.com'),)),
1095 'subjectAltName': (('DNS', 'www.verisign.com'),
1096 ('DNS', 'verisign.com'),
1097 ('DNS', 'www.verisign.net'),
1098 ('DNS', 'verisign.net'),
1099 ('DNS', 'www.verisign.mobi'),
1100 ('DNS', 'verisign.mobi'),
1101 ('DNS', 'www.verisign.eu'),
1102 ('DNS', 'verisign.eu')),
1103 'version': 3}
Thomas Woutersed03b412007-08-28 21:37:11 +00001104
Antoine Pitrou152efa22010-05-16 18:19:27 +00001105This other example first creates an SSL context, instructs it to verify
1106certificates sent by peers, and feeds it a set of recognized certificate
1107authorities (CA)::
1108
1109 >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001110 >>> context.verify_mode = ssl.CERT_REQUIRED
Antoine Pitrou152efa22010-05-16 18:19:27 +00001111 >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
1112
1113(it is assumed your operating system places a bundle of all CA certificates
1114in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have
1115to adjust the location)
1116
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001117When you use the context to connect to a server, :const:`CERT_REQUIRED`
Antoine Pitrou152efa22010-05-16 18:19:27 +00001118validates the server certificate: it ensures that the server certificate
1119was signed with one of the CA certificates, and checks the signature for
1120correctness::
1121
1122 >>> conn = context.wrap_socket(socket.socket(socket.AF_INET))
1123 >>> conn.connect(("linuxfr.org", 443))
1124
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001125You should then fetch the certificate and check its fields for conformity::
Antoine Pitrou152efa22010-05-16 18:19:27 +00001126
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001127 >>> cert = conn.getpeercert()
1128 >>> ssl.match_hostname(cert, "linuxfr.org")
1129
1130Visual inspection shows that the certificate does identify the desired service
1131(that is, the HTTPS host ``linuxfr.org``)::
1132
1133 >>> pprint.pprint(cert)
Antoine Pitrou441ae042012-01-06 20:06:15 +01001134 {'issuer': ((('organizationName', 'CAcert Inc.'),),
1135 (('organizationalUnitName', 'http://www.CAcert.org'),),
1136 (('commonName', 'CAcert Class 3 Root'),)),
1137 'notAfter': 'Jun 7 21:02:24 2013 GMT',
1138 'notBefore': 'Jun 8 21:02:24 2011 GMT',
1139 'serialNumber': 'D3E9',
Antoine Pitrou152efa22010-05-16 18:19:27 +00001140 'subject': ((('commonName', 'linuxfr.org'),),),
Antoine Pitrou441ae042012-01-06 20:06:15 +01001141 'subjectAltName': (('DNS', 'linuxfr.org'),
1142 ('othername', '<unsupported>'),
1143 ('DNS', 'linuxfr.org'),
1144 ('othername', '<unsupported>'),
1145 ('DNS', 'dev.linuxfr.org'),
1146 ('othername', '<unsupported>'),
1147 ('DNS', 'prod.linuxfr.org'),
1148 ('othername', '<unsupported>'),
1149 ('DNS', 'alpha.linuxfr.org'),
1150 ('othername', '<unsupported>'),
1151 ('DNS', '*.linuxfr.org'),
1152 ('othername', '<unsupported>')),
1153 'version': 3}
Antoine Pitrou152efa22010-05-16 18:19:27 +00001154
1155Now that you are assured of its authenticity, you can proceed to talk with
1156the server::
1157
Antoine Pitroudab64262010-09-19 13:31:06 +00001158 >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
1159 >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
Antoine Pitrou152efa22010-05-16 18:19:27 +00001160 [b'HTTP/1.1 302 Found',
1161 b'Date: Sun, 16 May 2010 13:43:28 GMT',
1162 b'Server: Apache/2.2',
1163 b'Location: https://linuxfr.org/pub/',
1164 b'Vary: Accept-Encoding',
1165 b'Connection: close',
1166 b'Content-Type: text/html; charset=iso-8859-1',
1167 b'',
1168 b'']
1169
Antoine Pitrou152efa22010-05-16 18:19:27 +00001170See the discussion of :ref:`ssl-security` below.
1171
1172
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001173Server-side operation
1174^^^^^^^^^^^^^^^^^^^^^
1175
Antoine Pitrou152efa22010-05-16 18:19:27 +00001176For server operation, typically you'll need to have a server certificate, and
1177private key, each in a file. You'll first create a context holding the key
1178and the certificate, so that clients can check your authenticity. Then
1179you'll open a socket, bind it to a port, call :meth:`listen` on it, and start
1180waiting for clients to connect::
Thomas Woutersed03b412007-08-28 21:37:11 +00001181
1182 import socket, ssl
1183
Antoine Pitrou152efa22010-05-16 18:19:27 +00001184 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1185 context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")
1186
Thomas Woutersed03b412007-08-28 21:37:11 +00001187 bindsocket = socket.socket()
1188 bindsocket.bind(('myaddr.mydomain.com', 10023))
1189 bindsocket.listen(5)
1190
Antoine Pitrou152efa22010-05-16 18:19:27 +00001191When a client connects, you'll call :meth:`accept` on the socket to get the
1192new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket`
1193method to create a server-side SSL socket for the connection::
Thomas Woutersed03b412007-08-28 21:37:11 +00001194
1195 while True:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001196 newsocket, fromaddr = bindsocket.accept()
1197 connstream = context.wrap_socket(newsocket, server_side=True)
1198 try:
1199 deal_with_client(connstream)
1200 finally:
Antoine Pitroub205d582011-01-02 22:09:27 +00001201 connstream.shutdown(socket.SHUT_RDWR)
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001202 connstream.close()
Thomas Woutersed03b412007-08-28 21:37:11 +00001203
Antoine Pitrou152efa22010-05-16 18:19:27 +00001204Then you'll read data from the ``connstream`` and do something with it till you
Georg Brandl7f01a132009-09-16 15:58:14 +00001205are finished with the client (or the client is finished with you)::
Thomas Woutersed03b412007-08-28 21:37:11 +00001206
1207 def deal_with_client(connstream):
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001208 data = connstream.recv(1024)
1209 # empty data means the client is finished with us
1210 while data:
1211 if not do_something(connstream, data):
1212 # we'll assume do_something returns False
1213 # when we're finished with client
1214 break
1215 data = connstream.recv(1024)
1216 # finished with client
Thomas Woutersed03b412007-08-28 21:37:11 +00001217
Antoine Pitrou152efa22010-05-16 18:19:27 +00001218And go back to listening for new client connections (of course, a real server
1219would probably handle each client connection in a separate thread, or put
1220the sockets in non-blocking mode and use an event loop).
1221
1222
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001223.. _ssl-nonblocking:
1224
1225Notes on non-blocking sockets
1226-----------------------------
1227
1228When working with non-blocking sockets, there are several things you need
1229to be aware of:
1230
1231- Calling :func:`~select.select` tells you that the OS-level socket can be
1232 read from (or written to), but it does not imply that there is sufficient
1233 data at the upper SSL layer. For example, only part of an SSL frame might
1234 have arrived. Therefore, you must be ready to handle :meth:`SSLSocket.recv`
1235 and :meth:`SSLSocket.send` failures, and retry after another call to
1236 :func:`~select.select`.
1237
1238 (of course, similar provisions apply when using other primitives such as
1239 :func:`~select.poll`)
1240
1241- The SSL handshake itself will be non-blocking: the
1242 :meth:`SSLSocket.do_handshake` method has to be retried until it returns
1243 successfully. Here is a synopsis using :func:`~select.select` to wait for
1244 the socket's readiness::
1245
1246 while True:
1247 try:
1248 sock.do_handshake()
1249 break
Antoine Pitrou873bf262011-10-27 23:59:03 +02001250 except ssl.SSLWantReadError:
1251 select.select([sock], [], [])
1252 except ssl.SSLWantWriteError:
1253 select.select([], [sock], [])
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001254
1255
Antoine Pitrou152efa22010-05-16 18:19:27 +00001256.. _ssl-security:
1257
1258Security considerations
1259-----------------------
1260
1261Verifying certificates
1262^^^^^^^^^^^^^^^^^^^^^^
1263
1264:const:`CERT_NONE` is the default. Since it does not authenticate the other
1265peer, it can be insecure, especially in client mode where most of time you
1266would like to ensure the authenticity of the server you're talking to.
1267Therefore, when in client mode, it is highly recommended to use
1268:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001269have to check that the server certificate, which can be obtained by calling
1270:meth:`SSLSocket.getpeercert`, matches the desired service. For many
1271protocols and applications, the service can be identified by the hostname;
1272in this case, the :func:`match_hostname` function can be used.
Antoine Pitrou152efa22010-05-16 18:19:27 +00001273
1274In server mode, if you want to authenticate your clients using the SSL layer
1275(rather than using a higher-level authentication mechanism), you'll also have
1276to specify :const:`CERT_REQUIRED` and similarly check the client certificate.
1277
1278 .. note::
1279
1280 In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are
1281 equivalent unless anonymous ciphers are enabled (they are disabled
1282 by default).
Thomas Woutersed03b412007-08-28 21:37:11 +00001283
Antoine Pitroub5218772010-05-21 09:56:06 +00001284Protocol versions
1285^^^^^^^^^^^^^^^^^
1286
1287SSL version 2 is considered insecure and is therefore dangerous to use. If
1288you want maximum compatibility between clients and servers, it is recommended
1289to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable
1290SSLv2 explicitly using the :data:`SSLContext.options` attribute::
1291
1292 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1293 context.options |= ssl.OP_NO_SSLv2
1294
1295The SSL context created above will allow SSLv3 and TLSv1 connections, but
1296not SSLv2.
1297
Antoine Pitroub7ffed82012-01-04 02:53:44 +01001298Cipher selection
1299^^^^^^^^^^^^^^^^
1300
1301If you have advanced security requirements, fine-tuning of the ciphers
1302enabled when negotiating a SSL session is possible through the
1303:meth:`SSLContext.set_ciphers` method. Starting from Python 3.2.3, the
1304ssl module disables certain weak ciphers by default, but you may want
1305to further restrict the cipher choice. For example::
1306
1307 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1308 context.set_ciphers('HIGH:!aNULL:!eNULL')
1309
1310The ``!aNULL:!eNULL`` part of the cipher spec is necessary to disable ciphers
1311which don't provide both encryption and authentication. Be sure to read
1312OpenSSL's documentation about the `cipher list
1313format <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
1314If you want to check which ciphers are enabled by a given cipher list,
1315use the ``openssl ciphers`` command on your system.
1316
Georg Brandl48310cd2009-01-03 21:18:54 +00001317
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318.. seealso::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001319
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001320 Class :class:`socket.socket`
Georg Brandl4a6cf6c2013-10-06 18:20:31 +02001321 Documentation of underlying :mod:`socket` class
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001322
Georg Brandl4a6cf6c2013-10-06 18:20:31 +02001323 `SSL/TLS Strong Encryption: An Introduction <http://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html>`_
1324 Intro from the Apache webserver documentation
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001325
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001326 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
1327 Steve Kent
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001328
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001329 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
1330 D. Eastlake et. al.
Thomas Wouters89d996e2007-09-08 17:39:28 +00001331
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001332 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
1333 Housley et. al.
Antoine Pitroud5323212010-10-22 18:19:07 +00001334
1335 `RFC 4366: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc4366>`_
1336 Blake-Wilson et. al.