blob: 40dc710b1677a05fcbe9967bdf0a7d63bf547b6b [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
286 in :rfc:`2818`, except that IP addresses are not currently supported.
287 In addition to HTTPS, this function should be suitable for checking the
288 identity of servers in various SSL-based protocols such as FTPS, IMAPS,
289 POPS and others.
290
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
Thomas Woutersed03b412007-08-28 21:37:11 +0000304.. function:: cert_time_to_seconds(timestring)
305
Georg Brandl7f01a132009-09-16 15:58:14 +0000306 Returns a floating-point value containing a normal seconds-after-the-epoch
307 time value, given the time-string representing the "notBefore" or "notAfter"
308 date from a certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000309
310 Here's an example::
311
312 >>> import ssl
313 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
314 1178694000.0
315 >>> import time
316 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
317 'Wed May 9 00:00:00 2007'
Thomas Woutersed03b412007-08-28 21:37:11 +0000318
Georg Brandl7f01a132009-09-16 15:58:14 +0000319.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000320
Georg Brandl7f01a132009-09-16 15:58:14 +0000321 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
322 *port-number*) pair, fetches the server's certificate, and returns it as a
323 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
324 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
325 specified, it should be a file containing a list of root certificates, the
326 same format as used for the same parameter in :func:`wrap_socket`. The call
327 will attempt to validate the server certificate against that set of root
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000328 certificates, and will fail if the validation attempt fails.
329
Antoine Pitrou15399c32011-04-28 19:23:55 +0200330 .. versionchanged:: 3.3
331 This function is now IPv6-compatible.
332
Georg Brandl7f01a132009-09-16 15:58:14 +0000333.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000334
335 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
336 string version of the same certificate.
337
Georg Brandl7f01a132009-09-16 15:58:14 +0000338.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000339
Georg Brandl7f01a132009-09-16 15:58:14 +0000340 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
341 bytes for that same certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000342
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000343Constants
344^^^^^^^^^
345
Thomas Woutersed03b412007-08-28 21:37:11 +0000346.. data:: CERT_NONE
347
Antoine Pitrou152efa22010-05-16 18:19:27 +0000348 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
349 parameter to :func:`wrap_socket`. In this mode (the default), no
350 certificates will be required from the other side of the socket connection.
351 If a certificate is received from the other end, no attempt to validate it
352 is made.
353
354 See the discussion of :ref:`ssl-security` below.
Thomas Woutersed03b412007-08-28 21:37:11 +0000355
356.. data:: CERT_OPTIONAL
357
Antoine Pitrou152efa22010-05-16 18:19:27 +0000358 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
359 parameter to :func:`wrap_socket`. In this mode no certificates will be
360 required from the other side of the socket connection; but if they
361 are provided, validation will be attempted and an :class:`SSLError`
362 will be raised on failure.
363
364 Use of this setting requires a valid set of CA certificates to
365 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
366 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000367
368.. data:: CERT_REQUIRED
369
Antoine Pitrou152efa22010-05-16 18:19:27 +0000370 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
371 parameter to :func:`wrap_socket`. In this mode, certificates are
372 required from the other side of the socket connection; an :class:`SSLError`
373 will be raised if no certificate is provided, or if its validation fails.
374
375 Use of this setting requires a valid set of CA certificates to
376 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
377 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000378
379.. data:: PROTOCOL_SSLv2
380
381 Selects SSL version 2 as the channel encryption protocol.
382
Victor Stinner3de49192011-05-09 00:42:58 +0200383 This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
384 flag.
385
Antoine Pitrou8eac60d2010-05-16 14:19:41 +0000386 .. warning::
387
388 SSL version 2 is insecure. Its use is highly discouraged.
389
Thomas Woutersed03b412007-08-28 21:37:11 +0000390.. data:: PROTOCOL_SSLv23
391
Georg Brandl7f01a132009-09-16 15:58:14 +0000392 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
393 setting to use with servers for maximum compatibility with the other end of
394 an SSL connection, but it may cause the specific ciphers chosen for the
395 encryption to be of fairly low quality.
Thomas Woutersed03b412007-08-28 21:37:11 +0000396
397.. data:: PROTOCOL_SSLv3
398
Georg Brandl7f01a132009-09-16 15:58:14 +0000399 Selects SSL version 3 as the channel encryption protocol. For clients, this
400 is the maximally compatible SSL variant.
Thomas Woutersed03b412007-08-28 21:37:11 +0000401
402.. data:: PROTOCOL_TLSv1
403
Georg Brandl7f01a132009-09-16 15:58:14 +0000404 Selects TLS version 1 as the channel encryption protocol. This is the most
405 modern version, and probably the best choice for maximum protection, if both
406 sides can speak it.
Thomas Woutersed03b412007-08-28 21:37:11 +0000407
Antoine Pitroub5218772010-05-21 09:56:06 +0000408.. data:: OP_ALL
409
410 Enables workarounds for various bugs present in other SSL implementations.
Antoine Pitrou9f6b02e2012-01-27 10:02:55 +0100411 This option is set by default. It does not necessarily set the same
412 flags as OpenSSL's ``SSL_OP_ALL`` constant.
Antoine Pitroub5218772010-05-21 09:56:06 +0000413
414 .. versionadded:: 3.2
415
416.. data:: OP_NO_SSLv2
417
418 Prevents an SSLv2 connection. This option is only applicable in
419 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
420 choosing SSLv2 as the protocol version.
421
422 .. versionadded:: 3.2
423
424.. data:: OP_NO_SSLv3
425
426 Prevents an SSLv3 connection. This option is only applicable in
427 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
428 choosing SSLv3 as the protocol version.
429
430 .. versionadded:: 3.2
431
432.. data:: OP_NO_TLSv1
433
434 Prevents a TLSv1 connection. This option is only applicable in
435 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
436 choosing TLSv1 as the protocol version.
437
438 .. versionadded:: 3.2
439
Antoine Pitrou6db49442011-12-19 13:27:11 +0100440.. data:: OP_CIPHER_SERVER_PREFERENCE
441
442 Use the server's cipher ordering preference, rather than the client's.
443 This option has no effect on client sockets and SSLv2 server sockets.
444
445 .. versionadded:: 3.3
446
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100447.. data:: OP_SINGLE_DH_USE
448
449 Prevents re-use of the same DH key for distinct SSL sessions. This
450 improves forward secrecy but requires more computational resources.
451 This option only applies to server sockets.
452
453 .. versionadded:: 3.3
454
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100455.. data:: OP_SINGLE_ECDH_USE
456
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100457 Prevents re-use of the same ECDH key for distinct SSL sessions. This
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100458 improves forward secrecy but requires more computational resources.
459 This option only applies to server sockets.
460
461 .. versionadded:: 3.3
462
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100463.. data:: OP_NO_COMPRESSION
464
465 Disable compression on the SSL channel. This is useful if the application
466 protocol supports its own compression scheme.
467
468 This option is only available with OpenSSL 1.0.0 and later.
469
470 .. versionadded:: 3.3
471
Antoine Pitrou501da612011-12-21 09:27:41 +0100472.. data:: HAS_ECDH
473
474 Whether the OpenSSL library has built-in support for Elliptic Curve-based
475 Diffie-Hellman key exchange. This should be true unless the feature was
476 explicitly disabled by the distributor.
477
478 .. versionadded:: 3.3
479
Antoine Pitroud5323212010-10-22 18:19:07 +0000480.. data:: HAS_SNI
481
482 Whether the OpenSSL library has built-in support for the *Server Name
483 Indication* extension to the SSLv3 and TLSv1 protocols (as defined in
484 :rfc:`4366`). When true, you can use the *server_hostname* argument to
485 :meth:`SSLContext.wrap_socket`.
486
487 .. versionadded:: 3.2
488
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100489.. data:: HAS_NPN
490
491 Whether the OpenSSL library has built-in support for *Next Protocol
492 Negotiation* as described in the `NPN draft specification
493 <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. When true,
494 you can use the :meth:`SSLContext.set_npn_protocols` method to advertise
495 which protocols you want to support.
496
497 .. versionadded:: 3.3
498
Antoine Pitroud6494802011-07-21 01:11:30 +0200499.. data:: CHANNEL_BINDING_TYPES
500
501 List of supported TLS channel binding types. Strings in this list
502 can be used as arguments to :meth:`SSLSocket.get_channel_binding`.
503
504 .. versionadded:: 3.3
505
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000506.. data:: OPENSSL_VERSION
507
508 The version string of the OpenSSL library loaded by the interpreter::
509
510 >>> ssl.OPENSSL_VERSION
511 'OpenSSL 0.9.8k 25 Mar 2009'
512
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000513 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000514
515.. data:: OPENSSL_VERSION_INFO
516
517 A tuple of five integers representing version information about the
518 OpenSSL library::
519
520 >>> ssl.OPENSSL_VERSION_INFO
521 (0, 9, 8, 11, 15)
522
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000523 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000524
525.. data:: OPENSSL_VERSION_NUMBER
526
527 The raw version number of the OpenSSL library, as a single integer::
528
529 >>> ssl.OPENSSL_VERSION_NUMBER
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000530 9470143
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000531 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000532 '0x9080bf'
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000533
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000534 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000535
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100536.. data:: ALERT_DESCRIPTION_HANDSHAKE_FAILURE
537 ALERT_DESCRIPTION_INTERNAL_ERROR
538 ALERT_DESCRIPTION_*
539
540 Alert Descriptions from :rfc:`5246` and others. The `IANA TLS Alert Registry
541 <http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6>`_
542 contains this list and references to the RFCs where their meaning is defined.
543
544 Used as the return value of the callback function in
545 :meth:`SSLContext.set_servername_callback`.
546
547 .. versionadded:: 3.4
548
Thomas Woutersed03b412007-08-28 21:37:11 +0000549
Antoine Pitrou152efa22010-05-16 18:19:27 +0000550SSL Sockets
551-----------
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000552
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000553SSL sockets provide the following methods of :ref:`socket-objects`:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000554
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000555- :meth:`~socket.socket.accept()`
556- :meth:`~socket.socket.bind()`
557- :meth:`~socket.socket.close()`
558- :meth:`~socket.socket.connect()`
559- :meth:`~socket.socket.detach()`
560- :meth:`~socket.socket.fileno()`
561- :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`
562- :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`
563- :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`,
564 :meth:`~socket.socket.setblocking()`
565- :meth:`~socket.socket.listen()`
566- :meth:`~socket.socket.makefile()`
567- :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()`
568 (but passing a non-zero ``flags`` argument is not allowed)
569- :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with
570 the same limitation)
571- :meth:`~socket.socket.shutdown()`
572
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +0200573However, since the SSL (and TLS) protocol has its own framing atop
574of TCP, the SSL sockets abstraction can, in certain respects, diverge from
575the specification of normal, OS-level sockets. See especially the
576:ref:`notes on non-blocking sockets <ssl-nonblocking>`.
577
578SSL sockets also have the following additional methods and attributes:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000579
Bill Janssen48dc27c2007-12-05 03:38:10 +0000580.. method:: SSLSocket.do_handshake()
581
Antoine Pitroub3593ca2011-07-11 01:39:19 +0200582 Perform the SSL setup handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000583
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000584.. method:: SSLSocket.getpeercert(binary_form=False)
585
Georg Brandl7f01a132009-09-16 15:58:14 +0000586 If there is no certificate for the peer on the other end of the connection,
587 returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000588
Georg Brandl7f01a132009-09-16 15:58:14 +0000589 If the parameter ``binary_form`` is :const:`False`, and a certificate was
590 received from the peer, this method returns a :class:`dict` instance. If the
591 certificate was not validated, the dict is empty. If the certificate was
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200592 validated, it returns a dict with several keys, amongst them ``subject``
593 (the principal for which the certificate was issued) and ``issuer``
594 (the principal issuing the certificate). If a certificate contains an
595 instance of the *Subject Alternative Name* extension (see :rfc:`3280`),
596 there will also be a ``subjectAltName`` key in the dictionary.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000597
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200598 The ``subject`` and ``issuer`` fields are tuples containing the sequence
599 of relative distinguished names (RDNs) given in the certificate's data
600 structure for the respective fields, and each RDN is a sequence of
601 name-value pairs. Here is a real-world example::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000602
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200603 {'issuer': ((('countryName', 'IL'),),
604 (('organizationName', 'StartCom Ltd.'),),
605 (('organizationalUnitName',
606 'Secure Digital Certificate Signing'),),
607 (('commonName',
608 'StartCom Class 2 Primary Intermediate Server CA'),)),
609 'notAfter': 'Nov 22 08:15:19 2013 GMT',
610 'notBefore': 'Nov 21 03:09:52 2011 GMT',
611 'serialNumber': '95F0',
612 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
613 (('countryName', 'US'),),
614 (('stateOrProvinceName', 'California'),),
615 (('localityName', 'San Francisco'),),
616 (('organizationName', 'Electronic Frontier Foundation, Inc.'),),
617 (('commonName', '*.eff.org'),),
618 (('emailAddress', 'hostmaster@eff.org'),)),
619 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
620 'version': 3}
621
622 .. note::
623 To validate a certificate for a particular service, you can use the
624 :func:`match_hostname` function.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000625
Georg Brandl7f01a132009-09-16 15:58:14 +0000626 If the ``binary_form`` parameter is :const:`True`, and a certificate was
627 provided, this method returns the DER-encoded form of the entire certificate
628 as a sequence of bytes, or :const:`None` if the peer did not provide a
629 certificate. This return value is independent of validation; if validation
630 was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000631 been validated, but if :const:`CERT_NONE` was used to establish the
632 connection, the certificate, if present, will not have been validated.
633
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
783 Specify which protocols the socket should avertise during the SSL/TLS
784 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 Pitrou58ddc9d2013-01-05 21:20:29 +0100796.. method:: SSLContext.set_servername_callback(server_name_callback)
797
798 Register a callback function that will be called after the TLS Client Hello
799 handshake message has been received by the SSL/TLS server when the TLS client
800 specifies a server name indication. The server name indication mechanism
801 is specified in :rfc:`6066` section 3 - Server Name Indication.
802
803 Only one callback can be set per ``SSLContext``. If *server_name_callback*
804 is ``None`` then the callback is disabled. Calling this function a
805 subsequent time will disable the previously registered callback.
806
807 The callback function, *server_name_callback*, will be called with three
808 arguments; the first being the :class:`ssl.SSLSocket`, the second is a string
809 that represents the server name that the client is intending to communicate
810 and the third argument is the original :class:`SSLContext`. The server name
811 argument is the IDNA decoded server name.
812
813 A typical use of this callback is to change the :class:`ssl.SSLSocket`'s
814 :attr:`SSLSocket.context` attribute to a new object of type
815 :class:`SSLContext` representing a certificate chain that matches the server
816 name.
817
818 Due to the early negotiation phase of the TLS connection, only limited
819 methods and attributes are usable like
820 :meth:`SSLSocket.selected_npn_protocol` and :attr:`SSLSocket.context`.
821 :meth:`SSLSocket.getpeercert`, :meth:`SSLSocket.getpeercert`,
822 :meth:`SSLSocket.cipher` and :meth:`SSLSocket.compress` methods require that
823 the TLS connection has progressed beyond the TLS Client Hello and therefore
824 will not contain return meaningful values nor can they be called safely.
825
826 The *server_name_callback* function must return ``None`` to allow the
827 the TLS negotiation to continue. If a TLS failure is required, a constant
828 :const:`ALERT_DESCRIPTION_* <ALERT_DESCRIPTION_INTERNAL_ERROR>` can be
829 returned. Other return values will result in a TLS fatal error with
830 :const:`ALERT_DESCRIPTION_INTERNAL_ERROR`.
831
832 If there is a IDNA decoding error on the server name, the TLS connection
833 will terminate with an :const:`ALERT_DESCRIPTION_INTERNAL_ERROR` fatal TLS
834 alert message to the client.
835
836 If an exception is raised from the *server_name_callback* function the TLS
837 connection will terminate with a fatal TLS alert message
838 :const:`ALERT_DESCRIPTION_HANDSHAKE_FAILURE`.
839
840 This method will raise :exc:`NotImplementedError` if the OpenSSL library
841 had OPENSSL_NO_TLSEXT defined when it was built.
842
843 .. versionadded:: 3.4
844
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100845.. method:: SSLContext.load_dh_params(dhfile)
846
847 Load the key generation parameters for Diffie-Helman (DH) key exchange.
848 Using DH key exchange improves forward secrecy at the expense of
849 computational resources (both on the server and on the client).
850 The *dhfile* parameter should be the path to a file containing DH
851 parameters in PEM format.
852
853 This setting doesn't apply to client sockets. You can also use the
854 :data:`OP_SINGLE_DH_USE` option to further improve security.
855
856 .. versionadded:: 3.3
857
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100858.. method:: SSLContext.set_ecdh_curve(curve_name)
859
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100860 Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key
861 exchange. ECDH is significantly faster than regular DH while arguably
862 as secure. The *curve_name* parameter should be a string describing
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100863 a well-known elliptic curve, for example ``prime256v1`` for a widely
864 supported curve.
865
866 This setting doesn't apply to client sockets. You can also use the
867 :data:`OP_SINGLE_ECDH_USE` option to further improve security.
868
Antoine Pitrou501da612011-12-21 09:27:41 +0100869 This method is not available if :data:`HAS_ECDH` is False.
870
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100871 .. versionadded:: 3.3
872
873 .. seealso::
874 `SSL/TLS & Perfect Forward Secrecy <http://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy.html>`_
875 Vincent Bernat.
876
Antoine Pitroud5323212010-10-22 18:19:07 +0000877.. method:: SSLContext.wrap_socket(sock, server_side=False, \
878 do_handshake_on_connect=True, suppress_ragged_eofs=True, \
879 server_hostname=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000880
881 Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
882 object. The SSL socket is tied to the context, its settings and
883 certificates. The parameters *server_side*, *do_handshake_on_connect*
884 and *suppress_ragged_eofs* have the same meaning as in the top-level
885 :func:`wrap_socket` function.
886
Antoine Pitroud5323212010-10-22 18:19:07 +0000887 On client connections, the optional parameter *server_hostname* specifies
888 the hostname of the service which we are connecting to. This allows a
889 single server to host multiple SSL-based services with distinct certificates,
890 quite similarly to HTTP virtual hosts. Specifying *server_hostname*
891 will raise a :exc:`ValueError` if the OpenSSL library doesn't have support
892 for it (that is, if :data:`HAS_SNI` is :const:`False`). Specifying
893 *server_hostname* will also raise a :exc:`ValueError` if *server_side*
894 is true.
895
Antoine Pitroub0182c82010-10-12 20:09:02 +0000896.. method:: SSLContext.session_stats()
897
898 Get statistics about the SSL sessions created or managed by this context.
899 A dictionary is returned which maps the names of each `piece of information
900 <http://www.openssl.org/docs/ssl/SSL_CTX_sess_number.html>`_ to their
901 numeric values. For example, here is the total number of hits and misses
902 in the session cache since the context was created::
903
904 >>> stats = context.session_stats()
905 >>> stats['hits'], stats['misses']
906 (0, 0)
907
Antoine Pitroub5218772010-05-21 09:56:06 +0000908.. attribute:: SSLContext.options
909
910 An integer representing the set of SSL options enabled on this context.
911 The default value is :data:`OP_ALL`, but you can specify other options
912 such as :data:`OP_NO_SSLv2` by ORing them together.
913
914 .. note::
915 With versions of OpenSSL older than 0.9.8m, it is only possible
916 to set options, not to clear them. Attempting to clear an option
917 (by resetting the corresponding bits) will raise a ``ValueError``.
918
Antoine Pitrou152efa22010-05-16 18:19:27 +0000919.. attribute:: SSLContext.protocol
920
921 The protocol version chosen when constructing the context. This attribute
922 is read-only.
923
924.. attribute:: SSLContext.verify_mode
925
926 Whether to try to verify other peers' certificates and how to behave
927 if verification fails. This attribute must be one of
928 :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.
929
930
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000931.. index:: single: certificates
932
933.. index:: single: X509 certificate
934
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000935.. _ssl-certificates:
936
Thomas Woutersed03b412007-08-28 21:37:11 +0000937Certificates
938------------
939
Georg Brandl7f01a132009-09-16 15:58:14 +0000940Certificates in general are part of a public-key / private-key system. In this
941system, each *principal*, (which may be a machine, or a person, or an
942organization) is assigned a unique two-part encryption key. One part of the key
943is public, and is called the *public key*; the other part is kept secret, and is
944called the *private key*. The two parts are related, in that if you encrypt a
945message with one of the parts, you can decrypt it with the other part, and
946**only** with the other part.
Thomas Woutersed03b412007-08-28 21:37:11 +0000947
Georg Brandl7f01a132009-09-16 15:58:14 +0000948A certificate contains information about two principals. It contains the name
949of a *subject*, and the subject's public key. It also contains a statement by a
950second principal, the *issuer*, that the subject is who he claims to be, and
951that this is indeed the subject's public key. The issuer's statement is signed
952with the issuer's private key, which only the issuer knows. However, anyone can
953verify the issuer's statement by finding the issuer's public key, decrypting the
954statement with it, and comparing it to the other information in the certificate.
955The certificate also contains information about the time period over which it is
956valid. This is expressed as two fields, called "notBefore" and "notAfter".
Thomas Woutersed03b412007-08-28 21:37:11 +0000957
Georg Brandl7f01a132009-09-16 15:58:14 +0000958In the Python use of certificates, a client or server can use a certificate to
959prove who they are. The other side of a network connection can also be required
960to produce a certificate, and that certificate can be validated to the
961satisfaction of the client or server that requires such validation. The
962connection attempt can be set to raise an exception if the validation fails.
963Validation is done automatically, by the underlying OpenSSL framework; the
964application need not concern itself with its mechanics. But the application
965does usually need to provide sets of certificates to allow this process to take
966place.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000967
Georg Brandl7f01a132009-09-16 15:58:14 +0000968Python uses files to contain certificates. They should be formatted as "PEM"
969(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
970and a footer line::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000971
972 -----BEGIN CERTIFICATE-----
973 ... (certificate in base64 PEM encoding) ...
974 -----END CERTIFICATE-----
975
Antoine Pitrou152efa22010-05-16 18:19:27 +0000976Certificate chains
977^^^^^^^^^^^^^^^^^^
978
Georg Brandl7f01a132009-09-16 15:58:14 +0000979The Python files which contain certificates can contain a sequence of
980certificates, sometimes called a *certificate chain*. This chain should start
981with the specific certificate for the principal who "is" the client or server,
982and then the certificate for the issuer of that certificate, and then the
983certificate for the issuer of *that* certificate, and so on up the chain till
984you get to a certificate which is *self-signed*, that is, a certificate which
985has the same subject and issuer, sometimes called a *root certificate*. The
986certificates should just be concatenated together in the certificate file. For
987example, suppose we had a three certificate chain, from our server certificate
988to the certificate of the certification authority that signed our server
989certificate, to the root certificate of the agency which issued the
990certification authority's certificate::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000991
992 -----BEGIN CERTIFICATE-----
993 ... (certificate for your server)...
994 -----END CERTIFICATE-----
995 -----BEGIN CERTIFICATE-----
996 ... (the certificate for the CA)...
997 -----END CERTIFICATE-----
998 -----BEGIN CERTIFICATE-----
999 ... (the root certificate for the CA's issuer)...
1000 -----END CERTIFICATE-----
1001
Antoine Pitrou152efa22010-05-16 18:19:27 +00001002CA certificates
1003^^^^^^^^^^^^^^^
1004
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001005If you are going to require validation of the other side of the connection's
1006certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandl7f01a132009-09-16 15:58:14 +00001007chains for each issuer you are willing to trust. Again, this file just contains
1008these chains concatenated together. For validation, Python will use the first
1009chain it finds in the file which matches. Some "standard" root certificates are
1010available from various certification authorities: `CACert.org
1011<http://www.cacert.org/index.php?id=3>`_, `Thawte
1012<http://www.thawte.com/roots/>`_, `Verisign
1013<http://www.verisign.com/support/roots.html>`_, `Positive SSL
1014<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
1015(used by python.org), `Equifax and GeoTrust
1016<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001017
Georg Brandl7f01a132009-09-16 15:58:14 +00001018In general, if you are using SSL3 or TLS1, you don't need to put the full chain
1019in your "CA certs" file; you only need the root certificates, and the remote
1020peer is supposed to furnish the other certificates necessary to chain from its
1021certificate to a root certificate. See :rfc:`4158` for more discussion of the
1022way in which certification chains can be built.
Thomas Woutersed03b412007-08-28 21:37:11 +00001023
Antoine Pitrou152efa22010-05-16 18:19:27 +00001024Combined key and certificate
1025^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1026
1027Often the private key is stored in the same file as the certificate; in this
1028case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain`
1029and :func:`wrap_socket` needs to be passed. If the private key is stored
1030with the certificate, it should come before the first certificate in
1031the certificate chain::
1032
1033 -----BEGIN RSA PRIVATE KEY-----
1034 ... (private key in base64 encoding) ...
1035 -----END RSA PRIVATE KEY-----
1036 -----BEGIN CERTIFICATE-----
1037 ... (certificate in base64 PEM encoding) ...
1038 -----END CERTIFICATE-----
1039
1040Self-signed certificates
1041^^^^^^^^^^^^^^^^^^^^^^^^
1042
Georg Brandl7f01a132009-09-16 15:58:14 +00001043If you are going to create a server that provides SSL-encrypted connection
1044services, you will need to acquire a certificate for that service. There are
1045many ways of acquiring appropriate certificates, such as buying one from a
1046certification authority. Another common practice is to generate a self-signed
1047certificate. The simplest way to do this is with the OpenSSL package, using
1048something like the following::
Thomas Woutersed03b412007-08-28 21:37:11 +00001049
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001050 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
1051 Generating a 1024 bit RSA private key
1052 .......++++++
1053 .............................++++++
1054 writing new private key to 'cert.pem'
1055 -----
1056 You are about to be asked to enter information that will be incorporated
1057 into your certificate request.
1058 What you are about to enter is what is called a Distinguished Name or a DN.
1059 There are quite a few fields but you can leave some blank
1060 For some fields there will be a default value,
1061 If you enter '.', the field will be left blank.
1062 -----
1063 Country Name (2 letter code) [AU]:US
1064 State or Province Name (full name) [Some-State]:MyState
1065 Locality Name (eg, city) []:Some City
1066 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
1067 Organizational Unit Name (eg, section) []:My Group
1068 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
1069 Email Address []:ops@myserver.mygroup.myorganization.com
1070 %
Thomas Woutersed03b412007-08-28 21:37:11 +00001071
Georg Brandl7f01a132009-09-16 15:58:14 +00001072The disadvantage of a self-signed certificate is that it is its own root
1073certificate, and no one else will have it in their cache of known (and trusted)
1074root certificates.
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001075
1076
Thomas Woutersed03b412007-08-28 21:37:11 +00001077Examples
1078--------
1079
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001080Testing for SSL support
1081^^^^^^^^^^^^^^^^^^^^^^^
1082
Georg Brandl7f01a132009-09-16 15:58:14 +00001083To test for the presence of SSL support in a Python installation, user code
1084should use the following idiom::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001085
1086 try:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001087 import ssl
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001088 except ImportError:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001089 pass
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001090 else:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001091 ... # do something that requires SSL support
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001092
1093Client-side operation
1094^^^^^^^^^^^^^^^^^^^^^
1095
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001096This example connects to an SSL server and prints the server's certificate::
Thomas Woutersed03b412007-08-28 21:37:11 +00001097
1098 import socket, ssl, pprint
1099
1100 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001101 # require a certificate from the server
1102 ssl_sock = ssl.wrap_socket(s,
1103 ca_certs="/etc/ca_certs_file",
1104 cert_reqs=ssl.CERT_REQUIRED)
Thomas Woutersed03b412007-08-28 21:37:11 +00001105 ssl_sock.connect(('www.verisign.com', 443))
1106
Georg Brandl6911e3c2007-09-04 07:15:32 +00001107 pprint.pprint(ssl_sock.getpeercert())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001108 # note that closing the SSLSocket will also close the underlying socket
Thomas Woutersed03b412007-08-28 21:37:11 +00001109 ssl_sock.close()
1110
Antoine Pitrou441ae042012-01-06 20:06:15 +01001111As of January 6, 2012, the certificate printed by this program looks like
Georg Brandl7f01a132009-09-16 15:58:14 +00001112this::
Thomas Woutersed03b412007-08-28 21:37:11 +00001113
Antoine Pitrou441ae042012-01-06 20:06:15 +01001114 {'issuer': ((('countryName', 'US'),),
1115 (('organizationName', 'VeriSign, Inc.'),),
1116 (('organizationalUnitName', 'VeriSign Trust Network'),),
1117 (('organizationalUnitName',
1118 'Terms of use at https://www.verisign.com/rpa (c)06'),),
1119 (('commonName',
1120 'VeriSign Class 3 Extended Validation SSL SGC CA'),)),
1121 'notAfter': 'May 25 23:59:59 2012 GMT',
1122 'notBefore': 'May 26 00:00:00 2010 GMT',
1123 'serialNumber': '53D2BEF924A7245E83CA01E46CAA2477',
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001124 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
1125 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
1126 (('businessCategory', 'V1.0, Clause 5.(b)'),),
1127 (('serialNumber', '2497886'),),
1128 (('countryName', 'US'),),
1129 (('postalCode', '94043'),),
1130 (('stateOrProvinceName', 'California'),),
1131 (('localityName', 'Mountain View'),),
1132 (('streetAddress', '487 East Middlefield Road'),),
1133 (('organizationName', 'VeriSign, Inc.'),),
1134 (('organizationalUnitName', ' Production Security Services'),),
Antoine Pitrou441ae042012-01-06 20:06:15 +01001135 (('commonName', 'www.verisign.com'),)),
1136 'subjectAltName': (('DNS', 'www.verisign.com'),
1137 ('DNS', 'verisign.com'),
1138 ('DNS', 'www.verisign.net'),
1139 ('DNS', 'verisign.net'),
1140 ('DNS', 'www.verisign.mobi'),
1141 ('DNS', 'verisign.mobi'),
1142 ('DNS', 'www.verisign.eu'),
1143 ('DNS', 'verisign.eu')),
1144 'version': 3}
Thomas Woutersed03b412007-08-28 21:37:11 +00001145
Antoine Pitrou152efa22010-05-16 18:19:27 +00001146This other example first creates an SSL context, instructs it to verify
1147certificates sent by peers, and feeds it a set of recognized certificate
1148authorities (CA)::
1149
1150 >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001151 >>> context.verify_mode = ssl.CERT_REQUIRED
Antoine Pitrou152efa22010-05-16 18:19:27 +00001152 >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
1153
1154(it is assumed your operating system places a bundle of all CA certificates
1155in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have
1156to adjust the location)
1157
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001158When you use the context to connect to a server, :const:`CERT_REQUIRED`
Antoine Pitrou152efa22010-05-16 18:19:27 +00001159validates the server certificate: it ensures that the server certificate
1160was signed with one of the CA certificates, and checks the signature for
1161correctness::
1162
1163 >>> conn = context.wrap_socket(socket.socket(socket.AF_INET))
1164 >>> conn.connect(("linuxfr.org", 443))
1165
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001166You should then fetch the certificate and check its fields for conformity::
Antoine Pitrou152efa22010-05-16 18:19:27 +00001167
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001168 >>> cert = conn.getpeercert()
1169 >>> ssl.match_hostname(cert, "linuxfr.org")
1170
1171Visual inspection shows that the certificate does identify the desired service
1172(that is, the HTTPS host ``linuxfr.org``)::
1173
1174 >>> pprint.pprint(cert)
Antoine Pitrou441ae042012-01-06 20:06:15 +01001175 {'issuer': ((('organizationName', 'CAcert Inc.'),),
1176 (('organizationalUnitName', 'http://www.CAcert.org'),),
1177 (('commonName', 'CAcert Class 3 Root'),)),
1178 'notAfter': 'Jun 7 21:02:24 2013 GMT',
1179 'notBefore': 'Jun 8 21:02:24 2011 GMT',
1180 'serialNumber': 'D3E9',
Antoine Pitrou152efa22010-05-16 18:19:27 +00001181 'subject': ((('commonName', 'linuxfr.org'),),),
Antoine Pitrou441ae042012-01-06 20:06:15 +01001182 'subjectAltName': (('DNS', 'linuxfr.org'),
1183 ('othername', '<unsupported>'),
1184 ('DNS', 'linuxfr.org'),
1185 ('othername', '<unsupported>'),
1186 ('DNS', 'dev.linuxfr.org'),
1187 ('othername', '<unsupported>'),
1188 ('DNS', 'prod.linuxfr.org'),
1189 ('othername', '<unsupported>'),
1190 ('DNS', 'alpha.linuxfr.org'),
1191 ('othername', '<unsupported>'),
1192 ('DNS', '*.linuxfr.org'),
1193 ('othername', '<unsupported>')),
1194 'version': 3}
Antoine Pitrou152efa22010-05-16 18:19:27 +00001195
1196Now that you are assured of its authenticity, you can proceed to talk with
1197the server::
1198
Antoine Pitroudab64262010-09-19 13:31:06 +00001199 >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
1200 >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
Antoine Pitrou152efa22010-05-16 18:19:27 +00001201 [b'HTTP/1.1 302 Found',
1202 b'Date: Sun, 16 May 2010 13:43:28 GMT',
1203 b'Server: Apache/2.2',
1204 b'Location: https://linuxfr.org/pub/',
1205 b'Vary: Accept-Encoding',
1206 b'Connection: close',
1207 b'Content-Type: text/html; charset=iso-8859-1',
1208 b'',
1209 b'']
1210
Antoine Pitrou152efa22010-05-16 18:19:27 +00001211See the discussion of :ref:`ssl-security` below.
1212
1213
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001214Server-side operation
1215^^^^^^^^^^^^^^^^^^^^^
1216
Antoine Pitrou152efa22010-05-16 18:19:27 +00001217For server operation, typically you'll need to have a server certificate, and
1218private key, each in a file. You'll first create a context holding the key
1219and the certificate, so that clients can check your authenticity. Then
1220you'll open a socket, bind it to a port, call :meth:`listen` on it, and start
1221waiting for clients to connect::
Thomas Woutersed03b412007-08-28 21:37:11 +00001222
1223 import socket, ssl
1224
Antoine Pitrou152efa22010-05-16 18:19:27 +00001225 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1226 context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")
1227
Thomas Woutersed03b412007-08-28 21:37:11 +00001228 bindsocket = socket.socket()
1229 bindsocket.bind(('myaddr.mydomain.com', 10023))
1230 bindsocket.listen(5)
1231
Antoine Pitrou152efa22010-05-16 18:19:27 +00001232When a client connects, you'll call :meth:`accept` on the socket to get the
1233new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket`
1234method to create a server-side SSL socket for the connection::
Thomas Woutersed03b412007-08-28 21:37:11 +00001235
1236 while True:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001237 newsocket, fromaddr = bindsocket.accept()
1238 connstream = context.wrap_socket(newsocket, server_side=True)
1239 try:
1240 deal_with_client(connstream)
1241 finally:
Antoine Pitroub205d582011-01-02 22:09:27 +00001242 connstream.shutdown(socket.SHUT_RDWR)
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001243 connstream.close()
Thomas Woutersed03b412007-08-28 21:37:11 +00001244
Antoine Pitrou152efa22010-05-16 18:19:27 +00001245Then you'll read data from the ``connstream`` and do something with it till you
Georg Brandl7f01a132009-09-16 15:58:14 +00001246are finished with the client (or the client is finished with you)::
Thomas Woutersed03b412007-08-28 21:37:11 +00001247
1248 def deal_with_client(connstream):
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001249 data = connstream.recv(1024)
1250 # empty data means the client is finished with us
1251 while data:
1252 if not do_something(connstream, data):
1253 # we'll assume do_something returns False
1254 # when we're finished with client
1255 break
1256 data = connstream.recv(1024)
1257 # finished with client
Thomas Woutersed03b412007-08-28 21:37:11 +00001258
Antoine Pitrou152efa22010-05-16 18:19:27 +00001259And go back to listening for new client connections (of course, a real server
1260would probably handle each client connection in a separate thread, or put
1261the sockets in non-blocking mode and use an event loop).
1262
1263
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001264.. _ssl-nonblocking:
1265
1266Notes on non-blocking sockets
1267-----------------------------
1268
1269When working with non-blocking sockets, there are several things you need
1270to be aware of:
1271
1272- Calling :func:`~select.select` tells you that the OS-level socket can be
1273 read from (or written to), but it does not imply that there is sufficient
1274 data at the upper SSL layer. For example, only part of an SSL frame might
1275 have arrived. Therefore, you must be ready to handle :meth:`SSLSocket.recv`
1276 and :meth:`SSLSocket.send` failures, and retry after another call to
1277 :func:`~select.select`.
1278
1279 (of course, similar provisions apply when using other primitives such as
1280 :func:`~select.poll`)
1281
1282- The SSL handshake itself will be non-blocking: the
1283 :meth:`SSLSocket.do_handshake` method has to be retried until it returns
1284 successfully. Here is a synopsis using :func:`~select.select` to wait for
1285 the socket's readiness::
1286
1287 while True:
1288 try:
1289 sock.do_handshake()
1290 break
Antoine Pitrou873bf262011-10-27 23:59:03 +02001291 except ssl.SSLWantReadError:
1292 select.select([sock], [], [])
1293 except ssl.SSLWantWriteError:
1294 select.select([], [sock], [])
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001295
1296
Antoine Pitrou152efa22010-05-16 18:19:27 +00001297.. _ssl-security:
1298
1299Security considerations
1300-----------------------
1301
1302Verifying certificates
1303^^^^^^^^^^^^^^^^^^^^^^
1304
1305:const:`CERT_NONE` is the default. Since it does not authenticate the other
1306peer, it can be insecure, especially in client mode where most of time you
1307would like to ensure the authenticity of the server you're talking to.
1308Therefore, when in client mode, it is highly recommended to use
1309:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001310have to check that the server certificate, which can be obtained by calling
1311:meth:`SSLSocket.getpeercert`, matches the desired service. For many
1312protocols and applications, the service can be identified by the hostname;
1313in this case, the :func:`match_hostname` function can be used.
Antoine Pitrou152efa22010-05-16 18:19:27 +00001314
1315In server mode, if you want to authenticate your clients using the SSL layer
1316(rather than using a higher-level authentication mechanism), you'll also have
1317to specify :const:`CERT_REQUIRED` and similarly check the client certificate.
1318
1319 .. note::
1320
1321 In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are
1322 equivalent unless anonymous ciphers are enabled (they are disabled
1323 by default).
Thomas Woutersed03b412007-08-28 21:37:11 +00001324
Antoine Pitroub5218772010-05-21 09:56:06 +00001325Protocol versions
1326^^^^^^^^^^^^^^^^^
1327
1328SSL version 2 is considered insecure and is therefore dangerous to use. If
1329you want maximum compatibility between clients and servers, it is recommended
1330to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable
1331SSLv2 explicitly using the :data:`SSLContext.options` attribute::
1332
1333 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1334 context.options |= ssl.OP_NO_SSLv2
1335
1336The SSL context created above will allow SSLv3 and TLSv1 connections, but
1337not SSLv2.
1338
Antoine Pitroub7ffed82012-01-04 02:53:44 +01001339Cipher selection
1340^^^^^^^^^^^^^^^^
1341
1342If you have advanced security requirements, fine-tuning of the ciphers
1343enabled when negotiating a SSL session is possible through the
1344:meth:`SSLContext.set_ciphers` method. Starting from Python 3.2.3, the
1345ssl module disables certain weak ciphers by default, but you may want
1346to further restrict the cipher choice. For example::
1347
1348 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1349 context.set_ciphers('HIGH:!aNULL:!eNULL')
1350
1351The ``!aNULL:!eNULL`` part of the cipher spec is necessary to disable ciphers
1352which don't provide both encryption and authentication. Be sure to read
1353OpenSSL's documentation about the `cipher list
1354format <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
1355If you want to check which ciphers are enabled by a given cipher list,
1356use the ``openssl ciphers`` command on your system.
1357
Georg Brandl48310cd2009-01-03 21:18:54 +00001358
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001359.. seealso::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001360
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001361 Class :class:`socket.socket`
1362 Documentation of underlying :mod:`socket` class
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001363
Antoine Pitrouf394e472011-10-07 16:58:07 +02001364 `TLS (Transport Layer Security) and SSL (Secure Socket Layer) <http://www3.rad.com/networks/applications/secure/tls.htm>`_
1365 Debby Koren
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001366
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001367 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
1368 Steve Kent
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001369
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001370 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
1371 D. Eastlake et. al.
Thomas Wouters89d996e2007-09-08 17:39:28 +00001372
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001373 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
1374 Housley et. al.
Antoine Pitroud5323212010-10-22 18:19:07 +00001375
1376 `RFC 4366: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc4366>`_
1377 Blake-Wilson et. al.
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001378
1379 `RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2 <http://www.ietf.org/rfc/rfc5246>`_
1380 T. Dierks et. al.
1381
1382 `RFC 6066: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc6066>`_
1383 D. Eastlake
1384
1385 `IANA TLS: Transport Layer Security (TLS) Parameters <http://www.iana.org/assignments/tls-parameters/tls-parameters.xml>`_
1386 IANA