blob: 9f3760e87aadeb935db3752584da11ce411c6366 [file] [log] [blame]
Antoine Pitroue1bc8982011-01-02 22:12:22 +00001:mod:`ssl` --- TLS/SSL wrapper for socket objects
2=================================================
Thomas Woutersed03b412007-08-28 21:37:11 +00003
4.. module:: ssl
Antoine Pitroue1bc8982011-01-02 22:12:22 +00005 :synopsis: TLS/SSL wrapper for socket objects
Thomas Wouters47b49bf2007-08-30 22:15:33 +00006
7.. moduleauthor:: Bill Janssen <bill.janssen@gmail.com>
Thomas Wouters47b49bf2007-08-30 22:15:33 +00008.. sectionauthor:: Bill Janssen <bill.janssen@gmail.com>
9
Thomas Woutersed03b412007-08-28 21:37:11 +000010
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011.. index:: single: OpenSSL; (use in module ssl)
12
13.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
14
Raymond Hettinger469271d2011-01-27 20:38:46 +000015**Source code:** :source:`Lib/ssl.py`
16
17--------------
18
Georg Brandl7f01a132009-09-16 15:58:14 +000019This module provides access to Transport Layer Security (often known as "Secure
20Sockets Layer") encryption and peer authentication facilities for network
21sockets, both client-side and server-side. This module uses the OpenSSL
22library. It is available on all modern Unix systems, Windows, Mac OS X, and
23probably additional platforms, as long as OpenSSL is installed on that platform.
Thomas Woutersed03b412007-08-28 21:37:11 +000024
25.. note::
26
Georg Brandl7f01a132009-09-16 15:58:14 +000027 Some behavior may be platform dependent, since calls are made to the
28 operating system socket APIs. The installed version of OpenSSL may also
29 cause variations in behavior.
Thomas Woutersed03b412007-08-28 21:37:11 +000030
Georg Brandl7f01a132009-09-16 15:58:14 +000031This section documents the objects and functions in the ``ssl`` module; for more
32general information about TLS, SSL, and certificates, the reader is referred to
33the documents in the "See Also" section at the bottom.
Thomas Woutersed03b412007-08-28 21:37:11 +000034
Georg Brandl7f01a132009-09-16 15:58:14 +000035This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
36:class:`socket.socket` type, and provides a socket-like wrapper that also
37encrypts and decrypts the data going over the socket with SSL. It supports
Antoine Pitroudab64262010-09-19 13:31:06 +000038additional methods such as :meth:`getpeercert`, which retrieves the
39certificate of the other side of the connection, and :meth:`cipher`,which
40retrieves the cipher being used for the secure connection.
Thomas Woutersed03b412007-08-28 21:37:11 +000041
Antoine Pitrou152efa22010-05-16 18:19:27 +000042For more sophisticated applications, the :class:`ssl.SSLContext` class
43helps manage settings and certificates, which can then be inherited
44by SSL sockets created through the :meth:`SSLContext.wrap_socket` method.
45
46
Thomas Wouters1b7f8912007-09-19 03:06:30 +000047Functions, Constants, and Exceptions
48------------------------------------
49
50.. exception:: SSLError
51
Antoine Pitrou59fdd672010-10-08 10:37:08 +000052 Raised to signal an error from the underlying SSL implementation
53 (currently provided by the OpenSSL library). This signifies some
54 problem in the higher-level encryption and authentication layer that's
55 superimposed on the underlying network connection. This error
Antoine Pitrou5574c302011-10-12 17:53:43 +020056 is a subtype of :exc:`OSError`. The error code and message of
57 :exc:`SSLError` instances are provided by the OpenSSL library.
58
59 .. versionchanged:: 3.3
60 :exc:`SSLError` used to be a subtype of :exc:`socket.error`.
Antoine Pitrou59fdd672010-10-08 10:37:08 +000061
62.. exception:: CertificateError
63
64 Raised to signal an error with a certificate (such as mismatching
65 hostname). Certificate errors detected by OpenSSL, though, raise
66 an :exc:`SSLError`.
67
68
69Socket creation
70^^^^^^^^^^^^^^^
71
72The following function allows for standalone socket creation. Starting from
73Python 3.2, it can be more flexible to use :meth:`SSLContext.wrap_socket`
74instead.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000075
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +000076.. 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 +000077
Georg Brandl7f01a132009-09-16 15:58:14 +000078 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
79 of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
80 the underlying socket in an SSL context. For client-side sockets, the
81 context construction is lazy; if the underlying socket isn't connected yet,
82 the context construction will be performed after :meth:`connect` is called on
83 the socket. For server-side sockets, if the socket has no remote peer, it is
84 assumed to be a listening socket, and the server-side SSL wrapping is
85 automatically performed on client connections accepted via the :meth:`accept`
86 method. :func:`wrap_socket` may raise :exc:`SSLError`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000087
Georg Brandl7f01a132009-09-16 15:58:14 +000088 The ``keyfile`` and ``certfile`` parameters specify optional files which
89 contain a certificate to be used to identify the local side of the
90 connection. See the discussion of :ref:`ssl-certificates` for more
91 information on how the certificate is stored in the ``certfile``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000092
Georg Brandl7f01a132009-09-16 15:58:14 +000093 The parameter ``server_side`` is a boolean which identifies whether
94 server-side or client-side behavior is desired from this socket.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000095
Georg Brandl7f01a132009-09-16 15:58:14 +000096 The parameter ``cert_reqs`` specifies whether a certificate is required from
97 the other side of the connection, and whether it will be validated if
98 provided. It must be one of the three values :const:`CERT_NONE`
99 (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
100 if provided), or :const:`CERT_REQUIRED` (required and validated). If the
101 value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
102 parameter must point to a file of CA certificates.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000103
Georg Brandl7f01a132009-09-16 15:58:14 +0000104 The ``ca_certs`` file contains a set of concatenated "certification
105 authority" certificates, which are used to validate certificates passed from
106 the other end of the connection. See the discussion of
107 :ref:`ssl-certificates` for more information about how to arrange the
108 certificates in this file.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000109
Georg Brandl7f01a132009-09-16 15:58:14 +0000110 The parameter ``ssl_version`` specifies which version of the SSL protocol to
111 use. Typically, the server chooses a particular protocol version, and the
112 client must adapt to the server's choice. Most of the versions are not
113 interoperable with the other versions. If not specified, for client-side
114 operation, the default SSL version is SSLv3; for server-side operation,
115 SSLv23. These version selections provide the most compatibility with other
116 versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000117
Georg Brandl7f01a132009-09-16 15:58:14 +0000118 Here's a table showing which versions in a client (down the side) can connect
119 to which versions in a server (along the top):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000120
121 .. table::
122
123 ======================== ========= ========= ========== =========
124 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1**
Christian Heimes255f53b2007-12-08 15:33:56 +0000125 ------------------------ --------- --------- ---------- ---------
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000126 *SSLv2* yes no yes no
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000127 *SSLv3* yes yes yes no
128 *SSLv23* yes no yes no
129 *TLSv1* no no yes yes
130 ======================== ========= ========= ========== =========
131
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000132 .. note::
133
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000134 Which connections succeed will vary depending on the version of
135 OpenSSL. For instance, in some older versions of OpenSSL (such
136 as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an
137 SSLv23 server. Another example: beginning with OpenSSL 1.0.0,
138 an SSLv23 client will not actually attempt SSLv2 connections
139 unless you explicitly enable SSLv2 ciphers; for example, you
140 might specify ``"ALL"`` or ``"SSLv2"`` as the *ciphers* parameter
141 to enable them.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000142
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000143 The *ciphers* parameter sets the available ciphers for this SSL object.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000144 It should be a string in the `OpenSSL cipher list format
145 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000146
Bill Janssen48dc27c2007-12-05 03:38:10 +0000147 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
148 handshake automatically after doing a :meth:`socket.connect`, or whether the
Georg Brandl7f01a132009-09-16 15:58:14 +0000149 application program will call it explicitly, by invoking the
150 :meth:`SSLSocket.do_handshake` method. Calling
151 :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
152 blocking behavior of the socket I/O involved in the handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000153
Georg Brandl7f01a132009-09-16 15:58:14 +0000154 The parameter ``suppress_ragged_eofs`` specifies how the
Antoine Pitroudab64262010-09-19 13:31:06 +0000155 :meth:`SSLSocket.recv` method should signal unexpected EOF from the other end
Georg Brandl7f01a132009-09-16 15:58:14 +0000156 of the connection. If specified as :const:`True` (the default), it returns a
Antoine Pitroudab64262010-09-19 13:31:06 +0000157 normal EOF (an empty bytes object) in response to unexpected EOF errors
158 raised from the underlying socket; if :const:`False`, it will raise the
159 exceptions back to the caller.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000160
Ezio Melotti4d5195b2010-04-20 10:57:44 +0000161 .. versionchanged:: 3.2
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000162 New optional argument *ciphers*.
163
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000164Random generation
165^^^^^^^^^^^^^^^^^
166
Victor Stinner99c8b162011-05-24 12:05:19 +0200167.. function:: RAND_bytes(num)
168
Victor Stinnera6752062011-05-25 11:27:40 +0200169 Returns *num* cryptographically strong pseudo-random bytes. Raises an
170 :class:`SSLError` if the PRNG has not been seeded with enough data or if the
171 operation is not supported by the current RAND method. :func:`RAND_status`
172 can be used to check the status of the PRNG and :func:`RAND_add` can be used
173 to seed the PRNG.
Victor Stinner99c8b162011-05-24 12:05:19 +0200174
Victor Stinner19fb53c2011-05-24 21:32:40 +0200175 Read the Wikipedia article, `Cryptographically secure pseudorandom number
Victor Stinnera6752062011-05-25 11:27:40 +0200176 generator (CSPRNG)
Victor Stinner19fb53c2011-05-24 21:32:40 +0200177 <http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator>`_,
178 to get the requirements of a cryptographically generator.
179
Victor Stinner99c8b162011-05-24 12:05:19 +0200180 .. versionadded:: 3.3
181
182.. function:: RAND_pseudo_bytes(num)
183
184 Returns (bytes, is_cryptographic): bytes are *num* pseudo-random bytes,
185 is_cryptographic is True if the bytes generated are cryptographically
Victor Stinnera6752062011-05-25 11:27:40 +0200186 strong. Raises an :class:`SSLError` if the operation is not supported by the
187 current RAND method.
Victor Stinner99c8b162011-05-24 12:05:19 +0200188
Victor Stinner19fb53c2011-05-24 21:32:40 +0200189 Generated pseudo-random byte sequences will be unique if they are of
190 sufficient length, but are not necessarily unpredictable. They can be used
191 for non-cryptographic purposes and for certain purposes in cryptographic
192 protocols, but usually not for key generation etc.
193
Victor Stinner99c8b162011-05-24 12:05:19 +0200194 .. versionadded:: 3.3
195
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000196.. function:: RAND_status()
197
Georg Brandl7f01a132009-09-16 15:58:14 +0000198 Returns True if the SSL pseudo-random number generator has been seeded with
199 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
200 and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
201 number generator.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000202
203.. function:: RAND_egd(path)
204
Victor Stinner99c8b162011-05-24 12:05:19 +0200205 If you are running an entropy-gathering daemon (EGD) somewhere, and *path*
Georg Brandl7f01a132009-09-16 15:58:14 +0000206 is the pathname of a socket connection open to it, this will read 256 bytes
207 of randomness from the socket, and add it to the SSL pseudo-random number
208 generator to increase the security of generated secret keys. This is
209 typically only necessary on systems without better sources of randomness.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000210
Georg Brandl7f01a132009-09-16 15:58:14 +0000211 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
212 of entropy-gathering daemons.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000213
214.. function:: RAND_add(bytes, entropy)
215
Victor Stinner99c8b162011-05-24 12:05:19 +0200216 Mixes the given *bytes* into the SSL pseudo-random number generator. The
217 parameter *entropy* (a float) is a lower bound on the entropy contained in
Georg Brandl7f01a132009-09-16 15:58:14 +0000218 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
219 information on sources of entropy.
Thomas Woutersed03b412007-08-28 21:37:11 +0000220
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000221Certificate handling
222^^^^^^^^^^^^^^^^^^^^
223
224.. function:: match_hostname(cert, hostname)
225
226 Verify that *cert* (in decoded format as returned by
227 :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules
228 applied are those for checking the identity of HTTPS servers as outlined
229 in :rfc:`2818`, except that IP addresses are not currently supported.
230 In addition to HTTPS, this function should be suitable for checking the
231 identity of servers in various SSL-based protocols such as FTPS, IMAPS,
232 POPS and others.
233
234 :exc:`CertificateError` is raised on failure. On success, the function
235 returns nothing::
236
237 >>> cert = {'subject': ((('commonName', 'example.com'),),)}
238 >>> ssl.match_hostname(cert, "example.com")
239 >>> ssl.match_hostname(cert, "example.org")
240 Traceback (most recent call last):
241 File "<stdin>", line 1, in <module>
242 File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
243 ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'
244
245 .. versionadded:: 3.2
246
Thomas Woutersed03b412007-08-28 21:37:11 +0000247.. function:: cert_time_to_seconds(timestring)
248
Georg Brandl7f01a132009-09-16 15:58:14 +0000249 Returns a floating-point value containing a normal seconds-after-the-epoch
250 time value, given the time-string representing the "notBefore" or "notAfter"
251 date from a certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000252
253 Here's an example::
254
255 >>> import ssl
256 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
257 1178694000.0
258 >>> import time
259 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
260 'Wed May 9 00:00:00 2007'
Thomas Woutersed03b412007-08-28 21:37:11 +0000261
Georg Brandl7f01a132009-09-16 15:58:14 +0000262.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000263
Georg Brandl7f01a132009-09-16 15:58:14 +0000264 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
265 *port-number*) pair, fetches the server's certificate, and returns it as a
266 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
267 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
268 specified, it should be a file containing a list of root certificates, the
269 same format as used for the same parameter in :func:`wrap_socket`. The call
270 will attempt to validate the server certificate against that set of root
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000271 certificates, and will fail if the validation attempt fails.
272
Antoine Pitrou15399c32011-04-28 19:23:55 +0200273 .. versionchanged:: 3.3
274 This function is now IPv6-compatible.
275
Georg Brandl7f01a132009-09-16 15:58:14 +0000276.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000277
278 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
279 string version of the same certificate.
280
Georg Brandl7f01a132009-09-16 15:58:14 +0000281.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000282
Georg Brandl7f01a132009-09-16 15:58:14 +0000283 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
284 bytes for that same certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000285
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000286Constants
287^^^^^^^^^
288
Thomas Woutersed03b412007-08-28 21:37:11 +0000289.. data:: CERT_NONE
290
Antoine Pitrou152efa22010-05-16 18:19:27 +0000291 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
292 parameter to :func:`wrap_socket`. In this mode (the default), no
293 certificates will be required from the other side of the socket connection.
294 If a certificate is received from the other end, no attempt to validate it
295 is made.
296
297 See the discussion of :ref:`ssl-security` below.
Thomas Woutersed03b412007-08-28 21:37:11 +0000298
299.. data:: CERT_OPTIONAL
300
Antoine Pitrou152efa22010-05-16 18:19:27 +0000301 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
302 parameter to :func:`wrap_socket`. In this mode no certificates will be
303 required from the other side of the socket connection; but if they
304 are provided, validation will be attempted and an :class:`SSLError`
305 will be raised on failure.
306
307 Use of this setting requires a valid set of CA certificates to
308 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
309 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000310
311.. data:: CERT_REQUIRED
312
Antoine Pitrou152efa22010-05-16 18:19:27 +0000313 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
314 parameter to :func:`wrap_socket`. In this mode, certificates are
315 required from the other side of the socket connection; an :class:`SSLError`
316 will be raised if no certificate is provided, or if its validation fails.
317
318 Use of this setting requires a valid set of CA certificates to
319 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
320 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000321
322.. data:: PROTOCOL_SSLv2
323
324 Selects SSL version 2 as the channel encryption protocol.
325
Victor Stinner3de49192011-05-09 00:42:58 +0200326 This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
327 flag.
328
Antoine Pitrou8eac60d2010-05-16 14:19:41 +0000329 .. warning::
330
331 SSL version 2 is insecure. Its use is highly discouraged.
332
Thomas Woutersed03b412007-08-28 21:37:11 +0000333.. data:: PROTOCOL_SSLv23
334
Georg Brandl7f01a132009-09-16 15:58:14 +0000335 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
336 setting to use with servers for maximum compatibility with the other end of
337 an SSL connection, but it may cause the specific ciphers chosen for the
338 encryption to be of fairly low quality.
Thomas Woutersed03b412007-08-28 21:37:11 +0000339
340.. data:: PROTOCOL_SSLv3
341
Georg Brandl7f01a132009-09-16 15:58:14 +0000342 Selects SSL version 3 as the channel encryption protocol. For clients, this
343 is the maximally compatible SSL variant.
Thomas Woutersed03b412007-08-28 21:37:11 +0000344
345.. data:: PROTOCOL_TLSv1
346
Georg Brandl7f01a132009-09-16 15:58:14 +0000347 Selects TLS version 1 as the channel encryption protocol. This is the most
348 modern version, and probably the best choice for maximum protection, if both
349 sides can speak it.
Thomas Woutersed03b412007-08-28 21:37:11 +0000350
Antoine Pitroub5218772010-05-21 09:56:06 +0000351.. data:: OP_ALL
352
353 Enables workarounds for various bugs present in other SSL implementations.
354 This option is set by default.
355
356 .. versionadded:: 3.2
357
358.. data:: OP_NO_SSLv2
359
360 Prevents an SSLv2 connection. This option is only applicable in
361 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
362 choosing SSLv2 as the protocol version.
363
364 .. versionadded:: 3.2
365
366.. data:: OP_NO_SSLv3
367
368 Prevents an SSLv3 connection. This option is only applicable in
369 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
370 choosing SSLv3 as the protocol version.
371
372 .. versionadded:: 3.2
373
374.. data:: OP_NO_TLSv1
375
376 Prevents a TLSv1 connection. This option is only applicable in
377 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
378 choosing TLSv1 as the protocol version.
379
380 .. versionadded:: 3.2
381
Antoine Pitroud5323212010-10-22 18:19:07 +0000382.. data:: HAS_SNI
383
384 Whether the OpenSSL library has built-in support for the *Server Name
385 Indication* extension to the SSLv3 and TLSv1 protocols (as defined in
386 :rfc:`4366`). When true, you can use the *server_hostname* argument to
387 :meth:`SSLContext.wrap_socket`.
388
389 .. versionadded:: 3.2
390
Antoine Pitroud6494802011-07-21 01:11:30 +0200391.. data:: CHANNEL_BINDING_TYPES
392
393 List of supported TLS channel binding types. Strings in this list
394 can be used as arguments to :meth:`SSLSocket.get_channel_binding`.
395
396 .. versionadded:: 3.3
397
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000398.. data:: OPENSSL_VERSION
399
400 The version string of the OpenSSL library loaded by the interpreter::
401
402 >>> ssl.OPENSSL_VERSION
403 'OpenSSL 0.9.8k 25 Mar 2009'
404
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000405 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000406
407.. data:: OPENSSL_VERSION_INFO
408
409 A tuple of five integers representing version information about the
410 OpenSSL library::
411
412 >>> ssl.OPENSSL_VERSION_INFO
413 (0, 9, 8, 11, 15)
414
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000415 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000416
417.. data:: OPENSSL_VERSION_NUMBER
418
419 The raw version number of the OpenSSL library, as a single integer::
420
421 >>> ssl.OPENSSL_VERSION_NUMBER
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000422 9470143
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000423 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000424 '0x9080bf'
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000425
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000426 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000427
Thomas Woutersed03b412007-08-28 21:37:11 +0000428
Antoine Pitrou152efa22010-05-16 18:19:27 +0000429SSL Sockets
430-----------
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000431
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000432SSL sockets provide the following methods of :ref:`socket-objects`:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000433
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000434- :meth:`~socket.socket.accept()`
435- :meth:`~socket.socket.bind()`
436- :meth:`~socket.socket.close()`
437- :meth:`~socket.socket.connect()`
438- :meth:`~socket.socket.detach()`
439- :meth:`~socket.socket.fileno()`
440- :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`
441- :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`
442- :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`,
443 :meth:`~socket.socket.setblocking()`
444- :meth:`~socket.socket.listen()`
445- :meth:`~socket.socket.makefile()`
446- :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()`
447 (but passing a non-zero ``flags`` argument is not allowed)
448- :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with
449 the same limitation)
450- :meth:`~socket.socket.shutdown()`
451
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +0200452However, since the SSL (and TLS) protocol has its own framing atop
453of TCP, the SSL sockets abstraction can, in certain respects, diverge from
454the specification of normal, OS-level sockets. See especially the
455:ref:`notes on non-blocking sockets <ssl-nonblocking>`.
456
457SSL sockets also have the following additional methods and attributes:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000458
Bill Janssen48dc27c2007-12-05 03:38:10 +0000459.. method:: SSLSocket.do_handshake()
460
Antoine Pitroub3593ca2011-07-11 01:39:19 +0200461 Perform the SSL setup handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000462
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000463.. method:: SSLSocket.getpeercert(binary_form=False)
464
Georg Brandl7f01a132009-09-16 15:58:14 +0000465 If there is no certificate for the peer on the other end of the connection,
466 returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000467
Georg Brandl7f01a132009-09-16 15:58:14 +0000468 If the parameter ``binary_form`` is :const:`False`, and a certificate was
469 received from the peer, this method returns a :class:`dict` instance. If the
470 certificate was not validated, the dict is empty. If the certificate was
471 validated, it returns a dict with the keys ``subject`` (the principal for
472 which the certificate was issued), and ``notAfter`` (the time after which the
Antoine Pitroufb046912010-11-09 20:21:19 +0000473 certificate should not be trusted). If a certificate contains an instance
474 of the *Subject Alternative Name* extension (see :rfc:`3280`), there will
475 also be a ``subjectAltName`` key in the dictionary.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000476
477 The "subject" field is a tuple containing the sequence of relative
Georg Brandl7f01a132009-09-16 15:58:14 +0000478 distinguished names (RDNs) given in the certificate's data structure for the
479 principal, and each RDN is a sequence of name-value pairs::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000480
481 {'notAfter': 'Feb 16 16:54:50 2013 GMT',
Ezio Melotti985e24d2009-09-13 07:54:02 +0000482 'subject': ((('countryName', 'US'),),
483 (('stateOrProvinceName', 'Delaware'),),
484 (('localityName', 'Wilmington'),),
485 (('organizationName', 'Python Software Foundation'),),
486 (('organizationalUnitName', 'SSL'),),
487 (('commonName', 'somemachine.python.org'),))}
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000488
Georg Brandl7f01a132009-09-16 15:58:14 +0000489 If the ``binary_form`` parameter is :const:`True`, and a certificate was
490 provided, this method returns the DER-encoded form of the entire certificate
491 as a sequence of bytes, or :const:`None` if the peer did not provide a
492 certificate. This return value is independent of validation; if validation
493 was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000494 been validated, but if :const:`CERT_NONE` was used to establish the
495 connection, the certificate, if present, will not have been validated.
496
Antoine Pitroufb046912010-11-09 20:21:19 +0000497 .. versionchanged:: 3.2
498 The returned dictionary includes additional items such as ``issuer``
499 and ``notBefore``.
500
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000501.. method:: SSLSocket.cipher()
502
Georg Brandl7f01a132009-09-16 15:58:14 +0000503 Returns a three-value tuple containing the name of the cipher being used, the
504 version of the SSL protocol that defines its use, and the number of secret
505 bits being used. If no connection has been established, returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000506
Antoine Pitroud6494802011-07-21 01:11:30 +0200507.. method:: SSLSocket.get_channel_binding(cb_type="tls-unique")
508
509 Get channel binding data for current connection, as a bytes object. Returns
510 ``None`` if not connected or the handshake has not been completed.
511
512 The *cb_type* parameter allow selection of the desired channel binding
513 type. Valid channel binding types are listed in the
514 :data:`CHANNEL_BINDING_TYPES` list. Currently only the 'tls-unique' channel
515 binding, defined by :rfc:`5929`, is supported. :exc:`ValueError` will be
516 raised if an unsupported channel binding type is requested.
517
518 .. versionadded:: 3.3
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000519
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000520.. method:: SSLSocket.unwrap()
521
Georg Brandl7f01a132009-09-16 15:58:14 +0000522 Performs the SSL shutdown handshake, which removes the TLS layer from the
523 underlying socket, and returns the underlying socket object. This can be
524 used to go from encrypted operation over a connection to unencrypted. The
525 returned socket should always be used for further communication with the
526 other side of the connection, rather than the original socket.
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000527
Antoine Pitrou152efa22010-05-16 18:19:27 +0000528
Antoine Pitrouec883db2010-05-24 21:20:20 +0000529.. attribute:: SSLSocket.context
530
531 The :class:`SSLContext` object this SSL socket is tied to. If the SSL
532 socket was created using the top-level :func:`wrap_socket` function
533 (rather than :meth:`SSLContext.wrap_socket`), this is a custom context
534 object created for this SSL socket.
535
536 .. versionadded:: 3.2
537
538
Antoine Pitrou152efa22010-05-16 18:19:27 +0000539SSL Contexts
540------------
541
Antoine Pitroucafaad42010-05-24 15:58:43 +0000542.. versionadded:: 3.2
543
Antoine Pitroub0182c82010-10-12 20:09:02 +0000544An SSL context holds various data longer-lived than single SSL connections,
545such as SSL configuration options, certificate(s) and private key(s).
546It also manages a cache of SSL sessions for server-side sockets, in order
547to speed up repeated connections from the same clients.
548
Antoine Pitrou152efa22010-05-16 18:19:27 +0000549.. class:: SSLContext(protocol)
550
Antoine Pitroub0182c82010-10-12 20:09:02 +0000551 Create a new SSL context. You must pass *protocol* which must be one
552 of the ``PROTOCOL_*`` constants defined in this module.
553 :data:`PROTOCOL_SSLv23` is recommended for maximum interoperability.
554
Antoine Pitrou152efa22010-05-16 18:19:27 +0000555
556:class:`SSLContext` objects have the following methods and attributes:
557
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200558.. method:: SSLContext.load_cert_chain(certfile, keyfile=None, password=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000559
560 Load a private key and the corresponding certificate. The *certfile*
561 string must be the path to a single file in PEM format containing the
562 certificate as well as any number of CA certificates needed to establish
563 the certificate's authenticity. The *keyfile* string, if present, must
564 point to a file containing the private key in. Otherwise the private
565 key will be taken from *certfile* as well. See the discussion of
566 :ref:`ssl-certificates` for more information on how the certificate
567 is stored in the *certfile*.
568
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200569 The *password* argument may be a function to call to get the password for
570 decrypting the private key. It will only be called if the private key is
571 encrypted and a password is necessary. It will be called with no arguments,
572 and it should return a string, bytes, or bytearray. If the return value is
573 a string it will be encoded as UTF-8 before using it to decrypt the key.
574 Alternatively a string, bytes, or bytearray value may be supplied directly
575 as the *password* argument. It will be ignored if the private key is not
576 encrypted and no password is needed.
577
578 If the *password* argument is not specified and a password is required,
579 OpenSSL's built-in password prompting mechanism will be used to
580 interactively prompt the user for a password.
581
Antoine Pitrou152efa22010-05-16 18:19:27 +0000582 An :class:`SSLError` is raised if the private key doesn't
583 match with the certificate.
584
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200585 .. versionchanged:: 3.3
586 New optional argument *password*.
587
Antoine Pitrou152efa22010-05-16 18:19:27 +0000588.. method:: SSLContext.load_verify_locations(cafile=None, capath=None)
589
590 Load a set of "certification authority" (CA) certificates used to validate
591 other peers' certificates when :data:`verify_mode` is other than
592 :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified.
593
594 The *cafile* string, if present, is the path to a file of concatenated
595 CA certificates in PEM format. See the discussion of
596 :ref:`ssl-certificates` for more information about how to arrange the
597 certificates in this file.
598
599 The *capath* string, if present, is
600 the path to a directory containing several CA certificates in PEM format,
601 following an `OpenSSL specific layout
602 <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
603
Antoine Pitrou664c2d12010-11-17 20:29:42 +0000604.. method:: SSLContext.set_default_verify_paths()
605
606 Load a set of default "certification authority" (CA) certificates from
607 a filesystem path defined when building the OpenSSL library. Unfortunately,
608 there's no easy way to know whether this method succeeds: no error is
609 returned if no certificates are to be found. When the OpenSSL library is
610 provided as part of the operating system, though, it is likely to be
611 configured properly.
612
Antoine Pitrou152efa22010-05-16 18:19:27 +0000613.. method:: SSLContext.set_ciphers(ciphers)
614
615 Set the available ciphers for sockets created with this context.
616 It should be a string in the `OpenSSL cipher list format
617 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
618 If no cipher can be selected (because compile-time options or other
619 configuration forbids use of all the specified ciphers), an
620 :class:`SSLError` will be raised.
621
622 .. note::
623 when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
624 give the currently selected cipher.
625
Antoine Pitroud5323212010-10-22 18:19:07 +0000626.. method:: SSLContext.wrap_socket(sock, server_side=False, \
627 do_handshake_on_connect=True, suppress_ragged_eofs=True, \
628 server_hostname=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000629
630 Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
631 object. The SSL socket is tied to the context, its settings and
632 certificates. The parameters *server_side*, *do_handshake_on_connect*
633 and *suppress_ragged_eofs* have the same meaning as in the top-level
634 :func:`wrap_socket` function.
635
Antoine Pitroud5323212010-10-22 18:19:07 +0000636 On client connections, the optional parameter *server_hostname* specifies
637 the hostname of the service which we are connecting to. This allows a
638 single server to host multiple SSL-based services with distinct certificates,
639 quite similarly to HTTP virtual hosts. Specifying *server_hostname*
640 will raise a :exc:`ValueError` if the OpenSSL library doesn't have support
641 for it (that is, if :data:`HAS_SNI` is :const:`False`). Specifying
642 *server_hostname* will also raise a :exc:`ValueError` if *server_side*
643 is true.
644
Antoine Pitroub0182c82010-10-12 20:09:02 +0000645.. method:: SSLContext.session_stats()
646
647 Get statistics about the SSL sessions created or managed by this context.
648 A dictionary is returned which maps the names of each `piece of information
649 <http://www.openssl.org/docs/ssl/SSL_CTX_sess_number.html>`_ to their
650 numeric values. For example, here is the total number of hits and misses
651 in the session cache since the context was created::
652
653 >>> stats = context.session_stats()
654 >>> stats['hits'], stats['misses']
655 (0, 0)
656
Antoine Pitroub5218772010-05-21 09:56:06 +0000657.. attribute:: SSLContext.options
658
659 An integer representing the set of SSL options enabled on this context.
660 The default value is :data:`OP_ALL`, but you can specify other options
661 such as :data:`OP_NO_SSLv2` by ORing them together.
662
663 .. note::
664 With versions of OpenSSL older than 0.9.8m, it is only possible
665 to set options, not to clear them. Attempting to clear an option
666 (by resetting the corresponding bits) will raise a ``ValueError``.
667
Antoine Pitrou152efa22010-05-16 18:19:27 +0000668.. attribute:: SSLContext.protocol
669
670 The protocol version chosen when constructing the context. This attribute
671 is read-only.
672
673.. attribute:: SSLContext.verify_mode
674
675 Whether to try to verify other peers' certificates and how to behave
676 if verification fails. This attribute must be one of
677 :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.
678
679
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000680.. index:: single: certificates
681
682.. index:: single: X509 certificate
683
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000684.. _ssl-certificates:
685
Thomas Woutersed03b412007-08-28 21:37:11 +0000686Certificates
687------------
688
Georg Brandl7f01a132009-09-16 15:58:14 +0000689Certificates in general are part of a public-key / private-key system. In this
690system, each *principal*, (which may be a machine, or a person, or an
691organization) is assigned a unique two-part encryption key. One part of the key
692is public, and is called the *public key*; the other part is kept secret, and is
693called the *private key*. The two parts are related, in that if you encrypt a
694message with one of the parts, you can decrypt it with the other part, and
695**only** with the other part.
Thomas Woutersed03b412007-08-28 21:37:11 +0000696
Georg Brandl7f01a132009-09-16 15:58:14 +0000697A certificate contains information about two principals. It contains the name
698of a *subject*, and the subject's public key. It also contains a statement by a
699second principal, the *issuer*, that the subject is who he claims to be, and
700that this is indeed the subject's public key. The issuer's statement is signed
701with the issuer's private key, which only the issuer knows. However, anyone can
702verify the issuer's statement by finding the issuer's public key, decrypting the
703statement with it, and comparing it to the other information in the certificate.
704The certificate also contains information about the time period over which it is
705valid. This is expressed as two fields, called "notBefore" and "notAfter".
Thomas Woutersed03b412007-08-28 21:37:11 +0000706
Georg Brandl7f01a132009-09-16 15:58:14 +0000707In the Python use of certificates, a client or server can use a certificate to
708prove who they are. The other side of a network connection can also be required
709to produce a certificate, and that certificate can be validated to the
710satisfaction of the client or server that requires such validation. The
711connection attempt can be set to raise an exception if the validation fails.
712Validation is done automatically, by the underlying OpenSSL framework; the
713application need not concern itself with its mechanics. But the application
714does usually need to provide sets of certificates to allow this process to take
715place.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000716
Georg Brandl7f01a132009-09-16 15:58:14 +0000717Python uses files to contain certificates. They should be formatted as "PEM"
718(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
719and a footer line::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000720
721 -----BEGIN CERTIFICATE-----
722 ... (certificate in base64 PEM encoding) ...
723 -----END CERTIFICATE-----
724
Antoine Pitrou152efa22010-05-16 18:19:27 +0000725Certificate chains
726^^^^^^^^^^^^^^^^^^
727
Georg Brandl7f01a132009-09-16 15:58:14 +0000728The Python files which contain certificates can contain a sequence of
729certificates, sometimes called a *certificate chain*. This chain should start
730with the specific certificate for the principal who "is" the client or server,
731and then the certificate for the issuer of that certificate, and then the
732certificate for the issuer of *that* certificate, and so on up the chain till
733you get to a certificate which is *self-signed*, that is, a certificate which
734has the same subject and issuer, sometimes called a *root certificate*. The
735certificates should just be concatenated together in the certificate file. For
736example, suppose we had a three certificate chain, from our server certificate
737to the certificate of the certification authority that signed our server
738certificate, to the root certificate of the agency which issued the
739certification authority's certificate::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000740
741 -----BEGIN CERTIFICATE-----
742 ... (certificate for your server)...
743 -----END CERTIFICATE-----
744 -----BEGIN CERTIFICATE-----
745 ... (the certificate for the CA)...
746 -----END CERTIFICATE-----
747 -----BEGIN CERTIFICATE-----
748 ... (the root certificate for the CA's issuer)...
749 -----END CERTIFICATE-----
750
Antoine Pitrou152efa22010-05-16 18:19:27 +0000751CA certificates
752^^^^^^^^^^^^^^^
753
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000754If you are going to require validation of the other side of the connection's
755certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandl7f01a132009-09-16 15:58:14 +0000756chains for each issuer you are willing to trust. Again, this file just contains
757these chains concatenated together. For validation, Python will use the first
758chain it finds in the file which matches. Some "standard" root certificates are
759available from various certification authorities: `CACert.org
760<http://www.cacert.org/index.php?id=3>`_, `Thawte
761<http://www.thawte.com/roots/>`_, `Verisign
762<http://www.verisign.com/support/roots.html>`_, `Positive SSL
763<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
764(used by python.org), `Equifax and GeoTrust
765<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000766
Georg Brandl7f01a132009-09-16 15:58:14 +0000767In general, if you are using SSL3 or TLS1, you don't need to put the full chain
768in your "CA certs" file; you only need the root certificates, and the remote
769peer is supposed to furnish the other certificates necessary to chain from its
770certificate to a root certificate. See :rfc:`4158` for more discussion of the
771way in which certification chains can be built.
Thomas Woutersed03b412007-08-28 21:37:11 +0000772
Antoine Pitrou152efa22010-05-16 18:19:27 +0000773Combined key and certificate
774^^^^^^^^^^^^^^^^^^^^^^^^^^^^
775
776Often the private key is stored in the same file as the certificate; in this
777case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain`
778and :func:`wrap_socket` needs to be passed. If the private key is stored
779with the certificate, it should come before the first certificate in
780the certificate chain::
781
782 -----BEGIN RSA PRIVATE KEY-----
783 ... (private key in base64 encoding) ...
784 -----END RSA PRIVATE KEY-----
785 -----BEGIN CERTIFICATE-----
786 ... (certificate in base64 PEM encoding) ...
787 -----END CERTIFICATE-----
788
789Self-signed certificates
790^^^^^^^^^^^^^^^^^^^^^^^^
791
Georg Brandl7f01a132009-09-16 15:58:14 +0000792If you are going to create a server that provides SSL-encrypted connection
793services, you will need to acquire a certificate for that service. There are
794many ways of acquiring appropriate certificates, such as buying one from a
795certification authority. Another common practice is to generate a self-signed
796certificate. The simplest way to do this is with the OpenSSL package, using
797something like the following::
Thomas Woutersed03b412007-08-28 21:37:11 +0000798
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000799 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
800 Generating a 1024 bit RSA private key
801 .......++++++
802 .............................++++++
803 writing new private key to 'cert.pem'
804 -----
805 You are about to be asked to enter information that will be incorporated
806 into your certificate request.
807 What you are about to enter is what is called a Distinguished Name or a DN.
808 There are quite a few fields but you can leave some blank
809 For some fields there will be a default value,
810 If you enter '.', the field will be left blank.
811 -----
812 Country Name (2 letter code) [AU]:US
813 State or Province Name (full name) [Some-State]:MyState
814 Locality Name (eg, city) []:Some City
815 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
816 Organizational Unit Name (eg, section) []:My Group
817 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
818 Email Address []:ops@myserver.mygroup.myorganization.com
819 %
Thomas Woutersed03b412007-08-28 21:37:11 +0000820
Georg Brandl7f01a132009-09-16 15:58:14 +0000821The disadvantage of a self-signed certificate is that it is its own root
822certificate, and no one else will have it in their cache of known (and trusted)
823root certificates.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000824
825
Thomas Woutersed03b412007-08-28 21:37:11 +0000826Examples
827--------
828
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000829Testing for SSL support
830^^^^^^^^^^^^^^^^^^^^^^^
831
Georg Brandl7f01a132009-09-16 15:58:14 +0000832To test for the presence of SSL support in a Python installation, user code
833should use the following idiom::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000834
835 try:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000836 import ssl
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000837 except ImportError:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000838 pass
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000839 else:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000840 ... # do something that requires SSL support
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000841
842Client-side operation
843^^^^^^^^^^^^^^^^^^^^^
844
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000845This example connects to an SSL server and prints the server's certificate::
Thomas Woutersed03b412007-08-28 21:37:11 +0000846
847 import socket, ssl, pprint
848
849 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000850 # require a certificate from the server
851 ssl_sock = ssl.wrap_socket(s,
852 ca_certs="/etc/ca_certs_file",
853 cert_reqs=ssl.CERT_REQUIRED)
Thomas Woutersed03b412007-08-28 21:37:11 +0000854 ssl_sock.connect(('www.verisign.com', 443))
855
Georg Brandl6911e3c2007-09-04 07:15:32 +0000856 pprint.pprint(ssl_sock.getpeercert())
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000857 # note that closing the SSLSocket will also close the underlying socket
Thomas Woutersed03b412007-08-28 21:37:11 +0000858 ssl_sock.close()
859
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000860As of October 6, 2010, the certificate printed by this program looks like
Georg Brandl7f01a132009-09-16 15:58:14 +0000861this::
Thomas Woutersed03b412007-08-28 21:37:11 +0000862
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000863 {'notAfter': 'May 25 23:59:59 2012 GMT',
864 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
865 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
866 (('businessCategory', 'V1.0, Clause 5.(b)'),),
867 (('serialNumber', '2497886'),),
868 (('countryName', 'US'),),
869 (('postalCode', '94043'),),
870 (('stateOrProvinceName', 'California'),),
871 (('localityName', 'Mountain View'),),
872 (('streetAddress', '487 East Middlefield Road'),),
873 (('organizationName', 'VeriSign, Inc.'),),
874 (('organizationalUnitName', ' Production Security Services'),),
875 (('commonName', 'www.verisign.com'),))}
Thomas Woutersed03b412007-08-28 21:37:11 +0000876
Antoine Pitrou152efa22010-05-16 18:19:27 +0000877This other example first creates an SSL context, instructs it to verify
878certificates sent by peers, and feeds it a set of recognized certificate
879authorities (CA)::
880
881 >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000882 >>> context.verify_mode = ssl.CERT_REQUIRED
Antoine Pitrou152efa22010-05-16 18:19:27 +0000883 >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
884
885(it is assumed your operating system places a bundle of all CA certificates
886in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have
887to adjust the location)
888
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000889When you use the context to connect to a server, :const:`CERT_REQUIRED`
Antoine Pitrou152efa22010-05-16 18:19:27 +0000890validates the server certificate: it ensures that the server certificate
891was signed with one of the CA certificates, and checks the signature for
892correctness::
893
894 >>> conn = context.wrap_socket(socket.socket(socket.AF_INET))
895 >>> conn.connect(("linuxfr.org", 443))
896
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000897You should then fetch the certificate and check its fields for conformity::
Antoine Pitrou152efa22010-05-16 18:19:27 +0000898
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000899 >>> cert = conn.getpeercert()
900 >>> ssl.match_hostname(cert, "linuxfr.org")
901
902Visual inspection shows that the certificate does identify the desired service
903(that is, the HTTPS host ``linuxfr.org``)::
904
905 >>> pprint.pprint(cert)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000906 {'notAfter': 'Jun 26 21:41:46 2011 GMT',
907 'subject': ((('commonName', 'linuxfr.org'),),),
908 'subjectAltName': (('DNS', 'linuxfr.org'), ('othername', '<unsupported>'))}
909
910Now that you are assured of its authenticity, you can proceed to talk with
911the server::
912
Antoine Pitroudab64262010-09-19 13:31:06 +0000913 >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
914 >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
Antoine Pitrou152efa22010-05-16 18:19:27 +0000915 [b'HTTP/1.1 302 Found',
916 b'Date: Sun, 16 May 2010 13:43:28 GMT',
917 b'Server: Apache/2.2',
918 b'Location: https://linuxfr.org/pub/',
919 b'Vary: Accept-Encoding',
920 b'Connection: close',
921 b'Content-Type: text/html; charset=iso-8859-1',
922 b'',
923 b'']
924
Antoine Pitrou152efa22010-05-16 18:19:27 +0000925See the discussion of :ref:`ssl-security` below.
926
927
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000928Server-side operation
929^^^^^^^^^^^^^^^^^^^^^
930
Antoine Pitrou152efa22010-05-16 18:19:27 +0000931For server operation, typically you'll need to have a server certificate, and
932private key, each in a file. You'll first create a context holding the key
933and the certificate, so that clients can check your authenticity. Then
934you'll open a socket, bind it to a port, call :meth:`listen` on it, and start
935waiting for clients to connect::
Thomas Woutersed03b412007-08-28 21:37:11 +0000936
937 import socket, ssl
938
Antoine Pitrou152efa22010-05-16 18:19:27 +0000939 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
940 context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")
941
Thomas Woutersed03b412007-08-28 21:37:11 +0000942 bindsocket = socket.socket()
943 bindsocket.bind(('myaddr.mydomain.com', 10023))
944 bindsocket.listen(5)
945
Antoine Pitrou152efa22010-05-16 18:19:27 +0000946When a client connects, you'll call :meth:`accept` on the socket to get the
947new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket`
948method to create a server-side SSL socket for the connection::
Thomas Woutersed03b412007-08-28 21:37:11 +0000949
950 while True:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000951 newsocket, fromaddr = bindsocket.accept()
952 connstream = context.wrap_socket(newsocket, server_side=True)
953 try:
954 deal_with_client(connstream)
955 finally:
Antoine Pitroub205d582011-01-02 22:09:27 +0000956 connstream.shutdown(socket.SHUT_RDWR)
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000957 connstream.close()
Thomas Woutersed03b412007-08-28 21:37:11 +0000958
Antoine Pitrou152efa22010-05-16 18:19:27 +0000959Then you'll read data from the ``connstream`` and do something with it till you
Georg Brandl7f01a132009-09-16 15:58:14 +0000960are finished with the client (or the client is finished with you)::
Thomas Woutersed03b412007-08-28 21:37:11 +0000961
962 def deal_with_client(connstream):
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000963 data = connstream.recv(1024)
964 # empty data means the client is finished with us
965 while data:
966 if not do_something(connstream, data):
967 # we'll assume do_something returns False
968 # when we're finished with client
969 break
970 data = connstream.recv(1024)
971 # finished with client
Thomas Woutersed03b412007-08-28 21:37:11 +0000972
Antoine Pitrou152efa22010-05-16 18:19:27 +0000973And go back to listening for new client connections (of course, a real server
974would probably handle each client connection in a separate thread, or put
975the sockets in non-blocking mode and use an event loop).
976
977
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +0200978.. _ssl-nonblocking:
979
980Notes on non-blocking sockets
981-----------------------------
982
983When working with non-blocking sockets, there are several things you need
984to be aware of:
985
986- Calling :func:`~select.select` tells you that the OS-level socket can be
987 read from (or written to), but it does not imply that there is sufficient
988 data at the upper SSL layer. For example, only part of an SSL frame might
989 have arrived. Therefore, you must be ready to handle :meth:`SSLSocket.recv`
990 and :meth:`SSLSocket.send` failures, and retry after another call to
991 :func:`~select.select`.
992
993 (of course, similar provisions apply when using other primitives such as
994 :func:`~select.poll`)
995
996- The SSL handshake itself will be non-blocking: the
997 :meth:`SSLSocket.do_handshake` method has to be retried until it returns
998 successfully. Here is a synopsis using :func:`~select.select` to wait for
999 the socket's readiness::
1000
1001 while True:
1002 try:
1003 sock.do_handshake()
1004 break
1005 except ssl.SSLError as err:
1006 if err.args[0] == ssl.SSL_ERROR_WANT_READ:
1007 select.select([sock], [], [])
1008 elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
1009 select.select([], [sock], [])
1010 else:
1011 raise
1012
1013
Antoine Pitrou152efa22010-05-16 18:19:27 +00001014.. _ssl-security:
1015
1016Security considerations
1017-----------------------
1018
1019Verifying certificates
1020^^^^^^^^^^^^^^^^^^^^^^
1021
1022:const:`CERT_NONE` is the default. Since it does not authenticate the other
1023peer, it can be insecure, especially in client mode where most of time you
1024would like to ensure the authenticity of the server you're talking to.
1025Therefore, when in client mode, it is highly recommended to use
1026:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001027have to check that the server certificate, which can be obtained by calling
1028:meth:`SSLSocket.getpeercert`, matches the desired service. For many
1029protocols and applications, the service can be identified by the hostname;
1030in this case, the :func:`match_hostname` function can be used.
Antoine Pitrou152efa22010-05-16 18:19:27 +00001031
1032In server mode, if you want to authenticate your clients using the SSL layer
1033(rather than using a higher-level authentication mechanism), you'll also have
1034to specify :const:`CERT_REQUIRED` and similarly check the client certificate.
1035
1036 .. note::
1037
1038 In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are
1039 equivalent unless anonymous ciphers are enabled (they are disabled
1040 by default).
Thomas Woutersed03b412007-08-28 21:37:11 +00001041
Antoine Pitroub5218772010-05-21 09:56:06 +00001042Protocol versions
1043^^^^^^^^^^^^^^^^^
1044
1045SSL version 2 is considered insecure and is therefore dangerous to use. If
1046you want maximum compatibility between clients and servers, it is recommended
1047to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable
1048SSLv2 explicitly using the :data:`SSLContext.options` attribute::
1049
1050 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1051 context.options |= ssl.OP_NO_SSLv2
1052
1053The SSL context created above will allow SSLv3 and TLSv1 connections, but
1054not SSLv2.
1055
Georg Brandl48310cd2009-01-03 21:18:54 +00001056
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001057.. seealso::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001058
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001059 Class :class:`socket.socket`
1060 Documentation of underlying :mod:`socket` class
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001061
Antoine Pitrouf394e472011-10-07 16:58:07 +02001062 `TLS (Transport Layer Security) and SSL (Secure Socket Layer) <http://www3.rad.com/networks/applications/secure/tls.htm>`_
1063 Debby Koren
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001064
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001065 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
1066 Steve Kent
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001067
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001068 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
1069 D. Eastlake et. al.
Thomas Wouters89d996e2007-09-08 17:39:28 +00001070
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001071 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
1072 Housley et. al.
Antoine Pitroud5323212010-10-22 18:19:07 +00001073
1074 `RFC 4366: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc4366>`_
1075 Blake-Wilson et. al.