blob: 295d007f067be6f1a7e36195a647b3fedb6edddb [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
167 Returns *num* cryptographically strong pseudo-random bytes.
168
Victor Stinner19fb53c2011-05-24 21:32:40 +0200169 Read the Wikipedia article, `Cryptographically secure pseudorandom number
170 generator
171 <http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator>`_,
172 to get the requirements of a cryptographically generator.
173
Victor Stinner99c8b162011-05-24 12:05:19 +0200174 .. versionadded:: 3.3
175
176.. function:: RAND_pseudo_bytes(num)
177
178 Returns (bytes, is_cryptographic): bytes are *num* pseudo-random bytes,
179 is_cryptographic is True if the bytes generated are cryptographically
180 strong.
181
Victor Stinner19fb53c2011-05-24 21:32:40 +0200182 Generated pseudo-random byte sequences will be unique if they are of
183 sufficient length, but are not necessarily unpredictable. They can be used
184 for non-cryptographic purposes and for certain purposes in cryptographic
185 protocols, but usually not for key generation etc.
186
Victor Stinner99c8b162011-05-24 12:05:19 +0200187 .. versionadded:: 3.3
188
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000189.. function:: RAND_status()
190
Georg Brandl7f01a132009-09-16 15:58:14 +0000191 Returns True if the SSL pseudo-random number generator has been seeded with
192 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
193 and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
194 number generator.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000195
196.. function:: RAND_egd(path)
197
Victor Stinner99c8b162011-05-24 12:05:19 +0200198 If you are running an entropy-gathering daemon (EGD) somewhere, and *path*
Georg Brandl7f01a132009-09-16 15:58:14 +0000199 is the pathname of a socket connection open to it, this will read 256 bytes
200 of randomness from the socket, and add it to the SSL pseudo-random number
201 generator to increase the security of generated secret keys. This is
202 typically only necessary on systems without better sources of randomness.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000203
Georg Brandl7f01a132009-09-16 15:58:14 +0000204 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
205 of entropy-gathering daemons.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000206
207.. function:: RAND_add(bytes, entropy)
208
Victor Stinner99c8b162011-05-24 12:05:19 +0200209 Mixes the given *bytes* into the SSL pseudo-random number generator. The
210 parameter *entropy* (a float) is a lower bound on the entropy contained in
Georg Brandl7f01a132009-09-16 15:58:14 +0000211 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
212 information on sources of entropy.
Thomas Woutersed03b412007-08-28 21:37:11 +0000213
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000214Certificate handling
215^^^^^^^^^^^^^^^^^^^^
216
217.. function:: match_hostname(cert, hostname)
218
219 Verify that *cert* (in decoded format as returned by
220 :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules
221 applied are those for checking the identity of HTTPS servers as outlined
222 in :rfc:`2818`, except that IP addresses are not currently supported.
223 In addition to HTTPS, this function should be suitable for checking the
224 identity of servers in various SSL-based protocols such as FTPS, IMAPS,
225 POPS and others.
226
227 :exc:`CertificateError` is raised on failure. On success, the function
228 returns nothing::
229
230 >>> cert = {'subject': ((('commonName', 'example.com'),),)}
231 >>> ssl.match_hostname(cert, "example.com")
232 >>> ssl.match_hostname(cert, "example.org")
233 Traceback (most recent call last):
234 File "<stdin>", line 1, in <module>
235 File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
236 ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'
237
238 .. versionadded:: 3.2
239
Thomas Woutersed03b412007-08-28 21:37:11 +0000240.. function:: cert_time_to_seconds(timestring)
241
Georg Brandl7f01a132009-09-16 15:58:14 +0000242 Returns a floating-point value containing a normal seconds-after-the-epoch
243 time value, given the time-string representing the "notBefore" or "notAfter"
244 date from a certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000245
246 Here's an example::
247
248 >>> import ssl
249 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
250 1178694000.0
251 >>> import time
252 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
253 'Wed May 9 00:00:00 2007'
Thomas Woutersed03b412007-08-28 21:37:11 +0000254
Georg Brandl7f01a132009-09-16 15:58:14 +0000255.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000256
Georg Brandl7f01a132009-09-16 15:58:14 +0000257 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
258 *port-number*) pair, fetches the server's certificate, and returns it as a
259 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
260 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
261 specified, it should be a file containing a list of root certificates, the
262 same format as used for the same parameter in :func:`wrap_socket`. The call
263 will attempt to validate the server certificate against that set of root
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000264 certificates, and will fail if the validation attempt fails.
265
Antoine Pitrou15399c32011-04-28 19:23:55 +0200266 .. versionchanged:: 3.3
267 This function is now IPv6-compatible.
268
Georg Brandl7f01a132009-09-16 15:58:14 +0000269.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000270
271 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
272 string version of the same certificate.
273
Georg Brandl7f01a132009-09-16 15:58:14 +0000274.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000275
Georg Brandl7f01a132009-09-16 15:58:14 +0000276 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
277 bytes for that same certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000278
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000279Constants
280^^^^^^^^^
281
Thomas Woutersed03b412007-08-28 21:37:11 +0000282.. data:: CERT_NONE
283
Antoine Pitrou152efa22010-05-16 18:19:27 +0000284 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
285 parameter to :func:`wrap_socket`. In this mode (the default), no
286 certificates will be required from the other side of the socket connection.
287 If a certificate is received from the other end, no attempt to validate it
288 is made.
289
290 See the discussion of :ref:`ssl-security` below.
Thomas Woutersed03b412007-08-28 21:37:11 +0000291
292.. data:: CERT_OPTIONAL
293
Antoine Pitrou152efa22010-05-16 18:19:27 +0000294 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
295 parameter to :func:`wrap_socket`. In this mode no certificates will be
296 required from the other side of the socket connection; but if they
297 are provided, validation will be attempted and an :class:`SSLError`
298 will be raised on failure.
299
300 Use of this setting requires a valid set of CA certificates to
301 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
302 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000303
304.. data:: CERT_REQUIRED
305
Antoine Pitrou152efa22010-05-16 18:19:27 +0000306 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
307 parameter to :func:`wrap_socket`. In this mode, certificates are
308 required from the other side of the socket connection; an :class:`SSLError`
309 will be raised if no certificate is provided, or if its validation fails.
310
311 Use of this setting requires a valid set of CA certificates to
312 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
313 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000314
315.. data:: PROTOCOL_SSLv2
316
317 Selects SSL version 2 as the channel encryption protocol.
318
Victor Stinner3de49192011-05-09 00:42:58 +0200319 This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
320 flag.
321
Antoine Pitrou8eac60d2010-05-16 14:19:41 +0000322 .. warning::
323
324 SSL version 2 is insecure. Its use is highly discouraged.
325
Thomas Woutersed03b412007-08-28 21:37:11 +0000326.. data:: PROTOCOL_SSLv23
327
Georg Brandl7f01a132009-09-16 15:58:14 +0000328 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
329 setting to use with servers for maximum compatibility with the other end of
330 an SSL connection, but it may cause the specific ciphers chosen for the
331 encryption to be of fairly low quality.
Thomas Woutersed03b412007-08-28 21:37:11 +0000332
333.. data:: PROTOCOL_SSLv3
334
Georg Brandl7f01a132009-09-16 15:58:14 +0000335 Selects SSL version 3 as the channel encryption protocol. For clients, this
336 is the maximally compatible SSL variant.
Thomas Woutersed03b412007-08-28 21:37:11 +0000337
338.. data:: PROTOCOL_TLSv1
339
Georg Brandl7f01a132009-09-16 15:58:14 +0000340 Selects TLS version 1 as the channel encryption protocol. This is the most
341 modern version, and probably the best choice for maximum protection, if both
342 sides can speak it.
Thomas Woutersed03b412007-08-28 21:37:11 +0000343
Antoine Pitroub5218772010-05-21 09:56:06 +0000344.. data:: OP_ALL
345
346 Enables workarounds for various bugs present in other SSL implementations.
347 This option is set by default.
348
349 .. versionadded:: 3.2
350
351.. data:: OP_NO_SSLv2
352
353 Prevents an SSLv2 connection. This option is only applicable in
354 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
355 choosing SSLv2 as the protocol version.
356
357 .. versionadded:: 3.2
358
359.. data:: OP_NO_SSLv3
360
361 Prevents an SSLv3 connection. This option is only applicable in
362 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
363 choosing SSLv3 as the protocol version.
364
365 .. versionadded:: 3.2
366
367.. data:: OP_NO_TLSv1
368
369 Prevents a TLSv1 connection. This option is only applicable in
370 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
371 choosing TLSv1 as the protocol version.
372
373 .. versionadded:: 3.2
374
Antoine Pitroud5323212010-10-22 18:19:07 +0000375.. data:: HAS_SNI
376
377 Whether the OpenSSL library has built-in support for the *Server Name
378 Indication* extension to the SSLv3 and TLSv1 protocols (as defined in
379 :rfc:`4366`). When true, you can use the *server_hostname* argument to
380 :meth:`SSLContext.wrap_socket`.
381
382 .. versionadded:: 3.2
383
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000384.. data:: OPENSSL_VERSION
385
386 The version string of the OpenSSL library loaded by the interpreter::
387
388 >>> ssl.OPENSSL_VERSION
389 'OpenSSL 0.9.8k 25 Mar 2009'
390
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000391 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000392
393.. data:: OPENSSL_VERSION_INFO
394
395 A tuple of five integers representing version information about the
396 OpenSSL library::
397
398 >>> ssl.OPENSSL_VERSION_INFO
399 (0, 9, 8, 11, 15)
400
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000401 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000402
403.. data:: OPENSSL_VERSION_NUMBER
404
405 The raw version number of the OpenSSL library, as a single integer::
406
407 >>> ssl.OPENSSL_VERSION_NUMBER
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000408 9470143
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000409 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000410 '0x9080bf'
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000411
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000412 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000413
Thomas Woutersed03b412007-08-28 21:37:11 +0000414
Antoine Pitrou152efa22010-05-16 18:19:27 +0000415SSL Sockets
416-----------
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000417
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000418SSL sockets provide the following methods of :ref:`socket-objects`:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000419
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000420- :meth:`~socket.socket.accept()`
421- :meth:`~socket.socket.bind()`
422- :meth:`~socket.socket.close()`
423- :meth:`~socket.socket.connect()`
424- :meth:`~socket.socket.detach()`
425- :meth:`~socket.socket.fileno()`
426- :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`
427- :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`
428- :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`,
429 :meth:`~socket.socket.setblocking()`
430- :meth:`~socket.socket.listen()`
431- :meth:`~socket.socket.makefile()`
432- :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()`
433 (but passing a non-zero ``flags`` argument is not allowed)
434- :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with
435 the same limitation)
436- :meth:`~socket.socket.shutdown()`
437
438They also have the following additional methods and attributes:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000439
Bill Janssen48dc27c2007-12-05 03:38:10 +0000440.. method:: SSLSocket.do_handshake()
441
Georg Brandl7f01a132009-09-16 15:58:14 +0000442 Performs the SSL setup handshake. If the socket is non-blocking, this method
443 may raise :exc:`SSLError` with the value of the exception instance's
444 ``args[0]`` being either :const:`SSL_ERROR_WANT_READ` or
445 :const:`SSL_ERROR_WANT_WRITE`, and should be called again until it stops
446 raising those exceptions. Here's an example of how to do that::
Bill Janssen48dc27c2007-12-05 03:38:10 +0000447
448 while True:
449 try:
450 sock.do_handshake()
451 break
452 except ssl.SSLError as err:
453 if err.args[0] == ssl.SSL_ERROR_WANT_READ:
454 select.select([sock], [], [])
455 elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
456 select.select([], [sock], [])
457 else:
458 raise
459
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000460.. method:: SSLSocket.getpeercert(binary_form=False)
461
Georg Brandl7f01a132009-09-16 15:58:14 +0000462 If there is no certificate for the peer on the other end of the connection,
463 returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000464
Georg Brandl7f01a132009-09-16 15:58:14 +0000465 If the parameter ``binary_form`` is :const:`False`, and a certificate was
466 received from the peer, this method returns a :class:`dict` instance. If the
467 certificate was not validated, the dict is empty. If the certificate was
468 validated, it returns a dict with the keys ``subject`` (the principal for
469 which the certificate was issued), and ``notAfter`` (the time after which the
Antoine Pitroufb046912010-11-09 20:21:19 +0000470 certificate should not be trusted). If a certificate contains an instance
471 of the *Subject Alternative Name* extension (see :rfc:`3280`), there will
472 also be a ``subjectAltName`` key in the dictionary.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000473
474 The "subject" field is a tuple containing the sequence of relative
Georg Brandl7f01a132009-09-16 15:58:14 +0000475 distinguished names (RDNs) given in the certificate's data structure for the
476 principal, and each RDN is a sequence of name-value pairs::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000477
478 {'notAfter': 'Feb 16 16:54:50 2013 GMT',
Ezio Melotti985e24d2009-09-13 07:54:02 +0000479 'subject': ((('countryName', 'US'),),
480 (('stateOrProvinceName', 'Delaware'),),
481 (('localityName', 'Wilmington'),),
482 (('organizationName', 'Python Software Foundation'),),
483 (('organizationalUnitName', 'SSL'),),
484 (('commonName', 'somemachine.python.org'),))}
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000485
Georg Brandl7f01a132009-09-16 15:58:14 +0000486 If the ``binary_form`` parameter is :const:`True`, and a certificate was
487 provided, this method returns the DER-encoded form of the entire certificate
488 as a sequence of bytes, or :const:`None` if the peer did not provide a
489 certificate. This return value is independent of validation; if validation
490 was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000491 been validated, but if :const:`CERT_NONE` was used to establish the
492 connection, the certificate, if present, will not have been validated.
493
Antoine Pitroufb046912010-11-09 20:21:19 +0000494 .. versionchanged:: 3.2
495 The returned dictionary includes additional items such as ``issuer``
496 and ``notBefore``.
497
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000498.. method:: SSLSocket.cipher()
499
Georg Brandl7f01a132009-09-16 15:58:14 +0000500 Returns a three-value tuple containing the name of the cipher being used, the
501 version of the SSL protocol that defines its use, and the number of secret
502 bits being used. If no connection has been established, returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000503
504
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000505.. method:: SSLSocket.unwrap()
506
Georg Brandl7f01a132009-09-16 15:58:14 +0000507 Performs the SSL shutdown handshake, which removes the TLS layer from the
508 underlying socket, and returns the underlying socket object. This can be
509 used to go from encrypted operation over a connection to unencrypted. The
510 returned socket should always be used for further communication with the
511 other side of the connection, rather than the original socket.
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000512
Antoine Pitrou152efa22010-05-16 18:19:27 +0000513
Antoine Pitrouec883db2010-05-24 21:20:20 +0000514.. attribute:: SSLSocket.context
515
516 The :class:`SSLContext` object this SSL socket is tied to. If the SSL
517 socket was created using the top-level :func:`wrap_socket` function
518 (rather than :meth:`SSLContext.wrap_socket`), this is a custom context
519 object created for this SSL socket.
520
521 .. versionadded:: 3.2
522
523
Antoine Pitrou152efa22010-05-16 18:19:27 +0000524SSL Contexts
525------------
526
Antoine Pitroucafaad42010-05-24 15:58:43 +0000527.. versionadded:: 3.2
528
Antoine Pitroub0182c82010-10-12 20:09:02 +0000529An SSL context holds various data longer-lived than single SSL connections,
530such as SSL configuration options, certificate(s) and private key(s).
531It also manages a cache of SSL sessions for server-side sockets, in order
532to speed up repeated connections from the same clients.
533
Antoine Pitrou152efa22010-05-16 18:19:27 +0000534.. class:: SSLContext(protocol)
535
Antoine Pitroub0182c82010-10-12 20:09:02 +0000536 Create a new SSL context. You must pass *protocol* which must be one
537 of the ``PROTOCOL_*`` constants defined in this module.
538 :data:`PROTOCOL_SSLv23` is recommended for maximum interoperability.
539
Antoine Pitrou152efa22010-05-16 18:19:27 +0000540
541:class:`SSLContext` objects have the following methods and attributes:
542
543.. method:: SSLContext.load_cert_chain(certfile, keyfile=None)
544
545 Load a private key and the corresponding certificate. The *certfile*
546 string must be the path to a single file in PEM format containing the
547 certificate as well as any number of CA certificates needed to establish
548 the certificate's authenticity. The *keyfile* string, if present, must
549 point to a file containing the private key in. Otherwise the private
550 key will be taken from *certfile* as well. See the discussion of
551 :ref:`ssl-certificates` for more information on how the certificate
552 is stored in the *certfile*.
553
554 An :class:`SSLError` is raised if the private key doesn't
555 match with the certificate.
556
557.. method:: SSLContext.load_verify_locations(cafile=None, capath=None)
558
559 Load a set of "certification authority" (CA) certificates used to validate
560 other peers' certificates when :data:`verify_mode` is other than
561 :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified.
562
563 The *cafile* string, if present, is the path to a file of concatenated
564 CA certificates in PEM format. See the discussion of
565 :ref:`ssl-certificates` for more information about how to arrange the
566 certificates in this file.
567
568 The *capath* string, if present, is
569 the path to a directory containing several CA certificates in PEM format,
570 following an `OpenSSL specific layout
571 <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
572
Antoine Pitrou664c2d12010-11-17 20:29:42 +0000573.. method:: SSLContext.set_default_verify_paths()
574
575 Load a set of default "certification authority" (CA) certificates from
576 a filesystem path defined when building the OpenSSL library. Unfortunately,
577 there's no easy way to know whether this method succeeds: no error is
578 returned if no certificates are to be found. When the OpenSSL library is
579 provided as part of the operating system, though, it is likely to be
580 configured properly.
581
Antoine Pitrou152efa22010-05-16 18:19:27 +0000582.. method:: SSLContext.set_ciphers(ciphers)
583
584 Set the available ciphers for sockets created with this context.
585 It should be a string in the `OpenSSL cipher list format
586 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
587 If no cipher can be selected (because compile-time options or other
588 configuration forbids use of all the specified ciphers), an
589 :class:`SSLError` will be raised.
590
591 .. note::
592 when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
593 give the currently selected cipher.
594
Antoine Pitroud5323212010-10-22 18:19:07 +0000595.. method:: SSLContext.wrap_socket(sock, server_side=False, \
596 do_handshake_on_connect=True, suppress_ragged_eofs=True, \
597 server_hostname=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000598
599 Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
600 object. The SSL socket is tied to the context, its settings and
601 certificates. The parameters *server_side*, *do_handshake_on_connect*
602 and *suppress_ragged_eofs* have the same meaning as in the top-level
603 :func:`wrap_socket` function.
604
Antoine Pitroud5323212010-10-22 18:19:07 +0000605 On client connections, the optional parameter *server_hostname* specifies
606 the hostname of the service which we are connecting to. This allows a
607 single server to host multiple SSL-based services with distinct certificates,
608 quite similarly to HTTP virtual hosts. Specifying *server_hostname*
609 will raise a :exc:`ValueError` if the OpenSSL library doesn't have support
610 for it (that is, if :data:`HAS_SNI` is :const:`False`). Specifying
611 *server_hostname* will also raise a :exc:`ValueError` if *server_side*
612 is true.
613
Antoine Pitroub0182c82010-10-12 20:09:02 +0000614.. method:: SSLContext.session_stats()
615
616 Get statistics about the SSL sessions created or managed by this context.
617 A dictionary is returned which maps the names of each `piece of information
618 <http://www.openssl.org/docs/ssl/SSL_CTX_sess_number.html>`_ to their
619 numeric values. For example, here is the total number of hits and misses
620 in the session cache since the context was created::
621
622 >>> stats = context.session_stats()
623 >>> stats['hits'], stats['misses']
624 (0, 0)
625
Antoine Pitroub5218772010-05-21 09:56:06 +0000626.. attribute:: SSLContext.options
627
628 An integer representing the set of SSL options enabled on this context.
629 The default value is :data:`OP_ALL`, but you can specify other options
630 such as :data:`OP_NO_SSLv2` by ORing them together.
631
632 .. note::
633 With versions of OpenSSL older than 0.9.8m, it is only possible
634 to set options, not to clear them. Attempting to clear an option
635 (by resetting the corresponding bits) will raise a ``ValueError``.
636
Antoine Pitrou152efa22010-05-16 18:19:27 +0000637.. attribute:: SSLContext.protocol
638
639 The protocol version chosen when constructing the context. This attribute
640 is read-only.
641
642.. attribute:: SSLContext.verify_mode
643
644 Whether to try to verify other peers' certificates and how to behave
645 if verification fails. This attribute must be one of
646 :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.
647
648
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000649.. index:: single: certificates
650
651.. index:: single: X509 certificate
652
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000653.. _ssl-certificates:
654
Thomas Woutersed03b412007-08-28 21:37:11 +0000655Certificates
656------------
657
Georg Brandl7f01a132009-09-16 15:58:14 +0000658Certificates in general are part of a public-key / private-key system. In this
659system, each *principal*, (which may be a machine, or a person, or an
660organization) is assigned a unique two-part encryption key. One part of the key
661is public, and is called the *public key*; the other part is kept secret, and is
662called the *private key*. The two parts are related, in that if you encrypt a
663message with one of the parts, you can decrypt it with the other part, and
664**only** with the other part.
Thomas Woutersed03b412007-08-28 21:37:11 +0000665
Georg Brandl7f01a132009-09-16 15:58:14 +0000666A certificate contains information about two principals. It contains the name
667of a *subject*, and the subject's public key. It also contains a statement by a
668second principal, the *issuer*, that the subject is who he claims to be, and
669that this is indeed the subject's public key. The issuer's statement is signed
670with the issuer's private key, which only the issuer knows. However, anyone can
671verify the issuer's statement by finding the issuer's public key, decrypting the
672statement with it, and comparing it to the other information in the certificate.
673The certificate also contains information about the time period over which it is
674valid. This is expressed as two fields, called "notBefore" and "notAfter".
Thomas Woutersed03b412007-08-28 21:37:11 +0000675
Georg Brandl7f01a132009-09-16 15:58:14 +0000676In the Python use of certificates, a client or server can use a certificate to
677prove who they are. The other side of a network connection can also be required
678to produce a certificate, and that certificate can be validated to the
679satisfaction of the client or server that requires such validation. The
680connection attempt can be set to raise an exception if the validation fails.
681Validation is done automatically, by the underlying OpenSSL framework; the
682application need not concern itself with its mechanics. But the application
683does usually need to provide sets of certificates to allow this process to take
684place.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000685
Georg Brandl7f01a132009-09-16 15:58:14 +0000686Python uses files to contain certificates. They should be formatted as "PEM"
687(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
688and a footer line::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000689
690 -----BEGIN CERTIFICATE-----
691 ... (certificate in base64 PEM encoding) ...
692 -----END CERTIFICATE-----
693
Antoine Pitrou152efa22010-05-16 18:19:27 +0000694Certificate chains
695^^^^^^^^^^^^^^^^^^
696
Georg Brandl7f01a132009-09-16 15:58:14 +0000697The Python files which contain certificates can contain a sequence of
698certificates, sometimes called a *certificate chain*. This chain should start
699with the specific certificate for the principal who "is" the client or server,
700and then the certificate for the issuer of that certificate, and then the
701certificate for the issuer of *that* certificate, and so on up the chain till
702you get to a certificate which is *self-signed*, that is, a certificate which
703has the same subject and issuer, sometimes called a *root certificate*. The
704certificates should just be concatenated together in the certificate file. For
705example, suppose we had a three certificate chain, from our server certificate
706to the certificate of the certification authority that signed our server
707certificate, to the root certificate of the agency which issued the
708certification authority's certificate::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000709
710 -----BEGIN CERTIFICATE-----
711 ... (certificate for your server)...
712 -----END CERTIFICATE-----
713 -----BEGIN CERTIFICATE-----
714 ... (the certificate for the CA)...
715 -----END CERTIFICATE-----
716 -----BEGIN CERTIFICATE-----
717 ... (the root certificate for the CA's issuer)...
718 -----END CERTIFICATE-----
719
Antoine Pitrou152efa22010-05-16 18:19:27 +0000720CA certificates
721^^^^^^^^^^^^^^^
722
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000723If you are going to require validation of the other side of the connection's
724certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandl7f01a132009-09-16 15:58:14 +0000725chains for each issuer you are willing to trust. Again, this file just contains
726these chains concatenated together. For validation, Python will use the first
727chain it finds in the file which matches. Some "standard" root certificates are
728available from various certification authorities: `CACert.org
729<http://www.cacert.org/index.php?id=3>`_, `Thawte
730<http://www.thawte.com/roots/>`_, `Verisign
731<http://www.verisign.com/support/roots.html>`_, `Positive SSL
732<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
733(used by python.org), `Equifax and GeoTrust
734<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000735
Georg Brandl7f01a132009-09-16 15:58:14 +0000736In general, if you are using SSL3 or TLS1, you don't need to put the full chain
737in your "CA certs" file; you only need the root certificates, and the remote
738peer is supposed to furnish the other certificates necessary to chain from its
739certificate to a root certificate. See :rfc:`4158` for more discussion of the
740way in which certification chains can be built.
Thomas Woutersed03b412007-08-28 21:37:11 +0000741
Antoine Pitrou152efa22010-05-16 18:19:27 +0000742Combined key and certificate
743^^^^^^^^^^^^^^^^^^^^^^^^^^^^
744
745Often the private key is stored in the same file as the certificate; in this
746case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain`
747and :func:`wrap_socket` needs to be passed. If the private key is stored
748with the certificate, it should come before the first certificate in
749the certificate chain::
750
751 -----BEGIN RSA PRIVATE KEY-----
752 ... (private key in base64 encoding) ...
753 -----END RSA PRIVATE KEY-----
754 -----BEGIN CERTIFICATE-----
755 ... (certificate in base64 PEM encoding) ...
756 -----END CERTIFICATE-----
757
758Self-signed certificates
759^^^^^^^^^^^^^^^^^^^^^^^^
760
Georg Brandl7f01a132009-09-16 15:58:14 +0000761If you are going to create a server that provides SSL-encrypted connection
762services, you will need to acquire a certificate for that service. There are
763many ways of acquiring appropriate certificates, such as buying one from a
764certification authority. Another common practice is to generate a self-signed
765certificate. The simplest way to do this is with the OpenSSL package, using
766something like the following::
Thomas Woutersed03b412007-08-28 21:37:11 +0000767
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000768 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
769 Generating a 1024 bit RSA private key
770 .......++++++
771 .............................++++++
772 writing new private key to 'cert.pem'
773 -----
774 You are about to be asked to enter information that will be incorporated
775 into your certificate request.
776 What you are about to enter is what is called a Distinguished Name or a DN.
777 There are quite a few fields but you can leave some blank
778 For some fields there will be a default value,
779 If you enter '.', the field will be left blank.
780 -----
781 Country Name (2 letter code) [AU]:US
782 State or Province Name (full name) [Some-State]:MyState
783 Locality Name (eg, city) []:Some City
784 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
785 Organizational Unit Name (eg, section) []:My Group
786 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
787 Email Address []:ops@myserver.mygroup.myorganization.com
788 %
Thomas Woutersed03b412007-08-28 21:37:11 +0000789
Georg Brandl7f01a132009-09-16 15:58:14 +0000790The disadvantage of a self-signed certificate is that it is its own root
791certificate, and no one else will have it in their cache of known (and trusted)
792root certificates.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000793
794
Thomas Woutersed03b412007-08-28 21:37:11 +0000795Examples
796--------
797
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000798Testing for SSL support
799^^^^^^^^^^^^^^^^^^^^^^^
800
Georg Brandl7f01a132009-09-16 15:58:14 +0000801To test for the presence of SSL support in a Python installation, user code
802should use the following idiom::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000803
804 try:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000805 import ssl
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000806 except ImportError:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000807 pass
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000808 else:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000809 ... # do something that requires SSL support
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000810
811Client-side operation
812^^^^^^^^^^^^^^^^^^^^^
813
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000814This example connects to an SSL server and prints the server's certificate::
Thomas Woutersed03b412007-08-28 21:37:11 +0000815
816 import socket, ssl, pprint
817
818 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000819 # require a certificate from the server
820 ssl_sock = ssl.wrap_socket(s,
821 ca_certs="/etc/ca_certs_file",
822 cert_reqs=ssl.CERT_REQUIRED)
Thomas Woutersed03b412007-08-28 21:37:11 +0000823 ssl_sock.connect(('www.verisign.com', 443))
824
Georg Brandl6911e3c2007-09-04 07:15:32 +0000825 pprint.pprint(ssl_sock.getpeercert())
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000826 # note that closing the SSLSocket will also close the underlying socket
Thomas Woutersed03b412007-08-28 21:37:11 +0000827 ssl_sock.close()
828
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000829As of October 6, 2010, the certificate printed by this program looks like
Georg Brandl7f01a132009-09-16 15:58:14 +0000830this::
Thomas Woutersed03b412007-08-28 21:37:11 +0000831
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000832 {'notAfter': 'May 25 23:59:59 2012 GMT',
833 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
834 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
835 (('businessCategory', 'V1.0, Clause 5.(b)'),),
836 (('serialNumber', '2497886'),),
837 (('countryName', 'US'),),
838 (('postalCode', '94043'),),
839 (('stateOrProvinceName', 'California'),),
840 (('localityName', 'Mountain View'),),
841 (('streetAddress', '487 East Middlefield Road'),),
842 (('organizationName', 'VeriSign, Inc.'),),
843 (('organizationalUnitName', ' Production Security Services'),),
844 (('commonName', 'www.verisign.com'),))}
Thomas Woutersed03b412007-08-28 21:37:11 +0000845
Antoine Pitrou152efa22010-05-16 18:19:27 +0000846This other example first creates an SSL context, instructs it to verify
847certificates sent by peers, and feeds it a set of recognized certificate
848authorities (CA)::
849
850 >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000851 >>> context.verify_mode = ssl.CERT_REQUIRED
Antoine Pitrou152efa22010-05-16 18:19:27 +0000852 >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
853
854(it is assumed your operating system places a bundle of all CA certificates
855in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have
856to adjust the location)
857
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000858When you use the context to connect to a server, :const:`CERT_REQUIRED`
Antoine Pitrou152efa22010-05-16 18:19:27 +0000859validates the server certificate: it ensures that the server certificate
860was signed with one of the CA certificates, and checks the signature for
861correctness::
862
863 >>> conn = context.wrap_socket(socket.socket(socket.AF_INET))
864 >>> conn.connect(("linuxfr.org", 443))
865
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000866You should then fetch the certificate and check its fields for conformity::
Antoine Pitrou152efa22010-05-16 18:19:27 +0000867
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000868 >>> cert = conn.getpeercert()
869 >>> ssl.match_hostname(cert, "linuxfr.org")
870
871Visual inspection shows that the certificate does identify the desired service
872(that is, the HTTPS host ``linuxfr.org``)::
873
874 >>> pprint.pprint(cert)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000875 {'notAfter': 'Jun 26 21:41:46 2011 GMT',
876 'subject': ((('commonName', 'linuxfr.org'),),),
877 'subjectAltName': (('DNS', 'linuxfr.org'), ('othername', '<unsupported>'))}
878
879Now that you are assured of its authenticity, you can proceed to talk with
880the server::
881
Antoine Pitroudab64262010-09-19 13:31:06 +0000882 >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
883 >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
Antoine Pitrou152efa22010-05-16 18:19:27 +0000884 [b'HTTP/1.1 302 Found',
885 b'Date: Sun, 16 May 2010 13:43:28 GMT',
886 b'Server: Apache/2.2',
887 b'Location: https://linuxfr.org/pub/',
888 b'Vary: Accept-Encoding',
889 b'Connection: close',
890 b'Content-Type: text/html; charset=iso-8859-1',
891 b'',
892 b'']
893
Antoine Pitrou152efa22010-05-16 18:19:27 +0000894See the discussion of :ref:`ssl-security` below.
895
896
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000897Server-side operation
898^^^^^^^^^^^^^^^^^^^^^
899
Antoine Pitrou152efa22010-05-16 18:19:27 +0000900For server operation, typically you'll need to have a server certificate, and
901private key, each in a file. You'll first create a context holding the key
902and the certificate, so that clients can check your authenticity. Then
903you'll open a socket, bind it to a port, call :meth:`listen` on it, and start
904waiting for clients to connect::
Thomas Woutersed03b412007-08-28 21:37:11 +0000905
906 import socket, ssl
907
Antoine Pitrou152efa22010-05-16 18:19:27 +0000908 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
909 context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")
910
Thomas Woutersed03b412007-08-28 21:37:11 +0000911 bindsocket = socket.socket()
912 bindsocket.bind(('myaddr.mydomain.com', 10023))
913 bindsocket.listen(5)
914
Antoine Pitrou152efa22010-05-16 18:19:27 +0000915When a client connects, you'll call :meth:`accept` on the socket to get the
916new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket`
917method to create a server-side SSL socket for the connection::
Thomas Woutersed03b412007-08-28 21:37:11 +0000918
919 while True:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000920 newsocket, fromaddr = bindsocket.accept()
921 connstream = context.wrap_socket(newsocket, server_side=True)
922 try:
923 deal_with_client(connstream)
924 finally:
Antoine Pitroub205d582011-01-02 22:09:27 +0000925 connstream.shutdown(socket.SHUT_RDWR)
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000926 connstream.close()
Thomas Woutersed03b412007-08-28 21:37:11 +0000927
Antoine Pitrou152efa22010-05-16 18:19:27 +0000928Then you'll read data from the ``connstream`` and do something with it till you
Georg Brandl7f01a132009-09-16 15:58:14 +0000929are finished with the client (or the client is finished with you)::
Thomas Woutersed03b412007-08-28 21:37:11 +0000930
931 def deal_with_client(connstream):
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000932 data = connstream.recv(1024)
933 # empty data means the client is finished with us
934 while data:
935 if not do_something(connstream, data):
936 # we'll assume do_something returns False
937 # when we're finished with client
938 break
939 data = connstream.recv(1024)
940 # finished with client
Thomas Woutersed03b412007-08-28 21:37:11 +0000941
Antoine Pitrou152efa22010-05-16 18:19:27 +0000942And go back to listening for new client connections (of course, a real server
943would probably handle each client connection in a separate thread, or put
944the sockets in non-blocking mode and use an event loop).
945
946
947.. _ssl-security:
948
949Security considerations
950-----------------------
951
952Verifying certificates
953^^^^^^^^^^^^^^^^^^^^^^
954
955:const:`CERT_NONE` is the default. Since it does not authenticate the other
956peer, it can be insecure, especially in client mode where most of time you
957would like to ensure the authenticity of the server you're talking to.
958Therefore, when in client mode, it is highly recommended to use
959:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000960have to check that the server certificate, which can be obtained by calling
961:meth:`SSLSocket.getpeercert`, matches the desired service. For many
962protocols and applications, the service can be identified by the hostname;
963in this case, the :func:`match_hostname` function can be used.
Antoine Pitrou152efa22010-05-16 18:19:27 +0000964
965In server mode, if you want to authenticate your clients using the SSL layer
966(rather than using a higher-level authentication mechanism), you'll also have
967to specify :const:`CERT_REQUIRED` and similarly check the client certificate.
968
969 .. note::
970
971 In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are
972 equivalent unless anonymous ciphers are enabled (they are disabled
973 by default).
Thomas Woutersed03b412007-08-28 21:37:11 +0000974
Antoine Pitroub5218772010-05-21 09:56:06 +0000975Protocol versions
976^^^^^^^^^^^^^^^^^
977
978SSL version 2 is considered insecure and is therefore dangerous to use. If
979you want maximum compatibility between clients and servers, it is recommended
980to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable
981SSLv2 explicitly using the :data:`SSLContext.options` attribute::
982
983 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
984 context.options |= ssl.OP_NO_SSLv2
985
986The SSL context created above will allow SSLv3 and TLSv1 connections, but
987not SSLv2.
988
Georg Brandl48310cd2009-01-03 21:18:54 +0000989
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000990.. seealso::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000991
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000992 Class :class:`socket.socket`
993 Documentation of underlying :mod:`socket` class
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000994
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000995 `Introducing SSL and Certificates using OpenSSL <http://old.pseudonym.org/ssl/wwwj-index.html>`_
996 Frederick J. Hirsch
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000997
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000998 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
999 Steve Kent
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001000
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001001 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
1002 D. Eastlake et. al.
Thomas Wouters89d996e2007-09-08 17:39:28 +00001003
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001004 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
1005 Housley et. al.
Antoine Pitroud5323212010-10-22 18:19:07 +00001006
1007 `RFC 4366: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc4366>`_
1008 Blake-Wilson et. al.