blob: 59ebcd4863570e72ead919df50e39208203ca567 [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
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010029 cause variations in behavior. For example, TLSv1.1 and TLSv1.2 come with
30 openssl version 1.0.1.
Thomas Woutersed03b412007-08-28 21:37:11 +000031
Georg Brandl7f01a132009-09-16 15:58:14 +000032This section documents the objects and functions in the ``ssl`` module; for more
33general information about TLS, SSL, and certificates, the reader is referred to
34the documents in the "See Also" section at the bottom.
Thomas Woutersed03b412007-08-28 21:37:11 +000035
Georg Brandl7f01a132009-09-16 15:58:14 +000036This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
37:class:`socket.socket` type, and provides a socket-like wrapper that also
38encrypts and decrypts the data going over the socket with SSL. It supports
Antoine Pitroudab64262010-09-19 13:31:06 +000039additional methods such as :meth:`getpeercert`, which retrieves the
40certificate of the other side of the connection, and :meth:`cipher`,which
41retrieves the cipher being used for the secure connection.
Thomas Woutersed03b412007-08-28 21:37:11 +000042
Antoine Pitrou152efa22010-05-16 18:19:27 +000043For more sophisticated applications, the :class:`ssl.SSLContext` class
44helps manage settings and certificates, which can then be inherited
45by SSL sockets created through the :meth:`SSLContext.wrap_socket` method.
46
47
Thomas Wouters1b7f8912007-09-19 03:06:30 +000048Functions, Constants, and Exceptions
49------------------------------------
50
51.. exception:: SSLError
52
Antoine Pitrou59fdd672010-10-08 10:37:08 +000053 Raised to signal an error from the underlying SSL implementation
54 (currently provided by the OpenSSL library). This signifies some
55 problem in the higher-level encryption and authentication layer that's
56 superimposed on the underlying network connection. This error
Antoine Pitrou5574c302011-10-12 17:53:43 +020057 is a subtype of :exc:`OSError`. The error code and message of
58 :exc:`SSLError` instances are provided by the OpenSSL library.
59
60 .. versionchanged:: 3.3
61 :exc:`SSLError` used to be a subtype of :exc:`socket.error`.
Antoine Pitrou59fdd672010-10-08 10:37:08 +000062
Antoine Pitrou3b36fb12012-06-22 21:11:52 +020063 .. attribute:: library
64
65 A string mnemonic designating the OpenSSL submodule in which the error
66 occurred, such as ``SSL``, ``PEM`` or ``X509``. The range of possible
67 values depends on the OpenSSL version.
68
69 .. versionadded:: 3.3
70
71 .. attribute:: reason
72
73 A string mnemonic designating the reason this error occurred, for
74 example ``CERTIFICATE_VERIFY_FAILED``. The range of possible
75 values depends on the OpenSSL version.
76
77 .. versionadded:: 3.3
78
Antoine Pitrou41032a62011-10-27 23:56:55 +020079.. exception:: SSLZeroReturnError
80
81 A subclass of :exc:`SSLError` raised when trying to read or write and
82 the SSL connection has been closed cleanly. Note that this doesn't
83 mean that the underlying transport (read TCP) has been closed.
84
85 .. versionadded:: 3.3
86
87.. exception:: SSLWantReadError
88
89 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
90 <ssl-nonblocking>` when trying to read or write data, but more data needs
91 to be received on the underlying TCP transport before the request can be
92 fulfilled.
93
94 .. versionadded:: 3.3
95
96.. exception:: SSLWantWriteError
97
98 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
99 <ssl-nonblocking>` when trying to read or write data, but more data needs
100 to be sent on the underlying TCP transport before the request can be
101 fulfilled.
102
103 .. versionadded:: 3.3
104
105.. exception:: SSLSyscallError
106
107 A subclass of :exc:`SSLError` raised when a system error was encountered
108 while trying to fulfill an operation on a SSL socket. Unfortunately,
109 there is no easy way to inspect the original errno number.
110
111 .. versionadded:: 3.3
112
113.. exception:: SSLEOFError
114
115 A subclass of :exc:`SSLError` raised when the SSL connection has been
Antoine Pitrouf3dc2d72011-10-28 00:01:03 +0200116 terminated abruptly. Generally, you shouldn't try to reuse the underlying
Antoine Pitrou41032a62011-10-27 23:56:55 +0200117 transport when this error is encountered.
118
119 .. versionadded:: 3.3
120
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000121.. exception:: CertificateError
122
123 Raised to signal an error with a certificate (such as mismatching
124 hostname). Certificate errors detected by OpenSSL, though, raise
125 an :exc:`SSLError`.
126
127
128Socket creation
129^^^^^^^^^^^^^^^
130
131The following function allows for standalone socket creation. Starting from
132Python 3.2, it can be more flexible to use :meth:`SSLContext.wrap_socket`
133instead.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000134
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000135.. 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 +0000136
Georg Brandl7f01a132009-09-16 15:58:14 +0000137 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
138 of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
139 the underlying socket in an SSL context. For client-side sockets, the
140 context construction is lazy; if the underlying socket isn't connected yet,
141 the context construction will be performed after :meth:`connect` is called on
142 the socket. For server-side sockets, if the socket has no remote peer, it is
143 assumed to be a listening socket, and the server-side SSL wrapping is
144 automatically performed on client connections accepted via the :meth:`accept`
145 method. :func:`wrap_socket` may raise :exc:`SSLError`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000146
Georg Brandl7f01a132009-09-16 15:58:14 +0000147 The ``keyfile`` and ``certfile`` parameters specify optional files which
148 contain a certificate to be used to identify the local side of the
149 connection. See the discussion of :ref:`ssl-certificates` for more
150 information on how the certificate is stored in the ``certfile``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000151
Georg Brandl7f01a132009-09-16 15:58:14 +0000152 The parameter ``server_side`` is a boolean which identifies whether
153 server-side or client-side behavior is desired from this socket.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000154
Georg Brandl7f01a132009-09-16 15:58:14 +0000155 The parameter ``cert_reqs`` specifies whether a certificate is required from
156 the other side of the connection, and whether it will be validated if
157 provided. It must be one of the three values :const:`CERT_NONE`
158 (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
159 if provided), or :const:`CERT_REQUIRED` (required and validated). If the
160 value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
161 parameter must point to a file of CA certificates.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000162
Georg Brandl7f01a132009-09-16 15:58:14 +0000163 The ``ca_certs`` file contains a set of concatenated "certification
164 authority" certificates, which are used to validate certificates passed from
165 the other end of the connection. See the discussion of
166 :ref:`ssl-certificates` for more information about how to arrange the
167 certificates in this file.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000168
Georg Brandl7f01a132009-09-16 15:58:14 +0000169 The parameter ``ssl_version`` specifies which version of the SSL protocol to
170 use. Typically, the server chooses a particular protocol version, and the
171 client must adapt to the server's choice. Most of the versions are not
Antoine Pitrou84a2edc2012-01-09 21:35:11 +0100172 interoperable with the other versions. If not specified, the default is
173 :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other
Georg Brandl7f01a132009-09-16 15:58:14 +0000174 versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000175
Georg Brandl7f01a132009-09-16 15:58:14 +0000176 Here's a table showing which versions in a client (down the side) can connect
177 to which versions in a server (along the top):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000178
179 .. table::
180
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100181 ======================== ========= ========= ========== ========= =========== ===========
182 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1** **TLSv1.1** **TLSv1.2**
183 ------------------------ --------- --------- ---------- --------- ----------- -----------
184 *SSLv2* yes no yes no no no
185 *SSLv3* no yes yes no no no
186 *SSLv23* yes no yes no no no
187 *TLSv1* no no yes yes no no
188 *TLSv1.1* no no yes no yes no
189 *TLSv1.2* no no yes no no yes
190 ======================== ========= ========= ========== ========= =========== ===========
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000191
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000192 .. note::
193
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000194 Which connections succeed will vary depending on the version of
195 OpenSSL. For instance, in some older versions of OpenSSL (such
196 as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an
197 SSLv23 server. Another example: beginning with OpenSSL 1.0.0,
198 an SSLv23 client will not actually attempt SSLv2 connections
199 unless you explicitly enable SSLv2 ciphers; for example, you
200 might specify ``"ALL"`` or ``"SSLv2"`` as the *ciphers* parameter
201 to enable them.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000202
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000203 The *ciphers* parameter sets the available ciphers for this SSL object.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000204 It should be a string in the `OpenSSL cipher list format
205 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000206
Bill Janssen48dc27c2007-12-05 03:38:10 +0000207 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
208 handshake automatically after doing a :meth:`socket.connect`, or whether the
Georg Brandl7f01a132009-09-16 15:58:14 +0000209 application program will call it explicitly, by invoking the
210 :meth:`SSLSocket.do_handshake` method. Calling
211 :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
212 blocking behavior of the socket I/O involved in the handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000213
Georg Brandl7f01a132009-09-16 15:58:14 +0000214 The parameter ``suppress_ragged_eofs`` specifies how the
Antoine Pitroudab64262010-09-19 13:31:06 +0000215 :meth:`SSLSocket.recv` method should signal unexpected EOF from the other end
Georg Brandl7f01a132009-09-16 15:58:14 +0000216 of the connection. If specified as :const:`True` (the default), it returns a
Antoine Pitroudab64262010-09-19 13:31:06 +0000217 normal EOF (an empty bytes object) in response to unexpected EOF errors
218 raised from the underlying socket; if :const:`False`, it will raise the
219 exceptions back to the caller.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000220
Ezio Melotti4d5195b2010-04-20 10:57:44 +0000221 .. versionchanged:: 3.2
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000222 New optional argument *ciphers*.
223
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000224Random generation
225^^^^^^^^^^^^^^^^^
226
Victor Stinner99c8b162011-05-24 12:05:19 +0200227.. function:: RAND_bytes(num)
228
Victor Stinnera6752062011-05-25 11:27:40 +0200229 Returns *num* cryptographically strong pseudo-random bytes. Raises an
230 :class:`SSLError` if the PRNG has not been seeded with enough data or if the
231 operation is not supported by the current RAND method. :func:`RAND_status`
232 can be used to check the status of the PRNG and :func:`RAND_add` can be used
233 to seed the PRNG.
Victor Stinner99c8b162011-05-24 12:05:19 +0200234
Victor Stinner19fb53c2011-05-24 21:32:40 +0200235 Read the Wikipedia article, `Cryptographically secure pseudorandom number
Victor Stinnera6752062011-05-25 11:27:40 +0200236 generator (CSPRNG)
Victor Stinner19fb53c2011-05-24 21:32:40 +0200237 <http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator>`_,
238 to get the requirements of a cryptographically generator.
239
Victor Stinner99c8b162011-05-24 12:05:19 +0200240 .. versionadded:: 3.3
241
242.. function:: RAND_pseudo_bytes(num)
243
244 Returns (bytes, is_cryptographic): bytes are *num* pseudo-random bytes,
245 is_cryptographic is True if the bytes generated are cryptographically
Victor Stinnera6752062011-05-25 11:27:40 +0200246 strong. Raises an :class:`SSLError` if the operation is not supported by the
247 current RAND method.
Victor Stinner99c8b162011-05-24 12:05:19 +0200248
Victor Stinner19fb53c2011-05-24 21:32:40 +0200249 Generated pseudo-random byte sequences will be unique if they are of
250 sufficient length, but are not necessarily unpredictable. They can be used
251 for non-cryptographic purposes and for certain purposes in cryptographic
252 protocols, but usually not for key generation etc.
253
Victor Stinner99c8b162011-05-24 12:05:19 +0200254 .. versionadded:: 3.3
255
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000256.. function:: RAND_status()
257
Georg Brandl7f01a132009-09-16 15:58:14 +0000258 Returns True if the SSL pseudo-random number generator has been seeded with
259 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
260 and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
261 number generator.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000262
263.. function:: RAND_egd(path)
264
Victor Stinner99c8b162011-05-24 12:05:19 +0200265 If you are running an entropy-gathering daemon (EGD) somewhere, and *path*
Georg Brandl7f01a132009-09-16 15:58:14 +0000266 is the pathname of a socket connection open to it, this will read 256 bytes
267 of randomness from the socket, and add it to the SSL pseudo-random number
268 generator to increase the security of generated secret keys. This is
269 typically only necessary on systems without better sources of randomness.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000270
Georg Brandl7f01a132009-09-16 15:58:14 +0000271 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
272 of entropy-gathering daemons.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000273
274.. function:: RAND_add(bytes, entropy)
275
Victor Stinner99c8b162011-05-24 12:05:19 +0200276 Mixes the given *bytes* into the SSL pseudo-random number generator. The
277 parameter *entropy* (a float) is a lower bound on the entropy contained in
Georg Brandl7f01a132009-09-16 15:58:14 +0000278 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
279 information on sources of entropy.
Thomas Woutersed03b412007-08-28 21:37:11 +0000280
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000281Certificate handling
282^^^^^^^^^^^^^^^^^^^^
283
284.. function:: match_hostname(cert, hostname)
285
286 Verify that *cert* (in decoded format as returned by
287 :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules
288 applied are those for checking the identity of HTTPS servers as outlined
289 in :rfc:`2818`, except that IP addresses are not currently supported.
290 In addition to HTTPS, this function should be suitable for checking the
291 identity of servers in various SSL-based protocols such as FTPS, IMAPS,
292 POPS and others.
293
294 :exc:`CertificateError` is raised on failure. On success, the function
295 returns nothing::
296
297 >>> cert = {'subject': ((('commonName', 'example.com'),),)}
298 >>> ssl.match_hostname(cert, "example.com")
299 >>> ssl.match_hostname(cert, "example.org")
300 Traceback (most recent call last):
301 File "<stdin>", line 1, in <module>
302 File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
303 ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'
304
305 .. versionadded:: 3.2
306
Thomas Woutersed03b412007-08-28 21:37:11 +0000307.. function:: cert_time_to_seconds(timestring)
308
Georg Brandl7f01a132009-09-16 15:58:14 +0000309 Returns a floating-point value containing a normal seconds-after-the-epoch
310 time value, given the time-string representing the "notBefore" or "notAfter"
311 date from a certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000312
313 Here's an example::
314
315 >>> import ssl
316 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
317 1178694000.0
318 >>> import time
319 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
320 'Wed May 9 00:00:00 2007'
Thomas Woutersed03b412007-08-28 21:37:11 +0000321
Georg Brandl7f01a132009-09-16 15:58:14 +0000322.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000323
Georg Brandl7f01a132009-09-16 15:58:14 +0000324 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
325 *port-number*) pair, fetches the server's certificate, and returns it as a
326 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
327 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
328 specified, it should be a file containing a list of root certificates, the
329 same format as used for the same parameter in :func:`wrap_socket`. The call
330 will attempt to validate the server certificate against that set of root
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000331 certificates, and will fail if the validation attempt fails.
332
Antoine Pitrou15399c32011-04-28 19:23:55 +0200333 .. versionchanged:: 3.3
334 This function is now IPv6-compatible.
335
Georg Brandl7f01a132009-09-16 15:58:14 +0000336.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000337
338 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
339 string version of the same certificate.
340
Georg Brandl7f01a132009-09-16 15:58:14 +0000341.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000342
Georg Brandl7f01a132009-09-16 15:58:14 +0000343 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
344 bytes for that same certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000345
Christian Heimes6d7ad132013-06-09 18:02:55 +0200346.. function:: get_default_verify_paths()
347
348 Returns a named tuple with paths to OpenSSL's default cafile and capath.
349 The paths are the same as used by
350 :meth:`SSLContext.set_default_verify_paths`. The return value is a
351 :term:`named tuple` ``DefaultVerifyPaths``:
352
353 * :attr:`cafile` - resolved path to cafile or None if the file doesn't exist,
354 * :attr:`capath` - resolved path to capath or None if the directory doesn't exist,
355 * :attr:`openssl_cafile_env` - OpenSSL's environment key that points to a cafile,
356 * :attr:`openssl_cafile` - hard coded path to a cafile,
357 * :attr:`openssl_capath_env` - OpenSSL's environment key that points to a capath,
358 * :attr:`openssl_capath` - hard coded path to a capath directory
359
360 .. versionadded:: 3.4
361
Christian Heimes46bebee2013-06-09 19:03:31 +0200362.. function:: enum_cert_store(store_name, cert_type='certificate')
363
364 Retrieve certificates from Windows' system cert store. *store_name* may be
365 one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert
366 stores, too. *cert_type* is either ``certificate`` for X.509 certificates
367 or ``crl`` for X.509 certificate revocation lists.
368
369 The function returns a list of (bytes, encoding_type) tuples. The
370 encoding_type flag can be interpreted with :const:`X509_ASN_ENCODING` or
371 :const:`PKCS_7_ASN_ENCODING`.
372
373 Availability: Windows.
374
375 .. versionadded:: 3.4
Christian Heimes6d7ad132013-06-09 18:02:55 +0200376
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000377Constants
378^^^^^^^^^
379
Thomas Woutersed03b412007-08-28 21:37:11 +0000380.. data:: CERT_NONE
381
Antoine Pitrou152efa22010-05-16 18:19:27 +0000382 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
383 parameter to :func:`wrap_socket`. In this mode (the default), no
384 certificates will be required from the other side of the socket connection.
385 If a certificate is received from the other end, no attempt to validate it
386 is made.
387
388 See the discussion of :ref:`ssl-security` below.
Thomas Woutersed03b412007-08-28 21:37:11 +0000389
390.. data:: CERT_OPTIONAL
391
Antoine Pitrou152efa22010-05-16 18:19:27 +0000392 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
393 parameter to :func:`wrap_socket`. In this mode no certificates will be
394 required from the other side of the socket connection; but if they
395 are provided, validation will be attempted and an :class:`SSLError`
396 will be raised on failure.
397
398 Use of this setting requires a valid set of CA certificates to
399 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
400 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000401
402.. data:: CERT_REQUIRED
403
Antoine Pitrou152efa22010-05-16 18:19:27 +0000404 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
405 parameter to :func:`wrap_socket`. In this mode, certificates are
406 required from the other side of the socket connection; an :class:`SSLError`
407 will be raised if no certificate is provided, or if its validation fails.
408
409 Use of this setting requires a valid set of CA certificates to
410 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
411 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000412
413.. data:: PROTOCOL_SSLv2
414
415 Selects SSL version 2 as the channel encryption protocol.
416
Victor Stinner3de49192011-05-09 00:42:58 +0200417 This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
418 flag.
419
Antoine Pitrou8eac60d2010-05-16 14:19:41 +0000420 .. warning::
421
422 SSL version 2 is insecure. Its use is highly discouraged.
423
Thomas Woutersed03b412007-08-28 21:37:11 +0000424.. data:: PROTOCOL_SSLv23
425
Georg Brandl7f01a132009-09-16 15:58:14 +0000426 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
427 setting to use with servers for maximum compatibility with the other end of
428 an SSL connection, but it may cause the specific ciphers chosen for the
429 encryption to be of fairly low quality.
Thomas Woutersed03b412007-08-28 21:37:11 +0000430
431.. data:: PROTOCOL_SSLv3
432
Georg Brandl7f01a132009-09-16 15:58:14 +0000433 Selects SSL version 3 as the channel encryption protocol. For clients, this
434 is the maximally compatible SSL variant.
Thomas Woutersed03b412007-08-28 21:37:11 +0000435
436.. data:: PROTOCOL_TLSv1
437
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100438 Selects TLS version 1.0 as the channel encryption protocol.
439
440.. data:: PROTOCOL_TLSv1_1
441
442
443 Selects TLS version 1.1 as the channel encryption protocol.
444 Available only with openssl version 1.0.1+.
445
446 .. versionadded:: 3.4
447
448.. data:: PROTOCOL_TLSv1_2
449
450
451 Selects TLS version 1.2 as the channel encryption protocol. This is the most
Georg Brandl7f01a132009-09-16 15:58:14 +0000452 modern version, and probably the best choice for maximum protection, if both
453 sides can speak it.
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100454 Available only with openssl version 1.0.1+.
455
456 .. versionadded:: 3.4
Thomas Woutersed03b412007-08-28 21:37:11 +0000457
Antoine Pitroub5218772010-05-21 09:56:06 +0000458.. data:: OP_ALL
459
460 Enables workarounds for various bugs present in other SSL implementations.
Antoine Pitrou9f6b02e2012-01-27 10:02:55 +0100461 This option is set by default. It does not necessarily set the same
462 flags as OpenSSL's ``SSL_OP_ALL`` constant.
Antoine Pitroub5218772010-05-21 09:56:06 +0000463
464 .. versionadded:: 3.2
465
466.. data:: OP_NO_SSLv2
467
468 Prevents an SSLv2 connection. This option is only applicable in
469 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
470 choosing SSLv2 as the protocol version.
471
472 .. versionadded:: 3.2
473
474.. data:: OP_NO_SSLv3
475
476 Prevents an SSLv3 connection. This option is only applicable in
477 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
478 choosing SSLv3 as the protocol version.
479
480 .. versionadded:: 3.2
481
482.. data:: OP_NO_TLSv1
483
484 Prevents a TLSv1 connection. This option is only applicable in
485 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
486 choosing TLSv1 as the protocol version.
487
488 .. versionadded:: 3.2
489
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100490.. data:: OP_NO_TLSv1_1
491
492 Prevents a TLSv1.1 connection. This option is only applicable in conjunction
493 with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.1 as
494 the protocol version. Available only with openssl version 1.0.1+.
495
496 .. versionadded:: 3.4
497
498.. data:: OP_NO_TLSv1_2
499
500 Prevents a TLSv1.2 connection. This option is only applicable in conjunction
501 with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.2 as
502 the protocol version. Available only with openssl version 1.0.1+.
503
504 .. versionadded:: 3.4
505
Antoine Pitrou6db49442011-12-19 13:27:11 +0100506.. data:: OP_CIPHER_SERVER_PREFERENCE
507
508 Use the server's cipher ordering preference, rather than the client's.
509 This option has no effect on client sockets and SSLv2 server sockets.
510
511 .. versionadded:: 3.3
512
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100513.. data:: OP_SINGLE_DH_USE
514
515 Prevents re-use of the same DH key for distinct SSL sessions. This
516 improves forward secrecy but requires more computational resources.
517 This option only applies to server sockets.
518
519 .. versionadded:: 3.3
520
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100521.. data:: OP_SINGLE_ECDH_USE
522
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100523 Prevents re-use of the same ECDH key for distinct SSL sessions. This
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100524 improves forward secrecy but requires more computational resources.
525 This option only applies to server sockets.
526
527 .. versionadded:: 3.3
528
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100529.. data:: OP_NO_COMPRESSION
530
531 Disable compression on the SSL channel. This is useful if the application
532 protocol supports its own compression scheme.
533
534 This option is only available with OpenSSL 1.0.0 and later.
535
536 .. versionadded:: 3.3
537
Antoine Pitrou501da612011-12-21 09:27:41 +0100538.. data:: HAS_ECDH
539
540 Whether the OpenSSL library has built-in support for Elliptic Curve-based
541 Diffie-Hellman key exchange. This should be true unless the feature was
542 explicitly disabled by the distributor.
543
544 .. versionadded:: 3.3
545
Antoine Pitroud5323212010-10-22 18:19:07 +0000546.. data:: HAS_SNI
547
548 Whether the OpenSSL library has built-in support for the *Server Name
549 Indication* extension to the SSLv3 and TLSv1 protocols (as defined in
550 :rfc:`4366`). When true, you can use the *server_hostname* argument to
551 :meth:`SSLContext.wrap_socket`.
552
553 .. versionadded:: 3.2
554
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100555.. data:: HAS_NPN
556
557 Whether the OpenSSL library has built-in support for *Next Protocol
558 Negotiation* as described in the `NPN draft specification
559 <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. When true,
560 you can use the :meth:`SSLContext.set_npn_protocols` method to advertise
561 which protocols you want to support.
562
563 .. versionadded:: 3.3
564
Antoine Pitroud6494802011-07-21 01:11:30 +0200565.. data:: CHANNEL_BINDING_TYPES
566
567 List of supported TLS channel binding types. Strings in this list
568 can be used as arguments to :meth:`SSLSocket.get_channel_binding`.
569
570 .. versionadded:: 3.3
571
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000572.. data:: OPENSSL_VERSION
573
574 The version string of the OpenSSL library loaded by the interpreter::
575
576 >>> ssl.OPENSSL_VERSION
577 'OpenSSL 0.9.8k 25 Mar 2009'
578
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000579 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000580
581.. data:: OPENSSL_VERSION_INFO
582
583 A tuple of five integers representing version information about the
584 OpenSSL library::
585
586 >>> ssl.OPENSSL_VERSION_INFO
587 (0, 9, 8, 11, 15)
588
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000589 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000590
591.. data:: OPENSSL_VERSION_NUMBER
592
593 The raw version number of the OpenSSL library, as a single integer::
594
595 >>> ssl.OPENSSL_VERSION_NUMBER
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000596 9470143
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000597 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000598 '0x9080bf'
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000599
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000600 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000601
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100602.. data:: ALERT_DESCRIPTION_HANDSHAKE_FAILURE
603 ALERT_DESCRIPTION_INTERNAL_ERROR
604 ALERT_DESCRIPTION_*
605
606 Alert Descriptions from :rfc:`5246` and others. The `IANA TLS Alert Registry
607 <http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6>`_
608 contains this list and references to the RFCs where their meaning is defined.
609
610 Used as the return value of the callback function in
611 :meth:`SSLContext.set_servername_callback`.
612
613 .. versionadded:: 3.4
614
Christian Heimes46bebee2013-06-09 19:03:31 +0200615.. data:: X509_ASN_ENCODING
616 PKCS_7_ASN_ENCODING
617
618 Encoding flags for :func:`enum_cert_store`.
619
620 Availability: Windows.
621
622 .. versionadded:: 3.4
623
Thomas Woutersed03b412007-08-28 21:37:11 +0000624
Antoine Pitrou152efa22010-05-16 18:19:27 +0000625SSL Sockets
626-----------
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000627
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000628SSL sockets provide the following methods of :ref:`socket-objects`:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000629
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000630- :meth:`~socket.socket.accept()`
631- :meth:`~socket.socket.bind()`
632- :meth:`~socket.socket.close()`
633- :meth:`~socket.socket.connect()`
634- :meth:`~socket.socket.detach()`
635- :meth:`~socket.socket.fileno()`
636- :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`
637- :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`
638- :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`,
639 :meth:`~socket.socket.setblocking()`
640- :meth:`~socket.socket.listen()`
641- :meth:`~socket.socket.makefile()`
642- :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()`
643 (but passing a non-zero ``flags`` argument is not allowed)
644- :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with
645 the same limitation)
646- :meth:`~socket.socket.shutdown()`
647
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +0200648However, since the SSL (and TLS) protocol has its own framing atop
649of TCP, the SSL sockets abstraction can, in certain respects, diverge from
650the specification of normal, OS-level sockets. See especially the
651:ref:`notes on non-blocking sockets <ssl-nonblocking>`.
652
653SSL sockets also have the following additional methods and attributes:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000654
Bill Janssen48dc27c2007-12-05 03:38:10 +0000655.. method:: SSLSocket.do_handshake()
656
Antoine Pitroub3593ca2011-07-11 01:39:19 +0200657 Perform the SSL setup handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000658
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000659.. method:: SSLSocket.getpeercert(binary_form=False)
660
Georg Brandl7f01a132009-09-16 15:58:14 +0000661 If there is no certificate for the peer on the other end of the connection,
Antoine Pitrou20b85552013-09-29 19:50:53 +0200662 return ``None``. If the SSL handshake hasn't been done yet, raise
663 :exc:`ValueError`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000664
Antoine Pitroud34941a2013-04-16 20:27:17 +0200665 If the ``binary_form`` parameter is :const:`False`, and a certificate was
Georg Brandl7f01a132009-09-16 15:58:14 +0000666 received from the peer, this method returns a :class:`dict` instance. If the
667 certificate was not validated, the dict is empty. If the certificate was
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200668 validated, it returns a dict with several keys, amongst them ``subject``
669 (the principal for which the certificate was issued) and ``issuer``
670 (the principal issuing the certificate). If a certificate contains an
671 instance of the *Subject Alternative Name* extension (see :rfc:`3280`),
672 there will also be a ``subjectAltName`` key in the dictionary.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000673
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200674 The ``subject`` and ``issuer`` fields are tuples containing the sequence
675 of relative distinguished names (RDNs) given in the certificate's data
676 structure for the respective fields, and each RDN is a sequence of
677 name-value pairs. Here is a real-world example::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000678
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200679 {'issuer': ((('countryName', 'IL'),),
680 (('organizationName', 'StartCom Ltd.'),),
681 (('organizationalUnitName',
682 'Secure Digital Certificate Signing'),),
683 (('commonName',
684 'StartCom Class 2 Primary Intermediate Server CA'),)),
685 'notAfter': 'Nov 22 08:15:19 2013 GMT',
686 'notBefore': 'Nov 21 03:09:52 2011 GMT',
687 'serialNumber': '95F0',
688 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
689 (('countryName', 'US'),),
690 (('stateOrProvinceName', 'California'),),
691 (('localityName', 'San Francisco'),),
692 (('organizationName', 'Electronic Frontier Foundation, Inc.'),),
693 (('commonName', '*.eff.org'),),
694 (('emailAddress', 'hostmaster@eff.org'),)),
695 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
696 'version': 3}
697
698 .. note::
699 To validate a certificate for a particular service, you can use the
700 :func:`match_hostname` function.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000701
Georg Brandl7f01a132009-09-16 15:58:14 +0000702 If the ``binary_form`` parameter is :const:`True`, and a certificate was
703 provided, this method returns the DER-encoded form of the entire certificate
704 as a sequence of bytes, or :const:`None` if the peer did not provide a
Antoine Pitroud34941a2013-04-16 20:27:17 +0200705 certificate. Whether the peer provides a certificate depends on the SSL
706 socket's role:
707
708 * for a client SSL socket, the server will always provide a certificate,
709 regardless of whether validation was required;
710
711 * for a server SSL socket, the client will only provide a certificate
712 when requested by the server; therefore :meth:`getpeercert` will return
713 :const:`None` if you used :const:`CERT_NONE` (rather than
714 :const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000715
Antoine Pitroufb046912010-11-09 20:21:19 +0000716 .. versionchanged:: 3.2
717 The returned dictionary includes additional items such as ``issuer``
718 and ``notBefore``.
719
Antoine Pitrou20b85552013-09-29 19:50:53 +0200720 .. versionchanged:: 3.4
721 :exc:`ValueError` is raised when the handshake isn't done.
722
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000723.. method:: SSLSocket.cipher()
724
Georg Brandl7f01a132009-09-16 15:58:14 +0000725 Returns a three-value tuple containing the name of the cipher being used, the
726 version of the SSL protocol that defines its use, and the number of secret
727 bits being used. If no connection has been established, returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000728
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100729.. method:: SSLSocket.compression()
730
731 Return the compression algorithm being used as a string, or ``None``
732 if the connection isn't compressed.
733
734 If the higher-level protocol supports its own compression mechanism,
735 you can use :data:`OP_NO_COMPRESSION` to disable SSL-level compression.
736
737 .. versionadded:: 3.3
738
Antoine Pitroud6494802011-07-21 01:11:30 +0200739.. method:: SSLSocket.get_channel_binding(cb_type="tls-unique")
740
741 Get channel binding data for current connection, as a bytes object. Returns
742 ``None`` if not connected or the handshake has not been completed.
743
744 The *cb_type* parameter allow selection of the desired channel binding
745 type. Valid channel binding types are listed in the
746 :data:`CHANNEL_BINDING_TYPES` list. Currently only the 'tls-unique' channel
747 binding, defined by :rfc:`5929`, is supported. :exc:`ValueError` will be
748 raised if an unsupported channel binding type is requested.
749
750 .. versionadded:: 3.3
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000751
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100752.. method:: SSLSocket.selected_npn_protocol()
753
754 Returns the protocol that was selected during the TLS/SSL handshake. If
755 :meth:`SSLContext.set_npn_protocols` was not called, or if the other party
756 does not support NPN, or if the handshake has not yet happened, this will
757 return ``None``.
758
759 .. versionadded:: 3.3
760
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000761.. method:: SSLSocket.unwrap()
762
Georg Brandl7f01a132009-09-16 15:58:14 +0000763 Performs the SSL shutdown handshake, which removes the TLS layer from the
764 underlying socket, and returns the underlying socket object. This can be
765 used to go from encrypted operation over a connection to unencrypted. The
766 returned socket should always be used for further communication with the
767 other side of the connection, rather than the original socket.
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000768
Antoine Pitrouec883db2010-05-24 21:20:20 +0000769.. attribute:: SSLSocket.context
770
771 The :class:`SSLContext` object this SSL socket is tied to. If the SSL
772 socket was created using the top-level :func:`wrap_socket` function
773 (rather than :meth:`SSLContext.wrap_socket`), this is a custom context
774 object created for this SSL socket.
775
776 .. versionadded:: 3.2
777
778
Antoine Pitrou152efa22010-05-16 18:19:27 +0000779SSL Contexts
780------------
781
Antoine Pitroucafaad42010-05-24 15:58:43 +0000782.. versionadded:: 3.2
783
Antoine Pitroub0182c82010-10-12 20:09:02 +0000784An SSL context holds various data longer-lived than single SSL connections,
785such as SSL configuration options, certificate(s) and private key(s).
786It also manages a cache of SSL sessions for server-side sockets, in order
787to speed up repeated connections from the same clients.
788
Antoine Pitrou152efa22010-05-16 18:19:27 +0000789.. class:: SSLContext(protocol)
790
Antoine Pitroub0182c82010-10-12 20:09:02 +0000791 Create a new SSL context. You must pass *protocol* which must be one
792 of the ``PROTOCOL_*`` constants defined in this module.
793 :data:`PROTOCOL_SSLv23` is recommended for maximum interoperability.
794
Antoine Pitrou152efa22010-05-16 18:19:27 +0000795
796:class:`SSLContext` objects have the following methods and attributes:
797
Christian Heimes9a5395a2013-06-17 15:44:12 +0200798.. method:: SSLContext.cert_store_stats()
799
800 Get statistics about quantities of loaded X.509 certificates, count of
801 X.509 certificates flagged as CA certificates and certificate revocation
802 lists as dictionary.
803
804 Example for a context with one CA cert and one other cert::
805
806 >>> context.cert_store_stats()
807 {'crl': 0, 'x509_ca': 1, 'x509': 2}
808
809 .. versionadded:: 3.4
810
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200811.. method:: SSLContext.load_cert_chain(certfile, keyfile=None, password=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000812
813 Load a private key and the corresponding certificate. The *certfile*
814 string must be the path to a single file in PEM format containing the
815 certificate as well as any number of CA certificates needed to establish
816 the certificate's authenticity. The *keyfile* string, if present, must
817 point to a file containing the private key in. Otherwise the private
818 key will be taken from *certfile* as well. See the discussion of
819 :ref:`ssl-certificates` for more information on how the certificate
820 is stored in the *certfile*.
821
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200822 The *password* argument may be a function to call to get the password for
823 decrypting the private key. It will only be called if the private key is
824 encrypted and a password is necessary. It will be called with no arguments,
825 and it should return a string, bytes, or bytearray. If the return value is
826 a string it will be encoded as UTF-8 before using it to decrypt the key.
827 Alternatively a string, bytes, or bytearray value may be supplied directly
828 as the *password* argument. It will be ignored if the private key is not
829 encrypted and no password is needed.
830
831 If the *password* argument is not specified and a password is required,
832 OpenSSL's built-in password prompting mechanism will be used to
833 interactively prompt the user for a password.
834
Antoine Pitrou152efa22010-05-16 18:19:27 +0000835 An :class:`SSLError` is raised if the private key doesn't
836 match with the certificate.
837
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200838 .. versionchanged:: 3.3
839 New optional argument *password*.
840
Antoine Pitrou152efa22010-05-16 18:19:27 +0000841.. method:: SSLContext.load_verify_locations(cafile=None, capath=None)
842
843 Load a set of "certification authority" (CA) certificates used to validate
844 other peers' certificates when :data:`verify_mode` is other than
845 :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified.
846
Christian Heimes3e738f92013-06-09 18:07:16 +0200847 The *cafile* string, if present, is the path to a file of concatenated
Antoine Pitrou152efa22010-05-16 18:19:27 +0000848 CA certificates in PEM format. See the discussion of
849 :ref:`ssl-certificates` for more information about how to arrange the
850 certificates in this file.
851
852 The *capath* string, if present, is
853 the path to a directory containing several CA certificates in PEM format,
854 following an `OpenSSL specific layout
855 <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
856
Christian Heimes9a5395a2013-06-17 15:44:12 +0200857.. method:: SSLContext.get_ca_certs(binary_form=False)
858
859 Get a list of loaded "certification authority" (CA) certificates. If the
860 ``binary_form`` parameter is :const:`False` each list
861 entry is a dict like the output of :meth:`SSLSocket.getpeercert`. Otherwise
862 the method returns a list of DER-encoded certificates. The returned list
863 does not contain certificates from *capath* unless a certificate was
864 requested and loaded by a SSL connection.
865
Larry Hastingsd36fc432013-08-03 02:49:53 -0700866 .. versionadded:: 3.4
Christian Heimes9a5395a2013-06-17 15:44:12 +0200867
Antoine Pitrou664c2d12010-11-17 20:29:42 +0000868.. method:: SSLContext.set_default_verify_paths()
869
870 Load a set of default "certification authority" (CA) certificates from
871 a filesystem path defined when building the OpenSSL library. Unfortunately,
872 there's no easy way to know whether this method succeeds: no error is
873 returned if no certificates are to be found. When the OpenSSL library is
874 provided as part of the operating system, though, it is likely to be
875 configured properly.
876
Antoine Pitrou152efa22010-05-16 18:19:27 +0000877.. method:: SSLContext.set_ciphers(ciphers)
878
879 Set the available ciphers for sockets created with this context.
880 It should be a string in the `OpenSSL cipher list format
881 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
882 If no cipher can be selected (because compile-time options or other
883 configuration forbids use of all the specified ciphers), an
884 :class:`SSLError` will be raised.
885
886 .. note::
887 when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
888 give the currently selected cipher.
889
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100890.. method:: SSLContext.set_npn_protocols(protocols)
891
R David Murrayc7f75792013-06-26 15:11:12 -0400892 Specify which protocols the socket should advertise during the SSL/TLS
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100893 handshake. It should be a list of strings, like ``['http/1.1', 'spdy/2']``,
894 ordered by preference. The selection of a protocol will happen during the
895 handshake, and will play out according to the `NPN draft specification
896 <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. After a
897 successful handshake, the :meth:`SSLSocket.selected_npn_protocol` method will
898 return the agreed-upon protocol.
899
900 This method will raise :exc:`NotImplementedError` if :data:`HAS_NPN` is
901 False.
902
903 .. versionadded:: 3.3
904
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100905.. method:: SSLContext.set_servername_callback(server_name_callback)
906
907 Register a callback function that will be called after the TLS Client Hello
908 handshake message has been received by the SSL/TLS server when the TLS client
909 specifies a server name indication. The server name indication mechanism
910 is specified in :rfc:`6066` section 3 - Server Name Indication.
911
912 Only one callback can be set per ``SSLContext``. If *server_name_callback*
913 is ``None`` then the callback is disabled. Calling this function a
914 subsequent time will disable the previously registered callback.
915
916 The callback function, *server_name_callback*, will be called with three
917 arguments; the first being the :class:`ssl.SSLSocket`, the second is a string
918 that represents the server name that the client is intending to communicate
Antoine Pitrou50b24d02013-04-11 20:48:42 +0200919 (or :const:`None` if the TLS Client Hello does not contain a server name)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100920 and the third argument is the original :class:`SSLContext`. The server name
921 argument is the IDNA decoded server name.
922
923 A typical use of this callback is to change the :class:`ssl.SSLSocket`'s
924 :attr:`SSLSocket.context` attribute to a new object of type
925 :class:`SSLContext` representing a certificate chain that matches the server
926 name.
927
928 Due to the early negotiation phase of the TLS connection, only limited
929 methods and attributes are usable like
930 :meth:`SSLSocket.selected_npn_protocol` and :attr:`SSLSocket.context`.
931 :meth:`SSLSocket.getpeercert`, :meth:`SSLSocket.getpeercert`,
932 :meth:`SSLSocket.cipher` and :meth:`SSLSocket.compress` methods require that
933 the TLS connection has progressed beyond the TLS Client Hello and therefore
934 will not contain return meaningful values nor can they be called safely.
935
936 The *server_name_callback* function must return ``None`` to allow the
Terry Jan Reedy8e7586b2013-03-11 18:38:13 -0400937 TLS negotiation to continue. If a TLS failure is required, a constant
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100938 :const:`ALERT_DESCRIPTION_* <ALERT_DESCRIPTION_INTERNAL_ERROR>` can be
939 returned. Other return values will result in a TLS fatal error with
940 :const:`ALERT_DESCRIPTION_INTERNAL_ERROR`.
941
942 If there is a IDNA decoding error on the server name, the TLS connection
943 will terminate with an :const:`ALERT_DESCRIPTION_INTERNAL_ERROR` fatal TLS
944 alert message to the client.
945
946 If an exception is raised from the *server_name_callback* function the TLS
947 connection will terminate with a fatal TLS alert message
948 :const:`ALERT_DESCRIPTION_HANDSHAKE_FAILURE`.
949
950 This method will raise :exc:`NotImplementedError` if the OpenSSL library
951 had OPENSSL_NO_TLSEXT defined when it was built.
952
953 .. versionadded:: 3.4
954
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100955.. method:: SSLContext.load_dh_params(dhfile)
956
957 Load the key generation parameters for Diffie-Helman (DH) key exchange.
958 Using DH key exchange improves forward secrecy at the expense of
959 computational resources (both on the server and on the client).
960 The *dhfile* parameter should be the path to a file containing DH
961 parameters in PEM format.
962
963 This setting doesn't apply to client sockets. You can also use the
964 :data:`OP_SINGLE_DH_USE` option to further improve security.
965
966 .. versionadded:: 3.3
967
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100968.. method:: SSLContext.set_ecdh_curve(curve_name)
969
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100970 Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key
971 exchange. ECDH is significantly faster than regular DH while arguably
972 as secure. The *curve_name* parameter should be a string describing
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100973 a well-known elliptic curve, for example ``prime256v1`` for a widely
974 supported curve.
975
976 This setting doesn't apply to client sockets. You can also use the
977 :data:`OP_SINGLE_ECDH_USE` option to further improve security.
978
Antoine Pitrou501da612011-12-21 09:27:41 +0100979 This method is not available if :data:`HAS_ECDH` is False.
980
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100981 .. versionadded:: 3.3
982
983 .. seealso::
984 `SSL/TLS & Perfect Forward Secrecy <http://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy.html>`_
985 Vincent Bernat.
986
Antoine Pitroud5323212010-10-22 18:19:07 +0000987.. method:: SSLContext.wrap_socket(sock, server_side=False, \
988 do_handshake_on_connect=True, suppress_ragged_eofs=True, \
989 server_hostname=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000990
991 Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
992 object. The SSL socket is tied to the context, its settings and
993 certificates. The parameters *server_side*, *do_handshake_on_connect*
994 and *suppress_ragged_eofs* have the same meaning as in the top-level
995 :func:`wrap_socket` function.
996
Antoine Pitroud5323212010-10-22 18:19:07 +0000997 On client connections, the optional parameter *server_hostname* specifies
998 the hostname of the service which we are connecting to. This allows a
999 single server to host multiple SSL-based services with distinct certificates,
1000 quite similarly to HTTP virtual hosts. Specifying *server_hostname*
1001 will raise a :exc:`ValueError` if the OpenSSL library doesn't have support
1002 for it (that is, if :data:`HAS_SNI` is :const:`False`). Specifying
1003 *server_hostname* will also raise a :exc:`ValueError` if *server_side*
1004 is true.
1005
Antoine Pitroub0182c82010-10-12 20:09:02 +00001006.. method:: SSLContext.session_stats()
1007
1008 Get statistics about the SSL sessions created or managed by this context.
1009 A dictionary is returned which maps the names of each `piece of information
1010 <http://www.openssl.org/docs/ssl/SSL_CTX_sess_number.html>`_ to their
1011 numeric values. For example, here is the total number of hits and misses
1012 in the session cache since the context was created::
1013
1014 >>> stats = context.session_stats()
1015 >>> stats['hits'], stats['misses']
1016 (0, 0)
1017
Antoine Pitroub5218772010-05-21 09:56:06 +00001018.. attribute:: SSLContext.options
1019
1020 An integer representing the set of SSL options enabled on this context.
1021 The default value is :data:`OP_ALL`, but you can specify other options
1022 such as :data:`OP_NO_SSLv2` by ORing them together.
1023
1024 .. note::
1025 With versions of OpenSSL older than 0.9.8m, it is only possible
1026 to set options, not to clear them. Attempting to clear an option
1027 (by resetting the corresponding bits) will raise a ``ValueError``.
1028
Antoine Pitrou152efa22010-05-16 18:19:27 +00001029.. attribute:: SSLContext.protocol
1030
1031 The protocol version chosen when constructing the context. This attribute
1032 is read-only.
1033
1034.. attribute:: SSLContext.verify_mode
1035
1036 Whether to try to verify other peers' certificates and how to behave
1037 if verification fails. This attribute must be one of
1038 :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.
1039
1040
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001041.. index:: single: certificates
1042
1043.. index:: single: X509 certificate
1044
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001045.. _ssl-certificates:
1046
Thomas Woutersed03b412007-08-28 21:37:11 +00001047Certificates
1048------------
1049
Georg Brandl7f01a132009-09-16 15:58:14 +00001050Certificates in general are part of a public-key / private-key system. In this
1051system, each *principal*, (which may be a machine, or a person, or an
1052organization) is assigned a unique two-part encryption key. One part of the key
1053is public, and is called the *public key*; the other part is kept secret, and is
1054called the *private key*. The two parts are related, in that if you encrypt a
1055message with one of the parts, you can decrypt it with the other part, and
1056**only** with the other part.
Thomas Woutersed03b412007-08-28 21:37:11 +00001057
Georg Brandl7f01a132009-09-16 15:58:14 +00001058A certificate contains information about two principals. It contains the name
1059of a *subject*, and the subject's public key. It also contains a statement by a
1060second principal, the *issuer*, that the subject is who he claims to be, and
1061that this is indeed the subject's public key. The issuer's statement is signed
1062with the issuer's private key, which only the issuer knows. However, anyone can
1063verify the issuer's statement by finding the issuer's public key, decrypting the
1064statement with it, and comparing it to the other information in the certificate.
1065The certificate also contains information about the time period over which it is
1066valid. This is expressed as two fields, called "notBefore" and "notAfter".
Thomas Woutersed03b412007-08-28 21:37:11 +00001067
Georg Brandl7f01a132009-09-16 15:58:14 +00001068In the Python use of certificates, a client or server can use a certificate to
1069prove who they are. The other side of a network connection can also be required
1070to produce a certificate, and that certificate can be validated to the
1071satisfaction of the client or server that requires such validation. The
1072connection attempt can be set to raise an exception if the validation fails.
1073Validation is done automatically, by the underlying OpenSSL framework; the
1074application need not concern itself with its mechanics. But the application
1075does usually need to provide sets of certificates to allow this process to take
1076place.
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001077
Georg Brandl7f01a132009-09-16 15:58:14 +00001078Python uses files to contain certificates. They should be formatted as "PEM"
1079(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
1080and a footer line::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001081
1082 -----BEGIN CERTIFICATE-----
1083 ... (certificate in base64 PEM encoding) ...
1084 -----END CERTIFICATE-----
1085
Antoine Pitrou152efa22010-05-16 18:19:27 +00001086Certificate chains
1087^^^^^^^^^^^^^^^^^^
1088
Georg Brandl7f01a132009-09-16 15:58:14 +00001089The Python files which contain certificates can contain a sequence of
1090certificates, sometimes called a *certificate chain*. This chain should start
1091with the specific certificate for the principal who "is" the client or server,
1092and then the certificate for the issuer of that certificate, and then the
1093certificate for the issuer of *that* certificate, and so on up the chain till
1094you get to a certificate which is *self-signed*, that is, a certificate which
1095has the same subject and issuer, sometimes called a *root certificate*. The
1096certificates should just be concatenated together in the certificate file. For
1097example, suppose we had a three certificate chain, from our server certificate
1098to the certificate of the certification authority that signed our server
1099certificate, to the root certificate of the agency which issued the
1100certification authority's certificate::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001101
1102 -----BEGIN CERTIFICATE-----
1103 ... (certificate for your server)...
1104 -----END CERTIFICATE-----
1105 -----BEGIN CERTIFICATE-----
1106 ... (the certificate for the CA)...
1107 -----END CERTIFICATE-----
1108 -----BEGIN CERTIFICATE-----
1109 ... (the root certificate for the CA's issuer)...
1110 -----END CERTIFICATE-----
1111
Antoine Pitrou152efa22010-05-16 18:19:27 +00001112CA certificates
1113^^^^^^^^^^^^^^^
1114
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001115If you are going to require validation of the other side of the connection's
1116certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandl7f01a132009-09-16 15:58:14 +00001117chains for each issuer you are willing to trust. Again, this file just contains
1118these chains concatenated together. For validation, Python will use the first
1119chain it finds in the file which matches. Some "standard" root certificates are
1120available from various certification authorities: `CACert.org
1121<http://www.cacert.org/index.php?id=3>`_, `Thawte
1122<http://www.thawte.com/roots/>`_, `Verisign
1123<http://www.verisign.com/support/roots.html>`_, `Positive SSL
1124<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
1125(used by python.org), `Equifax and GeoTrust
1126<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001127
Georg Brandl7f01a132009-09-16 15:58:14 +00001128In general, if you are using SSL3 or TLS1, you don't need to put the full chain
1129in your "CA certs" file; you only need the root certificates, and the remote
1130peer is supposed to furnish the other certificates necessary to chain from its
1131certificate to a root certificate. See :rfc:`4158` for more discussion of the
1132way in which certification chains can be built.
Thomas Woutersed03b412007-08-28 21:37:11 +00001133
Antoine Pitrou152efa22010-05-16 18:19:27 +00001134Combined key and certificate
1135^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1136
1137Often the private key is stored in the same file as the certificate; in this
1138case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain`
1139and :func:`wrap_socket` needs to be passed. If the private key is stored
1140with the certificate, it should come before the first certificate in
1141the certificate chain::
1142
1143 -----BEGIN RSA PRIVATE KEY-----
1144 ... (private key in base64 encoding) ...
1145 -----END RSA PRIVATE KEY-----
1146 -----BEGIN CERTIFICATE-----
1147 ... (certificate in base64 PEM encoding) ...
1148 -----END CERTIFICATE-----
1149
1150Self-signed certificates
1151^^^^^^^^^^^^^^^^^^^^^^^^
1152
Georg Brandl7f01a132009-09-16 15:58:14 +00001153If you are going to create a server that provides SSL-encrypted connection
1154services, you will need to acquire a certificate for that service. There are
1155many ways of acquiring appropriate certificates, such as buying one from a
1156certification authority. Another common practice is to generate a self-signed
1157certificate. The simplest way to do this is with the OpenSSL package, using
1158something like the following::
Thomas Woutersed03b412007-08-28 21:37:11 +00001159
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001160 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
1161 Generating a 1024 bit RSA private key
1162 .......++++++
1163 .............................++++++
1164 writing new private key to 'cert.pem'
1165 -----
1166 You are about to be asked to enter information that will be incorporated
1167 into your certificate request.
1168 What you are about to enter is what is called a Distinguished Name or a DN.
1169 There are quite a few fields but you can leave some blank
1170 For some fields there will be a default value,
1171 If you enter '.', the field will be left blank.
1172 -----
1173 Country Name (2 letter code) [AU]:US
1174 State or Province Name (full name) [Some-State]:MyState
1175 Locality Name (eg, city) []:Some City
1176 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
1177 Organizational Unit Name (eg, section) []:My Group
1178 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
1179 Email Address []:ops@myserver.mygroup.myorganization.com
1180 %
Thomas Woutersed03b412007-08-28 21:37:11 +00001181
Georg Brandl7f01a132009-09-16 15:58:14 +00001182The disadvantage of a self-signed certificate is that it is its own root
1183certificate, and no one else will have it in their cache of known (and trusted)
1184root certificates.
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001185
1186
Thomas Woutersed03b412007-08-28 21:37:11 +00001187Examples
1188--------
1189
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001190Testing for SSL support
1191^^^^^^^^^^^^^^^^^^^^^^^
1192
Georg Brandl7f01a132009-09-16 15:58:14 +00001193To test for the presence of SSL support in a Python installation, user code
1194should use the following idiom::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001195
1196 try:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001197 import ssl
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001198 except ImportError:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001199 pass
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001200 else:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001201 ... # do something that requires SSL support
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001202
1203Client-side operation
1204^^^^^^^^^^^^^^^^^^^^^
1205
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001206This example connects to an SSL server and prints the server's certificate::
Thomas Woutersed03b412007-08-28 21:37:11 +00001207
1208 import socket, ssl, pprint
1209
1210 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001211 # require a certificate from the server
1212 ssl_sock = ssl.wrap_socket(s,
1213 ca_certs="/etc/ca_certs_file",
1214 cert_reqs=ssl.CERT_REQUIRED)
Thomas Woutersed03b412007-08-28 21:37:11 +00001215 ssl_sock.connect(('www.verisign.com', 443))
1216
Georg Brandl6911e3c2007-09-04 07:15:32 +00001217 pprint.pprint(ssl_sock.getpeercert())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001218 # note that closing the SSLSocket will also close the underlying socket
Thomas Woutersed03b412007-08-28 21:37:11 +00001219 ssl_sock.close()
1220
Antoine Pitrou441ae042012-01-06 20:06:15 +01001221As of January 6, 2012, the certificate printed by this program looks like
Georg Brandl7f01a132009-09-16 15:58:14 +00001222this::
Thomas Woutersed03b412007-08-28 21:37:11 +00001223
Antoine Pitrou441ae042012-01-06 20:06:15 +01001224 {'issuer': ((('countryName', 'US'),),
1225 (('organizationName', 'VeriSign, Inc.'),),
1226 (('organizationalUnitName', 'VeriSign Trust Network'),),
1227 (('organizationalUnitName',
1228 'Terms of use at https://www.verisign.com/rpa (c)06'),),
1229 (('commonName',
1230 'VeriSign Class 3 Extended Validation SSL SGC CA'),)),
1231 'notAfter': 'May 25 23:59:59 2012 GMT',
1232 'notBefore': 'May 26 00:00:00 2010 GMT',
1233 'serialNumber': '53D2BEF924A7245E83CA01E46CAA2477',
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001234 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
1235 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
1236 (('businessCategory', 'V1.0, Clause 5.(b)'),),
1237 (('serialNumber', '2497886'),),
1238 (('countryName', 'US'),),
1239 (('postalCode', '94043'),),
1240 (('stateOrProvinceName', 'California'),),
1241 (('localityName', 'Mountain View'),),
1242 (('streetAddress', '487 East Middlefield Road'),),
1243 (('organizationName', 'VeriSign, Inc.'),),
1244 (('organizationalUnitName', ' Production Security Services'),),
Antoine Pitrou441ae042012-01-06 20:06:15 +01001245 (('commonName', 'www.verisign.com'),)),
1246 'subjectAltName': (('DNS', 'www.verisign.com'),
1247 ('DNS', 'verisign.com'),
1248 ('DNS', 'www.verisign.net'),
1249 ('DNS', 'verisign.net'),
1250 ('DNS', 'www.verisign.mobi'),
1251 ('DNS', 'verisign.mobi'),
1252 ('DNS', 'www.verisign.eu'),
1253 ('DNS', 'verisign.eu')),
1254 'version': 3}
Thomas Woutersed03b412007-08-28 21:37:11 +00001255
Antoine Pitrou152efa22010-05-16 18:19:27 +00001256This other example first creates an SSL context, instructs it to verify
1257certificates sent by peers, and feeds it a set of recognized certificate
1258authorities (CA)::
1259
1260 >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001261 >>> context.verify_mode = ssl.CERT_REQUIRED
Antoine Pitrou152efa22010-05-16 18:19:27 +00001262 >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
1263
1264(it is assumed your operating system places a bundle of all CA certificates
1265in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have
1266to adjust the location)
1267
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001268When you use the context to connect to a server, :const:`CERT_REQUIRED`
Antoine Pitrou152efa22010-05-16 18:19:27 +00001269validates the server certificate: it ensures that the server certificate
1270was signed with one of the CA certificates, and checks the signature for
1271correctness::
1272
1273 >>> conn = context.wrap_socket(socket.socket(socket.AF_INET))
1274 >>> conn.connect(("linuxfr.org", 443))
1275
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001276You should then fetch the certificate and check its fields for conformity::
Antoine Pitrou152efa22010-05-16 18:19:27 +00001277
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001278 >>> cert = conn.getpeercert()
1279 >>> ssl.match_hostname(cert, "linuxfr.org")
1280
1281Visual inspection shows that the certificate does identify the desired service
1282(that is, the HTTPS host ``linuxfr.org``)::
1283
1284 >>> pprint.pprint(cert)
Antoine Pitrou441ae042012-01-06 20:06:15 +01001285 {'issuer': ((('organizationName', 'CAcert Inc.'),),
1286 (('organizationalUnitName', 'http://www.CAcert.org'),),
1287 (('commonName', 'CAcert Class 3 Root'),)),
1288 'notAfter': 'Jun 7 21:02:24 2013 GMT',
1289 'notBefore': 'Jun 8 21:02:24 2011 GMT',
1290 'serialNumber': 'D3E9',
Antoine Pitrou152efa22010-05-16 18:19:27 +00001291 'subject': ((('commonName', 'linuxfr.org'),),),
Antoine Pitrou441ae042012-01-06 20:06:15 +01001292 'subjectAltName': (('DNS', 'linuxfr.org'),
1293 ('othername', '<unsupported>'),
1294 ('DNS', 'linuxfr.org'),
1295 ('othername', '<unsupported>'),
1296 ('DNS', 'dev.linuxfr.org'),
1297 ('othername', '<unsupported>'),
1298 ('DNS', 'prod.linuxfr.org'),
1299 ('othername', '<unsupported>'),
1300 ('DNS', 'alpha.linuxfr.org'),
1301 ('othername', '<unsupported>'),
1302 ('DNS', '*.linuxfr.org'),
1303 ('othername', '<unsupported>')),
1304 'version': 3}
Antoine Pitrou152efa22010-05-16 18:19:27 +00001305
1306Now that you are assured of its authenticity, you can proceed to talk with
1307the server::
1308
Antoine Pitroudab64262010-09-19 13:31:06 +00001309 >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
1310 >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
Antoine Pitrou152efa22010-05-16 18:19:27 +00001311 [b'HTTP/1.1 302 Found',
1312 b'Date: Sun, 16 May 2010 13:43:28 GMT',
1313 b'Server: Apache/2.2',
1314 b'Location: https://linuxfr.org/pub/',
1315 b'Vary: Accept-Encoding',
1316 b'Connection: close',
1317 b'Content-Type: text/html; charset=iso-8859-1',
1318 b'',
1319 b'']
1320
Antoine Pitrou152efa22010-05-16 18:19:27 +00001321See the discussion of :ref:`ssl-security` below.
1322
1323
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001324Server-side operation
1325^^^^^^^^^^^^^^^^^^^^^
1326
Antoine Pitrou152efa22010-05-16 18:19:27 +00001327For server operation, typically you'll need to have a server certificate, and
1328private key, each in a file. You'll first create a context holding the key
1329and the certificate, so that clients can check your authenticity. Then
1330you'll open a socket, bind it to a port, call :meth:`listen` on it, and start
1331waiting for clients to connect::
Thomas Woutersed03b412007-08-28 21:37:11 +00001332
1333 import socket, ssl
1334
Antoine Pitrou152efa22010-05-16 18:19:27 +00001335 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1336 context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")
1337
Thomas Woutersed03b412007-08-28 21:37:11 +00001338 bindsocket = socket.socket()
1339 bindsocket.bind(('myaddr.mydomain.com', 10023))
1340 bindsocket.listen(5)
1341
Antoine Pitrou152efa22010-05-16 18:19:27 +00001342When a client connects, you'll call :meth:`accept` on the socket to get the
1343new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket`
1344method to create a server-side SSL socket for the connection::
Thomas Woutersed03b412007-08-28 21:37:11 +00001345
1346 while True:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001347 newsocket, fromaddr = bindsocket.accept()
1348 connstream = context.wrap_socket(newsocket, server_side=True)
1349 try:
1350 deal_with_client(connstream)
1351 finally:
Antoine Pitroub205d582011-01-02 22:09:27 +00001352 connstream.shutdown(socket.SHUT_RDWR)
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001353 connstream.close()
Thomas Woutersed03b412007-08-28 21:37:11 +00001354
Antoine Pitrou152efa22010-05-16 18:19:27 +00001355Then you'll read data from the ``connstream`` and do something with it till you
Georg Brandl7f01a132009-09-16 15:58:14 +00001356are finished with the client (or the client is finished with you)::
Thomas Woutersed03b412007-08-28 21:37:11 +00001357
1358 def deal_with_client(connstream):
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001359 data = connstream.recv(1024)
1360 # empty data means the client is finished with us
1361 while data:
1362 if not do_something(connstream, data):
1363 # we'll assume do_something returns False
1364 # when we're finished with client
1365 break
1366 data = connstream.recv(1024)
1367 # finished with client
Thomas Woutersed03b412007-08-28 21:37:11 +00001368
Antoine Pitrou152efa22010-05-16 18:19:27 +00001369And go back to listening for new client connections (of course, a real server
1370would probably handle each client connection in a separate thread, or put
1371the sockets in non-blocking mode and use an event loop).
1372
1373
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001374.. _ssl-nonblocking:
1375
1376Notes on non-blocking sockets
1377-----------------------------
1378
1379When working with non-blocking sockets, there are several things you need
1380to be aware of:
1381
1382- Calling :func:`~select.select` tells you that the OS-level socket can be
1383 read from (or written to), but it does not imply that there is sufficient
1384 data at the upper SSL layer. For example, only part of an SSL frame might
1385 have arrived. Therefore, you must be ready to handle :meth:`SSLSocket.recv`
1386 and :meth:`SSLSocket.send` failures, and retry after another call to
1387 :func:`~select.select`.
1388
1389 (of course, similar provisions apply when using other primitives such as
1390 :func:`~select.poll`)
1391
1392- The SSL handshake itself will be non-blocking: the
1393 :meth:`SSLSocket.do_handshake` method has to be retried until it returns
1394 successfully. Here is a synopsis using :func:`~select.select` to wait for
1395 the socket's readiness::
1396
1397 while True:
1398 try:
1399 sock.do_handshake()
1400 break
Antoine Pitrou873bf262011-10-27 23:59:03 +02001401 except ssl.SSLWantReadError:
1402 select.select([sock], [], [])
1403 except ssl.SSLWantWriteError:
1404 select.select([], [sock], [])
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001405
1406
Antoine Pitrou152efa22010-05-16 18:19:27 +00001407.. _ssl-security:
1408
1409Security considerations
1410-----------------------
1411
1412Verifying certificates
1413^^^^^^^^^^^^^^^^^^^^^^
1414
1415:const:`CERT_NONE` is the default. Since it does not authenticate the other
1416peer, it can be insecure, especially in client mode where most of time you
1417would like to ensure the authenticity of the server you're talking to.
1418Therefore, when in client mode, it is highly recommended to use
1419:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001420have to check that the server certificate, which can be obtained by calling
1421:meth:`SSLSocket.getpeercert`, matches the desired service. For many
1422protocols and applications, the service can be identified by the hostname;
1423in this case, the :func:`match_hostname` function can be used.
Antoine Pitrou152efa22010-05-16 18:19:27 +00001424
1425In server mode, if you want to authenticate your clients using the SSL layer
1426(rather than using a higher-level authentication mechanism), you'll also have
1427to specify :const:`CERT_REQUIRED` and similarly check the client certificate.
1428
1429 .. note::
1430
1431 In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are
1432 equivalent unless anonymous ciphers are enabled (they are disabled
1433 by default).
Thomas Woutersed03b412007-08-28 21:37:11 +00001434
Antoine Pitroub5218772010-05-21 09:56:06 +00001435Protocol versions
1436^^^^^^^^^^^^^^^^^
1437
1438SSL version 2 is considered insecure and is therefore dangerous to use. If
1439you want maximum compatibility between clients and servers, it is recommended
1440to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable
1441SSLv2 explicitly using the :data:`SSLContext.options` attribute::
1442
1443 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1444 context.options |= ssl.OP_NO_SSLv2
1445
1446The SSL context created above will allow SSLv3 and TLSv1 connections, but
1447not SSLv2.
1448
Antoine Pitroub7ffed82012-01-04 02:53:44 +01001449Cipher selection
1450^^^^^^^^^^^^^^^^
1451
1452If you have advanced security requirements, fine-tuning of the ciphers
1453enabled when negotiating a SSL session is possible through the
1454:meth:`SSLContext.set_ciphers` method. Starting from Python 3.2.3, the
1455ssl module disables certain weak ciphers by default, but you may want
1456to further restrict the cipher choice. For example::
1457
1458 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1459 context.set_ciphers('HIGH:!aNULL:!eNULL')
1460
1461The ``!aNULL:!eNULL`` part of the cipher spec is necessary to disable ciphers
1462which don't provide both encryption and authentication. Be sure to read
1463OpenSSL's documentation about the `cipher list
1464format <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
1465If you want to check which ciphers are enabled by a given cipher list,
1466use the ``openssl ciphers`` command on your system.
1467
Georg Brandl48310cd2009-01-03 21:18:54 +00001468
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001469.. seealso::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001470
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471 Class :class:`socket.socket`
Georg Brandl4a6cf6c2013-10-06 18:20:31 +02001472 Documentation of underlying :mod:`socket` class
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001473
Georg Brandl4a6cf6c2013-10-06 18:20:31 +02001474 `SSL/TLS Strong Encryption: An Introduction <http://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html>`_
1475 Intro from the Apache webserver documentation
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001476
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001477 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
1478 Steve Kent
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001479
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001480 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
1481 D. Eastlake et. al.
Thomas Wouters89d996e2007-09-08 17:39:28 +00001482
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001483 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
1484 Housley et. al.
Antoine Pitroud5323212010-10-22 18:19:07 +00001485
1486 `RFC 4366: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc4366>`_
1487 Blake-Wilson et. al.
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001488
1489 `RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2 <http://www.ietf.org/rfc/rfc5246>`_
1490 T. Dierks et. al.
1491
1492 `RFC 6066: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc6066>`_
1493 D. Eastlake
1494
1495 `IANA TLS: Transport Layer Security (TLS) Parameters <http://www.iana.org/assignments/tls-parameters/tls-parameters.xml>`_
1496 IANA