blob: a688e4609d4e7004749020c1a3b196faa6f29215 [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
Georg Brandl7f01a132009-09-16 15:58:14 +000031This section documents the objects and functions in the ``ssl`` module; for more
32general information about TLS, SSL, and certificates, the reader is referred to
33the documents in the "See Also" section at the bottom.
Thomas Woutersed03b412007-08-28 21:37:11 +000034
Georg Brandl7f01a132009-09-16 15:58:14 +000035This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
36:class:`socket.socket` type, and provides a socket-like wrapper that also
37encrypts and decrypts the data going over the socket with SSL. It supports
Antoine Pitroudab64262010-09-19 13:31:06 +000038additional methods such as :meth:`getpeercert`, which retrieves the
39certificate of the other side of the connection, and :meth:`cipher`,which
40retrieves the cipher being used for the secure connection.
Thomas Woutersed03b412007-08-28 21:37:11 +000041
Antoine Pitrou152efa22010-05-16 18:19:27 +000042For more sophisticated applications, the :class:`ssl.SSLContext` class
43helps manage settings and certificates, which can then be inherited
44by SSL sockets created through the :meth:`SSLContext.wrap_socket` method.
45
46
Thomas Wouters1b7f8912007-09-19 03:06:30 +000047Functions, Constants, and Exceptions
48------------------------------------
49
50.. exception:: SSLError
51
Antoine Pitrou59fdd672010-10-08 10:37:08 +000052 Raised to signal an error from the underlying SSL implementation
53 (currently provided by the OpenSSL library). This signifies some
54 problem in the higher-level encryption and authentication layer that's
55 superimposed on the underlying network connection. This error
Antoine Pitrou5574c302011-10-12 17:53:43 +020056 is a subtype of :exc:`OSError`. The error code and message of
57 :exc:`SSLError` instances are provided by the OpenSSL library.
58
59 .. versionchanged:: 3.3
60 :exc:`SSLError` used to be a subtype of :exc:`socket.error`.
Antoine Pitrou59fdd672010-10-08 10:37:08 +000061
Antoine Pitrou3b36fb12012-06-22 21:11:52 +020062 .. attribute:: library
63
64 A string mnemonic designating the OpenSSL submodule in which the error
65 occurred, such as ``SSL``, ``PEM`` or ``X509``. The range of possible
66 values depends on the OpenSSL version.
67
68 .. versionadded:: 3.3
69
70 .. attribute:: reason
71
72 A string mnemonic designating the reason this error occurred, for
73 example ``CERTIFICATE_VERIFY_FAILED``. The range of possible
74 values depends on the OpenSSL version.
75
76 .. versionadded:: 3.3
77
Antoine Pitrou41032a62011-10-27 23:56:55 +020078.. exception:: SSLZeroReturnError
79
80 A subclass of :exc:`SSLError` raised when trying to read or write and
81 the SSL connection has been closed cleanly. Note that this doesn't
82 mean that the underlying transport (read TCP) has been closed.
83
84 .. versionadded:: 3.3
85
86.. exception:: SSLWantReadError
87
88 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
89 <ssl-nonblocking>` when trying to read or write data, but more data needs
90 to be received on the underlying TCP transport before the request can be
91 fulfilled.
92
93 .. versionadded:: 3.3
94
95.. exception:: SSLWantWriteError
96
97 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
98 <ssl-nonblocking>` when trying to read or write data, but more data needs
99 to be sent on the underlying TCP transport before the request can be
100 fulfilled.
101
102 .. versionadded:: 3.3
103
104.. exception:: SSLSyscallError
105
106 A subclass of :exc:`SSLError` raised when a system error was encountered
107 while trying to fulfill an operation on a SSL socket. Unfortunately,
108 there is no easy way to inspect the original errno number.
109
110 .. versionadded:: 3.3
111
112.. exception:: SSLEOFError
113
114 A subclass of :exc:`SSLError` raised when the SSL connection has been
Antoine Pitrouf3dc2d72011-10-28 00:01:03 +0200115 terminated abruptly. Generally, you shouldn't try to reuse the underlying
Antoine Pitrou41032a62011-10-27 23:56:55 +0200116 transport when this error is encountered.
117
118 .. versionadded:: 3.3
119
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000120.. exception:: CertificateError
121
122 Raised to signal an error with a certificate (such as mismatching
123 hostname). Certificate errors detected by OpenSSL, though, raise
124 an :exc:`SSLError`.
125
126
127Socket creation
128^^^^^^^^^^^^^^^
129
130The following function allows for standalone socket creation. Starting from
131Python 3.2, it can be more flexible to use :meth:`SSLContext.wrap_socket`
132instead.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000133
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000134.. 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 +0000135
Georg Brandl7f01a132009-09-16 15:58:14 +0000136 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
137 of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
138 the underlying socket in an SSL context. For client-side sockets, the
139 context construction is lazy; if the underlying socket isn't connected yet,
140 the context construction will be performed after :meth:`connect` is called on
141 the socket. For server-side sockets, if the socket has no remote peer, it is
142 assumed to be a listening socket, and the server-side SSL wrapping is
143 automatically performed on client connections accepted via the :meth:`accept`
144 method. :func:`wrap_socket` may raise :exc:`SSLError`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000145
Georg Brandl7f01a132009-09-16 15:58:14 +0000146 The ``keyfile`` and ``certfile`` parameters specify optional files which
147 contain a certificate to be used to identify the local side of the
148 connection. See the discussion of :ref:`ssl-certificates` for more
149 information on how the certificate is stored in the ``certfile``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000150
Georg Brandl7f01a132009-09-16 15:58:14 +0000151 The parameter ``server_side`` is a boolean which identifies whether
152 server-side or client-side behavior is desired from this socket.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000153
Georg Brandl7f01a132009-09-16 15:58:14 +0000154 The parameter ``cert_reqs`` specifies whether a certificate is required from
155 the other side of the connection, and whether it will be validated if
156 provided. It must be one of the three values :const:`CERT_NONE`
157 (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
158 if provided), or :const:`CERT_REQUIRED` (required and validated). If the
159 value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
160 parameter must point to a file of CA certificates.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000161
Georg Brandl7f01a132009-09-16 15:58:14 +0000162 The ``ca_certs`` file contains a set of concatenated "certification
163 authority" certificates, which are used to validate certificates passed from
164 the other end of the connection. See the discussion of
165 :ref:`ssl-certificates` for more information about how to arrange the
166 certificates in this file.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000167
Georg Brandl7f01a132009-09-16 15:58:14 +0000168 The parameter ``ssl_version`` specifies which version of the SSL protocol to
169 use. Typically, the server chooses a particular protocol version, and the
170 client must adapt to the server's choice. Most of the versions are not
Antoine Pitrou84a2edc2012-01-09 21:35:11 +0100171 interoperable with the other versions. If not specified, the default is
172 :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other
Georg Brandl7f01a132009-09-16 15:58:14 +0000173 versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000174
Georg Brandl7f01a132009-09-16 15:58:14 +0000175 Here's a table showing which versions in a client (down the side) can connect
176 to which versions in a server (along the top):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000177
178 .. table::
179
180 ======================== ========= ========= ========== =========
181 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1**
Christian Heimes255f53b2007-12-08 15:33:56 +0000182 ------------------------ --------- --------- ---------- ---------
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000183 *SSLv2* yes no yes no
Antoine Pitrouac8bfca2012-01-09 21:43:18 +0100184 *SSLv3* no yes yes no
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000185 *SSLv23* yes no yes no
186 *TLSv1* no no yes yes
187 ======================== ========= ========= ========== =========
188
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000189 .. note::
190
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000191 Which connections succeed will vary depending on the version of
192 OpenSSL. For instance, in some older versions of OpenSSL (such
193 as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an
194 SSLv23 server. Another example: beginning with OpenSSL 1.0.0,
195 an SSLv23 client will not actually attempt SSLv2 connections
196 unless you explicitly enable SSLv2 ciphers; for example, you
197 might specify ``"ALL"`` or ``"SSLv2"`` as the *ciphers* parameter
198 to enable them.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000199
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000200 The *ciphers* parameter sets the available ciphers for this SSL object.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000201 It should be a string in the `OpenSSL cipher list format
202 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000203
Bill Janssen48dc27c2007-12-05 03:38:10 +0000204 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
205 handshake automatically after doing a :meth:`socket.connect`, or whether the
Georg Brandl7f01a132009-09-16 15:58:14 +0000206 application program will call it explicitly, by invoking the
207 :meth:`SSLSocket.do_handshake` method. Calling
208 :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
209 blocking behavior of the socket I/O involved in the handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000210
Georg Brandl7f01a132009-09-16 15:58:14 +0000211 The parameter ``suppress_ragged_eofs`` specifies how the
Antoine Pitroudab64262010-09-19 13:31:06 +0000212 :meth:`SSLSocket.recv` method should signal unexpected EOF from the other end
Georg Brandl7f01a132009-09-16 15:58:14 +0000213 of the connection. If specified as :const:`True` (the default), it returns a
Antoine Pitroudab64262010-09-19 13:31:06 +0000214 normal EOF (an empty bytes object) in response to unexpected EOF errors
215 raised from the underlying socket; if :const:`False`, it will raise the
216 exceptions back to the caller.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000217
Ezio Melotti4d5195b2010-04-20 10:57:44 +0000218 .. versionchanged:: 3.2
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000219 New optional argument *ciphers*.
220
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000221Random generation
222^^^^^^^^^^^^^^^^^
223
Victor Stinner99c8b162011-05-24 12:05:19 +0200224.. function:: RAND_bytes(num)
225
Victor Stinnera6752062011-05-25 11:27:40 +0200226 Returns *num* cryptographically strong pseudo-random bytes. Raises an
227 :class:`SSLError` if the PRNG has not been seeded with enough data or if the
228 operation is not supported by the current RAND method. :func:`RAND_status`
229 can be used to check the status of the PRNG and :func:`RAND_add` can be used
230 to seed the PRNG.
Victor Stinner99c8b162011-05-24 12:05:19 +0200231
Victor Stinner19fb53c2011-05-24 21:32:40 +0200232 Read the Wikipedia article, `Cryptographically secure pseudorandom number
Victor Stinnera6752062011-05-25 11:27:40 +0200233 generator (CSPRNG)
Victor Stinner19fb53c2011-05-24 21:32:40 +0200234 <http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator>`_,
235 to get the requirements of a cryptographically generator.
236
Victor Stinner99c8b162011-05-24 12:05:19 +0200237 .. versionadded:: 3.3
238
239.. function:: RAND_pseudo_bytes(num)
240
241 Returns (bytes, is_cryptographic): bytes are *num* pseudo-random bytes,
242 is_cryptographic is True if the bytes generated are cryptographically
Victor Stinnera6752062011-05-25 11:27:40 +0200243 strong. Raises an :class:`SSLError` if the operation is not supported by the
244 current RAND method.
Victor Stinner99c8b162011-05-24 12:05:19 +0200245
Victor Stinner19fb53c2011-05-24 21:32:40 +0200246 Generated pseudo-random byte sequences will be unique if they are of
247 sufficient length, but are not necessarily unpredictable. They can be used
248 for non-cryptographic purposes and for certain purposes in cryptographic
249 protocols, but usually not for key generation etc.
250
Victor Stinner99c8b162011-05-24 12:05:19 +0200251 .. versionadded:: 3.3
252
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000253.. function:: RAND_status()
254
Georg Brandl7f01a132009-09-16 15:58:14 +0000255 Returns True if the SSL pseudo-random number generator has been seeded with
256 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
257 and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
258 number generator.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000259
260.. function:: RAND_egd(path)
261
Victor Stinner99c8b162011-05-24 12:05:19 +0200262 If you are running an entropy-gathering daemon (EGD) somewhere, and *path*
Georg Brandl7f01a132009-09-16 15:58:14 +0000263 is the pathname of a socket connection open to it, this will read 256 bytes
264 of randomness from the socket, and add it to the SSL pseudo-random number
265 generator to increase the security of generated secret keys. This is
266 typically only necessary on systems without better sources of randomness.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000267
Georg Brandl7f01a132009-09-16 15:58:14 +0000268 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
269 of entropy-gathering daemons.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000270
271.. function:: RAND_add(bytes, entropy)
272
Victor Stinner99c8b162011-05-24 12:05:19 +0200273 Mixes the given *bytes* into the SSL pseudo-random number generator. The
274 parameter *entropy* (a float) is a lower bound on the entropy contained in
Georg Brandl7f01a132009-09-16 15:58:14 +0000275 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
276 information on sources of entropy.
Thomas Woutersed03b412007-08-28 21:37:11 +0000277
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000278Certificate handling
279^^^^^^^^^^^^^^^^^^^^
280
281.. function:: match_hostname(cert, hostname)
282
283 Verify that *cert* (in decoded format as returned by
284 :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules
285 applied are those for checking the identity of HTTPS servers as outlined
Georg Brandl72c98d32013-10-27 07:16:53 +0100286 in :rfc:`2818` and :rfc:`6125`, except that IP addresses are not currently
287 supported. In addition to HTTPS, this function should be suitable for
288 checking the identity of servers in various SSL-based protocols such as
289 FTPS, IMAPS, POPS and others.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000290
291 :exc:`CertificateError` is raised on failure. On success, the function
292 returns nothing::
293
294 >>> cert = {'subject': ((('commonName', 'example.com'),),)}
295 >>> ssl.match_hostname(cert, "example.com")
296 >>> ssl.match_hostname(cert, "example.org")
297 Traceback (most recent call last):
298 File "<stdin>", line 1, in <module>
299 File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
300 ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'
301
302 .. versionadded:: 3.2
303
Georg Brandl72c98d32013-10-27 07:16:53 +0100304 .. versionchanged:: 3.3.3
305 The function now follows :rfc:`6125`, section 6.4.3 and does neither
306 match multiple wildcards (e.g. ``*.*.com`` or ``*a*.example.org``) nor
307 a wildcard inside an internationalized domain names (IDN) fragment.
308 IDN A-labels such as ``www*.xn--pthon-kva.org`` are still supported,
309 but ``x*.python.org`` no longer matches ``xn--tda.python.org``.
310
Thomas Woutersed03b412007-08-28 21:37:11 +0000311.. function:: cert_time_to_seconds(timestring)
312
Georg Brandl7f01a132009-09-16 15:58:14 +0000313 Returns a floating-point value containing a normal seconds-after-the-epoch
314 time value, given the time-string representing the "notBefore" or "notAfter"
315 date from a certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000316
317 Here's an example::
318
319 >>> import ssl
320 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
321 1178694000.0
322 >>> import time
323 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
324 'Wed May 9 00:00:00 2007'
Thomas Woutersed03b412007-08-28 21:37:11 +0000325
Georg Brandl7f01a132009-09-16 15:58:14 +0000326.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000327
Georg Brandl7f01a132009-09-16 15:58:14 +0000328 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
329 *port-number*) pair, fetches the server's certificate, and returns it as a
330 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
331 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
332 specified, it should be a file containing a list of root certificates, the
333 same format as used for the same parameter in :func:`wrap_socket`. The call
334 will attempt to validate the server certificate against that set of root
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000335 certificates, and will fail if the validation attempt fails.
336
Antoine Pitrou15399c32011-04-28 19:23:55 +0200337 .. versionchanged:: 3.3
338 This function is now IPv6-compatible.
339
Georg Brandl7f01a132009-09-16 15:58:14 +0000340.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000341
342 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
343 string version of the same certificate.
344
Georg Brandl7f01a132009-09-16 15:58:14 +0000345.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000346
Georg Brandl7f01a132009-09-16 15:58:14 +0000347 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
348 bytes for that same certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000349
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000350Constants
351^^^^^^^^^
352
Thomas Woutersed03b412007-08-28 21:37:11 +0000353.. data:: CERT_NONE
354
Antoine Pitrou152efa22010-05-16 18:19:27 +0000355 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
356 parameter to :func:`wrap_socket`. In this mode (the default), no
357 certificates will be required from the other side of the socket connection.
358 If a certificate is received from the other end, no attempt to validate it
359 is made.
360
361 See the discussion of :ref:`ssl-security` below.
Thomas Woutersed03b412007-08-28 21:37:11 +0000362
363.. data:: CERT_OPTIONAL
364
Antoine Pitrou152efa22010-05-16 18:19:27 +0000365 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
366 parameter to :func:`wrap_socket`. In this mode no certificates will be
367 required from the other side of the socket connection; but if they
368 are provided, validation will be attempted and an :class:`SSLError`
369 will be raised on failure.
370
371 Use of this setting requires a valid set of CA certificates to
372 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
373 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000374
375.. data:: CERT_REQUIRED
376
Antoine Pitrou152efa22010-05-16 18:19:27 +0000377 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
378 parameter to :func:`wrap_socket`. In this mode, certificates are
379 required from the other side of the socket connection; an :class:`SSLError`
380 will be raised if no certificate is provided, or if its validation fails.
381
382 Use of this setting requires a valid set of CA certificates to
383 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
384 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000385
386.. data:: PROTOCOL_SSLv2
387
388 Selects SSL version 2 as the channel encryption protocol.
389
Victor Stinner3de49192011-05-09 00:42:58 +0200390 This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
391 flag.
392
Antoine Pitrou8eac60d2010-05-16 14:19:41 +0000393 .. warning::
394
395 SSL version 2 is insecure. Its use is highly discouraged.
396
Thomas Woutersed03b412007-08-28 21:37:11 +0000397.. data:: PROTOCOL_SSLv23
398
Georg Brandl7f01a132009-09-16 15:58:14 +0000399 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
400 setting to use with servers for maximum compatibility with the other end of
401 an SSL connection, but it may cause the specific ciphers chosen for the
402 encryption to be of fairly low quality.
Thomas Woutersed03b412007-08-28 21:37:11 +0000403
404.. data:: PROTOCOL_SSLv3
405
Georg Brandl7f01a132009-09-16 15:58:14 +0000406 Selects SSL version 3 as the channel encryption protocol. For clients, this
407 is the maximally compatible SSL variant.
Thomas Woutersed03b412007-08-28 21:37:11 +0000408
409.. data:: PROTOCOL_TLSv1
410
Georg Brandl7f01a132009-09-16 15:58:14 +0000411 Selects TLS version 1 as the channel encryption protocol. This is the most
412 modern version, and probably the best choice for maximum protection, if both
413 sides can speak it.
Thomas Woutersed03b412007-08-28 21:37:11 +0000414
Antoine Pitroub5218772010-05-21 09:56:06 +0000415.. data:: OP_ALL
416
417 Enables workarounds for various bugs present in other SSL implementations.
Antoine Pitrou9f6b02e2012-01-27 10:02:55 +0100418 This option is set by default. It does not necessarily set the same
419 flags as OpenSSL's ``SSL_OP_ALL`` constant.
Antoine Pitroub5218772010-05-21 09:56:06 +0000420
421 .. versionadded:: 3.2
422
423.. data:: OP_NO_SSLv2
424
425 Prevents an SSLv2 connection. This option is only applicable in
426 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
427 choosing SSLv2 as the protocol version.
428
429 .. versionadded:: 3.2
430
431.. data:: OP_NO_SSLv3
432
433 Prevents an SSLv3 connection. This option is only applicable in
434 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
435 choosing SSLv3 as the protocol version.
436
437 .. versionadded:: 3.2
438
439.. data:: OP_NO_TLSv1
440
441 Prevents a TLSv1 connection. This option is only applicable in
442 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
443 choosing TLSv1 as the protocol version.
444
445 .. versionadded:: 3.2
446
Antoine Pitrou6db49442011-12-19 13:27:11 +0100447.. data:: OP_CIPHER_SERVER_PREFERENCE
448
449 Use the server's cipher ordering preference, rather than the client's.
450 This option has no effect on client sockets and SSLv2 server sockets.
451
452 .. versionadded:: 3.3
453
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100454.. data:: OP_SINGLE_DH_USE
455
456 Prevents re-use of the same DH key for distinct SSL sessions. This
457 improves forward secrecy but requires more computational resources.
458 This option only applies to server sockets.
459
460 .. versionadded:: 3.3
461
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100462.. data:: OP_SINGLE_ECDH_USE
463
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100464 Prevents re-use of the same ECDH key for distinct SSL sessions. This
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100465 improves forward secrecy but requires more computational resources.
466 This option only applies to server sockets.
467
468 .. versionadded:: 3.3
469
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100470.. data:: OP_NO_COMPRESSION
471
472 Disable compression on the SSL channel. This is useful if the application
473 protocol supports its own compression scheme.
474
475 This option is only available with OpenSSL 1.0.0 and later.
476
477 .. versionadded:: 3.3
478
Antoine Pitrou501da612011-12-21 09:27:41 +0100479.. data:: HAS_ECDH
480
481 Whether the OpenSSL library has built-in support for Elliptic Curve-based
482 Diffie-Hellman key exchange. This should be true unless the feature was
483 explicitly disabled by the distributor.
484
485 .. versionadded:: 3.3
486
Antoine Pitroud5323212010-10-22 18:19:07 +0000487.. data:: HAS_SNI
488
489 Whether the OpenSSL library has built-in support for the *Server Name
490 Indication* extension to the SSLv3 and TLSv1 protocols (as defined in
491 :rfc:`4366`). When true, you can use the *server_hostname* argument to
492 :meth:`SSLContext.wrap_socket`.
493
494 .. versionadded:: 3.2
495
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100496.. data:: HAS_NPN
497
498 Whether the OpenSSL library has built-in support for *Next Protocol
499 Negotiation* as described in the `NPN draft specification
500 <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. When true,
501 you can use the :meth:`SSLContext.set_npn_protocols` method to advertise
502 which protocols you want to support.
503
504 .. versionadded:: 3.3
505
Antoine Pitroud6494802011-07-21 01:11:30 +0200506.. data:: CHANNEL_BINDING_TYPES
507
508 List of supported TLS channel binding types. Strings in this list
509 can be used as arguments to :meth:`SSLSocket.get_channel_binding`.
510
511 .. versionadded:: 3.3
512
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000513.. data:: OPENSSL_VERSION
514
515 The version string of the OpenSSL library loaded by the interpreter::
516
517 >>> ssl.OPENSSL_VERSION
518 'OpenSSL 0.9.8k 25 Mar 2009'
519
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000520 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000521
522.. data:: OPENSSL_VERSION_INFO
523
524 A tuple of five integers representing version information about the
525 OpenSSL library::
526
527 >>> ssl.OPENSSL_VERSION_INFO
528 (0, 9, 8, 11, 15)
529
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000530 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000531
532.. data:: OPENSSL_VERSION_NUMBER
533
534 The raw version number of the OpenSSL library, as a single integer::
535
536 >>> ssl.OPENSSL_VERSION_NUMBER
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000537 9470143
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000538 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000539 '0x9080bf'
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000540
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000541 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000542
Thomas Woutersed03b412007-08-28 21:37:11 +0000543
Antoine Pitrou152efa22010-05-16 18:19:27 +0000544SSL Sockets
545-----------
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000547SSL sockets provide the following methods of :ref:`socket-objects`:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000548
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000549- :meth:`~socket.socket.accept()`
550- :meth:`~socket.socket.bind()`
551- :meth:`~socket.socket.close()`
552- :meth:`~socket.socket.connect()`
553- :meth:`~socket.socket.detach()`
554- :meth:`~socket.socket.fileno()`
555- :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`
556- :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`
557- :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`,
558 :meth:`~socket.socket.setblocking()`
559- :meth:`~socket.socket.listen()`
560- :meth:`~socket.socket.makefile()`
561- :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()`
562 (but passing a non-zero ``flags`` argument is not allowed)
563- :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with
564 the same limitation)
565- :meth:`~socket.socket.shutdown()`
566
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +0200567However, since the SSL (and TLS) protocol has its own framing atop
568of TCP, the SSL sockets abstraction can, in certain respects, diverge from
569the specification of normal, OS-level sockets. See especially the
570:ref:`notes on non-blocking sockets <ssl-nonblocking>`.
571
572SSL sockets also have the following additional methods and attributes:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000573
Bill Janssen48dc27c2007-12-05 03:38:10 +0000574.. method:: SSLSocket.do_handshake()
575
Antoine Pitroub3593ca2011-07-11 01:39:19 +0200576 Perform the SSL setup handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000577
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000578.. method:: SSLSocket.getpeercert(binary_form=False)
579
Georg Brandl7f01a132009-09-16 15:58:14 +0000580 If there is no certificate for the peer on the other end of the connection,
581 returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000582
Antoine Pitroud34941a2013-04-16 20:27:17 +0200583 If the ``binary_form`` parameter is :const:`False`, and a certificate was
Georg Brandl7f01a132009-09-16 15:58:14 +0000584 received from the peer, this method returns a :class:`dict` instance. If the
585 certificate was not validated, the dict is empty. If the certificate was
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200586 validated, it returns a dict with several keys, amongst them ``subject``
587 (the principal for which the certificate was issued) and ``issuer``
588 (the principal issuing the certificate). If a certificate contains an
589 instance of the *Subject Alternative Name* extension (see :rfc:`3280`),
590 there will also be a ``subjectAltName`` key in the dictionary.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000591
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200592 The ``subject`` and ``issuer`` fields are tuples containing the sequence
593 of relative distinguished names (RDNs) given in the certificate's data
594 structure for the respective fields, and each RDN is a sequence of
595 name-value pairs. Here is a real-world example::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000596
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200597 {'issuer': ((('countryName', 'IL'),),
598 (('organizationName', 'StartCom Ltd.'),),
599 (('organizationalUnitName',
600 'Secure Digital Certificate Signing'),),
601 (('commonName',
602 'StartCom Class 2 Primary Intermediate Server CA'),)),
603 'notAfter': 'Nov 22 08:15:19 2013 GMT',
604 'notBefore': 'Nov 21 03:09:52 2011 GMT',
605 'serialNumber': '95F0',
606 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
607 (('countryName', 'US'),),
608 (('stateOrProvinceName', 'California'),),
609 (('localityName', 'San Francisco'),),
610 (('organizationName', 'Electronic Frontier Foundation, Inc.'),),
611 (('commonName', '*.eff.org'),),
612 (('emailAddress', 'hostmaster@eff.org'),)),
613 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
614 'version': 3}
615
616 .. note::
617 To validate a certificate for a particular service, you can use the
618 :func:`match_hostname` function.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000619
Georg Brandl7f01a132009-09-16 15:58:14 +0000620 If the ``binary_form`` parameter is :const:`True`, and a certificate was
621 provided, this method returns the DER-encoded form of the entire certificate
622 as a sequence of bytes, or :const:`None` if the peer did not provide a
Antoine Pitroud34941a2013-04-16 20:27:17 +0200623 certificate. Whether the peer provides a certificate depends on the SSL
624 socket's role:
625
626 * for a client SSL socket, the server will always provide a certificate,
627 regardless of whether validation was required;
628
629 * for a server SSL socket, the client will only provide a certificate
630 when requested by the server; therefore :meth:`getpeercert` will return
631 :const:`None` if you used :const:`CERT_NONE` (rather than
632 :const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000633
Antoine Pitroufb046912010-11-09 20:21:19 +0000634 .. versionchanged:: 3.2
635 The returned dictionary includes additional items such as ``issuer``
636 and ``notBefore``.
637
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000638.. method:: SSLSocket.cipher()
639
Georg Brandl7f01a132009-09-16 15:58:14 +0000640 Returns a three-value tuple containing the name of the cipher being used, the
641 version of the SSL protocol that defines its use, and the number of secret
642 bits being used. If no connection has been established, returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000643
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100644.. method:: SSLSocket.compression()
645
646 Return the compression algorithm being used as a string, or ``None``
647 if the connection isn't compressed.
648
649 If the higher-level protocol supports its own compression mechanism,
650 you can use :data:`OP_NO_COMPRESSION` to disable SSL-level compression.
651
652 .. versionadded:: 3.3
653
Antoine Pitroud6494802011-07-21 01:11:30 +0200654.. method:: SSLSocket.get_channel_binding(cb_type="tls-unique")
655
656 Get channel binding data for current connection, as a bytes object. Returns
657 ``None`` if not connected or the handshake has not been completed.
658
659 The *cb_type* parameter allow selection of the desired channel binding
660 type. Valid channel binding types are listed in the
661 :data:`CHANNEL_BINDING_TYPES` list. Currently only the 'tls-unique' channel
662 binding, defined by :rfc:`5929`, is supported. :exc:`ValueError` will be
663 raised if an unsupported channel binding type is requested.
664
665 .. versionadded:: 3.3
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000666
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100667.. method:: SSLSocket.selected_npn_protocol()
668
669 Returns the protocol that was selected during the TLS/SSL handshake. If
670 :meth:`SSLContext.set_npn_protocols` was not called, or if the other party
671 does not support NPN, or if the handshake has not yet happened, this will
672 return ``None``.
673
674 .. versionadded:: 3.3
675
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000676.. method:: SSLSocket.unwrap()
677
Georg Brandl7f01a132009-09-16 15:58:14 +0000678 Performs the SSL shutdown handshake, which removes the TLS layer from the
679 underlying socket, and returns the underlying socket object. This can be
680 used to go from encrypted operation over a connection to unencrypted. The
681 returned socket should always be used for further communication with the
682 other side of the connection, rather than the original socket.
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000683
Antoine Pitrouec883db2010-05-24 21:20:20 +0000684.. attribute:: SSLSocket.context
685
686 The :class:`SSLContext` object this SSL socket is tied to. If the SSL
687 socket was created using the top-level :func:`wrap_socket` function
688 (rather than :meth:`SSLContext.wrap_socket`), this is a custom context
689 object created for this SSL socket.
690
691 .. versionadded:: 3.2
692
693
Antoine Pitrou152efa22010-05-16 18:19:27 +0000694SSL Contexts
695------------
696
Antoine Pitroucafaad42010-05-24 15:58:43 +0000697.. versionadded:: 3.2
698
Antoine Pitroub0182c82010-10-12 20:09:02 +0000699An SSL context holds various data longer-lived than single SSL connections,
700such as SSL configuration options, certificate(s) and private key(s).
701It also manages a cache of SSL sessions for server-side sockets, in order
702to speed up repeated connections from the same clients.
703
Antoine Pitrou152efa22010-05-16 18:19:27 +0000704.. class:: SSLContext(protocol)
705
Antoine Pitroub0182c82010-10-12 20:09:02 +0000706 Create a new SSL context. You must pass *protocol* which must be one
707 of the ``PROTOCOL_*`` constants defined in this module.
708 :data:`PROTOCOL_SSLv23` is recommended for maximum interoperability.
709
Antoine Pitrou152efa22010-05-16 18:19:27 +0000710
711:class:`SSLContext` objects have the following methods and attributes:
712
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200713.. method:: SSLContext.load_cert_chain(certfile, keyfile=None, password=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000714
715 Load a private key and the corresponding certificate. The *certfile*
716 string must be the path to a single file in PEM format containing the
717 certificate as well as any number of CA certificates needed to establish
718 the certificate's authenticity. The *keyfile* string, if present, must
719 point to a file containing the private key in. Otherwise the private
720 key will be taken from *certfile* as well. See the discussion of
721 :ref:`ssl-certificates` for more information on how the certificate
722 is stored in the *certfile*.
723
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200724 The *password* argument may be a function to call to get the password for
725 decrypting the private key. It will only be called if the private key is
726 encrypted and a password is necessary. It will be called with no arguments,
727 and it should return a string, bytes, or bytearray. If the return value is
728 a string it will be encoded as UTF-8 before using it to decrypt the key.
729 Alternatively a string, bytes, or bytearray value may be supplied directly
730 as the *password* argument. It will be ignored if the private key is not
731 encrypted and no password is needed.
732
733 If the *password* argument is not specified and a password is required,
734 OpenSSL's built-in password prompting mechanism will be used to
735 interactively prompt the user for a password.
736
Antoine Pitrou152efa22010-05-16 18:19:27 +0000737 An :class:`SSLError` is raised if the private key doesn't
738 match with the certificate.
739
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200740 .. versionchanged:: 3.3
741 New optional argument *password*.
742
Antoine Pitrou152efa22010-05-16 18:19:27 +0000743.. method:: SSLContext.load_verify_locations(cafile=None, capath=None)
744
745 Load a set of "certification authority" (CA) certificates used to validate
746 other peers' certificates when :data:`verify_mode` is other than
747 :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified.
748
749 The *cafile* string, if present, is the path to a file of concatenated
750 CA certificates in PEM format. See the discussion of
751 :ref:`ssl-certificates` for more information about how to arrange the
752 certificates in this file.
753
754 The *capath* string, if present, is
755 the path to a directory containing several CA certificates in PEM format,
756 following an `OpenSSL specific layout
757 <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
758
Antoine Pitrou664c2d12010-11-17 20:29:42 +0000759.. method:: SSLContext.set_default_verify_paths()
760
761 Load a set of default "certification authority" (CA) certificates from
762 a filesystem path defined when building the OpenSSL library. Unfortunately,
763 there's no easy way to know whether this method succeeds: no error is
764 returned if no certificates are to be found. When the OpenSSL library is
765 provided as part of the operating system, though, it is likely to be
766 configured properly.
767
Antoine Pitrou152efa22010-05-16 18:19:27 +0000768.. method:: SSLContext.set_ciphers(ciphers)
769
770 Set the available ciphers for sockets created with this context.
771 It should be a string in the `OpenSSL cipher list format
772 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
773 If no cipher can be selected (because compile-time options or other
774 configuration forbids use of all the specified ciphers), an
775 :class:`SSLError` will be raised.
776
777 .. note::
778 when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
779 give the currently selected cipher.
780
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100781.. method:: SSLContext.set_npn_protocols(protocols)
782
R David Murrayc7f75792013-06-26 15:11:12 -0400783 Specify which protocols the socket should advertise during the SSL/TLS
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100784 handshake. It should be a list of strings, like ``['http/1.1', 'spdy/2']``,
785 ordered by preference. The selection of a protocol will happen during the
786 handshake, and will play out according to the `NPN draft specification
787 <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. After a
788 successful handshake, the :meth:`SSLSocket.selected_npn_protocol` method will
789 return the agreed-upon protocol.
790
791 This method will raise :exc:`NotImplementedError` if :data:`HAS_NPN` is
792 False.
793
794 .. versionadded:: 3.3
795
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100796.. method:: SSLContext.load_dh_params(dhfile)
797
798 Load the key generation parameters for Diffie-Helman (DH) key exchange.
799 Using DH key exchange improves forward secrecy at the expense of
800 computational resources (both on the server and on the client).
801 The *dhfile* parameter should be the path to a file containing DH
802 parameters in PEM format.
803
804 This setting doesn't apply to client sockets. You can also use the
805 :data:`OP_SINGLE_DH_USE` option to further improve security.
806
807 .. versionadded:: 3.3
808
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100809.. method:: SSLContext.set_ecdh_curve(curve_name)
810
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100811 Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key
812 exchange. ECDH is significantly faster than regular DH while arguably
813 as secure. The *curve_name* parameter should be a string describing
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100814 a well-known elliptic curve, for example ``prime256v1`` for a widely
815 supported curve.
816
817 This setting doesn't apply to client sockets. You can also use the
818 :data:`OP_SINGLE_ECDH_USE` option to further improve security.
819
Antoine Pitrou501da612011-12-21 09:27:41 +0100820 This method is not available if :data:`HAS_ECDH` is False.
821
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100822 .. versionadded:: 3.3
823
824 .. seealso::
825 `SSL/TLS & Perfect Forward Secrecy <http://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy.html>`_
826 Vincent Bernat.
827
Antoine Pitroud5323212010-10-22 18:19:07 +0000828.. method:: SSLContext.wrap_socket(sock, server_side=False, \
829 do_handshake_on_connect=True, suppress_ragged_eofs=True, \
830 server_hostname=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000831
832 Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
833 object. The SSL socket is tied to the context, its settings and
834 certificates. The parameters *server_side*, *do_handshake_on_connect*
835 and *suppress_ragged_eofs* have the same meaning as in the top-level
836 :func:`wrap_socket` function.
837
Antoine Pitroud5323212010-10-22 18:19:07 +0000838 On client connections, the optional parameter *server_hostname* specifies
839 the hostname of the service which we are connecting to. This allows a
840 single server to host multiple SSL-based services with distinct certificates,
841 quite similarly to HTTP virtual hosts. Specifying *server_hostname*
842 will raise a :exc:`ValueError` if the OpenSSL library doesn't have support
843 for it (that is, if :data:`HAS_SNI` is :const:`False`). Specifying
844 *server_hostname* will also raise a :exc:`ValueError` if *server_side*
845 is true.
846
Antoine Pitroub0182c82010-10-12 20:09:02 +0000847.. method:: SSLContext.session_stats()
848
849 Get statistics about the SSL sessions created or managed by this context.
850 A dictionary is returned which maps the names of each `piece of information
851 <http://www.openssl.org/docs/ssl/SSL_CTX_sess_number.html>`_ to their
852 numeric values. For example, here is the total number of hits and misses
853 in the session cache since the context was created::
854
855 >>> stats = context.session_stats()
856 >>> stats['hits'], stats['misses']
857 (0, 0)
858
Antoine Pitroub5218772010-05-21 09:56:06 +0000859.. attribute:: SSLContext.options
860
861 An integer representing the set of SSL options enabled on this context.
862 The default value is :data:`OP_ALL`, but you can specify other options
863 such as :data:`OP_NO_SSLv2` by ORing them together.
864
865 .. note::
866 With versions of OpenSSL older than 0.9.8m, it is only possible
867 to set options, not to clear them. Attempting to clear an option
868 (by resetting the corresponding bits) will raise a ``ValueError``.
869
Antoine Pitrou152efa22010-05-16 18:19:27 +0000870.. attribute:: SSLContext.protocol
871
872 The protocol version chosen when constructing the context. This attribute
873 is read-only.
874
875.. attribute:: SSLContext.verify_mode
876
877 Whether to try to verify other peers' certificates and how to behave
878 if verification fails. This attribute must be one of
879 :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.
880
881
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000882.. index:: single: certificates
883
884.. index:: single: X509 certificate
885
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000886.. _ssl-certificates:
887
Thomas Woutersed03b412007-08-28 21:37:11 +0000888Certificates
889------------
890
Georg Brandl7f01a132009-09-16 15:58:14 +0000891Certificates in general are part of a public-key / private-key system. In this
892system, each *principal*, (which may be a machine, or a person, or an
893organization) is assigned a unique two-part encryption key. One part of the key
894is public, and is called the *public key*; the other part is kept secret, and is
895called the *private key*. The two parts are related, in that if you encrypt a
896message with one of the parts, you can decrypt it with the other part, and
897**only** with the other part.
Thomas Woutersed03b412007-08-28 21:37:11 +0000898
Georg Brandl7f01a132009-09-16 15:58:14 +0000899A certificate contains information about two principals. It contains the name
900of a *subject*, and the subject's public key. It also contains a statement by a
901second principal, the *issuer*, that the subject is who he claims to be, and
902that this is indeed the subject's public key. The issuer's statement is signed
903with the issuer's private key, which only the issuer knows. However, anyone can
904verify the issuer's statement by finding the issuer's public key, decrypting the
905statement with it, and comparing it to the other information in the certificate.
906The certificate also contains information about the time period over which it is
907valid. This is expressed as two fields, called "notBefore" and "notAfter".
Thomas Woutersed03b412007-08-28 21:37:11 +0000908
Georg Brandl7f01a132009-09-16 15:58:14 +0000909In the Python use of certificates, a client or server can use a certificate to
910prove who they are. The other side of a network connection can also be required
911to produce a certificate, and that certificate can be validated to the
912satisfaction of the client or server that requires such validation. The
913connection attempt can be set to raise an exception if the validation fails.
914Validation is done automatically, by the underlying OpenSSL framework; the
915application need not concern itself with its mechanics. But the application
916does usually need to provide sets of certificates to allow this process to take
917place.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000918
Georg Brandl7f01a132009-09-16 15:58:14 +0000919Python uses files to contain certificates. They should be formatted as "PEM"
920(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
921and a footer line::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000922
923 -----BEGIN CERTIFICATE-----
924 ... (certificate in base64 PEM encoding) ...
925 -----END CERTIFICATE-----
926
Antoine Pitrou152efa22010-05-16 18:19:27 +0000927Certificate chains
928^^^^^^^^^^^^^^^^^^
929
Georg Brandl7f01a132009-09-16 15:58:14 +0000930The Python files which contain certificates can contain a sequence of
931certificates, sometimes called a *certificate chain*. This chain should start
932with the specific certificate for the principal who "is" the client or server,
933and then the certificate for the issuer of that certificate, and then the
934certificate for the issuer of *that* certificate, and so on up the chain till
935you get to a certificate which is *self-signed*, that is, a certificate which
936has the same subject and issuer, sometimes called a *root certificate*. The
937certificates should just be concatenated together in the certificate file. For
938example, suppose we had a three certificate chain, from our server certificate
939to the certificate of the certification authority that signed our server
940certificate, to the root certificate of the agency which issued the
941certification authority's certificate::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000942
943 -----BEGIN CERTIFICATE-----
944 ... (certificate for your server)...
945 -----END CERTIFICATE-----
946 -----BEGIN CERTIFICATE-----
947 ... (the certificate for the CA)...
948 -----END CERTIFICATE-----
949 -----BEGIN CERTIFICATE-----
950 ... (the root certificate for the CA's issuer)...
951 -----END CERTIFICATE-----
952
Antoine Pitrou152efa22010-05-16 18:19:27 +0000953CA certificates
954^^^^^^^^^^^^^^^
955
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000956If you are going to require validation of the other side of the connection's
957certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandl7f01a132009-09-16 15:58:14 +0000958chains for each issuer you are willing to trust. Again, this file just contains
959these chains concatenated together. For validation, Python will use the first
960chain it finds in the file which matches. Some "standard" root certificates are
961available from various certification authorities: `CACert.org
962<http://www.cacert.org/index.php?id=3>`_, `Thawte
963<http://www.thawte.com/roots/>`_, `Verisign
964<http://www.verisign.com/support/roots.html>`_, `Positive SSL
965<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
966(used by python.org), `Equifax and GeoTrust
967<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000968
Georg Brandl7f01a132009-09-16 15:58:14 +0000969In general, if you are using SSL3 or TLS1, you don't need to put the full chain
970in your "CA certs" file; you only need the root certificates, and the remote
971peer is supposed to furnish the other certificates necessary to chain from its
972certificate to a root certificate. See :rfc:`4158` for more discussion of the
973way in which certification chains can be built.
Thomas Woutersed03b412007-08-28 21:37:11 +0000974
Antoine Pitrou152efa22010-05-16 18:19:27 +0000975Combined key and certificate
976^^^^^^^^^^^^^^^^^^^^^^^^^^^^
977
978Often the private key is stored in the same file as the certificate; in this
979case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain`
980and :func:`wrap_socket` needs to be passed. If the private key is stored
981with the certificate, it should come before the first certificate in
982the certificate chain::
983
984 -----BEGIN RSA PRIVATE KEY-----
985 ... (private key in base64 encoding) ...
986 -----END RSA PRIVATE KEY-----
987 -----BEGIN CERTIFICATE-----
988 ... (certificate in base64 PEM encoding) ...
989 -----END CERTIFICATE-----
990
991Self-signed certificates
992^^^^^^^^^^^^^^^^^^^^^^^^
993
Georg Brandl7f01a132009-09-16 15:58:14 +0000994If you are going to create a server that provides SSL-encrypted connection
995services, you will need to acquire a certificate for that service. There are
996many ways of acquiring appropriate certificates, such as buying one from a
997certification authority. Another common practice is to generate a self-signed
998certificate. The simplest way to do this is with the OpenSSL package, using
999something like the following::
Thomas Woutersed03b412007-08-28 21:37:11 +00001000
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001001 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
1002 Generating a 1024 bit RSA private key
1003 .......++++++
1004 .............................++++++
1005 writing new private key to 'cert.pem'
1006 -----
1007 You are about to be asked to enter information that will be incorporated
1008 into your certificate request.
1009 What you are about to enter is what is called a Distinguished Name or a DN.
1010 There are quite a few fields but you can leave some blank
1011 For some fields there will be a default value,
1012 If you enter '.', the field will be left blank.
1013 -----
1014 Country Name (2 letter code) [AU]:US
1015 State or Province Name (full name) [Some-State]:MyState
1016 Locality Name (eg, city) []:Some City
1017 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
1018 Organizational Unit Name (eg, section) []:My Group
1019 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
1020 Email Address []:ops@myserver.mygroup.myorganization.com
1021 %
Thomas Woutersed03b412007-08-28 21:37:11 +00001022
Georg Brandl7f01a132009-09-16 15:58:14 +00001023The disadvantage of a self-signed certificate is that it is its own root
1024certificate, and no one else will have it in their cache of known (and trusted)
1025root certificates.
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001026
1027
Thomas Woutersed03b412007-08-28 21:37:11 +00001028Examples
1029--------
1030
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001031Testing for SSL support
1032^^^^^^^^^^^^^^^^^^^^^^^
1033
Georg Brandl7f01a132009-09-16 15:58:14 +00001034To test for the presence of SSL support in a Python installation, user code
1035should use the following idiom::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001036
1037 try:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001038 import ssl
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001039 except ImportError:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001040 pass
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001041 else:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001042 ... # do something that requires SSL support
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001043
1044Client-side operation
1045^^^^^^^^^^^^^^^^^^^^^
1046
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001047This example connects to an SSL server and prints the server's certificate::
Thomas Woutersed03b412007-08-28 21:37:11 +00001048
1049 import socket, ssl, pprint
1050
1051 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001052 # require a certificate from the server
1053 ssl_sock = ssl.wrap_socket(s,
1054 ca_certs="/etc/ca_certs_file",
1055 cert_reqs=ssl.CERT_REQUIRED)
Thomas Woutersed03b412007-08-28 21:37:11 +00001056 ssl_sock.connect(('www.verisign.com', 443))
1057
Georg Brandl6911e3c2007-09-04 07:15:32 +00001058 pprint.pprint(ssl_sock.getpeercert())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001059 # note that closing the SSLSocket will also close the underlying socket
Thomas Woutersed03b412007-08-28 21:37:11 +00001060 ssl_sock.close()
1061
Antoine Pitrou441ae042012-01-06 20:06:15 +01001062As of January 6, 2012, the certificate printed by this program looks like
Georg Brandl7f01a132009-09-16 15:58:14 +00001063this::
Thomas Woutersed03b412007-08-28 21:37:11 +00001064
Antoine Pitrou441ae042012-01-06 20:06:15 +01001065 {'issuer': ((('countryName', 'US'),),
1066 (('organizationName', 'VeriSign, Inc.'),),
1067 (('organizationalUnitName', 'VeriSign Trust Network'),),
1068 (('organizationalUnitName',
1069 'Terms of use at https://www.verisign.com/rpa (c)06'),),
1070 (('commonName',
1071 'VeriSign Class 3 Extended Validation SSL SGC CA'),)),
1072 'notAfter': 'May 25 23:59:59 2012 GMT',
1073 'notBefore': 'May 26 00:00:00 2010 GMT',
1074 'serialNumber': '53D2BEF924A7245E83CA01E46CAA2477',
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001075 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
1076 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
1077 (('businessCategory', 'V1.0, Clause 5.(b)'),),
1078 (('serialNumber', '2497886'),),
1079 (('countryName', 'US'),),
1080 (('postalCode', '94043'),),
1081 (('stateOrProvinceName', 'California'),),
1082 (('localityName', 'Mountain View'),),
1083 (('streetAddress', '487 East Middlefield Road'),),
1084 (('organizationName', 'VeriSign, Inc.'),),
1085 (('organizationalUnitName', ' Production Security Services'),),
Antoine Pitrou441ae042012-01-06 20:06:15 +01001086 (('commonName', 'www.verisign.com'),)),
1087 'subjectAltName': (('DNS', 'www.verisign.com'),
1088 ('DNS', 'verisign.com'),
1089 ('DNS', 'www.verisign.net'),
1090 ('DNS', 'verisign.net'),
1091 ('DNS', 'www.verisign.mobi'),
1092 ('DNS', 'verisign.mobi'),
1093 ('DNS', 'www.verisign.eu'),
1094 ('DNS', 'verisign.eu')),
1095 'version': 3}
Thomas Woutersed03b412007-08-28 21:37:11 +00001096
Antoine Pitrou152efa22010-05-16 18:19:27 +00001097This other example first creates an SSL context, instructs it to verify
1098certificates sent by peers, and feeds it a set of recognized certificate
1099authorities (CA)::
1100
1101 >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001102 >>> context.verify_mode = ssl.CERT_REQUIRED
Antoine Pitrou152efa22010-05-16 18:19:27 +00001103 >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
1104
1105(it is assumed your operating system places a bundle of all CA certificates
1106in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have
1107to adjust the location)
1108
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001109When you use the context to connect to a server, :const:`CERT_REQUIRED`
Antoine Pitrou152efa22010-05-16 18:19:27 +00001110validates the server certificate: it ensures that the server certificate
1111was signed with one of the CA certificates, and checks the signature for
1112correctness::
1113
1114 >>> conn = context.wrap_socket(socket.socket(socket.AF_INET))
1115 >>> conn.connect(("linuxfr.org", 443))
1116
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001117You should then fetch the certificate and check its fields for conformity::
Antoine Pitrou152efa22010-05-16 18:19:27 +00001118
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001119 >>> cert = conn.getpeercert()
1120 >>> ssl.match_hostname(cert, "linuxfr.org")
1121
1122Visual inspection shows that the certificate does identify the desired service
1123(that is, the HTTPS host ``linuxfr.org``)::
1124
1125 >>> pprint.pprint(cert)
Antoine Pitrou441ae042012-01-06 20:06:15 +01001126 {'issuer': ((('organizationName', 'CAcert Inc.'),),
1127 (('organizationalUnitName', 'http://www.CAcert.org'),),
1128 (('commonName', 'CAcert Class 3 Root'),)),
1129 'notAfter': 'Jun 7 21:02:24 2013 GMT',
1130 'notBefore': 'Jun 8 21:02:24 2011 GMT',
1131 'serialNumber': 'D3E9',
Antoine Pitrou152efa22010-05-16 18:19:27 +00001132 'subject': ((('commonName', 'linuxfr.org'),),),
Antoine Pitrou441ae042012-01-06 20:06:15 +01001133 'subjectAltName': (('DNS', 'linuxfr.org'),
1134 ('othername', '<unsupported>'),
1135 ('DNS', 'linuxfr.org'),
1136 ('othername', '<unsupported>'),
1137 ('DNS', 'dev.linuxfr.org'),
1138 ('othername', '<unsupported>'),
1139 ('DNS', 'prod.linuxfr.org'),
1140 ('othername', '<unsupported>'),
1141 ('DNS', 'alpha.linuxfr.org'),
1142 ('othername', '<unsupported>'),
1143 ('DNS', '*.linuxfr.org'),
1144 ('othername', '<unsupported>')),
1145 'version': 3}
Antoine Pitrou152efa22010-05-16 18:19:27 +00001146
1147Now that you are assured of its authenticity, you can proceed to talk with
1148the server::
1149
Antoine Pitroudab64262010-09-19 13:31:06 +00001150 >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
1151 >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
Antoine Pitrou152efa22010-05-16 18:19:27 +00001152 [b'HTTP/1.1 302 Found',
1153 b'Date: Sun, 16 May 2010 13:43:28 GMT',
1154 b'Server: Apache/2.2',
1155 b'Location: https://linuxfr.org/pub/',
1156 b'Vary: Accept-Encoding',
1157 b'Connection: close',
1158 b'Content-Type: text/html; charset=iso-8859-1',
1159 b'',
1160 b'']
1161
Antoine Pitrou152efa22010-05-16 18:19:27 +00001162See the discussion of :ref:`ssl-security` below.
1163
1164
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001165Server-side operation
1166^^^^^^^^^^^^^^^^^^^^^
1167
Antoine Pitrou152efa22010-05-16 18:19:27 +00001168For server operation, typically you'll need to have a server certificate, and
1169private key, each in a file. You'll first create a context holding the key
1170and the certificate, so that clients can check your authenticity. Then
1171you'll open a socket, bind it to a port, call :meth:`listen` on it, and start
1172waiting for clients to connect::
Thomas Woutersed03b412007-08-28 21:37:11 +00001173
1174 import socket, ssl
1175
Antoine Pitrou152efa22010-05-16 18:19:27 +00001176 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1177 context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")
1178
Thomas Woutersed03b412007-08-28 21:37:11 +00001179 bindsocket = socket.socket()
1180 bindsocket.bind(('myaddr.mydomain.com', 10023))
1181 bindsocket.listen(5)
1182
Antoine Pitrou152efa22010-05-16 18:19:27 +00001183When a client connects, you'll call :meth:`accept` on the socket to get the
1184new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket`
1185method to create a server-side SSL socket for the connection::
Thomas Woutersed03b412007-08-28 21:37:11 +00001186
1187 while True:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001188 newsocket, fromaddr = bindsocket.accept()
1189 connstream = context.wrap_socket(newsocket, server_side=True)
1190 try:
1191 deal_with_client(connstream)
1192 finally:
Antoine Pitroub205d582011-01-02 22:09:27 +00001193 connstream.shutdown(socket.SHUT_RDWR)
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001194 connstream.close()
Thomas Woutersed03b412007-08-28 21:37:11 +00001195
Antoine Pitrou152efa22010-05-16 18:19:27 +00001196Then you'll read data from the ``connstream`` and do something with it till you
Georg Brandl7f01a132009-09-16 15:58:14 +00001197are finished with the client (or the client is finished with you)::
Thomas Woutersed03b412007-08-28 21:37:11 +00001198
1199 def deal_with_client(connstream):
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001200 data = connstream.recv(1024)
1201 # empty data means the client is finished with us
1202 while data:
1203 if not do_something(connstream, data):
1204 # we'll assume do_something returns False
1205 # when we're finished with client
1206 break
1207 data = connstream.recv(1024)
1208 # finished with client
Thomas Woutersed03b412007-08-28 21:37:11 +00001209
Antoine Pitrou152efa22010-05-16 18:19:27 +00001210And go back to listening for new client connections (of course, a real server
1211would probably handle each client connection in a separate thread, or put
1212the sockets in non-blocking mode and use an event loop).
1213
1214
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001215.. _ssl-nonblocking:
1216
1217Notes on non-blocking sockets
1218-----------------------------
1219
1220When working with non-blocking sockets, there are several things you need
1221to be aware of:
1222
1223- Calling :func:`~select.select` tells you that the OS-level socket can be
1224 read from (or written to), but it does not imply that there is sufficient
1225 data at the upper SSL layer. For example, only part of an SSL frame might
1226 have arrived. Therefore, you must be ready to handle :meth:`SSLSocket.recv`
1227 and :meth:`SSLSocket.send` failures, and retry after another call to
1228 :func:`~select.select`.
1229
1230 (of course, similar provisions apply when using other primitives such as
1231 :func:`~select.poll`)
1232
1233- The SSL handshake itself will be non-blocking: the
1234 :meth:`SSLSocket.do_handshake` method has to be retried until it returns
1235 successfully. Here is a synopsis using :func:`~select.select` to wait for
1236 the socket's readiness::
1237
1238 while True:
1239 try:
1240 sock.do_handshake()
1241 break
Antoine Pitrou873bf262011-10-27 23:59:03 +02001242 except ssl.SSLWantReadError:
1243 select.select([sock], [], [])
1244 except ssl.SSLWantWriteError:
1245 select.select([], [sock], [])
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001246
1247
Antoine Pitrou152efa22010-05-16 18:19:27 +00001248.. _ssl-security:
1249
1250Security considerations
1251-----------------------
1252
1253Verifying certificates
1254^^^^^^^^^^^^^^^^^^^^^^
1255
1256:const:`CERT_NONE` is the default. Since it does not authenticate the other
1257peer, it can be insecure, especially in client mode where most of time you
1258would like to ensure the authenticity of the server you're talking to.
1259Therefore, when in client mode, it is highly recommended to use
1260:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001261have to check that the server certificate, which can be obtained by calling
1262:meth:`SSLSocket.getpeercert`, matches the desired service. For many
1263protocols and applications, the service can be identified by the hostname;
1264in this case, the :func:`match_hostname` function can be used.
Antoine Pitrou152efa22010-05-16 18:19:27 +00001265
1266In server mode, if you want to authenticate your clients using the SSL layer
1267(rather than using a higher-level authentication mechanism), you'll also have
1268to specify :const:`CERT_REQUIRED` and similarly check the client certificate.
1269
1270 .. note::
1271
1272 In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are
1273 equivalent unless anonymous ciphers are enabled (they are disabled
1274 by default).
Thomas Woutersed03b412007-08-28 21:37:11 +00001275
Antoine Pitroub5218772010-05-21 09:56:06 +00001276Protocol versions
1277^^^^^^^^^^^^^^^^^
1278
1279SSL version 2 is considered insecure and is therefore dangerous to use. If
1280you want maximum compatibility between clients and servers, it is recommended
1281to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable
1282SSLv2 explicitly using the :data:`SSLContext.options` attribute::
1283
1284 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1285 context.options |= ssl.OP_NO_SSLv2
1286
1287The SSL context created above will allow SSLv3 and TLSv1 connections, but
1288not SSLv2.
1289
Antoine Pitroub7ffed82012-01-04 02:53:44 +01001290Cipher selection
1291^^^^^^^^^^^^^^^^
1292
1293If you have advanced security requirements, fine-tuning of the ciphers
1294enabled when negotiating a SSL session is possible through the
1295:meth:`SSLContext.set_ciphers` method. Starting from Python 3.2.3, the
1296ssl module disables certain weak ciphers by default, but you may want
1297to further restrict the cipher choice. For example::
1298
1299 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1300 context.set_ciphers('HIGH:!aNULL:!eNULL')
1301
1302The ``!aNULL:!eNULL`` part of the cipher spec is necessary to disable ciphers
1303which don't provide both encryption and authentication. Be sure to read
1304OpenSSL's documentation about the `cipher list
1305format <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
1306If you want to check which ciphers are enabled by a given cipher list,
1307use the ``openssl ciphers`` command on your system.
1308
Georg Brandl48310cd2009-01-03 21:18:54 +00001309
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001310.. seealso::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001311
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001312 Class :class:`socket.socket`
Georg Brandl4a6cf6c2013-10-06 18:20:31 +02001313 Documentation of underlying :mod:`socket` class
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001314
Georg Brandl4a6cf6c2013-10-06 18:20:31 +02001315 `SSL/TLS Strong Encryption: An Introduction <http://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html>`_
1316 Intro from the Apache webserver documentation
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001317
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
1319 Steve Kent
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001320
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001321 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
1322 D. Eastlake et. al.
Thomas Wouters89d996e2007-09-08 17:39:28 +00001323
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001324 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
1325 Housley et. al.
Antoine Pitroud5323212010-10-22 18:19:07 +00001326
1327 `RFC 4366: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc4366>`_
1328 Blake-Wilson et. al.