blob: a27270c1f934b50d501d6afa874520aa6281c450 [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
Christian Heimes3046fe42013-10-29 21:08:56 +010032.. warning::
Antoine Pitrou9eefe912013-11-17 15:35:33 +010033 Don't use this module without reading the :ref:`ssl-security`. Doing so
34 may lead to a false sense of security, as the default settings of the
35 ssl module are not necessarily appropriate for your application.
Christian Heimes3046fe42013-10-29 21:08:56 +010036
Christian Heimes3046fe42013-10-29 21:08:56 +010037
Georg Brandl7f01a132009-09-16 15:58:14 +000038This section documents the objects and functions in the ``ssl`` module; for more
39general information about TLS, SSL, and certificates, the reader is referred to
40the documents in the "See Also" section at the bottom.
Thomas Woutersed03b412007-08-28 21:37:11 +000041
Georg Brandl7f01a132009-09-16 15:58:14 +000042This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
43:class:`socket.socket` type, and provides a socket-like wrapper that also
44encrypts and decrypts the data going over the socket with SSL. It supports
Antoine Pitroudab64262010-09-19 13:31:06 +000045additional methods such as :meth:`getpeercert`, which retrieves the
46certificate of the other side of the connection, and :meth:`cipher`,which
47retrieves the cipher being used for the secure connection.
Thomas Woutersed03b412007-08-28 21:37:11 +000048
Antoine Pitrou152efa22010-05-16 18:19:27 +000049For more sophisticated applications, the :class:`ssl.SSLContext` class
50helps manage settings and certificates, which can then be inherited
51by SSL sockets created through the :meth:`SSLContext.wrap_socket` method.
52
53
Thomas Wouters1b7f8912007-09-19 03:06:30 +000054Functions, Constants, and Exceptions
55------------------------------------
56
57.. exception:: SSLError
58
Antoine Pitrou59fdd672010-10-08 10:37:08 +000059 Raised to signal an error from the underlying SSL implementation
60 (currently provided by the OpenSSL library). This signifies some
61 problem in the higher-level encryption and authentication layer that's
62 superimposed on the underlying network connection. This error
Antoine Pitrou5574c302011-10-12 17:53:43 +020063 is a subtype of :exc:`OSError`. The error code and message of
64 :exc:`SSLError` instances are provided by the OpenSSL library.
65
66 .. versionchanged:: 3.3
67 :exc:`SSLError` used to be a subtype of :exc:`socket.error`.
Antoine Pitrou59fdd672010-10-08 10:37:08 +000068
Antoine Pitrou3b36fb12012-06-22 21:11:52 +020069 .. attribute:: library
70
71 A string mnemonic designating the OpenSSL submodule in which the error
72 occurred, such as ``SSL``, ``PEM`` or ``X509``. The range of possible
73 values depends on the OpenSSL version.
74
75 .. versionadded:: 3.3
76
77 .. attribute:: reason
78
79 A string mnemonic designating the reason this error occurred, for
80 example ``CERTIFICATE_VERIFY_FAILED``. The range of possible
81 values depends on the OpenSSL version.
82
83 .. versionadded:: 3.3
84
Antoine Pitrou41032a62011-10-27 23:56:55 +020085.. exception:: SSLZeroReturnError
86
87 A subclass of :exc:`SSLError` raised when trying to read or write and
88 the SSL connection has been closed cleanly. Note that this doesn't
89 mean that the underlying transport (read TCP) has been closed.
90
91 .. versionadded:: 3.3
92
93.. exception:: SSLWantReadError
94
95 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
96 <ssl-nonblocking>` when trying to read or write data, but more data needs
97 to be received on the underlying TCP transport before the request can be
98 fulfilled.
99
100 .. versionadded:: 3.3
101
102.. exception:: SSLWantWriteError
103
104 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
105 <ssl-nonblocking>` when trying to read or write data, but more data needs
106 to be sent on the underlying TCP transport before the request can be
107 fulfilled.
108
109 .. versionadded:: 3.3
110
111.. exception:: SSLSyscallError
112
113 A subclass of :exc:`SSLError` raised when a system error was encountered
114 while trying to fulfill an operation on a SSL socket. Unfortunately,
115 there is no easy way to inspect the original errno number.
116
117 .. versionadded:: 3.3
118
119.. exception:: SSLEOFError
120
121 A subclass of :exc:`SSLError` raised when the SSL connection has been
Antoine Pitrouf3dc2d72011-10-28 00:01:03 +0200122 terminated abruptly. Generally, you shouldn't try to reuse the underlying
Antoine Pitrou41032a62011-10-27 23:56:55 +0200123 transport when this error is encountered.
124
125 .. versionadded:: 3.3
126
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000127.. exception:: CertificateError
128
129 Raised to signal an error with a certificate (such as mismatching
130 hostname). Certificate errors detected by OpenSSL, though, raise
131 an :exc:`SSLError`.
132
133
134Socket creation
135^^^^^^^^^^^^^^^
136
137The following function allows for standalone socket creation. Starting from
138Python 3.2, it can be more flexible to use :meth:`SSLContext.wrap_socket`
139instead.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000140
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000141.. 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 +0000142
Georg Brandl7f01a132009-09-16 15:58:14 +0000143 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
144 of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
Antoine Pitrou3e86ba42013-12-28 17:26:33 +0100145 the underlying socket in an SSL context. ``sock`` must be a
146 :data:`~socket.SOCK_STREAM` socket; other socket types are unsupported.
147
148 For client-side sockets, the context construction is lazy; if the
149 underlying socket isn't connected yet, the context construction will be
150 performed after :meth:`connect` is called on the socket. For
151 server-side sockets, if the socket has no remote peer, it is assumed
152 to be a listening socket, and the server-side SSL wrapping is
153 automatically performed on client connections accepted via the
154 :meth:`accept` method. :func:`wrap_socket` may raise :exc:`SSLError`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000155
Georg Brandl7f01a132009-09-16 15:58:14 +0000156 The ``keyfile`` and ``certfile`` parameters specify optional files which
157 contain a certificate to be used to identify the local side of the
158 connection. See the discussion of :ref:`ssl-certificates` for more
159 information on how the certificate is stored in the ``certfile``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000160
Georg Brandl7f01a132009-09-16 15:58:14 +0000161 The parameter ``server_side`` is a boolean which identifies whether
162 server-side or client-side behavior is desired from this socket.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000163
Georg Brandl7f01a132009-09-16 15:58:14 +0000164 The parameter ``cert_reqs`` specifies whether a certificate is required from
165 the other side of the connection, and whether it will be validated if
166 provided. It must be one of the three values :const:`CERT_NONE`
167 (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
168 if provided), or :const:`CERT_REQUIRED` (required and validated). If the
169 value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
170 parameter must point to a file of CA certificates.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000171
Georg Brandl7f01a132009-09-16 15:58:14 +0000172 The ``ca_certs`` file contains a set of concatenated "certification
173 authority" certificates, which are used to validate certificates passed from
174 the other end of the connection. See the discussion of
175 :ref:`ssl-certificates` for more information about how to arrange the
176 certificates in this file.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000177
Georg Brandl7f01a132009-09-16 15:58:14 +0000178 The parameter ``ssl_version`` specifies which version of the SSL protocol to
179 use. Typically, the server chooses a particular protocol version, and the
180 client must adapt to the server's choice. Most of the versions are not
Antoine Pitrou84a2edc2012-01-09 21:35:11 +0100181 interoperable with the other versions. If not specified, the default is
182 :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other
Georg Brandl7f01a132009-09-16 15:58:14 +0000183 versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000184
Georg Brandl7f01a132009-09-16 15:58:14 +0000185 Here's a table showing which versions in a client (down the side) can connect
186 to which versions in a server (along the top):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000187
188 .. table::
189
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100190 ======================== ========= ========= ========== ========= =========== ===========
191 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1** **TLSv1.1** **TLSv1.2**
192 ------------------------ --------- --------- ---------- --------- ----------- -----------
193 *SSLv2* yes no yes no no no
194 *SSLv3* no yes yes no no no
195 *SSLv23* yes no yes no no no
196 *TLSv1* no no yes yes no no
197 *TLSv1.1* no no yes no yes no
198 *TLSv1.2* no no yes no no yes
199 ======================== ========= ========= ========== ========= =========== ===========
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000200
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000201 .. note::
202
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000203 Which connections succeed will vary depending on the version of
204 OpenSSL. For instance, in some older versions of OpenSSL (such
205 as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an
206 SSLv23 server. Another example: beginning with OpenSSL 1.0.0,
207 an SSLv23 client will not actually attempt SSLv2 connections
208 unless you explicitly enable SSLv2 ciphers; for example, you
209 might specify ``"ALL"`` or ``"SSLv2"`` as the *ciphers* parameter
210 to enable them.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000211
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000212 The *ciphers* parameter sets the available ciphers for this SSL object.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000213 It should be a string in the `OpenSSL cipher list format
214 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000215
Bill Janssen48dc27c2007-12-05 03:38:10 +0000216 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
217 handshake automatically after doing a :meth:`socket.connect`, or whether the
Georg Brandl7f01a132009-09-16 15:58:14 +0000218 application program will call it explicitly, by invoking the
219 :meth:`SSLSocket.do_handshake` method. Calling
220 :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
221 blocking behavior of the socket I/O involved in the handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000222
Georg Brandl7f01a132009-09-16 15:58:14 +0000223 The parameter ``suppress_ragged_eofs`` specifies how the
Antoine Pitroudab64262010-09-19 13:31:06 +0000224 :meth:`SSLSocket.recv` method should signal unexpected EOF from the other end
Georg Brandl7f01a132009-09-16 15:58:14 +0000225 of the connection. If specified as :const:`True` (the default), it returns a
Antoine Pitroudab64262010-09-19 13:31:06 +0000226 normal EOF (an empty bytes object) in response to unexpected EOF errors
227 raised from the underlying socket; if :const:`False`, it will raise the
228 exceptions back to the caller.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000229
Ezio Melotti4d5195b2010-04-20 10:57:44 +0000230 .. versionchanged:: 3.2
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000231 New optional argument *ciphers*.
232
Antoine Pitrou5bef4102013-11-23 16:16:29 +0100233
234Context creation
235^^^^^^^^^^^^^^^^
236
237A convenience function helps create :class:`SSLContext` objects for common
238purposes.
239
240.. function:: create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None)
241
242 Return a new :class:`SSLContext` object with default settings for
243 the given *purpose*. The settings are chosen by the :mod:`ssl` module,
244 and usually represent a higher security level than when calling the
245 :class:`SSLContext` constructor directly.
246
247 *cafile*, *capath*, *cadata* represent optional CA certificates to
248 trust for certificate verification, as in
249 :meth:`SSLContext.load_verify_locations`. If all three are
250 :const:`None`, this function can choose to trust the system's default
251 CA certificates instead.
252
Donald Stufft6a2ba942014-03-23 19:05:28 -0400253 The settings in Python 3.4 are: :data:`PROTOCOL_SSLv23`, :data:`OP_NO_SSLv2`,
254 and :data:`OP_NO_SSLv3` with high encryption cipher suites without RC4 and
255 without unauthenticated cipher suites. Passing :data:`~Purpose.SERVER_AUTH`
256 as *purpose* sets :data:`~SSLContext.verify_mode` to :data:`CERT_REQUIRED`
257 and either loads CA certificates (when at least one of *cafile*, *capath* or
258 *cadata* is given) or uses :meth:`SSLContext.load_default_certs` to load
259 default CA certificates.
Antoine Pitrou5bef4102013-11-23 16:16:29 +0100260
261 .. note::
262 The protocol, options, cipher and other settings may change to more
263 restrictive values anytime without prior deprecation. The values
264 represent a fair balance between compatibility and security.
265
266 If your application needs specific settings, you should create a
267 :class:`SSLContext` and apply the settings yourself.
268
Donald Stufft6a2ba942014-03-23 19:05:28 -0400269 .. note::
270 If you find that when certain older clients or servers attempt to connect
271 with a :class:`SSLContext` created by this function that they get an
272 error stating "Protocol or cipher suite mismatch", it may be that they
273 only support SSL3.0 which this function excludes using the
274 :data:`OP_NO_SSLv3`. SSL3.0 has problematic security due to a number of
275 poor implementations and it's reliance on MD5 within the protocol. If you
276 wish to continue to use this function but still allow SSL 3.0 connections
277 you can re-enable them using::
278
279 ctx = ssl.create_default_context(Purpose.CLIENT_AUTH)
280 ctx.options &= ~ssl.OP_NO_SSLv3
281
Antoine Pitrou5bef4102013-11-23 16:16:29 +0100282 .. versionadded:: 3.4
283
284
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000285Random generation
286^^^^^^^^^^^^^^^^^
287
Victor Stinner99c8b162011-05-24 12:05:19 +0200288.. function:: RAND_bytes(num)
289
Victor Stinnera6752062011-05-25 11:27:40 +0200290 Returns *num* cryptographically strong pseudo-random bytes. Raises an
291 :class:`SSLError` if the PRNG has not been seeded with enough data or if the
292 operation is not supported by the current RAND method. :func:`RAND_status`
293 can be used to check the status of the PRNG and :func:`RAND_add` can be used
294 to seed the PRNG.
Victor Stinner99c8b162011-05-24 12:05:19 +0200295
Victor Stinner19fb53c2011-05-24 21:32:40 +0200296 Read the Wikipedia article, `Cryptographically secure pseudorandom number
Victor Stinnera6752062011-05-25 11:27:40 +0200297 generator (CSPRNG)
Victor Stinner19fb53c2011-05-24 21:32:40 +0200298 <http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator>`_,
299 to get the requirements of a cryptographically generator.
300
Victor Stinner99c8b162011-05-24 12:05:19 +0200301 .. versionadded:: 3.3
302
303.. function:: RAND_pseudo_bytes(num)
304
305 Returns (bytes, is_cryptographic): bytes are *num* pseudo-random bytes,
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200306 is_cryptographic is ``True`` if the bytes generated are cryptographically
Victor Stinnera6752062011-05-25 11:27:40 +0200307 strong. Raises an :class:`SSLError` if the operation is not supported by the
308 current RAND method.
Victor Stinner99c8b162011-05-24 12:05:19 +0200309
Victor Stinner19fb53c2011-05-24 21:32:40 +0200310 Generated pseudo-random byte sequences will be unique if they are of
311 sufficient length, but are not necessarily unpredictable. They can be used
312 for non-cryptographic purposes and for certain purposes in cryptographic
313 protocols, but usually not for key generation etc.
314
Victor Stinner99c8b162011-05-24 12:05:19 +0200315 .. versionadded:: 3.3
316
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000317.. function:: RAND_status()
318
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200319 Returns ``True`` if the SSL pseudo-random number generator has been seeded with
320 'enough' randomness, and ``False`` otherwise. You can use :func:`ssl.RAND_egd`
Georg Brandl7f01a132009-09-16 15:58:14 +0000321 and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
322 number generator.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000323
324.. function:: RAND_egd(path)
325
Victor Stinner99c8b162011-05-24 12:05:19 +0200326 If you are running an entropy-gathering daemon (EGD) somewhere, and *path*
Georg Brandl7f01a132009-09-16 15:58:14 +0000327 is the pathname of a socket connection open to it, this will read 256 bytes
328 of randomness from the socket, and add it to the SSL pseudo-random number
329 generator to increase the security of generated secret keys. This is
330 typically only necessary on systems without better sources of randomness.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000331
Georg Brandl7f01a132009-09-16 15:58:14 +0000332 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
333 of entropy-gathering daemons.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000334
335.. function:: RAND_add(bytes, entropy)
336
Victor Stinner99c8b162011-05-24 12:05:19 +0200337 Mixes the given *bytes* into the SSL pseudo-random number generator. The
338 parameter *entropy* (a float) is a lower bound on the entropy contained in
Georg Brandl7f01a132009-09-16 15:58:14 +0000339 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
340 information on sources of entropy.
Thomas Woutersed03b412007-08-28 21:37:11 +0000341
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000342Certificate handling
343^^^^^^^^^^^^^^^^^^^^
344
345.. function:: match_hostname(cert, hostname)
346
347 Verify that *cert* (in decoded format as returned by
348 :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules
349 applied are those for checking the identity of HTTPS servers as outlined
Georg Brandl72c98d32013-10-27 07:16:53 +0100350 in :rfc:`2818` and :rfc:`6125`, except that IP addresses are not currently
351 supported. In addition to HTTPS, this function should be suitable for
352 checking the identity of servers in various SSL-based protocols such as
353 FTPS, IMAPS, POPS and others.
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000354
355 :exc:`CertificateError` is raised on failure. On success, the function
356 returns nothing::
357
358 >>> cert = {'subject': ((('commonName', 'example.com'),),)}
359 >>> ssl.match_hostname(cert, "example.com")
360 >>> ssl.match_hostname(cert, "example.org")
361 Traceback (most recent call last):
362 File "<stdin>", line 1, in <module>
363 File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
364 ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'
365
366 .. versionadded:: 3.2
367
Georg Brandl72c98d32013-10-27 07:16:53 +0100368 .. versionchanged:: 3.3.3
369 The function now follows :rfc:`6125`, section 6.4.3 and does neither
370 match multiple wildcards (e.g. ``*.*.com`` or ``*a*.example.org``) nor
371 a wildcard inside an internationalized domain names (IDN) fragment.
372 IDN A-labels such as ``www*.xn--pthon-kva.org`` are still supported,
373 but ``x*.python.org`` no longer matches ``xn--tda.python.org``.
374
Antoine Pitrouc695c952014-04-28 20:57:36 +0200375.. function:: cert_time_to_seconds(cert_time)
Thomas Woutersed03b412007-08-28 21:37:11 +0000376
Antoine Pitrouc695c952014-04-28 20:57:36 +0200377 Return the time in seconds since the Epoch, given the ``cert_time``
378 string representing the "notBefore" or "notAfter" date from a
379 certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C
380 locale).
Thomas Woutersed03b412007-08-28 21:37:11 +0000381
Antoine Pitrouc695c952014-04-28 20:57:36 +0200382 Here's an example:
Thomas Woutersed03b412007-08-28 21:37:11 +0000383
Antoine Pitrouc695c952014-04-28 20:57:36 +0200384 .. doctest:: newcontext
385
386 >>> import ssl
387 >>> timestamp = ssl.cert_time_to_seconds("Jan 5 09:34:43 2018 GMT")
388 >>> timestamp
389 1515144883
390 >>> from datetime import datetime
391 >>> print(datetime.utcfromtimestamp(timestamp))
392 2018-01-05 09:34:43
393
394 "notBefore" or "notAfter" dates must use GMT (:rfc:`5280`).
395
396 .. versionchanged:: 3.5
397 Interpret the input time as a time in UTC as specified by 'GMT'
398 timezone in the input string. Local timezone was used
399 previously. Return an integer (no fractions of a second in the
400 input format)
Thomas Woutersed03b412007-08-28 21:37:11 +0000401
Antoine Pitrou94a5b662014-04-16 18:56:28 +0200402.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000403
Georg Brandl7f01a132009-09-16 15:58:14 +0000404 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
405 *port-number*) pair, fetches the server's certificate, and returns it as a
406 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
407 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
408 specified, it should be a file containing a list of root certificates, the
409 same format as used for the same parameter in :func:`wrap_socket`. The call
410 will attempt to validate the server certificate against that set of root
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000411 certificates, and will fail if the validation attempt fails.
412
Antoine Pitrou15399c32011-04-28 19:23:55 +0200413 .. versionchanged:: 3.3
414 This function is now IPv6-compatible.
415
Antoine Pitrou94a5b662014-04-16 18:56:28 +0200416 .. versionchanged:: 3.5
417 The default *ssl_version* is changed from :data:`PROTOCOL_SSLv3` to
418 :data:`PROTOCOL_SSLv23` for maximum compatibility with modern servers.
419
Georg Brandl7f01a132009-09-16 15:58:14 +0000420.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000421
422 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
423 string version of the same certificate.
424
Georg Brandl7f01a132009-09-16 15:58:14 +0000425.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000426
Georg Brandl7f01a132009-09-16 15:58:14 +0000427 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
428 bytes for that same certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000429
Christian Heimes6d7ad132013-06-09 18:02:55 +0200430.. function:: get_default_verify_paths()
431
432 Returns a named tuple with paths to OpenSSL's default cafile and capath.
433 The paths are the same as used by
434 :meth:`SSLContext.set_default_verify_paths`. The return value is a
435 :term:`named tuple` ``DefaultVerifyPaths``:
436
437 * :attr:`cafile` - resolved path to cafile or None if the file doesn't exist,
438 * :attr:`capath` - resolved path to capath or None if the directory doesn't exist,
439 * :attr:`openssl_cafile_env` - OpenSSL's environment key that points to a cafile,
440 * :attr:`openssl_cafile` - hard coded path to a cafile,
441 * :attr:`openssl_capath_env` - OpenSSL's environment key that points to a capath,
442 * :attr:`openssl_capath` - hard coded path to a capath directory
443
444 .. versionadded:: 3.4
445
Christian Heimes44109d72013-11-22 01:51:30 +0100446.. function:: enum_certificates(store_name)
Christian Heimes46bebee2013-06-09 19:03:31 +0200447
448 Retrieve certificates from Windows' system cert store. *store_name* may be
449 one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert
Christian Heimes44109d72013-11-22 01:51:30 +0100450 stores, too.
Christian Heimes46bebee2013-06-09 19:03:31 +0200451
Christian Heimes44109d72013-11-22 01:51:30 +0100452 The function returns a list of (cert_bytes, encoding_type, trust) tuples.
453 The encoding_type specifies the encoding of cert_bytes. It is either
454 :const:`x509_asn` for X.509 ASN.1 data or :const:`pkcs_7_asn` for
455 PKCS#7 ASN.1 data. Trust specifies the purpose of the certificate as a set
456 of OIDS or exactly ``True`` if the certificate is trustworthy for all
457 purposes.
458
459 Example::
460
461 >>> ssl.enum_certificates("CA")
462 [(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}),
463 (b'data...', 'x509_asn', True)]
Christian Heimes46bebee2013-06-09 19:03:31 +0200464
465 Availability: Windows.
466
467 .. versionadded:: 3.4
Christian Heimes6d7ad132013-06-09 18:02:55 +0200468
Christian Heimes44109d72013-11-22 01:51:30 +0100469.. function:: enum_crls(store_name)
470
471 Retrieve CRLs from Windows' system cert store. *store_name* may be
472 one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert
473 stores, too.
474
475 The function returns a list of (cert_bytes, encoding_type, trust) tuples.
476 The encoding_type specifies the encoding of cert_bytes. It is either
477 :const:`x509_asn` for X.509 ASN.1 data or :const:`pkcs_7_asn` for
478 PKCS#7 ASN.1 data.
479
480 Availability: Windows.
481
482 .. versionadded:: 3.4
483
484
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000485Constants
486^^^^^^^^^
487
Thomas Woutersed03b412007-08-28 21:37:11 +0000488.. data:: CERT_NONE
489
Antoine Pitrou152efa22010-05-16 18:19:27 +0000490 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
491 parameter to :func:`wrap_socket`. In this mode (the default), no
492 certificates will be required from the other side of the socket connection.
493 If a certificate is received from the other end, no attempt to validate it
494 is made.
495
496 See the discussion of :ref:`ssl-security` below.
Thomas Woutersed03b412007-08-28 21:37:11 +0000497
498.. data:: CERT_OPTIONAL
499
Antoine Pitrou152efa22010-05-16 18:19:27 +0000500 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
501 parameter to :func:`wrap_socket`. In this mode no certificates will be
502 required from the other side of the socket connection; but if they
503 are provided, validation will be attempted and an :class:`SSLError`
504 will be raised on failure.
505
506 Use of this setting requires a valid set of CA certificates to
507 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
508 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000509
510.. data:: CERT_REQUIRED
511
Antoine Pitrou152efa22010-05-16 18:19:27 +0000512 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
513 parameter to :func:`wrap_socket`. In this mode, certificates are
514 required from the other side of the socket connection; an :class:`SSLError`
515 will be raised if no certificate is provided, or if its validation fails.
516
517 Use of this setting requires a valid set of CA certificates to
518 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
519 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000520
Christian Heimes22587792013-11-21 23:56:13 +0100521.. data:: VERIFY_DEFAULT
522
523 Possible value for :attr:`SSLContext.verify_flags`. In this mode,
524 certificate revocation lists (CRLs) are not checked. By default OpenSSL
525 does neither require nor verify CRLs.
526
527 .. versionadded:: 3.4
528
529.. data:: VERIFY_CRL_CHECK_LEAF
530
531 Possible value for :attr:`SSLContext.verify_flags`. In this mode, only the
532 peer cert is check but non of the intermediate CA certificates. The mode
533 requires a valid CRL that is signed by the peer cert's issuer (its direct
534 ancestor CA). If no proper has been loaded
535 :attr:`SSLContext.load_verify_locations`, validation will fail.
536
537 .. versionadded:: 3.4
538
539.. data:: VERIFY_CRL_CHECK_CHAIN
540
541 Possible value for :attr:`SSLContext.verify_flags`. In this mode, CRLs of
542 all certificates in the peer cert chain are checked.
543
544 .. versionadded:: 3.4
545
546.. data:: VERIFY_X509_STRICT
547
548 Possible value for :attr:`SSLContext.verify_flags` to disable workarounds
549 for broken X.509 certificates.
550
551 .. versionadded:: 3.4
552
Thomas Woutersed03b412007-08-28 21:37:11 +0000553.. data:: PROTOCOL_SSLv2
554
555 Selects SSL version 2 as the channel encryption protocol.
556
Victor Stinner3de49192011-05-09 00:42:58 +0200557 This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
558 flag.
559
Antoine Pitrou8eac60d2010-05-16 14:19:41 +0000560 .. warning::
561
562 SSL version 2 is insecure. Its use is highly discouraged.
563
Thomas Woutersed03b412007-08-28 21:37:11 +0000564.. data:: PROTOCOL_SSLv23
565
Georg Brandl7f01a132009-09-16 15:58:14 +0000566 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
567 setting to use with servers for maximum compatibility with the other end of
568 an SSL connection, but it may cause the specific ciphers chosen for the
569 encryption to be of fairly low quality.
Thomas Woutersed03b412007-08-28 21:37:11 +0000570
571.. data:: PROTOCOL_SSLv3
572
Georg Brandl7f01a132009-09-16 15:58:14 +0000573 Selects SSL version 3 as the channel encryption protocol. For clients, this
574 is the maximally compatible SSL variant.
Thomas Woutersed03b412007-08-28 21:37:11 +0000575
576.. data:: PROTOCOL_TLSv1
577
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100578 Selects TLS version 1.0 as the channel encryption protocol.
579
580.. data:: PROTOCOL_TLSv1_1
581
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100582 Selects TLS version 1.1 as the channel encryption protocol.
583 Available only with openssl version 1.0.1+.
584
585 .. versionadded:: 3.4
586
587.. data:: PROTOCOL_TLSv1_2
588
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100589 Selects TLS version 1.2 as the channel encryption protocol. This is the most
Georg Brandl7f01a132009-09-16 15:58:14 +0000590 modern version, and probably the best choice for maximum protection, if both
R David Murray748bad22013-12-20 17:08:39 -0500591 sides can speak it. Available only with openssl version 1.0.1+.
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100592
593 .. versionadded:: 3.4
Thomas Woutersed03b412007-08-28 21:37:11 +0000594
Antoine Pitroub5218772010-05-21 09:56:06 +0000595.. data:: OP_ALL
596
597 Enables workarounds for various bugs present in other SSL implementations.
Antoine Pitrou9f6b02e2012-01-27 10:02:55 +0100598 This option is set by default. It does not necessarily set the same
599 flags as OpenSSL's ``SSL_OP_ALL`` constant.
Antoine Pitroub5218772010-05-21 09:56:06 +0000600
601 .. versionadded:: 3.2
602
603.. data:: OP_NO_SSLv2
604
605 Prevents an SSLv2 connection. This option is only applicable in
606 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
607 choosing SSLv2 as the protocol version.
608
609 .. versionadded:: 3.2
610
611.. data:: OP_NO_SSLv3
612
613 Prevents an SSLv3 connection. This option is only applicable in
614 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
615 choosing SSLv3 as the protocol version.
616
617 .. versionadded:: 3.2
618
619.. data:: OP_NO_TLSv1
620
621 Prevents a TLSv1 connection. This option is only applicable in
622 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
623 choosing TLSv1 as the protocol version.
624
625 .. versionadded:: 3.2
626
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100627.. data:: OP_NO_TLSv1_1
628
629 Prevents a TLSv1.1 connection. This option is only applicable in conjunction
630 with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.1 as
631 the protocol version. Available only with openssl version 1.0.1+.
632
633 .. versionadded:: 3.4
634
635.. data:: OP_NO_TLSv1_2
636
637 Prevents a TLSv1.2 connection. This option is only applicable in conjunction
638 with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.2 as
639 the protocol version. Available only with openssl version 1.0.1+.
640
641 .. versionadded:: 3.4
642
Antoine Pitrou6db49442011-12-19 13:27:11 +0100643.. data:: OP_CIPHER_SERVER_PREFERENCE
644
645 Use the server's cipher ordering preference, rather than the client's.
646 This option has no effect on client sockets and SSLv2 server sockets.
647
648 .. versionadded:: 3.3
649
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100650.. data:: OP_SINGLE_DH_USE
651
652 Prevents re-use of the same DH key for distinct SSL sessions. This
653 improves forward secrecy but requires more computational resources.
654 This option only applies to server sockets.
655
656 .. versionadded:: 3.3
657
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100658.. data:: OP_SINGLE_ECDH_USE
659
Antoine Pitrou0e576f12011-12-22 10:03:38 +0100660 Prevents re-use of the same ECDH key for distinct SSL sessions. This
Antoine Pitrou923df6f2011-12-19 17:16:51 +0100661 improves forward secrecy but requires more computational resources.
662 This option only applies to server sockets.
663
664 .. versionadded:: 3.3
665
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100666.. data:: OP_NO_COMPRESSION
667
668 Disable compression on the SSL channel. This is useful if the application
669 protocol supports its own compression scheme.
670
671 This option is only available with OpenSSL 1.0.0 and later.
672
673 .. versionadded:: 3.3
674
Antoine Pitrou501da612011-12-21 09:27:41 +0100675.. data:: HAS_ECDH
676
677 Whether the OpenSSL library has built-in support for Elliptic Curve-based
678 Diffie-Hellman key exchange. This should be true unless the feature was
679 explicitly disabled by the distributor.
680
681 .. versionadded:: 3.3
682
Antoine Pitroud5323212010-10-22 18:19:07 +0000683.. data:: HAS_SNI
684
685 Whether the OpenSSL library has built-in support for the *Server Name
686 Indication* extension to the SSLv3 and TLSv1 protocols (as defined in
687 :rfc:`4366`). When true, you can use the *server_hostname* argument to
688 :meth:`SSLContext.wrap_socket`.
689
690 .. versionadded:: 3.2
691
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100692.. data:: HAS_NPN
693
694 Whether the OpenSSL library has built-in support for *Next Protocol
695 Negotiation* as described in the `NPN draft specification
696 <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. When true,
697 you can use the :meth:`SSLContext.set_npn_protocols` method to advertise
698 which protocols you want to support.
699
700 .. versionadded:: 3.3
701
Antoine Pitroud6494802011-07-21 01:11:30 +0200702.. data:: CHANNEL_BINDING_TYPES
703
704 List of supported TLS channel binding types. Strings in this list
705 can be used as arguments to :meth:`SSLSocket.get_channel_binding`.
706
707 .. versionadded:: 3.3
708
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000709.. data:: OPENSSL_VERSION
710
711 The version string of the OpenSSL library loaded by the interpreter::
712
713 >>> ssl.OPENSSL_VERSION
714 'OpenSSL 0.9.8k 25 Mar 2009'
715
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000716 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000717
718.. data:: OPENSSL_VERSION_INFO
719
720 A tuple of five integers representing version information about the
721 OpenSSL library::
722
723 >>> ssl.OPENSSL_VERSION_INFO
724 (0, 9, 8, 11, 15)
725
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000726 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000727
728.. data:: OPENSSL_VERSION_NUMBER
729
730 The raw version number of the OpenSSL library, as a single integer::
731
732 >>> ssl.OPENSSL_VERSION_NUMBER
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000733 9470143
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000734 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000735 '0x9080bf'
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000736
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000737 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000738
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100739.. data:: ALERT_DESCRIPTION_HANDSHAKE_FAILURE
740 ALERT_DESCRIPTION_INTERNAL_ERROR
741 ALERT_DESCRIPTION_*
742
743 Alert Descriptions from :rfc:`5246` and others. The `IANA TLS Alert Registry
744 <http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6>`_
745 contains this list and references to the RFCs where their meaning is defined.
746
747 Used as the return value of the callback function in
748 :meth:`SSLContext.set_servername_callback`.
749
750 .. versionadded:: 3.4
751
Christian Heimes72d28502013-11-23 13:56:58 +0100752.. data:: Purpose.SERVER_AUTH
753
Antoine Pitrou5bef4102013-11-23 16:16:29 +0100754 Option for :func:`create_default_context` and
755 :meth:`SSLContext.load_default_certs`. This value indicates that the
756 context may be used to authenticate Web servers (therefore, it will
757 be used to create client-side sockets).
Christian Heimes72d28502013-11-23 13:56:58 +0100758
759 .. versionadded:: 3.4
760
Christian Heimes6b2ff982013-11-23 14:42:01 +0100761.. data:: Purpose.CLIENT_AUTH
Christian Heimes72d28502013-11-23 13:56:58 +0100762
Antoine Pitrou5bef4102013-11-23 16:16:29 +0100763 Option for :func:`create_default_context` and
764 :meth:`SSLContext.load_default_certs`. This value indicates that the
765 context may be used to authenticate Web clients (therefore, it will
766 be used to create server-side sockets).
Christian Heimes72d28502013-11-23 13:56:58 +0100767
768 .. versionadded:: 3.4
769
Thomas Woutersed03b412007-08-28 21:37:11 +0000770
Antoine Pitrou152efa22010-05-16 18:19:27 +0000771SSL Sockets
772-----------
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000773
Victor Stinner3c3d3c72014-10-10 12:06:51 +0200774.. class:: SSLSocket(socket.socket)
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000775
Victor Stinner3c3d3c72014-10-10 12:06:51 +0200776 SSL sockets provide the following methods of :ref:`socket-objects`:
Zachary Wareba9fb0d2014-06-11 15:02:25 -0500777
Victor Stinner3c3d3c72014-10-10 12:06:51 +0200778 - :meth:`~socket.socket.accept()`
779 - :meth:`~socket.socket.bind()`
780 - :meth:`~socket.socket.close()`
781 - :meth:`~socket.socket.connect()`
782 - :meth:`~socket.socket.detach()`
783 - :meth:`~socket.socket.fileno()`
784 - :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`
785 - :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`
786 - :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`,
787 :meth:`~socket.socket.setblocking()`
788 - :meth:`~socket.socket.listen()`
789 - :meth:`~socket.socket.makefile()`
790 - :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()`
791 (but passing a non-zero ``flags`` argument is not allowed)
792 - :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with
793 the same limitation)
Victor Stinner92127a52014-10-10 12:43:17 +0200794 - :meth:`~socket.socket.sendfile()` (but :mod:`os.sendfile` will be used
795 for plain-text sockets only, else :meth:`~socket.socket.send()` will be used)
Victor Stinner3c3d3c72014-10-10 12:06:51 +0200796 - :meth:`~socket.socket.shutdown()`
Zachary Wareba9fb0d2014-06-11 15:02:25 -0500797
Victor Stinner3c3d3c72014-10-10 12:06:51 +0200798 However, since the SSL (and TLS) protocol has its own framing atop
799 of TCP, the SSL sockets abstraction can, in certain respects, diverge from
800 the specification of normal, OS-level sockets. See especially the
801 :ref:`notes on non-blocking sockets <ssl-nonblocking>`.
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000802
Victor Stinnerd28fe8c2014-10-10 12:07:19 +0200803 Usually, :class:`SSLSocket` are not created directly, but using the
804 :func:`wrap_socket` function or the :meth:`SSLContext.wrap_socket` method.
805
Victor Stinner92127a52014-10-10 12:43:17 +0200806 .. versionchanged:: 3.5
807 The :meth:`sendfile` method was added.
808
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +0200809
810SSL sockets also have the following additional methods and attributes:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000811
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200812.. method:: SSLSocket.read(len=0, buffer=None)
813
814 Read up to *len* bytes of data from the SSL socket and return the result as
815 a ``bytes`` instance. If *buffer* is specified, then read into the buffer
816 instead, and return the number of bytes read.
817
Victor Stinner41f92c22014-10-10 12:05:56 +0200818 Raise :exc:`SSLWantReadError` or :exc:`SSLWantWriteError` if the socket is
Victor Stinnercfb2a0a2014-10-10 12:45:10 +0200819 :ref:`non-blocking <ssl-nonblocking>` and the read would block.
Victor Stinner41f92c22014-10-10 12:05:56 +0200820
821 As at any time a re-negotiation is possible, a call to :meth:`read` can also
822 cause write operations.
823
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200824.. method:: SSLSocket.write(buf)
825
826 Write *buf* to the SSL socket and return the number of bytes written. The
827 *buf* argument must be an object supporting the buffer interface.
828
Victor Stinner41f92c22014-10-10 12:05:56 +0200829 Raise :exc:`SSLWantReadError` or :exc:`SSLWantWriteError` if the socket is
Victor Stinnercfb2a0a2014-10-10 12:45:10 +0200830 :ref:`non-blocking <ssl-nonblocking>` and the write would block.
Victor Stinner41f92c22014-10-10 12:05:56 +0200831
832 As at any time a re-negotiation is possible, a call to :meth:`write` can
833 also cause read operations.
834
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200835.. note::
836
837 The :meth:`~SSLSocket.read` and :meth:`~SSLSocket.write` methods are the
838 low-level methods that read and write unencrypted, application-level data
839 and and decrypt/encrypt it to encrypted, wire-level data. These methods
840 require an active SSL connection, i.e. the handshake was completed and
841 :meth:`SSLSocket.unwrap` was not called.
842
843 Normally you should use the socket API methods like
844 :meth:`~socket.socket.recv` and :meth:`~socket.socket.send` instead of these
845 methods.
846
Bill Janssen48dc27c2007-12-05 03:38:10 +0000847.. method:: SSLSocket.do_handshake()
848
Antoine Pitroub3593ca2011-07-11 01:39:19 +0200849 Perform the SSL setup handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000850
Christian Heimes1aa9a752013-12-02 02:41:19 +0100851 .. versionchanged:: 3.4
Zachary Ware88a19772014-07-25 13:30:50 -0500852 The handshake method also performs :func:`match_hostname` when the
Christian Heimes1aa9a752013-12-02 02:41:19 +0100853 :attr:`~SSLContext.check_hostname` attribute of the socket's
854 :attr:`~SSLSocket.context` is true.
855
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000856.. method:: SSLSocket.getpeercert(binary_form=False)
857
Georg Brandl7f01a132009-09-16 15:58:14 +0000858 If there is no certificate for the peer on the other end of the connection,
Antoine Pitrou20b85552013-09-29 19:50:53 +0200859 return ``None``. If the SSL handshake hasn't been done yet, raise
860 :exc:`ValueError`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861
Antoine Pitroud34941a2013-04-16 20:27:17 +0200862 If the ``binary_form`` parameter is :const:`False`, and a certificate was
Georg Brandl7f01a132009-09-16 15:58:14 +0000863 received from the peer, this method returns a :class:`dict` instance. If the
864 certificate was not validated, the dict is empty. If the certificate was
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200865 validated, it returns a dict with several keys, amongst them ``subject``
866 (the principal for which the certificate was issued) and ``issuer``
867 (the principal issuing the certificate). If a certificate contains an
868 instance of the *Subject Alternative Name* extension (see :rfc:`3280`),
869 there will also be a ``subjectAltName`` key in the dictionary.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000870
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200871 The ``subject`` and ``issuer`` fields are tuples containing the sequence
872 of relative distinguished names (RDNs) given in the certificate's data
873 structure for the respective fields, and each RDN is a sequence of
874 name-value pairs. Here is a real-world example::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000875
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200876 {'issuer': ((('countryName', 'IL'),),
877 (('organizationName', 'StartCom Ltd.'),),
878 (('organizationalUnitName',
879 'Secure Digital Certificate Signing'),),
880 (('commonName',
881 'StartCom Class 2 Primary Intermediate Server CA'),)),
882 'notAfter': 'Nov 22 08:15:19 2013 GMT',
883 'notBefore': 'Nov 21 03:09:52 2011 GMT',
884 'serialNumber': '95F0',
885 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
886 (('countryName', 'US'),),
887 (('stateOrProvinceName', 'California'),),
888 (('localityName', 'San Francisco'),),
889 (('organizationName', 'Electronic Frontier Foundation, Inc.'),),
890 (('commonName', '*.eff.org'),),
891 (('emailAddress', 'hostmaster@eff.org'),)),
892 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
893 'version': 3}
894
895 .. note::
Larry Hastings3732ed22014-03-15 21:13:56 -0700896
Antoine Pitroub7c6c812012-08-16 22:14:43 +0200897 To validate a certificate for a particular service, you can use the
898 :func:`match_hostname` function.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000899
Georg Brandl7f01a132009-09-16 15:58:14 +0000900 If the ``binary_form`` parameter is :const:`True`, and a certificate was
901 provided, this method returns the DER-encoded form of the entire certificate
902 as a sequence of bytes, or :const:`None` if the peer did not provide a
Antoine Pitroud34941a2013-04-16 20:27:17 +0200903 certificate. Whether the peer provides a certificate depends on the SSL
904 socket's role:
905
906 * for a client SSL socket, the server will always provide a certificate,
907 regardless of whether validation was required;
908
909 * for a server SSL socket, the client will only provide a certificate
910 when requested by the server; therefore :meth:`getpeercert` will return
911 :const:`None` if you used :const:`CERT_NONE` (rather than
912 :const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000913
Antoine Pitroufb046912010-11-09 20:21:19 +0000914 .. versionchanged:: 3.2
915 The returned dictionary includes additional items such as ``issuer``
916 and ``notBefore``.
917
Antoine Pitrou20b85552013-09-29 19:50:53 +0200918 .. versionchanged:: 3.4
919 :exc:`ValueError` is raised when the handshake isn't done.
Christian Heimesbd3a7f92013-11-21 03:40:15 +0100920 The returned dictionary includes additional X509v3 extension items
Larry Hastings3732ed22014-03-15 21:13:56 -0700921 such as ``crlDistributionPoints``, ``caIssuers`` and ``OCSP`` URIs.
Christian Heimesbd3a7f92013-11-21 03:40:15 +0100922
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923.. method:: SSLSocket.cipher()
924
Georg Brandl7f01a132009-09-16 15:58:14 +0000925 Returns a three-value tuple containing the name of the cipher being used, the
926 version of the SSL protocol that defines its use, and the number of secret
927 bits being used. If no connection has been established, returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000928
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +0100929.. method:: SSLSocket.compression()
930
931 Return the compression algorithm being used as a string, or ``None``
932 if the connection isn't compressed.
933
934 If the higher-level protocol supports its own compression mechanism,
935 you can use :data:`OP_NO_COMPRESSION` to disable SSL-level compression.
936
937 .. versionadded:: 3.3
938
Antoine Pitroud6494802011-07-21 01:11:30 +0200939.. method:: SSLSocket.get_channel_binding(cb_type="tls-unique")
940
941 Get channel binding data for current connection, as a bytes object. Returns
942 ``None`` if not connected or the handshake has not been completed.
943
944 The *cb_type* parameter allow selection of the desired channel binding
945 type. Valid channel binding types are listed in the
946 :data:`CHANNEL_BINDING_TYPES` list. Currently only the 'tls-unique' channel
947 binding, defined by :rfc:`5929`, is supported. :exc:`ValueError` will be
948 raised if an unsupported channel binding type is requested.
949
950 .. versionadded:: 3.3
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000951
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100952.. method:: SSLSocket.selected_npn_protocol()
953
Antoine Pitrou47e40422014-09-04 21:00:10 +0200954 Returns the higher-level protocol that was selected during the TLS/SSL
955 handshake. If :meth:`SSLContext.set_npn_protocols` was not called, or
956 if the other party does not support NPN, or if the handshake has not yet
957 happened, this will return ``None``.
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100958
959 .. versionadded:: 3.3
960
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000961.. method:: SSLSocket.unwrap()
962
Georg Brandl7f01a132009-09-16 15:58:14 +0000963 Performs the SSL shutdown handshake, which removes the TLS layer from the
964 underlying socket, and returns the underlying socket object. This can be
965 used to go from encrypted operation over a connection to unencrypted. The
966 returned socket should always be used for further communication with the
967 other side of the connection, rather than the original socket.
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000968
Antoine Pitrou47e40422014-09-04 21:00:10 +0200969.. method:: SSLSocket.version()
970
971 Return the actual SSL protocol version negotiated by the connection
972 as a string, or ``None`` is no secure connection is established.
973 As of this writing, possible return values include ``"SSLv2"``,
974 ``"SSLv3"``, ``"TLSv1"``, ``"TLSv1.1"`` and ``"TLSv1.2"``.
975 Recent OpenSSL versions may define more return values.
976
977 .. versionadded:: 3.5
978
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200979.. method:: SSLSocket.pending()
980
981 Returns the number of already decrypted bytes available for read, pending on
982 the connection.
983
Antoine Pitrouec883db2010-05-24 21:20:20 +0000984.. attribute:: SSLSocket.context
985
986 The :class:`SSLContext` object this SSL socket is tied to. If the SSL
987 socket was created using the top-level :func:`wrap_socket` function
988 (rather than :meth:`SSLContext.wrap_socket`), this is a custom context
989 object created for this SSL socket.
990
991 .. versionadded:: 3.2
992
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200993.. attribute:: SSLSocket.server_side
994
995 A boolean which is ``True`` for server-side sockets and ``False`` for
996 client-side sockets.
997
Victor Stinner41f92c22014-10-10 12:05:56 +0200998 .. versionadded:: 3.2
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200999
1000.. attribute:: SSLSocket.server_hostname
1001
Victor Stinner41f92c22014-10-10 12:05:56 +02001002 Hostname of the server: :class:`str` type, or ``None`` for server-side
1003 socket or if the hostname was not specified in the constructor.
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001004
Victor Stinner41f92c22014-10-10 12:05:56 +02001005 .. versionadded:: 3.2
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001006
Antoine Pitrouec883db2010-05-24 21:20:20 +00001007
Antoine Pitrou152efa22010-05-16 18:19:27 +00001008SSL Contexts
1009------------
1010
Antoine Pitroucafaad42010-05-24 15:58:43 +00001011.. versionadded:: 3.2
1012
Antoine Pitroub0182c82010-10-12 20:09:02 +00001013An SSL context holds various data longer-lived than single SSL connections,
1014such as SSL configuration options, certificate(s) and private key(s).
1015It also manages a cache of SSL sessions for server-side sockets, in order
1016to speed up repeated connections from the same clients.
1017
Antoine Pitrou152efa22010-05-16 18:19:27 +00001018.. class:: SSLContext(protocol)
1019
Antoine Pitroub0182c82010-10-12 20:09:02 +00001020 Create a new SSL context. You must pass *protocol* which must be one
1021 of the ``PROTOCOL_*`` constants defined in this module.
Antoine Pitrou5bef4102013-11-23 16:16:29 +01001022 :data:`PROTOCOL_SSLv23` is currently recommended for maximum
1023 interoperability.
1024
1025 .. seealso::
1026 :func:`create_default_context` lets the :mod:`ssl` module choose
1027 security settings for a given purpose.
Antoine Pitroub0182c82010-10-12 20:09:02 +00001028
Antoine Pitrou152efa22010-05-16 18:19:27 +00001029
1030:class:`SSLContext` objects have the following methods and attributes:
1031
Christian Heimes9a5395a2013-06-17 15:44:12 +02001032.. method:: SSLContext.cert_store_stats()
1033
1034 Get statistics about quantities of loaded X.509 certificates, count of
1035 X.509 certificates flagged as CA certificates and certificate revocation
1036 lists as dictionary.
1037
1038 Example for a context with one CA cert and one other cert::
1039
1040 >>> context.cert_store_stats()
1041 {'crl': 0, 'x509_ca': 1, 'x509': 2}
1042
1043 .. versionadded:: 3.4
1044
Christian Heimesefff7062013-11-21 03:35:02 +01001045
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001046.. method:: SSLContext.load_cert_chain(certfile, keyfile=None, password=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001047
1048 Load a private key and the corresponding certificate. The *certfile*
1049 string must be the path to a single file in PEM format containing the
1050 certificate as well as any number of CA certificates needed to establish
1051 the certificate's authenticity. The *keyfile* string, if present, must
1052 point to a file containing the private key in. Otherwise the private
1053 key will be taken from *certfile* as well. See the discussion of
1054 :ref:`ssl-certificates` for more information on how the certificate
1055 is stored in the *certfile*.
1056
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001057 The *password* argument may be a function to call to get the password for
1058 decrypting the private key. It will only be called if the private key is
1059 encrypted and a password is necessary. It will be called with no arguments,
1060 and it should return a string, bytes, or bytearray. If the return value is
1061 a string it will be encoded as UTF-8 before using it to decrypt the key.
1062 Alternatively a string, bytes, or bytearray value may be supplied directly
1063 as the *password* argument. It will be ignored if the private key is not
1064 encrypted and no password is needed.
1065
1066 If the *password* argument is not specified and a password is required,
1067 OpenSSL's built-in password prompting mechanism will be used to
1068 interactively prompt the user for a password.
1069
Antoine Pitrou152efa22010-05-16 18:19:27 +00001070 An :class:`SSLError` is raised if the private key doesn't
1071 match with the certificate.
1072
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001073 .. versionchanged:: 3.3
1074 New optional argument *password*.
1075
Christian Heimes72d28502013-11-23 13:56:58 +01001076.. method:: SSLContext.load_default_certs(purpose=Purpose.SERVER_AUTH)
1077
1078 Load a set of default "certification authority" (CA) certificates from
1079 default locations. On Windows it loads CA certs from the ``CA`` and
1080 ``ROOT`` system stores. On other systems it calls
1081 :meth:`SSLContext.set_default_verify_paths`. In the future the method may
1082 load CA certificates from other locations, too.
1083
1084 The *purpose* flag specifies what kind of CA certificates are loaded. The
1085 default settings :data:`Purpose.SERVER_AUTH` loads certificates, that are
1086 flagged and trusted for TLS web server authentication (client side
Christian Heimes6b2ff982013-11-23 14:42:01 +01001087 sockets). :data:`Purpose.CLIENT_AUTH` loads CA certificates for client
Christian Heimes72d28502013-11-23 13:56:58 +01001088 certificate verification on the server side.
1089
1090 .. versionadded:: 3.4
1091
Christian Heimesefff7062013-11-21 03:35:02 +01001092.. method:: SSLContext.load_verify_locations(cafile=None, capath=None, cadata=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001093
1094 Load a set of "certification authority" (CA) certificates used to validate
1095 other peers' certificates when :data:`verify_mode` is other than
1096 :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified.
1097
Christian Heimes22587792013-11-21 23:56:13 +01001098 This method can also load certification revocation lists (CRLs) in PEM or
Donald Stufft8b852f12014-05-20 12:58:38 -04001099 DER format. In order to make use of CRLs, :attr:`SSLContext.verify_flags`
Christian Heimes22587792013-11-21 23:56:13 +01001100 must be configured properly.
1101
Christian Heimes3e738f92013-06-09 18:07:16 +02001102 The *cafile* string, if present, is the path to a file of concatenated
Antoine Pitrou152efa22010-05-16 18:19:27 +00001103 CA certificates in PEM format. See the discussion of
1104 :ref:`ssl-certificates` for more information about how to arrange the
1105 certificates in this file.
1106
1107 The *capath* string, if present, is
1108 the path to a directory containing several CA certificates in PEM format,
1109 following an `OpenSSL specific layout
1110 <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
1111
Christian Heimesefff7062013-11-21 03:35:02 +01001112 The *cadata* object, if present, is either an ASCII string of one or more
1113 PEM-encoded certificates or a bytes-like object of DER-encoded
1114 certificates. Like with *capath* extra lines around PEM-encoded
1115 certificates are ignored but at least one certificate must be present.
1116
1117 .. versionchanged:: 3.4
1118 New optional argument *cadata*
1119
Christian Heimes9a5395a2013-06-17 15:44:12 +02001120.. method:: SSLContext.get_ca_certs(binary_form=False)
1121
1122 Get a list of loaded "certification authority" (CA) certificates. If the
1123 ``binary_form`` parameter is :const:`False` each list
1124 entry is a dict like the output of :meth:`SSLSocket.getpeercert`. Otherwise
1125 the method returns a list of DER-encoded certificates. The returned list
1126 does not contain certificates from *capath* unless a certificate was
1127 requested and loaded by a SSL connection.
1128
Larry Hastingsd36fc432013-08-03 02:49:53 -07001129 .. versionadded:: 3.4
Christian Heimes9a5395a2013-06-17 15:44:12 +02001130
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001131.. method:: SSLContext.set_default_verify_paths()
1132
1133 Load a set of default "certification authority" (CA) certificates from
1134 a filesystem path defined when building the OpenSSL library. Unfortunately,
1135 there's no easy way to know whether this method succeeds: no error is
1136 returned if no certificates are to be found. When the OpenSSL library is
1137 provided as part of the operating system, though, it is likely to be
1138 configured properly.
1139
Antoine Pitrou152efa22010-05-16 18:19:27 +00001140.. method:: SSLContext.set_ciphers(ciphers)
1141
1142 Set the available ciphers for sockets created with this context.
1143 It should be a string in the `OpenSSL cipher list format
1144 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
1145 If no cipher can be selected (because compile-time options or other
1146 configuration forbids use of all the specified ciphers), an
1147 :class:`SSLError` will be raised.
1148
1149 .. note::
1150 when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
1151 give the currently selected cipher.
1152
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001153.. method:: SSLContext.set_npn_protocols(protocols)
1154
R David Murrayc7f75792013-06-26 15:11:12 -04001155 Specify which protocols the socket should advertise during the SSL/TLS
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001156 handshake. It should be a list of strings, like ``['http/1.1', 'spdy/2']``,
1157 ordered by preference. The selection of a protocol will happen during the
1158 handshake, and will play out according to the `NPN draft specification
1159 <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. After a
1160 successful handshake, the :meth:`SSLSocket.selected_npn_protocol` method will
1161 return the agreed-upon protocol.
1162
1163 This method will raise :exc:`NotImplementedError` if :data:`HAS_NPN` is
1164 False.
1165
1166 .. versionadded:: 3.3
1167
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001168.. method:: SSLContext.set_servername_callback(server_name_callback)
1169
1170 Register a callback function that will be called after the TLS Client Hello
1171 handshake message has been received by the SSL/TLS server when the TLS client
1172 specifies a server name indication. The server name indication mechanism
1173 is specified in :rfc:`6066` section 3 - Server Name Indication.
1174
1175 Only one callback can be set per ``SSLContext``. If *server_name_callback*
1176 is ``None`` then the callback is disabled. Calling this function a
1177 subsequent time will disable the previously registered callback.
1178
1179 The callback function, *server_name_callback*, will be called with three
1180 arguments; the first being the :class:`ssl.SSLSocket`, the second is a string
1181 that represents the server name that the client is intending to communicate
Antoine Pitrou50b24d02013-04-11 20:48:42 +02001182 (or :const:`None` if the TLS Client Hello does not contain a server name)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001183 and the third argument is the original :class:`SSLContext`. The server name
1184 argument is the IDNA decoded server name.
1185
1186 A typical use of this callback is to change the :class:`ssl.SSLSocket`'s
1187 :attr:`SSLSocket.context` attribute to a new object of type
1188 :class:`SSLContext` representing a certificate chain that matches the server
1189 name.
1190
1191 Due to the early negotiation phase of the TLS connection, only limited
1192 methods and attributes are usable like
1193 :meth:`SSLSocket.selected_npn_protocol` and :attr:`SSLSocket.context`.
1194 :meth:`SSLSocket.getpeercert`, :meth:`SSLSocket.getpeercert`,
1195 :meth:`SSLSocket.cipher` and :meth:`SSLSocket.compress` methods require that
1196 the TLS connection has progressed beyond the TLS Client Hello and therefore
1197 will not contain return meaningful values nor can they be called safely.
1198
1199 The *server_name_callback* function must return ``None`` to allow the
Terry Jan Reedy8e7586b2013-03-11 18:38:13 -04001200 TLS negotiation to continue. If a TLS failure is required, a constant
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001201 :const:`ALERT_DESCRIPTION_* <ALERT_DESCRIPTION_INTERNAL_ERROR>` can be
1202 returned. Other return values will result in a TLS fatal error with
1203 :const:`ALERT_DESCRIPTION_INTERNAL_ERROR`.
1204
Zachary Ware88a19772014-07-25 13:30:50 -05001205 If there is an IDNA decoding error on the server name, the TLS connection
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001206 will terminate with an :const:`ALERT_DESCRIPTION_INTERNAL_ERROR` fatal TLS
1207 alert message to the client.
1208
1209 If an exception is raised from the *server_name_callback* function the TLS
1210 connection will terminate with a fatal TLS alert message
1211 :const:`ALERT_DESCRIPTION_HANDSHAKE_FAILURE`.
1212
1213 This method will raise :exc:`NotImplementedError` if the OpenSSL library
1214 had OPENSSL_NO_TLSEXT defined when it was built.
1215
1216 .. versionadded:: 3.4
1217
Antoine Pitrou0e576f12011-12-22 10:03:38 +01001218.. method:: SSLContext.load_dh_params(dhfile)
1219
1220 Load the key generation parameters for Diffie-Helman (DH) key exchange.
1221 Using DH key exchange improves forward secrecy at the expense of
1222 computational resources (both on the server and on the client).
1223 The *dhfile* parameter should be the path to a file containing DH
1224 parameters in PEM format.
1225
1226 This setting doesn't apply to client sockets. You can also use the
1227 :data:`OP_SINGLE_DH_USE` option to further improve security.
1228
1229 .. versionadded:: 3.3
1230
Antoine Pitrou923df6f2011-12-19 17:16:51 +01001231.. method:: SSLContext.set_ecdh_curve(curve_name)
1232
Antoine Pitrou0e576f12011-12-22 10:03:38 +01001233 Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key
1234 exchange. ECDH is significantly faster than regular DH while arguably
1235 as secure. The *curve_name* parameter should be a string describing
Antoine Pitrou923df6f2011-12-19 17:16:51 +01001236 a well-known elliptic curve, for example ``prime256v1`` for a widely
1237 supported curve.
1238
1239 This setting doesn't apply to client sockets. You can also use the
1240 :data:`OP_SINGLE_ECDH_USE` option to further improve security.
1241
Antoine Pitrou501da612011-12-21 09:27:41 +01001242 This method is not available if :data:`HAS_ECDH` is False.
1243
Antoine Pitrou923df6f2011-12-19 17:16:51 +01001244 .. versionadded:: 3.3
1245
1246 .. seealso::
1247 `SSL/TLS & Perfect Forward Secrecy <http://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy.html>`_
1248 Vincent Bernat.
1249
Antoine Pitroud5323212010-10-22 18:19:07 +00001250.. method:: SSLContext.wrap_socket(sock, server_side=False, \
1251 do_handshake_on_connect=True, suppress_ragged_eofs=True, \
1252 server_hostname=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001253
1254 Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
Antoine Pitrou3e86ba42013-12-28 17:26:33 +01001255 object. *sock* must be a :data:`~socket.SOCK_STREAM` socket; other socket
1256 types are unsupported.
1257
1258 The returned SSL socket is tied to the context, its settings and
Antoine Pitrou152efa22010-05-16 18:19:27 +00001259 certificates. The parameters *server_side*, *do_handshake_on_connect*
1260 and *suppress_ragged_eofs* have the same meaning as in the top-level
1261 :func:`wrap_socket` function.
1262
Antoine Pitroud5323212010-10-22 18:19:07 +00001263 On client connections, the optional parameter *server_hostname* specifies
1264 the hostname of the service which we are connecting to. This allows a
1265 single server to host multiple SSL-based services with distinct certificates,
1266 quite similarly to HTTP virtual hosts. Specifying *server_hostname*
1267 will raise a :exc:`ValueError` if the OpenSSL library doesn't have support
1268 for it (that is, if :data:`HAS_SNI` is :const:`False`). Specifying
1269 *server_hostname* will also raise a :exc:`ValueError` if *server_side*
1270 is true.
1271
Victor Stinner805b2622014-10-10 12:49:08 +02001272.. method:: SSLContext.wrap_bio(incoming, outgoing, server_side=False, \
1273 server_hostname=None)
1274
1275 Create a new :class:`SSLObject` instance by wrapping the BIO objects
1276 *incoming* and *outgoing*. The SSL routines will read input data from the
1277 incoming BIO and write data to the outgoing BIO.
1278
1279 The *server_side* and *server_hostname* parameters have the same meaning as
1280 in :meth:`SSLContext.wrap_socket`.
1281
Antoine Pitroub0182c82010-10-12 20:09:02 +00001282.. method:: SSLContext.session_stats()
1283
1284 Get statistics about the SSL sessions created or managed by this context.
1285 A dictionary is returned which maps the names of each `piece of information
1286 <http://www.openssl.org/docs/ssl/SSL_CTX_sess_number.html>`_ to their
1287 numeric values. For example, here is the total number of hits and misses
1288 in the session cache since the context was created::
1289
1290 >>> stats = context.session_stats()
1291 >>> stats['hits'], stats['misses']
1292 (0, 0)
1293
Christian Heimesf22e8e52013-11-22 02:22:51 +01001294.. method:: SSLContext.get_ca_certs(binary_form=False)
1295
1296 Returns a list of dicts with information of loaded CA certs. If the
Serhiy Storchaka0e90e992013-11-29 12:19:53 +02001297 optional argument is true, returns a DER-encoded copy of the CA
Christian Heimesf22e8e52013-11-22 02:22:51 +01001298 certificate.
1299
1300 .. note::
1301 Certificates in a capath directory aren't loaded unless they have
1302 been used at least once.
1303
1304 .. versionadded:: 3.4
1305
Christian Heimes1aa9a752013-12-02 02:41:19 +01001306.. attribute:: SSLContext.check_hostname
1307
1308 Wether to match the peer cert's hostname with :func:`match_hostname` in
1309 :meth:`SSLSocket.do_handshake`. The context's
1310 :attr:`~SSLContext.verify_mode` must be set to :data:`CERT_OPTIONAL` or
1311 :data:`CERT_REQUIRED`, and you must pass *server_hostname* to
1312 :meth:`~SSLContext.wrap_socket` in order to match the hostname.
1313
1314 Example::
1315
1316 import socket, ssl
1317
1318 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1319 context.verify_mode = ssl.CERT_REQUIRED
1320 context.check_hostname = True
1321 context.load_default_certs()
1322
1323 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Berker Peksag38bf87c2014-07-17 05:00:36 +03001324 ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com')
1325 ssl_sock.connect(('www.verisign.com', 443))
Christian Heimes1aa9a752013-12-02 02:41:19 +01001326
1327 .. versionadded:: 3.4
1328
1329 .. note::
1330
1331 This features requires OpenSSL 0.9.8f or newer.
1332
Antoine Pitroub5218772010-05-21 09:56:06 +00001333.. attribute:: SSLContext.options
1334
1335 An integer representing the set of SSL options enabled on this context.
1336 The default value is :data:`OP_ALL`, but you can specify other options
1337 such as :data:`OP_NO_SSLv2` by ORing them together.
1338
1339 .. note::
1340 With versions of OpenSSL older than 0.9.8m, it is only possible
1341 to set options, not to clear them. Attempting to clear an option
1342 (by resetting the corresponding bits) will raise a ``ValueError``.
1343
Antoine Pitrou152efa22010-05-16 18:19:27 +00001344.. attribute:: SSLContext.protocol
1345
1346 The protocol version chosen when constructing the context. This attribute
1347 is read-only.
1348
Christian Heimes22587792013-11-21 23:56:13 +01001349.. attribute:: SSLContext.verify_flags
1350
1351 The flags for certificate verification operations. You can set flags like
1352 :data:`VERIFY_CRL_CHECK_LEAF` by ORing them together. By default OpenSSL
1353 does neither require nor verify certificate revocation lists (CRLs).
Christian Heimes2427b502013-11-23 11:24:32 +01001354 Available only with openssl version 0.9.8+.
Christian Heimes22587792013-11-21 23:56:13 +01001355
1356 .. versionadded:: 3.4
1357
Antoine Pitrou152efa22010-05-16 18:19:27 +00001358.. attribute:: SSLContext.verify_mode
1359
1360 Whether to try to verify other peers' certificates and how to behave
1361 if verification fails. This attribute must be one of
1362 :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.
1363
1364
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001365.. index:: single: certificates
1366
1367.. index:: single: X509 certificate
1368
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001369.. _ssl-certificates:
1370
Thomas Woutersed03b412007-08-28 21:37:11 +00001371Certificates
1372------------
1373
Georg Brandl7f01a132009-09-16 15:58:14 +00001374Certificates in general are part of a public-key / private-key system. In this
1375system, each *principal*, (which may be a machine, or a person, or an
1376organization) is assigned a unique two-part encryption key. One part of the key
1377is public, and is called the *public key*; the other part is kept secret, and is
1378called the *private key*. The two parts are related, in that if you encrypt a
1379message with one of the parts, you can decrypt it with the other part, and
1380**only** with the other part.
Thomas Woutersed03b412007-08-28 21:37:11 +00001381
Georg Brandl7f01a132009-09-16 15:58:14 +00001382A certificate contains information about two principals. It contains the name
1383of a *subject*, and the subject's public key. It also contains a statement by a
1384second principal, the *issuer*, that the subject is who he claims to be, and
1385that this is indeed the subject's public key. The issuer's statement is signed
1386with the issuer's private key, which only the issuer knows. However, anyone can
1387verify the issuer's statement by finding the issuer's public key, decrypting the
1388statement with it, and comparing it to the other information in the certificate.
1389The certificate also contains information about the time period over which it is
1390valid. This is expressed as two fields, called "notBefore" and "notAfter".
Thomas Woutersed03b412007-08-28 21:37:11 +00001391
Georg Brandl7f01a132009-09-16 15:58:14 +00001392In the Python use of certificates, a client or server can use a certificate to
1393prove who they are. The other side of a network connection can also be required
1394to produce a certificate, and that certificate can be validated to the
1395satisfaction of the client or server that requires such validation. The
1396connection attempt can be set to raise an exception if the validation fails.
1397Validation is done automatically, by the underlying OpenSSL framework; the
1398application need not concern itself with its mechanics. But the application
1399does usually need to provide sets of certificates to allow this process to take
1400place.
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001401
Georg Brandl7f01a132009-09-16 15:58:14 +00001402Python uses files to contain certificates. They should be formatted as "PEM"
1403(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
1404and a footer line::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001405
1406 -----BEGIN CERTIFICATE-----
1407 ... (certificate in base64 PEM encoding) ...
1408 -----END CERTIFICATE-----
1409
Antoine Pitrou152efa22010-05-16 18:19:27 +00001410Certificate chains
1411^^^^^^^^^^^^^^^^^^
1412
Georg Brandl7f01a132009-09-16 15:58:14 +00001413The Python files which contain certificates can contain a sequence of
1414certificates, sometimes called a *certificate chain*. This chain should start
1415with the specific certificate for the principal who "is" the client or server,
1416and then the certificate for the issuer of that certificate, and then the
1417certificate for the issuer of *that* certificate, and so on up the chain till
1418you get to a certificate which is *self-signed*, that is, a certificate which
1419has the same subject and issuer, sometimes called a *root certificate*. The
1420certificates should just be concatenated together in the certificate file. For
1421example, suppose we had a three certificate chain, from our server certificate
1422to the certificate of the certification authority that signed our server
1423certificate, to the root certificate of the agency which issued the
1424certification authority's certificate::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001425
1426 -----BEGIN CERTIFICATE-----
1427 ... (certificate for your server)...
1428 -----END CERTIFICATE-----
1429 -----BEGIN CERTIFICATE-----
1430 ... (the certificate for the CA)...
1431 -----END CERTIFICATE-----
1432 -----BEGIN CERTIFICATE-----
1433 ... (the root certificate for the CA's issuer)...
1434 -----END CERTIFICATE-----
1435
Antoine Pitrou152efa22010-05-16 18:19:27 +00001436CA certificates
1437^^^^^^^^^^^^^^^
1438
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001439If you are going to require validation of the other side of the connection's
1440certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandl7f01a132009-09-16 15:58:14 +00001441chains for each issuer you are willing to trust. Again, this file just contains
1442these chains concatenated together. For validation, Python will use the first
Donald Stufft41374652014-03-24 19:26:03 -04001443chain it finds in the file which matches. The platform's certificates file can
1444be used by calling :meth:`SSLContext.load_default_certs`, this is done
1445automatically with :func:`.create_default_context`.
Thomas Woutersed03b412007-08-28 21:37:11 +00001446
Antoine Pitrou152efa22010-05-16 18:19:27 +00001447Combined key and certificate
1448^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1449
1450Often the private key is stored in the same file as the certificate; in this
1451case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain`
1452and :func:`wrap_socket` needs to be passed. If the private key is stored
1453with the certificate, it should come before the first certificate in
1454the certificate chain::
1455
1456 -----BEGIN RSA PRIVATE KEY-----
1457 ... (private key in base64 encoding) ...
1458 -----END RSA PRIVATE KEY-----
1459 -----BEGIN CERTIFICATE-----
1460 ... (certificate in base64 PEM encoding) ...
1461 -----END CERTIFICATE-----
1462
1463Self-signed certificates
1464^^^^^^^^^^^^^^^^^^^^^^^^
1465
Georg Brandl7f01a132009-09-16 15:58:14 +00001466If you are going to create a server that provides SSL-encrypted connection
1467services, you will need to acquire a certificate for that service. There are
1468many ways of acquiring appropriate certificates, such as buying one from a
1469certification authority. Another common practice is to generate a self-signed
1470certificate. The simplest way to do this is with the OpenSSL package, using
1471something like the following::
Thomas Woutersed03b412007-08-28 21:37:11 +00001472
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001473 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
1474 Generating a 1024 bit RSA private key
1475 .......++++++
1476 .............................++++++
1477 writing new private key to 'cert.pem'
1478 -----
1479 You are about to be asked to enter information that will be incorporated
1480 into your certificate request.
1481 What you are about to enter is what is called a Distinguished Name or a DN.
1482 There are quite a few fields but you can leave some blank
1483 For some fields there will be a default value,
1484 If you enter '.', the field will be left blank.
1485 -----
1486 Country Name (2 letter code) [AU]:US
1487 State or Province Name (full name) [Some-State]:MyState
1488 Locality Name (eg, city) []:Some City
1489 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
1490 Organizational Unit Name (eg, section) []:My Group
1491 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
1492 Email Address []:ops@myserver.mygroup.myorganization.com
1493 %
Thomas Woutersed03b412007-08-28 21:37:11 +00001494
Georg Brandl7f01a132009-09-16 15:58:14 +00001495The disadvantage of a self-signed certificate is that it is its own root
1496certificate, and no one else will have it in their cache of known (and trusted)
1497root certificates.
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001498
1499
Thomas Woutersed03b412007-08-28 21:37:11 +00001500Examples
1501--------
1502
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001503Testing for SSL support
1504^^^^^^^^^^^^^^^^^^^^^^^
1505
Georg Brandl7f01a132009-09-16 15:58:14 +00001506To test for the presence of SSL support in a Python installation, user code
1507should use the following idiom::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001508
1509 try:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001510 import ssl
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001511 except ImportError:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001512 pass
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001513 else:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001514 ... # do something that requires SSL support
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001515
1516Client-side operation
1517^^^^^^^^^^^^^^^^^^^^^
1518
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001519This example connects to an SSL server and prints the server's certificate::
Thomas Woutersed03b412007-08-28 21:37:11 +00001520
1521 import socket, ssl, pprint
1522
1523 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001524 # require a certificate from the server
1525 ssl_sock = ssl.wrap_socket(s,
1526 ca_certs="/etc/ca_certs_file",
1527 cert_reqs=ssl.CERT_REQUIRED)
Thomas Woutersed03b412007-08-28 21:37:11 +00001528 ssl_sock.connect(('www.verisign.com', 443))
1529
Georg Brandl6911e3c2007-09-04 07:15:32 +00001530 pprint.pprint(ssl_sock.getpeercert())
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001531 # note that closing the SSLSocket will also close the underlying socket
Thomas Woutersed03b412007-08-28 21:37:11 +00001532 ssl_sock.close()
1533
Antoine Pitrou441ae042012-01-06 20:06:15 +01001534As of January 6, 2012, the certificate printed by this program looks like
Georg Brandl7f01a132009-09-16 15:58:14 +00001535this::
Thomas Woutersed03b412007-08-28 21:37:11 +00001536
Antoine Pitrou441ae042012-01-06 20:06:15 +01001537 {'issuer': ((('countryName', 'US'),),
1538 (('organizationName', 'VeriSign, Inc.'),),
1539 (('organizationalUnitName', 'VeriSign Trust Network'),),
1540 (('organizationalUnitName',
1541 'Terms of use at https://www.verisign.com/rpa (c)06'),),
1542 (('commonName',
1543 'VeriSign Class 3 Extended Validation SSL SGC CA'),)),
1544 'notAfter': 'May 25 23:59:59 2012 GMT',
1545 'notBefore': 'May 26 00:00:00 2010 GMT',
1546 'serialNumber': '53D2BEF924A7245E83CA01E46CAA2477',
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001547 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
1548 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
1549 (('businessCategory', 'V1.0, Clause 5.(b)'),),
1550 (('serialNumber', '2497886'),),
1551 (('countryName', 'US'),),
1552 (('postalCode', '94043'),),
1553 (('stateOrProvinceName', 'California'),),
1554 (('localityName', 'Mountain View'),),
1555 (('streetAddress', '487 East Middlefield Road'),),
1556 (('organizationName', 'VeriSign, Inc.'),),
1557 (('organizationalUnitName', ' Production Security Services'),),
Antoine Pitrou441ae042012-01-06 20:06:15 +01001558 (('commonName', 'www.verisign.com'),)),
1559 'subjectAltName': (('DNS', 'www.verisign.com'),
1560 ('DNS', 'verisign.com'),
1561 ('DNS', 'www.verisign.net'),
1562 ('DNS', 'verisign.net'),
1563 ('DNS', 'www.verisign.mobi'),
1564 ('DNS', 'verisign.mobi'),
1565 ('DNS', 'www.verisign.eu'),
1566 ('DNS', 'verisign.eu')),
1567 'version': 3}
Thomas Woutersed03b412007-08-28 21:37:11 +00001568
Antoine Pitrou152efa22010-05-16 18:19:27 +00001569This other example first creates an SSL context, instructs it to verify
1570certificates sent by peers, and feeds it a set of recognized certificate
1571authorities (CA)::
1572
1573 >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001574 >>> context.verify_mode = ssl.CERT_REQUIRED
Antoine Pitrou152efa22010-05-16 18:19:27 +00001575 >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
1576
1577(it is assumed your operating system places a bundle of all CA certificates
1578in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have
1579to adjust the location)
1580
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001581When you use the context to connect to a server, :const:`CERT_REQUIRED`
Antoine Pitrou152efa22010-05-16 18:19:27 +00001582validates the server certificate: it ensures that the server certificate
1583was signed with one of the CA certificates, and checks the signature for
1584correctness::
1585
1586 >>> conn = context.wrap_socket(socket.socket(socket.AF_INET))
1587 >>> conn.connect(("linuxfr.org", 443))
1588
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001589You should then fetch the certificate and check its fields for conformity::
Antoine Pitrou152efa22010-05-16 18:19:27 +00001590
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001591 >>> cert = conn.getpeercert()
1592 >>> ssl.match_hostname(cert, "linuxfr.org")
1593
1594Visual inspection shows that the certificate does identify the desired service
1595(that is, the HTTPS host ``linuxfr.org``)::
1596
1597 >>> pprint.pprint(cert)
Antoine Pitrou441ae042012-01-06 20:06:15 +01001598 {'issuer': ((('organizationName', 'CAcert Inc.'),),
1599 (('organizationalUnitName', 'http://www.CAcert.org'),),
1600 (('commonName', 'CAcert Class 3 Root'),)),
1601 'notAfter': 'Jun 7 21:02:24 2013 GMT',
1602 'notBefore': 'Jun 8 21:02:24 2011 GMT',
1603 'serialNumber': 'D3E9',
Antoine Pitrou152efa22010-05-16 18:19:27 +00001604 'subject': ((('commonName', 'linuxfr.org'),),),
Antoine Pitrou441ae042012-01-06 20:06:15 +01001605 'subjectAltName': (('DNS', 'linuxfr.org'),
1606 ('othername', '<unsupported>'),
1607 ('DNS', 'linuxfr.org'),
1608 ('othername', '<unsupported>'),
1609 ('DNS', 'dev.linuxfr.org'),
1610 ('othername', '<unsupported>'),
1611 ('DNS', 'prod.linuxfr.org'),
1612 ('othername', '<unsupported>'),
1613 ('DNS', 'alpha.linuxfr.org'),
1614 ('othername', '<unsupported>'),
1615 ('DNS', '*.linuxfr.org'),
1616 ('othername', '<unsupported>')),
1617 'version': 3}
Antoine Pitrou152efa22010-05-16 18:19:27 +00001618
1619Now that you are assured of its authenticity, you can proceed to talk with
1620the server::
1621
Antoine Pitroudab64262010-09-19 13:31:06 +00001622 >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
1623 >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
Antoine Pitrou152efa22010-05-16 18:19:27 +00001624 [b'HTTP/1.1 302 Found',
1625 b'Date: Sun, 16 May 2010 13:43:28 GMT',
1626 b'Server: Apache/2.2',
1627 b'Location: https://linuxfr.org/pub/',
1628 b'Vary: Accept-Encoding',
1629 b'Connection: close',
1630 b'Content-Type: text/html; charset=iso-8859-1',
1631 b'',
1632 b'']
1633
Antoine Pitrou152efa22010-05-16 18:19:27 +00001634See the discussion of :ref:`ssl-security` below.
1635
1636
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001637Server-side operation
1638^^^^^^^^^^^^^^^^^^^^^
1639
Antoine Pitrou152efa22010-05-16 18:19:27 +00001640For server operation, typically you'll need to have a server certificate, and
1641private key, each in a file. You'll first create a context holding the key
1642and the certificate, so that clients can check your authenticity. Then
1643you'll open a socket, bind it to a port, call :meth:`listen` on it, and start
1644waiting for clients to connect::
Thomas Woutersed03b412007-08-28 21:37:11 +00001645
1646 import socket, ssl
1647
Antoine Pitrouc5e075f2014-03-22 18:19:11 +01001648 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001649 context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")
1650
Thomas Woutersed03b412007-08-28 21:37:11 +00001651 bindsocket = socket.socket()
1652 bindsocket.bind(('myaddr.mydomain.com', 10023))
1653 bindsocket.listen(5)
1654
Antoine Pitrou152efa22010-05-16 18:19:27 +00001655When a client connects, you'll call :meth:`accept` on the socket to get the
1656new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket`
1657method to create a server-side SSL socket for the connection::
Thomas Woutersed03b412007-08-28 21:37:11 +00001658
1659 while True:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001660 newsocket, fromaddr = bindsocket.accept()
1661 connstream = context.wrap_socket(newsocket, server_side=True)
1662 try:
1663 deal_with_client(connstream)
1664 finally:
Antoine Pitroub205d582011-01-02 22:09:27 +00001665 connstream.shutdown(socket.SHUT_RDWR)
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001666 connstream.close()
Thomas Woutersed03b412007-08-28 21:37:11 +00001667
Antoine Pitrou152efa22010-05-16 18:19:27 +00001668Then you'll read data from the ``connstream`` and do something with it till you
Georg Brandl7f01a132009-09-16 15:58:14 +00001669are finished with the client (or the client is finished with you)::
Thomas Woutersed03b412007-08-28 21:37:11 +00001670
1671 def deal_with_client(connstream):
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001672 data = connstream.recv(1024)
1673 # empty data means the client is finished with us
1674 while data:
1675 if not do_something(connstream, data):
1676 # we'll assume do_something returns False
1677 # when we're finished with client
1678 break
1679 data = connstream.recv(1024)
1680 # finished with client
Thomas Woutersed03b412007-08-28 21:37:11 +00001681
Antoine Pitrou152efa22010-05-16 18:19:27 +00001682And go back to listening for new client connections (of course, a real server
1683would probably handle each client connection in a separate thread, or put
Victor Stinner29611452014-10-10 12:52:43 +02001684the sockets in :ref:`non-blocking mode <ssl-nonblocking>` and use an event loop).
Antoine Pitrou152efa22010-05-16 18:19:27 +00001685
1686
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001687.. _ssl-nonblocking:
1688
1689Notes on non-blocking sockets
1690-----------------------------
1691
Antoine Pitroub4bebda2014-04-29 10:03:28 +02001692SSL sockets behave slightly different than regular sockets in
1693non-blocking mode. When working with non-blocking sockets, there are
1694thus several things you need to be aware of:
1695
1696- Most :class:`SSLSocket` methods will raise either
1697 :exc:`SSLWantWriteError` or :exc:`SSLWantReadError` instead of
1698 :exc:`BlockingIOError` if an I/O operation would
1699 block. :exc:`SSLWantReadError` will be raised if a read operation on
1700 the underlying socket is necessary, and :exc:`SSLWantWriteError` for
1701 a write operation on the underlying socket. Note that attempts to
1702 *write* to an SSL socket may require *reading* from the underlying
1703 socket first, and attempts to *read* from the SSL socket may require
1704 a prior *write* to the underlying socket.
1705
1706 .. versionchanged:: 3.5
1707
1708 In earlier Python versions, the :meth:`!SSLSocket.send` method
1709 returned zero instead of raising :exc:`SSLWantWriteError` or
1710 :exc:`SSLWantReadError`.
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001711
1712- Calling :func:`~select.select` tells you that the OS-level socket can be
1713 read from (or written to), but it does not imply that there is sufficient
1714 data at the upper SSL layer. For example, only part of an SSL frame might
1715 have arrived. Therefore, you must be ready to handle :meth:`SSLSocket.recv`
1716 and :meth:`SSLSocket.send` failures, and retry after another call to
1717 :func:`~select.select`.
1718
Antoine Pitrou75e03382014-05-18 00:55:13 +02001719- Conversely, since the SSL layer has its own framing, a SSL socket may
1720 still have data available for reading without :func:`~select.select`
1721 being aware of it. Therefore, you should first call
1722 :meth:`SSLSocket.recv` to drain any potentially available data, and then
1723 only block on a :func:`~select.select` call if still necessary.
1724
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001725 (of course, similar provisions apply when using other primitives such as
Antoine Pitrou75e03382014-05-18 00:55:13 +02001726 :func:`~select.poll`, or those in the :mod:`selectors` module)
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001727
1728- The SSL handshake itself will be non-blocking: the
1729 :meth:`SSLSocket.do_handshake` method has to be retried until it returns
1730 successfully. Here is a synopsis using :func:`~select.select` to wait for
1731 the socket's readiness::
1732
1733 while True:
1734 try:
1735 sock.do_handshake()
1736 break
Antoine Pitrou873bf262011-10-27 23:59:03 +02001737 except ssl.SSLWantReadError:
1738 select.select([sock], [], [])
1739 except ssl.SSLWantWriteError:
1740 select.select([], [sock], [])
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001741
Victor Stinnercfb2a0a2014-10-10 12:45:10 +02001742.. seealso::
1743
Victor Stinner29611452014-10-10 12:52:43 +02001744 The :mod:`asyncio` module supports :ref:`non-blocking SSL sockets
1745 <ssl-nonblocking>` and provides a
Victor Stinnercfb2a0a2014-10-10 12:45:10 +02001746 higher level API. It polls for events using the :mod:`selectors` module and
1747 handles :exc:`SSLWantWriteError`, :exc:`SSLWantReadError` and
1748 :exc:`BlockingIOError` exceptions. It runs the SSL handshake asynchronously
1749 as well.
1750
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001751
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001752Memory BIO Support
1753------------------
1754
1755.. versionadded:: 3.5
1756
1757Ever since the SSL module was introduced in Python 2.6, the :class:`SSLSocket`
1758class has provided two related but distinct areas of functionality:
1759
1760- SSL protocol handling
1761- Network IO
1762
1763The network IO API is identical to that provided by :class:`socket.socket`,
1764from which :class:`SSLSocket` also inherits. This allows an SSL socket to be
1765used as a drop-in replacement for a regular socket, making it very easy to add
1766SSL support to an existing application.
1767
1768Combining SSL protocol handling and network IO usually works well, but there
1769are some cases where it doesn't. An example is async IO frameworks that want to
1770use a different IO multiplexing model than the "select/poll on a file
1771descriptor" (readiness based) model that is assumed by :class:`socket.socket`
1772and by the internal OpenSSL socket IO routines. This is mostly relevant for
1773platforms like Windows where this model is not efficient. For this purpose, a
1774reduced scope variant of :class:`SSLSocket` called :class:`SSLObject` is
1775provided.
1776
1777.. class:: SSLObject
1778
1779 A reduced-scope variant of :class:`SSLSocket` representing an SSL protocol
Victor Stinner2debf152014-10-10 13:04:08 +02001780 instance that does not contain any network IO methods. This class is
1781 typically used by framework authors that want to implement asynchronous IO
1782 for SSL through memory buffers.
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001783
Victor Stinner2debf152014-10-10 13:04:08 +02001784 This class implements an interface on top of a low-level SSL object as
1785 implemented by OpenSSL. This object captures the state of an SSL connection
1786 but does not provide any network IO itself. IO needs to be performed through
1787 separate "BIO" objects which are OpenSSL's IO abstraction layer.
1788
1789 An :class:`SSLObject` instance can be created using the
1790 :meth:`~SSLContext.wrap_bio` method. This method will create the
1791 :class:`SSLObject` instance and bind it to a pair of BIOs. The *incoming*
1792 BIO is used to pass data from Python to the SSL protocol instance, while the
1793 *outgoing* BIO is used to pass data the other way around.
1794
1795 The following methods are available:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001796
Victor Stinner805b2622014-10-10 12:49:08 +02001797 - :attr:`~SSLSocket.context`
1798 - :attr:`~SSLSocket.server_side`
1799 - :attr:`~SSLSocket.server_hostname`
1800 - :meth:`~SSLSocket.read`
1801 - :meth:`~SSLSocket.write`
1802 - :meth:`~SSLSocket.getpeercert`
1803 - :meth:`~SSLSocket.selected_npn_protocol`
1804 - :meth:`~SSLSocket.cipher`
1805 - :meth:`~SSLSocket.compression`
1806 - :meth:`~SSLSocket.pending`
1807 - :meth:`~SSLSocket.do_handshake`
1808 - :meth:`~SSLSocket.unwrap`
1809 - :meth:`~SSLSocket.get_channel_binding`
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001810
Victor Stinner2debf152014-10-10 13:04:08 +02001811 When compared to :class:`SSLSocket`, this object lacks the following
1812 features:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001813
Victor Stinner2debf152014-10-10 13:04:08 +02001814 - Any form of network IO incluging methods such as ``recv()`` and
1815 ``send()``.
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001816
Victor Stinner2debf152014-10-10 13:04:08 +02001817 - There is no *do_handshake_on_connect* machinery. You must always manually
1818 call :meth:`~SSLSocket.do_handshake` to start the handshake.
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001819
Victor Stinner2debf152014-10-10 13:04:08 +02001820 - There is no handling of *suppress_ragged_eofs*. All end-of-file conditions
1821 that are in violation of the protocol are reported via the
1822 :exc:`SSLEOFError` exception.
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001823
Victor Stinner2debf152014-10-10 13:04:08 +02001824 - The method :meth:`~SSLSocket.unwrap` call does not return anything,
1825 unlike for an SSL socket where it returns the underlying socket.
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001826
Victor Stinner2debf152014-10-10 13:04:08 +02001827 - The *server_name_callback* callback passed to
1828 :meth:`SSLContext.set_servername_callback` will get an :class:`SSLObject`
1829 instance instead of a :class:`SSLSocket` instance as its first parameter.
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001830
Victor Stinner2debf152014-10-10 13:04:08 +02001831 Some notes related to the use of :class:`SSLObject`:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001832
Victor Stinner2debf152014-10-10 13:04:08 +02001833 - All IO on an :class:`SSLObject` is :ref:`non-blocking <ssl-nonblocking>`.
1834 This means that for example :meth:`~SSLSocket.read` will raise an
1835 :exc:`SSLWantReadError` if it needs more data than the incoming BIO has
1836 available.
1837
1838 - There is no module-level ``wrap_bio()`` call like there is for
1839 :meth:`~SSLContext.wrap_socket`. An :class:`SSLObject` is always created
1840 via an :class:`SSLContext`.
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001841
Victor Stinner805b2622014-10-10 12:49:08 +02001842An SSLObject communicates with the outside world using memory buffers. The
1843class :class:`MemoryBIO` provides a memory buffer that can be used for this
1844purpose. It wraps an OpenSSL memory BIO (Basic IO) object:
1845
1846.. class:: MemoryBIO
1847
1848 A memory buffer that can be used to pass data between Python and an SSL
1849 protocol instance.
1850
1851 .. attribute:: MemoryBIO.pending
1852
1853 Return the number of bytes currently in the memory buffer.
1854
1855 .. attribute:: MemoryBIO.eof
1856
1857 A boolean indicating whether the memory BIO is current at the end-of-file
1858 position.
1859
1860 .. method:: MemoryBIO.read(n=-1)
1861
1862 Read up to *n* bytes from the memory buffer. If *n* is not specified or
1863 negative, all bytes are returned.
1864
1865 .. method:: MemoryBIO.write(buf)
1866
1867 Write the bytes from *buf* to the memory BIO. The *buf* argument must be an
1868 object supporting the buffer protocol.
1869
1870 The return value is the number of bytes written, which is always equal to
1871 the length of *buf*.
1872
1873 .. method:: MemoryBIO.write_eof()
1874
1875 Write an EOF marker to the memory BIO. After this method has been called, it
1876 is illegal to call :meth:`~MemoryBIO.write`. The attribute :attr:`eof` will
1877 become true after all data currently in the buffer has been read.
1878
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001879
Antoine Pitrou152efa22010-05-16 18:19:27 +00001880.. _ssl-security:
1881
1882Security considerations
1883-----------------------
1884
Antoine Pitrouc5e075f2014-03-22 18:19:11 +01001885Best defaults
1886^^^^^^^^^^^^^
Antoine Pitrou152efa22010-05-16 18:19:27 +00001887
Antoine Pitrouc5e075f2014-03-22 18:19:11 +01001888For **client use**, if you don't have any special requirements for your
1889security policy, it is highly recommended that you use the
1890:func:`create_default_context` function to create your SSL context.
1891It will load the system's trusted CA certificates, enable certificate
Antoine Pitrouf8cbbbb2014-03-23 16:31:08 +01001892validation and hostname checking, and try to choose reasonably secure
1893protocol and cipher settings.
Antoine Pitrouc5e075f2014-03-22 18:19:11 +01001894
1895For example, here is how you would use the :class:`smtplib.SMTP` class to
1896create a trusted, secure connection to a SMTP server::
1897
1898 >>> import ssl, smtplib
1899 >>> smtp = smtplib.SMTP("mail.python.org", port=587)
1900 >>> context = ssl.create_default_context()
1901 >>> smtp.starttls(context=context)
1902 (220, b'2.0.0 Ready to start TLS')
1903
1904If a client certificate is needed for the connection, it can be added with
1905:meth:`SSLContext.load_cert_chain`.
1906
1907By contrast, if you create the SSL context by calling the :class:`SSLContext`
Antoine Pitrouf8cbbbb2014-03-23 16:31:08 +01001908constructor yourself, it will not have certificate validation nor hostname
1909checking enabled by default. If you do so, please read the paragraphs below
1910to achieve a good security level.
Antoine Pitrouc5e075f2014-03-22 18:19:11 +01001911
1912Manual settings
1913^^^^^^^^^^^^^^^
1914
1915Verifying certificates
1916''''''''''''''''''''''
1917
Donald Stufft8b852f12014-05-20 12:58:38 -04001918When calling the :class:`SSLContext` constructor directly,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001919:const:`CERT_NONE` is the default. Since it does not authenticate the other
1920peer, it can be insecure, especially in client mode where most of time you
1921would like to ensure the authenticity of the server you're talking to.
1922Therefore, when in client mode, it is highly recommended to use
1923:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001924have to check that the server certificate, which can be obtained by calling
1925:meth:`SSLSocket.getpeercert`, matches the desired service. For many
1926protocols and applications, the service can be identified by the hostname;
Christian Heimes1aa9a752013-12-02 02:41:19 +01001927in this case, the :func:`match_hostname` function can be used. This common
1928check is automatically performed when :attr:`SSLContext.check_hostname` is
1929enabled.
Antoine Pitrou152efa22010-05-16 18:19:27 +00001930
1931In server mode, if you want to authenticate your clients using the SSL layer
1932(rather than using a higher-level authentication mechanism), you'll also have
1933to specify :const:`CERT_REQUIRED` and similarly check the client certificate.
1934
1935 .. note::
1936
1937 In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are
1938 equivalent unless anonymous ciphers are enabled (they are disabled
1939 by default).
Thomas Woutersed03b412007-08-28 21:37:11 +00001940
Antoine Pitroub5218772010-05-21 09:56:06 +00001941Protocol versions
Antoine Pitrouc5e075f2014-03-22 18:19:11 +01001942'''''''''''''''''
Antoine Pitroub5218772010-05-21 09:56:06 +00001943
1944SSL version 2 is considered insecure and is therefore dangerous to use. If
1945you want maximum compatibility between clients and servers, it is recommended
1946to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable
1947SSLv2 explicitly using the :data:`SSLContext.options` attribute::
1948
1949 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1950 context.options |= ssl.OP_NO_SSLv2
1951
Antoine Pitrouc5e075f2014-03-22 18:19:11 +01001952The SSL context created above will allow SSLv3 and TLSv1 (and later, if
1953supported by your system) connections, but not SSLv2.
Antoine Pitroub5218772010-05-21 09:56:06 +00001954
Antoine Pitroub7ffed82012-01-04 02:53:44 +01001955Cipher selection
Antoine Pitrouc5e075f2014-03-22 18:19:11 +01001956''''''''''''''''
Antoine Pitroub7ffed82012-01-04 02:53:44 +01001957
1958If you have advanced security requirements, fine-tuning of the ciphers
1959enabled when negotiating a SSL session is possible through the
1960:meth:`SSLContext.set_ciphers` method. Starting from Python 3.2.3, the
1961ssl module disables certain weak ciphers by default, but you may want
Donald Stufft79ccaa22014-03-21 21:33:34 -04001962to further restrict the cipher choice. Be sure to read OpenSSL's documentation
1963about the `cipher list format <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
1964If you want to check which ciphers are enabled by a given cipher list, use the
1965``openssl ciphers`` command on your system.
Antoine Pitroub7ffed82012-01-04 02:53:44 +01001966
Antoine Pitrou9eefe912013-11-17 15:35:33 +01001967Multi-processing
1968^^^^^^^^^^^^^^^^
1969
1970If using this module as part of a multi-processed application (using,
1971for example the :mod:`multiprocessing` or :mod:`concurrent.futures` modules),
1972be aware that OpenSSL's internal random number generator does not properly
1973handle forked processes. Applications must change the PRNG state of the
1974parent process if they use any SSL feature with :func:`os.fork`. Any
1975successful call of :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or
1976:func:`~ssl.RAND_pseudo_bytes` is sufficient.
1977
Georg Brandl48310cd2009-01-03 21:18:54 +00001978
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001979.. seealso::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001980
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001981 Class :class:`socket.socket`
Georg Brandl4a6cf6c2013-10-06 18:20:31 +02001982 Documentation of underlying :mod:`socket` class
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001983
Georg Brandl4a6cf6c2013-10-06 18:20:31 +02001984 `SSL/TLS Strong Encryption: An Introduction <http://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html>`_
1985 Intro from the Apache webserver documentation
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001986
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001987 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
1988 Steve Kent
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001989
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001990 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
1991 D. Eastlake et. al.
Thomas Wouters89d996e2007-09-08 17:39:28 +00001992
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001993 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
1994 Housley et. al.
Antoine Pitroud5323212010-10-22 18:19:07 +00001995
1996 `RFC 4366: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc4366>`_
1997 Blake-Wilson et. al.
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001998
1999 `RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2 <http://www.ietf.org/rfc/rfc5246>`_
2000 T. Dierks et. al.
2001
2002 `RFC 6066: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc6066>`_
2003 D. Eastlake
2004
2005 `IANA TLS: Transport Layer Security (TLS) Parameters <http://www.iana.org/assignments/tls-parameters/tls-parameters.xml>`_
2006 IANA