blob: ca71d20405b3313a9cdcd3f93e1aa0f9812bd7b4 [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
Georg Brandl7f01a132009-09-16 15:58:14 +000056 is a subtype of :exc:`socket.error`, which in turn is a subtype of
Antoine Pitrou59fdd672010-10-08 10:37:08 +000057 :exc:`IOError`. The error code and message of :exc:`SSLError` instances
58 are provided by the OpenSSL library.
59
60.. exception:: CertificateError
61
62 Raised to signal an error with a certificate (such as mismatching
63 hostname). Certificate errors detected by OpenSSL, though, raise
64 an :exc:`SSLError`.
65
66
67Socket creation
68^^^^^^^^^^^^^^^
69
70The following function allows for standalone socket creation. Starting from
71Python 3.2, it can be more flexible to use :meth:`SSLContext.wrap_socket`
72instead.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000073
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +000074.. 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 +000075
Georg Brandl7f01a132009-09-16 15:58:14 +000076 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
77 of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
78 the underlying socket in an SSL context. For client-side sockets, the
79 context construction is lazy; if the underlying socket isn't connected yet,
80 the context construction will be performed after :meth:`connect` is called on
81 the socket. For server-side sockets, if the socket has no remote peer, it is
82 assumed to be a listening socket, and the server-side SSL wrapping is
83 automatically performed on client connections accepted via the :meth:`accept`
84 method. :func:`wrap_socket` may raise :exc:`SSLError`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000085
Georg Brandl7f01a132009-09-16 15:58:14 +000086 The ``keyfile`` and ``certfile`` parameters specify optional files which
87 contain a certificate to be used to identify the local side of the
88 connection. See the discussion of :ref:`ssl-certificates` for more
89 information on how the certificate is stored in the ``certfile``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000090
Georg Brandl7f01a132009-09-16 15:58:14 +000091 The parameter ``server_side`` is a boolean which identifies whether
92 server-side or client-side behavior is desired from this socket.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000093
Georg Brandl7f01a132009-09-16 15:58:14 +000094 The parameter ``cert_reqs`` specifies whether a certificate is required from
95 the other side of the connection, and whether it will be validated if
96 provided. It must be one of the three values :const:`CERT_NONE`
97 (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
98 if provided), or :const:`CERT_REQUIRED` (required and validated). If the
99 value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
100 parameter must point to a file of CA certificates.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000101
Georg Brandl7f01a132009-09-16 15:58:14 +0000102 The ``ca_certs`` file contains a set of concatenated "certification
103 authority" certificates, which are used to validate certificates passed from
104 the other end of the connection. See the discussion of
105 :ref:`ssl-certificates` for more information about how to arrange the
106 certificates in this file.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000107
Georg Brandl7f01a132009-09-16 15:58:14 +0000108 The parameter ``ssl_version`` specifies which version of the SSL protocol to
109 use. Typically, the server chooses a particular protocol version, and the
110 client must adapt to the server's choice. Most of the versions are not
111 interoperable with the other versions. If not specified, for client-side
112 operation, the default SSL version is SSLv3; for server-side operation,
113 SSLv23. These version selections provide the most compatibility with other
114 versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000115
Georg Brandl7f01a132009-09-16 15:58:14 +0000116 Here's a table showing which versions in a client (down the side) can connect
117 to which versions in a server (along the top):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000118
119 .. table::
120
121 ======================== ========= ========= ========== =========
122 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1**
Christian Heimes255f53b2007-12-08 15:33:56 +0000123 ------------------------ --------- --------- ---------- ---------
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000124 *SSLv2* yes no yes no
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000125 *SSLv3* yes yes yes no
126 *SSLv23* yes no yes no
127 *TLSv1* no no yes yes
128 ======================== ========= ========= ========== =========
129
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000130 .. note::
131
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000132 Which connections succeed will vary depending on the version of
133 OpenSSL. For instance, in some older versions of OpenSSL (such
134 as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an
135 SSLv23 server. Another example: beginning with OpenSSL 1.0.0,
136 an SSLv23 client will not actually attempt SSLv2 connections
137 unless you explicitly enable SSLv2 ciphers; for example, you
138 might specify ``"ALL"`` or ``"SSLv2"`` as the *ciphers* parameter
139 to enable them.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000140
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000141 The *ciphers* parameter sets the available ciphers for this SSL object.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000142 It should be a string in the `OpenSSL cipher list format
143 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000144
Bill Janssen48dc27c2007-12-05 03:38:10 +0000145 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
146 handshake automatically after doing a :meth:`socket.connect`, or whether the
Georg Brandl7f01a132009-09-16 15:58:14 +0000147 application program will call it explicitly, by invoking the
148 :meth:`SSLSocket.do_handshake` method. Calling
149 :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
150 blocking behavior of the socket I/O involved in the handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000151
Georg Brandl7f01a132009-09-16 15:58:14 +0000152 The parameter ``suppress_ragged_eofs`` specifies how the
Antoine Pitroudab64262010-09-19 13:31:06 +0000153 :meth:`SSLSocket.recv` method should signal unexpected EOF from the other end
Georg Brandl7f01a132009-09-16 15:58:14 +0000154 of the connection. If specified as :const:`True` (the default), it returns a
Antoine Pitroudab64262010-09-19 13:31:06 +0000155 normal EOF (an empty bytes object) in response to unexpected EOF errors
156 raised from the underlying socket; if :const:`False`, it will raise the
157 exceptions back to the caller.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000158
Ezio Melotti4d5195b2010-04-20 10:57:44 +0000159 .. versionchanged:: 3.2
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000160 New optional argument *ciphers*.
161
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000162Random generation
163^^^^^^^^^^^^^^^^^
164
Victor Stinner99c8b162011-05-24 12:05:19 +0200165.. function:: RAND_bytes(num)
166
Victor Stinnera6752062011-05-25 11:27:40 +0200167 Returns *num* cryptographically strong pseudo-random bytes. Raises an
168 :class:`SSLError` if the PRNG has not been seeded with enough data or if the
169 operation is not supported by the current RAND method. :func:`RAND_status`
170 can be used to check the status of the PRNG and :func:`RAND_add` can be used
171 to seed the PRNG.
Victor Stinner99c8b162011-05-24 12:05:19 +0200172
Victor Stinner19fb53c2011-05-24 21:32:40 +0200173 Read the Wikipedia article, `Cryptographically secure pseudorandom number
Victor Stinnera6752062011-05-25 11:27:40 +0200174 generator (CSPRNG)
Victor Stinner19fb53c2011-05-24 21:32:40 +0200175 <http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator>`_,
176 to get the requirements of a cryptographically generator.
177
Victor Stinner99c8b162011-05-24 12:05:19 +0200178 .. versionadded:: 3.3
179
180.. function:: RAND_pseudo_bytes(num)
181
182 Returns (bytes, is_cryptographic): bytes are *num* pseudo-random bytes,
183 is_cryptographic is True if the bytes generated are cryptographically
Victor Stinnera6752062011-05-25 11:27:40 +0200184 strong. Raises an :class:`SSLError` if the operation is not supported by the
185 current RAND method.
Victor Stinner99c8b162011-05-24 12:05:19 +0200186
Victor Stinner19fb53c2011-05-24 21:32:40 +0200187 Generated pseudo-random byte sequences will be unique if they are of
188 sufficient length, but are not necessarily unpredictable. They can be used
189 for non-cryptographic purposes and for certain purposes in cryptographic
190 protocols, but usually not for key generation etc.
191
Victor Stinner99c8b162011-05-24 12:05:19 +0200192 .. versionadded:: 3.3
193
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000194.. function:: RAND_status()
195
Georg Brandl7f01a132009-09-16 15:58:14 +0000196 Returns True if the SSL pseudo-random number generator has been seeded with
197 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
198 and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
199 number generator.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000200
201.. function:: RAND_egd(path)
202
Victor Stinner99c8b162011-05-24 12:05:19 +0200203 If you are running an entropy-gathering daemon (EGD) somewhere, and *path*
Georg Brandl7f01a132009-09-16 15:58:14 +0000204 is the pathname of a socket connection open to it, this will read 256 bytes
205 of randomness from the socket, and add it to the SSL pseudo-random number
206 generator to increase the security of generated secret keys. This is
207 typically only necessary on systems without better sources of randomness.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000208
Georg Brandl7f01a132009-09-16 15:58:14 +0000209 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
210 of entropy-gathering daemons.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000211
212.. function:: RAND_add(bytes, entropy)
213
Victor Stinner99c8b162011-05-24 12:05:19 +0200214 Mixes the given *bytes* into the SSL pseudo-random number generator. The
215 parameter *entropy* (a float) is a lower bound on the entropy contained in
Georg Brandl7f01a132009-09-16 15:58:14 +0000216 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
217 information on sources of entropy.
Thomas Woutersed03b412007-08-28 21:37:11 +0000218
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000219Certificate handling
220^^^^^^^^^^^^^^^^^^^^
221
222.. function:: match_hostname(cert, hostname)
223
224 Verify that *cert* (in decoded format as returned by
225 :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules
226 applied are those for checking the identity of HTTPS servers as outlined
227 in :rfc:`2818`, except that IP addresses are not currently supported.
228 In addition to HTTPS, this function should be suitable for checking the
229 identity of servers in various SSL-based protocols such as FTPS, IMAPS,
230 POPS and others.
231
232 :exc:`CertificateError` is raised on failure. On success, the function
233 returns nothing::
234
235 >>> cert = {'subject': ((('commonName', 'example.com'),),)}
236 >>> ssl.match_hostname(cert, "example.com")
237 >>> ssl.match_hostname(cert, "example.org")
238 Traceback (most recent call last):
239 File "<stdin>", line 1, in <module>
240 File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
241 ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'
242
243 .. versionadded:: 3.2
244
Thomas Woutersed03b412007-08-28 21:37:11 +0000245.. function:: cert_time_to_seconds(timestring)
246
Georg Brandl7f01a132009-09-16 15:58:14 +0000247 Returns a floating-point value containing a normal seconds-after-the-epoch
248 time value, given the time-string representing the "notBefore" or "notAfter"
249 date from a certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000250
251 Here's an example::
252
253 >>> import ssl
254 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
255 1178694000.0
256 >>> import time
257 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
258 'Wed May 9 00:00:00 2007'
Thomas Woutersed03b412007-08-28 21:37:11 +0000259
Georg Brandl7f01a132009-09-16 15:58:14 +0000260.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000261
Georg Brandl7f01a132009-09-16 15:58:14 +0000262 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
263 *port-number*) pair, fetches the server's certificate, and returns it as a
264 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
265 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
266 specified, it should be a file containing a list of root certificates, the
267 same format as used for the same parameter in :func:`wrap_socket`. The call
268 will attempt to validate the server certificate against that set of root
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000269 certificates, and will fail if the validation attempt fails.
270
Antoine Pitrou15399c32011-04-28 19:23:55 +0200271 .. versionchanged:: 3.3
272 This function is now IPv6-compatible.
273
Georg Brandl7f01a132009-09-16 15:58:14 +0000274.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000275
276 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
277 string version of the same certificate.
278
Georg Brandl7f01a132009-09-16 15:58:14 +0000279.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000280
Georg Brandl7f01a132009-09-16 15:58:14 +0000281 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
282 bytes for that same certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000283
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000284Constants
285^^^^^^^^^
286
Thomas Woutersed03b412007-08-28 21:37:11 +0000287.. data:: CERT_NONE
288
Antoine Pitrou152efa22010-05-16 18:19:27 +0000289 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
290 parameter to :func:`wrap_socket`. In this mode (the default), no
291 certificates will be required from the other side of the socket connection.
292 If a certificate is received from the other end, no attempt to validate it
293 is made.
294
295 See the discussion of :ref:`ssl-security` below.
Thomas Woutersed03b412007-08-28 21:37:11 +0000296
297.. data:: CERT_OPTIONAL
298
Antoine Pitrou152efa22010-05-16 18:19:27 +0000299 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
300 parameter to :func:`wrap_socket`. In this mode no certificates will be
301 required from the other side of the socket connection; but if they
302 are provided, validation will be attempted and an :class:`SSLError`
303 will be raised on failure.
304
305 Use of this setting requires a valid set of CA certificates to
306 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
307 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000308
309.. data:: CERT_REQUIRED
310
Antoine Pitrou152efa22010-05-16 18:19:27 +0000311 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
312 parameter to :func:`wrap_socket`. In this mode, certificates are
313 required from the other side of the socket connection; an :class:`SSLError`
314 will be raised if no certificate is provided, or if its validation fails.
315
316 Use of this setting requires a valid set of CA certificates to
317 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
318 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000319
320.. data:: PROTOCOL_SSLv2
321
322 Selects SSL version 2 as the channel encryption protocol.
323
Victor Stinner3de49192011-05-09 00:42:58 +0200324 This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
325 flag.
326
Antoine Pitrou8eac60d2010-05-16 14:19:41 +0000327 .. warning::
328
329 SSL version 2 is insecure. Its use is highly discouraged.
330
Thomas Woutersed03b412007-08-28 21:37:11 +0000331.. data:: PROTOCOL_SSLv23
332
Georg Brandl7f01a132009-09-16 15:58:14 +0000333 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
334 setting to use with servers for maximum compatibility with the other end of
335 an SSL connection, but it may cause the specific ciphers chosen for the
336 encryption to be of fairly low quality.
Thomas Woutersed03b412007-08-28 21:37:11 +0000337
338.. data:: PROTOCOL_SSLv3
339
Georg Brandl7f01a132009-09-16 15:58:14 +0000340 Selects SSL version 3 as the channel encryption protocol. For clients, this
341 is the maximally compatible SSL variant.
Thomas Woutersed03b412007-08-28 21:37:11 +0000342
343.. data:: PROTOCOL_TLSv1
344
Georg Brandl7f01a132009-09-16 15:58:14 +0000345 Selects TLS version 1 as the channel encryption protocol. This is the most
346 modern version, and probably the best choice for maximum protection, if both
347 sides can speak it.
Thomas Woutersed03b412007-08-28 21:37:11 +0000348
Antoine Pitroub5218772010-05-21 09:56:06 +0000349.. data:: OP_ALL
350
351 Enables workarounds for various bugs present in other SSL implementations.
352 This option is set by default.
353
354 .. versionadded:: 3.2
355
356.. data:: OP_NO_SSLv2
357
358 Prevents an SSLv2 connection. This option is only applicable in
359 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
360 choosing SSLv2 as the protocol version.
361
362 .. versionadded:: 3.2
363
364.. data:: OP_NO_SSLv3
365
366 Prevents an SSLv3 connection. This option is only applicable in
367 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
368 choosing SSLv3 as the protocol version.
369
370 .. versionadded:: 3.2
371
372.. data:: OP_NO_TLSv1
373
374 Prevents a TLSv1 connection. This option is only applicable in
375 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
376 choosing TLSv1 as the protocol version.
377
378 .. versionadded:: 3.2
379
Antoine Pitroud5323212010-10-22 18:19:07 +0000380.. data:: HAS_SNI
381
382 Whether the OpenSSL library has built-in support for the *Server Name
383 Indication* extension to the SSLv3 and TLSv1 protocols (as defined in
384 :rfc:`4366`). When true, you can use the *server_hostname* argument to
385 :meth:`SSLContext.wrap_socket`.
386
387 .. versionadded:: 3.2
388
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000389.. data:: OPENSSL_VERSION
390
391 The version string of the OpenSSL library loaded by the interpreter::
392
393 >>> ssl.OPENSSL_VERSION
394 'OpenSSL 0.9.8k 25 Mar 2009'
395
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000396 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000397
398.. data:: OPENSSL_VERSION_INFO
399
400 A tuple of five integers representing version information about the
401 OpenSSL library::
402
403 >>> ssl.OPENSSL_VERSION_INFO
404 (0, 9, 8, 11, 15)
405
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000406 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000407
408.. data:: OPENSSL_VERSION_NUMBER
409
410 The raw version number of the OpenSSL library, as a single integer::
411
412 >>> ssl.OPENSSL_VERSION_NUMBER
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000413 9470143
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000414 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000415 '0x9080bf'
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000416
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000417 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000418
Thomas Woutersed03b412007-08-28 21:37:11 +0000419
Antoine Pitrou152efa22010-05-16 18:19:27 +0000420SSL Sockets
421-----------
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000422
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000423SSL sockets provide the following methods of :ref:`socket-objects`:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000424
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000425- :meth:`~socket.socket.accept()`
426- :meth:`~socket.socket.bind()`
427- :meth:`~socket.socket.close()`
428- :meth:`~socket.socket.connect()`
429- :meth:`~socket.socket.detach()`
430- :meth:`~socket.socket.fileno()`
431- :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`
432- :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`
433- :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`,
434 :meth:`~socket.socket.setblocking()`
435- :meth:`~socket.socket.listen()`
436- :meth:`~socket.socket.makefile()`
437- :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()`
438 (but passing a non-zero ``flags`` argument is not allowed)
439- :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with
440 the same limitation)
441- :meth:`~socket.socket.shutdown()`
442
443They also have the following additional methods and attributes:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000444
Bill Janssen48dc27c2007-12-05 03:38:10 +0000445.. method:: SSLSocket.do_handshake()
446
Georg Brandl7f01a132009-09-16 15:58:14 +0000447 Performs the SSL setup handshake. If the socket is non-blocking, this method
448 may raise :exc:`SSLError` with the value of the exception instance's
449 ``args[0]`` being either :const:`SSL_ERROR_WANT_READ` or
450 :const:`SSL_ERROR_WANT_WRITE`, and should be called again until it stops
451 raising those exceptions. Here's an example of how to do that::
Bill Janssen48dc27c2007-12-05 03:38:10 +0000452
453 while True:
454 try:
455 sock.do_handshake()
456 break
457 except ssl.SSLError as err:
458 if err.args[0] == ssl.SSL_ERROR_WANT_READ:
459 select.select([sock], [], [])
460 elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
461 select.select([], [sock], [])
462 else:
463 raise
464
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000465.. method:: SSLSocket.getpeercert(binary_form=False)
466
Georg Brandl7f01a132009-09-16 15:58:14 +0000467 If there is no certificate for the peer on the other end of the connection,
468 returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000469
Georg Brandl7f01a132009-09-16 15:58:14 +0000470 If the parameter ``binary_form`` is :const:`False`, and a certificate was
471 received from the peer, this method returns a :class:`dict` instance. If the
472 certificate was not validated, the dict is empty. If the certificate was
473 validated, it returns a dict with the keys ``subject`` (the principal for
474 which the certificate was issued), and ``notAfter`` (the time after which the
Antoine Pitroufb046912010-11-09 20:21:19 +0000475 certificate should not be trusted). If a certificate contains an instance
476 of the *Subject Alternative Name* extension (see :rfc:`3280`), there will
477 also be a ``subjectAltName`` key in the dictionary.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000478
479 The "subject" field is a tuple containing the sequence of relative
Georg Brandl7f01a132009-09-16 15:58:14 +0000480 distinguished names (RDNs) given in the certificate's data structure for the
481 principal, and each RDN is a sequence of name-value pairs::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000482
483 {'notAfter': 'Feb 16 16:54:50 2013 GMT',
Ezio Melotti985e24d2009-09-13 07:54:02 +0000484 'subject': ((('countryName', 'US'),),
485 (('stateOrProvinceName', 'Delaware'),),
486 (('localityName', 'Wilmington'),),
487 (('organizationName', 'Python Software Foundation'),),
488 (('organizationalUnitName', 'SSL'),),
489 (('commonName', 'somemachine.python.org'),))}
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000490
Georg Brandl7f01a132009-09-16 15:58:14 +0000491 If the ``binary_form`` parameter is :const:`True`, and a certificate was
492 provided, this method returns the DER-encoded form of the entire certificate
493 as a sequence of bytes, or :const:`None` if the peer did not provide a
494 certificate. This return value is independent of validation; if validation
495 was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000496 been validated, but if :const:`CERT_NONE` was used to establish the
497 connection, the certificate, if present, will not have been validated.
498
Antoine Pitroufb046912010-11-09 20:21:19 +0000499 .. versionchanged:: 3.2
500 The returned dictionary includes additional items such as ``issuer``
501 and ``notBefore``.
502
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000503.. method:: SSLSocket.cipher()
504
Georg Brandl7f01a132009-09-16 15:58:14 +0000505 Returns a three-value tuple containing the name of the cipher being used, the
506 version of the SSL protocol that defines its use, and the number of secret
507 bits being used. If no connection has been established, returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000508
509
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000510.. method:: SSLSocket.unwrap()
511
Georg Brandl7f01a132009-09-16 15:58:14 +0000512 Performs the SSL shutdown handshake, which removes the TLS layer from the
513 underlying socket, and returns the underlying socket object. This can be
514 used to go from encrypted operation over a connection to unencrypted. The
515 returned socket should always be used for further communication with the
516 other side of the connection, rather than the original socket.
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000517
Antoine Pitrou152efa22010-05-16 18:19:27 +0000518
Antoine Pitrouec883db2010-05-24 21:20:20 +0000519.. attribute:: SSLSocket.context
520
521 The :class:`SSLContext` object this SSL socket is tied to. If the SSL
522 socket was created using the top-level :func:`wrap_socket` function
523 (rather than :meth:`SSLContext.wrap_socket`), this is a custom context
524 object created for this SSL socket.
525
526 .. versionadded:: 3.2
527
528
Antoine Pitrou152efa22010-05-16 18:19:27 +0000529SSL Contexts
530------------
531
Antoine Pitroucafaad42010-05-24 15:58:43 +0000532.. versionadded:: 3.2
533
Antoine Pitroub0182c82010-10-12 20:09:02 +0000534An SSL context holds various data longer-lived than single SSL connections,
535such as SSL configuration options, certificate(s) and private key(s).
536It also manages a cache of SSL sessions for server-side sockets, in order
537to speed up repeated connections from the same clients.
538
Antoine Pitrou152efa22010-05-16 18:19:27 +0000539.. class:: SSLContext(protocol)
540
Antoine Pitroub0182c82010-10-12 20:09:02 +0000541 Create a new SSL context. You must pass *protocol* which must be one
542 of the ``PROTOCOL_*`` constants defined in this module.
543 :data:`PROTOCOL_SSLv23` is recommended for maximum interoperability.
544
Antoine Pitrou152efa22010-05-16 18:19:27 +0000545
546:class:`SSLContext` objects have the following methods and attributes:
547
548.. method:: SSLContext.load_cert_chain(certfile, keyfile=None)
549
550 Load a private key and the corresponding certificate. The *certfile*
551 string must be the path to a single file in PEM format containing the
552 certificate as well as any number of CA certificates needed to establish
553 the certificate's authenticity. The *keyfile* string, if present, must
554 point to a file containing the private key in. Otherwise the private
555 key will be taken from *certfile* as well. See the discussion of
556 :ref:`ssl-certificates` for more information on how the certificate
557 is stored in the *certfile*.
558
559 An :class:`SSLError` is raised if the private key doesn't
560 match with the certificate.
561
562.. method:: SSLContext.load_verify_locations(cafile=None, capath=None)
563
564 Load a set of "certification authority" (CA) certificates used to validate
565 other peers' certificates when :data:`verify_mode` is other than
566 :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified.
567
568 The *cafile* string, if present, is the path to a file of concatenated
569 CA certificates in PEM format. See the discussion of
570 :ref:`ssl-certificates` for more information about how to arrange the
571 certificates in this file.
572
573 The *capath* string, if present, is
574 the path to a directory containing several CA certificates in PEM format,
575 following an `OpenSSL specific layout
576 <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
577
Antoine Pitrou664c2d12010-11-17 20:29:42 +0000578.. method:: SSLContext.set_default_verify_paths()
579
580 Load a set of default "certification authority" (CA) certificates from
581 a filesystem path defined when building the OpenSSL library. Unfortunately,
582 there's no easy way to know whether this method succeeds: no error is
583 returned if no certificates are to be found. When the OpenSSL library is
584 provided as part of the operating system, though, it is likely to be
585 configured properly.
586
Antoine Pitrou152efa22010-05-16 18:19:27 +0000587.. method:: SSLContext.set_ciphers(ciphers)
588
589 Set the available ciphers for sockets created with this context.
590 It should be a string in the `OpenSSL cipher list format
591 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
592 If no cipher can be selected (because compile-time options or other
593 configuration forbids use of all the specified ciphers), an
594 :class:`SSLError` will be raised.
595
596 .. note::
597 when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
598 give the currently selected cipher.
599
Antoine Pitroud5323212010-10-22 18:19:07 +0000600.. method:: SSLContext.wrap_socket(sock, server_side=False, \
601 do_handshake_on_connect=True, suppress_ragged_eofs=True, \
602 server_hostname=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000603
604 Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
605 object. The SSL socket is tied to the context, its settings and
606 certificates. The parameters *server_side*, *do_handshake_on_connect*
607 and *suppress_ragged_eofs* have the same meaning as in the top-level
608 :func:`wrap_socket` function.
609
Antoine Pitroud5323212010-10-22 18:19:07 +0000610 On client connections, the optional parameter *server_hostname* specifies
611 the hostname of the service which we are connecting to. This allows a
612 single server to host multiple SSL-based services with distinct certificates,
613 quite similarly to HTTP virtual hosts. Specifying *server_hostname*
614 will raise a :exc:`ValueError` if the OpenSSL library doesn't have support
615 for it (that is, if :data:`HAS_SNI` is :const:`False`). Specifying
616 *server_hostname* will also raise a :exc:`ValueError` if *server_side*
617 is true.
618
Antoine Pitroub0182c82010-10-12 20:09:02 +0000619.. method:: SSLContext.session_stats()
620
621 Get statistics about the SSL sessions created or managed by this context.
622 A dictionary is returned which maps the names of each `piece of information
623 <http://www.openssl.org/docs/ssl/SSL_CTX_sess_number.html>`_ to their
624 numeric values. For example, here is the total number of hits and misses
625 in the session cache since the context was created::
626
627 >>> stats = context.session_stats()
628 >>> stats['hits'], stats['misses']
629 (0, 0)
630
Antoine Pitroub5218772010-05-21 09:56:06 +0000631.. attribute:: SSLContext.options
632
633 An integer representing the set of SSL options enabled on this context.
634 The default value is :data:`OP_ALL`, but you can specify other options
635 such as :data:`OP_NO_SSLv2` by ORing them together.
636
637 .. note::
638 With versions of OpenSSL older than 0.9.8m, it is only possible
639 to set options, not to clear them. Attempting to clear an option
640 (by resetting the corresponding bits) will raise a ``ValueError``.
641
Antoine Pitrou152efa22010-05-16 18:19:27 +0000642.. attribute:: SSLContext.protocol
643
644 The protocol version chosen when constructing the context. This attribute
645 is read-only.
646
647.. attribute:: SSLContext.verify_mode
648
649 Whether to try to verify other peers' certificates and how to behave
650 if verification fails. This attribute must be one of
651 :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.
652
653
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000654.. index:: single: certificates
655
656.. index:: single: X509 certificate
657
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000658.. _ssl-certificates:
659
Thomas Woutersed03b412007-08-28 21:37:11 +0000660Certificates
661------------
662
Georg Brandl7f01a132009-09-16 15:58:14 +0000663Certificates in general are part of a public-key / private-key system. In this
664system, each *principal*, (which may be a machine, or a person, or an
665organization) is assigned a unique two-part encryption key. One part of the key
666is public, and is called the *public key*; the other part is kept secret, and is
667called the *private key*. The two parts are related, in that if you encrypt a
668message with one of the parts, you can decrypt it with the other part, and
669**only** with the other part.
Thomas Woutersed03b412007-08-28 21:37:11 +0000670
Georg Brandl7f01a132009-09-16 15:58:14 +0000671A certificate contains information about two principals. It contains the name
672of a *subject*, and the subject's public key. It also contains a statement by a
673second principal, the *issuer*, that the subject is who he claims to be, and
674that this is indeed the subject's public key. The issuer's statement is signed
675with the issuer's private key, which only the issuer knows. However, anyone can
676verify the issuer's statement by finding the issuer's public key, decrypting the
677statement with it, and comparing it to the other information in the certificate.
678The certificate also contains information about the time period over which it is
679valid. This is expressed as two fields, called "notBefore" and "notAfter".
Thomas Woutersed03b412007-08-28 21:37:11 +0000680
Georg Brandl7f01a132009-09-16 15:58:14 +0000681In the Python use of certificates, a client or server can use a certificate to
682prove who they are. The other side of a network connection can also be required
683to produce a certificate, and that certificate can be validated to the
684satisfaction of the client or server that requires such validation. The
685connection attempt can be set to raise an exception if the validation fails.
686Validation is done automatically, by the underlying OpenSSL framework; the
687application need not concern itself with its mechanics. But the application
688does usually need to provide sets of certificates to allow this process to take
689place.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000690
Georg Brandl7f01a132009-09-16 15:58:14 +0000691Python uses files to contain certificates. They should be formatted as "PEM"
692(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
693and a footer line::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000694
695 -----BEGIN CERTIFICATE-----
696 ... (certificate in base64 PEM encoding) ...
697 -----END CERTIFICATE-----
698
Antoine Pitrou152efa22010-05-16 18:19:27 +0000699Certificate chains
700^^^^^^^^^^^^^^^^^^
701
Georg Brandl7f01a132009-09-16 15:58:14 +0000702The Python files which contain certificates can contain a sequence of
703certificates, sometimes called a *certificate chain*. This chain should start
704with the specific certificate for the principal who "is" the client or server,
705and then the certificate for the issuer of that certificate, and then the
706certificate for the issuer of *that* certificate, and so on up the chain till
707you get to a certificate which is *self-signed*, that is, a certificate which
708has the same subject and issuer, sometimes called a *root certificate*. The
709certificates should just be concatenated together in the certificate file. For
710example, suppose we had a three certificate chain, from our server certificate
711to the certificate of the certification authority that signed our server
712certificate, to the root certificate of the agency which issued the
713certification authority's certificate::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000714
715 -----BEGIN CERTIFICATE-----
716 ... (certificate for your server)...
717 -----END CERTIFICATE-----
718 -----BEGIN CERTIFICATE-----
719 ... (the certificate for the CA)...
720 -----END CERTIFICATE-----
721 -----BEGIN CERTIFICATE-----
722 ... (the root certificate for the CA's issuer)...
723 -----END CERTIFICATE-----
724
Antoine Pitrou152efa22010-05-16 18:19:27 +0000725CA certificates
726^^^^^^^^^^^^^^^
727
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000728If you are going to require validation of the other side of the connection's
729certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandl7f01a132009-09-16 15:58:14 +0000730chains for each issuer you are willing to trust. Again, this file just contains
731these chains concatenated together. For validation, Python will use the first
732chain it finds in the file which matches. Some "standard" root certificates are
733available from various certification authorities: `CACert.org
734<http://www.cacert.org/index.php?id=3>`_, `Thawte
735<http://www.thawte.com/roots/>`_, `Verisign
736<http://www.verisign.com/support/roots.html>`_, `Positive SSL
737<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
738(used by python.org), `Equifax and GeoTrust
739<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000740
Georg Brandl7f01a132009-09-16 15:58:14 +0000741In general, if you are using SSL3 or TLS1, you don't need to put the full chain
742in your "CA certs" file; you only need the root certificates, and the remote
743peer is supposed to furnish the other certificates necessary to chain from its
744certificate to a root certificate. See :rfc:`4158` for more discussion of the
745way in which certification chains can be built.
Thomas Woutersed03b412007-08-28 21:37:11 +0000746
Antoine Pitrou152efa22010-05-16 18:19:27 +0000747Combined key and certificate
748^^^^^^^^^^^^^^^^^^^^^^^^^^^^
749
750Often the private key is stored in the same file as the certificate; in this
751case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain`
752and :func:`wrap_socket` needs to be passed. If the private key is stored
753with the certificate, it should come before the first certificate in
754the certificate chain::
755
756 -----BEGIN RSA PRIVATE KEY-----
757 ... (private key in base64 encoding) ...
758 -----END RSA PRIVATE KEY-----
759 -----BEGIN CERTIFICATE-----
760 ... (certificate in base64 PEM encoding) ...
761 -----END CERTIFICATE-----
762
763Self-signed certificates
764^^^^^^^^^^^^^^^^^^^^^^^^
765
Georg Brandl7f01a132009-09-16 15:58:14 +0000766If you are going to create a server that provides SSL-encrypted connection
767services, you will need to acquire a certificate for that service. There are
768many ways of acquiring appropriate certificates, such as buying one from a
769certification authority. Another common practice is to generate a self-signed
770certificate. The simplest way to do this is with the OpenSSL package, using
771something like the following::
Thomas Woutersed03b412007-08-28 21:37:11 +0000772
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000773 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
774 Generating a 1024 bit RSA private key
775 .......++++++
776 .............................++++++
777 writing new private key to 'cert.pem'
778 -----
779 You are about to be asked to enter information that will be incorporated
780 into your certificate request.
781 What you are about to enter is what is called a Distinguished Name or a DN.
782 There are quite a few fields but you can leave some blank
783 For some fields there will be a default value,
784 If you enter '.', the field will be left blank.
785 -----
786 Country Name (2 letter code) [AU]:US
787 State or Province Name (full name) [Some-State]:MyState
788 Locality Name (eg, city) []:Some City
789 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
790 Organizational Unit Name (eg, section) []:My Group
791 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
792 Email Address []:ops@myserver.mygroup.myorganization.com
793 %
Thomas Woutersed03b412007-08-28 21:37:11 +0000794
Georg Brandl7f01a132009-09-16 15:58:14 +0000795The disadvantage of a self-signed certificate is that it is its own root
796certificate, and no one else will have it in their cache of known (and trusted)
797root certificates.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000798
799
Thomas Woutersed03b412007-08-28 21:37:11 +0000800Examples
801--------
802
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000803Testing for SSL support
804^^^^^^^^^^^^^^^^^^^^^^^
805
Georg Brandl7f01a132009-09-16 15:58:14 +0000806To test for the presence of SSL support in a Python installation, user code
807should use the following idiom::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000808
809 try:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000810 import ssl
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000811 except ImportError:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000812 pass
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000813 else:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000814 ... # do something that requires SSL support
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000815
816Client-side operation
817^^^^^^^^^^^^^^^^^^^^^
818
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000819This example connects to an SSL server and prints the server's certificate::
Thomas Woutersed03b412007-08-28 21:37:11 +0000820
821 import socket, ssl, pprint
822
823 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000824 # require a certificate from the server
825 ssl_sock = ssl.wrap_socket(s,
826 ca_certs="/etc/ca_certs_file",
827 cert_reqs=ssl.CERT_REQUIRED)
Thomas Woutersed03b412007-08-28 21:37:11 +0000828 ssl_sock.connect(('www.verisign.com', 443))
829
Georg Brandl6911e3c2007-09-04 07:15:32 +0000830 pprint.pprint(ssl_sock.getpeercert())
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000831 # note that closing the SSLSocket will also close the underlying socket
Thomas Woutersed03b412007-08-28 21:37:11 +0000832 ssl_sock.close()
833
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000834As of October 6, 2010, the certificate printed by this program looks like
Georg Brandl7f01a132009-09-16 15:58:14 +0000835this::
Thomas Woutersed03b412007-08-28 21:37:11 +0000836
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000837 {'notAfter': 'May 25 23:59:59 2012 GMT',
838 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
839 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
840 (('businessCategory', 'V1.0, Clause 5.(b)'),),
841 (('serialNumber', '2497886'),),
842 (('countryName', 'US'),),
843 (('postalCode', '94043'),),
844 (('stateOrProvinceName', 'California'),),
845 (('localityName', 'Mountain View'),),
846 (('streetAddress', '487 East Middlefield Road'),),
847 (('organizationName', 'VeriSign, Inc.'),),
848 (('organizationalUnitName', ' Production Security Services'),),
849 (('commonName', 'www.verisign.com'),))}
Thomas Woutersed03b412007-08-28 21:37:11 +0000850
Antoine Pitrou152efa22010-05-16 18:19:27 +0000851This other example first creates an SSL context, instructs it to verify
852certificates sent by peers, and feeds it a set of recognized certificate
853authorities (CA)::
854
855 >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000856 >>> context.verify_mode = ssl.CERT_REQUIRED
Antoine Pitrou152efa22010-05-16 18:19:27 +0000857 >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
858
859(it is assumed your operating system places a bundle of all CA certificates
860in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have
861to adjust the location)
862
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000863When you use the context to connect to a server, :const:`CERT_REQUIRED`
Antoine Pitrou152efa22010-05-16 18:19:27 +0000864validates the server certificate: it ensures that the server certificate
865was signed with one of the CA certificates, and checks the signature for
866correctness::
867
868 >>> conn = context.wrap_socket(socket.socket(socket.AF_INET))
869 >>> conn.connect(("linuxfr.org", 443))
870
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000871You should then fetch the certificate and check its fields for conformity::
Antoine Pitrou152efa22010-05-16 18:19:27 +0000872
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000873 >>> cert = conn.getpeercert()
874 >>> ssl.match_hostname(cert, "linuxfr.org")
875
876Visual inspection shows that the certificate does identify the desired service
877(that is, the HTTPS host ``linuxfr.org``)::
878
879 >>> pprint.pprint(cert)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000880 {'notAfter': 'Jun 26 21:41:46 2011 GMT',
881 'subject': ((('commonName', 'linuxfr.org'),),),
882 'subjectAltName': (('DNS', 'linuxfr.org'), ('othername', '<unsupported>'))}
883
884Now that you are assured of its authenticity, you can proceed to talk with
885the server::
886
Antoine Pitroudab64262010-09-19 13:31:06 +0000887 >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
888 >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
Antoine Pitrou152efa22010-05-16 18:19:27 +0000889 [b'HTTP/1.1 302 Found',
890 b'Date: Sun, 16 May 2010 13:43:28 GMT',
891 b'Server: Apache/2.2',
892 b'Location: https://linuxfr.org/pub/',
893 b'Vary: Accept-Encoding',
894 b'Connection: close',
895 b'Content-Type: text/html; charset=iso-8859-1',
896 b'',
897 b'']
898
Antoine Pitrou152efa22010-05-16 18:19:27 +0000899See the discussion of :ref:`ssl-security` below.
900
901
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000902Server-side operation
903^^^^^^^^^^^^^^^^^^^^^
904
Antoine Pitrou152efa22010-05-16 18:19:27 +0000905For server operation, typically you'll need to have a server certificate, and
906private key, each in a file. You'll first create a context holding the key
907and the certificate, so that clients can check your authenticity. Then
908you'll open a socket, bind it to a port, call :meth:`listen` on it, and start
909waiting for clients to connect::
Thomas Woutersed03b412007-08-28 21:37:11 +0000910
911 import socket, ssl
912
Antoine Pitrou152efa22010-05-16 18:19:27 +0000913 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
914 context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")
915
Thomas Woutersed03b412007-08-28 21:37:11 +0000916 bindsocket = socket.socket()
917 bindsocket.bind(('myaddr.mydomain.com', 10023))
918 bindsocket.listen(5)
919
Antoine Pitrou152efa22010-05-16 18:19:27 +0000920When a client connects, you'll call :meth:`accept` on the socket to get the
921new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket`
922method to create a server-side SSL socket for the connection::
Thomas Woutersed03b412007-08-28 21:37:11 +0000923
924 while True:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000925 newsocket, fromaddr = bindsocket.accept()
926 connstream = context.wrap_socket(newsocket, server_side=True)
927 try:
928 deal_with_client(connstream)
929 finally:
Antoine Pitroub205d582011-01-02 22:09:27 +0000930 connstream.shutdown(socket.SHUT_RDWR)
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000931 connstream.close()
Thomas Woutersed03b412007-08-28 21:37:11 +0000932
Antoine Pitrou152efa22010-05-16 18:19:27 +0000933Then you'll read data from the ``connstream`` and do something with it till you
Georg Brandl7f01a132009-09-16 15:58:14 +0000934are finished with the client (or the client is finished with you)::
Thomas Woutersed03b412007-08-28 21:37:11 +0000935
936 def deal_with_client(connstream):
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000937 data = connstream.recv(1024)
938 # empty data means the client is finished with us
939 while data:
940 if not do_something(connstream, data):
941 # we'll assume do_something returns False
942 # when we're finished with client
943 break
944 data = connstream.recv(1024)
945 # finished with client
Thomas Woutersed03b412007-08-28 21:37:11 +0000946
Antoine Pitrou152efa22010-05-16 18:19:27 +0000947And go back to listening for new client connections (of course, a real server
948would probably handle each client connection in a separate thread, or put
949the sockets in non-blocking mode and use an event loop).
950
951
952.. _ssl-security:
953
954Security considerations
955-----------------------
956
957Verifying certificates
958^^^^^^^^^^^^^^^^^^^^^^
959
960:const:`CERT_NONE` is the default. Since it does not authenticate the other
961peer, it can be insecure, especially in client mode where most of time you
962would like to ensure the authenticity of the server you're talking to.
963Therefore, when in client mode, it is highly recommended to use
964:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000965have to check that the server certificate, which can be obtained by calling
966:meth:`SSLSocket.getpeercert`, matches the desired service. For many
967protocols and applications, the service can be identified by the hostname;
968in this case, the :func:`match_hostname` function can be used.
Antoine Pitrou152efa22010-05-16 18:19:27 +0000969
970In server mode, if you want to authenticate your clients using the SSL layer
971(rather than using a higher-level authentication mechanism), you'll also have
972to specify :const:`CERT_REQUIRED` and similarly check the client certificate.
973
974 .. note::
975
976 In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are
977 equivalent unless anonymous ciphers are enabled (they are disabled
978 by default).
Thomas Woutersed03b412007-08-28 21:37:11 +0000979
Antoine Pitroub5218772010-05-21 09:56:06 +0000980Protocol versions
981^^^^^^^^^^^^^^^^^
982
983SSL version 2 is considered insecure and is therefore dangerous to use. If
984you want maximum compatibility between clients and servers, it is recommended
985to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable
986SSLv2 explicitly using the :data:`SSLContext.options` attribute::
987
988 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
989 context.options |= ssl.OP_NO_SSLv2
990
991The SSL context created above will allow SSLv3 and TLSv1 connections, but
992not SSLv2.
993
Georg Brandl48310cd2009-01-03 21:18:54 +0000994
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000995.. seealso::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000996
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000997 Class :class:`socket.socket`
998 Documentation of underlying :mod:`socket` class
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000999
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001000 `Introducing SSL and Certificates using OpenSSL <http://old.pseudonym.org/ssl/wwwj-index.html>`_
1001 Frederick J. Hirsch
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001002
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001003 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
1004 Steve Kent
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001005
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001006 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
1007 D. Eastlake et. al.
Thomas Wouters89d996e2007-09-08 17:39:28 +00001008
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001009 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
1010 Housley et. al.
Antoine Pitroud5323212010-10-22 18:19:07 +00001011
1012 `RFC 4366: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc4366>`_
1013 Blake-Wilson et. al.