blob: 5ece8cf979fe8d40a25a68be8ec912738973cd79 [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
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000165.. function:: RAND_status()
166
Georg Brandl7f01a132009-09-16 15:58:14 +0000167 Returns True if the SSL pseudo-random number generator has been seeded with
168 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
169 and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
170 number generator.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000171
172.. function:: RAND_egd(path)
173
174 If you are running an entropy-gathering daemon (EGD) somewhere, and ``path``
Georg Brandl7f01a132009-09-16 15:58:14 +0000175 is the pathname of a socket connection open to it, this will read 256 bytes
176 of randomness from the socket, and add it to the SSL pseudo-random number
177 generator to increase the security of generated secret keys. This is
178 typically only necessary on systems without better sources of randomness.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000179
Georg Brandl7f01a132009-09-16 15:58:14 +0000180 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
181 of entropy-gathering daemons.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000182
183.. function:: RAND_add(bytes, entropy)
184
Georg Brandl7f01a132009-09-16 15:58:14 +0000185 Mixes the given ``bytes`` into the SSL pseudo-random number generator. The
186 parameter ``entropy`` (a float) is a lower bound on the entropy contained in
187 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
188 information on sources of entropy.
Thomas Woutersed03b412007-08-28 21:37:11 +0000189
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000190Certificate handling
191^^^^^^^^^^^^^^^^^^^^
192
193.. function:: match_hostname(cert, hostname)
194
195 Verify that *cert* (in decoded format as returned by
196 :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules
197 applied are those for checking the identity of HTTPS servers as outlined
198 in :rfc:`2818`, except that IP addresses are not currently supported.
199 In addition to HTTPS, this function should be suitable for checking the
200 identity of servers in various SSL-based protocols such as FTPS, IMAPS,
201 POPS and others.
202
203 :exc:`CertificateError` is raised on failure. On success, the function
204 returns nothing::
205
206 >>> cert = {'subject': ((('commonName', 'example.com'),),)}
207 >>> ssl.match_hostname(cert, "example.com")
208 >>> ssl.match_hostname(cert, "example.org")
209 Traceback (most recent call last):
210 File "<stdin>", line 1, in <module>
211 File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
212 ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'
213
214 .. versionadded:: 3.2
215
Thomas Woutersed03b412007-08-28 21:37:11 +0000216.. function:: cert_time_to_seconds(timestring)
217
Georg Brandl7f01a132009-09-16 15:58:14 +0000218 Returns a floating-point value containing a normal seconds-after-the-epoch
219 time value, given the time-string representing the "notBefore" or "notAfter"
220 date from a certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000221
222 Here's an example::
223
224 >>> import ssl
225 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
226 1178694000.0
227 >>> import time
228 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
229 'Wed May 9 00:00:00 2007'
Thomas Woutersed03b412007-08-28 21:37:11 +0000230
Georg Brandl7f01a132009-09-16 15:58:14 +0000231.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000232
Georg Brandl7f01a132009-09-16 15:58:14 +0000233 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
234 *port-number*) pair, fetches the server's certificate, and returns it as a
235 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
236 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
237 specified, it should be a file containing a list of root certificates, the
238 same format as used for the same parameter in :func:`wrap_socket`. The call
239 will attempt to validate the server certificate against that set of root
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000240 certificates, and will fail if the validation attempt fails.
241
Antoine Pitrou15399c32011-04-28 19:23:55 +0200242 .. versionchanged:: 3.3
243 This function is now IPv6-compatible.
244
Georg Brandl7f01a132009-09-16 15:58:14 +0000245.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000246
247 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
248 string version of the same certificate.
249
Georg Brandl7f01a132009-09-16 15:58:14 +0000250.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000251
Georg Brandl7f01a132009-09-16 15:58:14 +0000252 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
253 bytes for that same certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000254
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000255Constants
256^^^^^^^^^
257
Thomas Woutersed03b412007-08-28 21:37:11 +0000258.. data:: CERT_NONE
259
Antoine Pitrou152efa22010-05-16 18:19:27 +0000260 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
261 parameter to :func:`wrap_socket`. In this mode (the default), no
262 certificates will be required from the other side of the socket connection.
263 If a certificate is received from the other end, no attempt to validate it
264 is made.
265
266 See the discussion of :ref:`ssl-security` below.
Thomas Woutersed03b412007-08-28 21:37:11 +0000267
268.. data:: CERT_OPTIONAL
269
Antoine Pitrou152efa22010-05-16 18:19:27 +0000270 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
271 parameter to :func:`wrap_socket`. In this mode no certificates will be
272 required from the other side of the socket connection; but if they
273 are provided, validation will be attempted and an :class:`SSLError`
274 will be raised on failure.
275
276 Use of this setting requires a valid set of CA certificates to
277 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
278 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000279
280.. data:: CERT_REQUIRED
281
Antoine Pitrou152efa22010-05-16 18:19:27 +0000282 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
283 parameter to :func:`wrap_socket`. In this mode, certificates are
284 required from the other side of the socket connection; an :class:`SSLError`
285 will be raised if no certificate is provided, or if its validation fails.
286
287 Use of this setting requires a valid set of CA certificates to
288 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
289 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000290
291.. data:: PROTOCOL_SSLv2
292
293 Selects SSL version 2 as the channel encryption protocol.
294
Victor Stinner3de49192011-05-09 00:42:58 +0200295 This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
296 flag.
297
Antoine Pitrou8eac60d2010-05-16 14:19:41 +0000298 .. warning::
299
300 SSL version 2 is insecure. Its use is highly discouraged.
301
Thomas Woutersed03b412007-08-28 21:37:11 +0000302.. data:: PROTOCOL_SSLv23
303
Georg Brandl7f01a132009-09-16 15:58:14 +0000304 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
305 setting to use with servers for maximum compatibility with the other end of
306 an SSL connection, but it may cause the specific ciphers chosen for the
307 encryption to be of fairly low quality.
Thomas Woutersed03b412007-08-28 21:37:11 +0000308
309.. data:: PROTOCOL_SSLv3
310
Georg Brandl7f01a132009-09-16 15:58:14 +0000311 Selects SSL version 3 as the channel encryption protocol. For clients, this
312 is the maximally compatible SSL variant.
Thomas Woutersed03b412007-08-28 21:37:11 +0000313
314.. data:: PROTOCOL_TLSv1
315
Georg Brandl7f01a132009-09-16 15:58:14 +0000316 Selects TLS version 1 as the channel encryption protocol. This is the most
317 modern version, and probably the best choice for maximum protection, if both
318 sides can speak it.
Thomas Woutersed03b412007-08-28 21:37:11 +0000319
Antoine Pitroub5218772010-05-21 09:56:06 +0000320.. data:: OP_ALL
321
322 Enables workarounds for various bugs present in other SSL implementations.
323 This option is set by default.
324
325 .. versionadded:: 3.2
326
327.. data:: OP_NO_SSLv2
328
329 Prevents an SSLv2 connection. This option is only applicable in
330 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
331 choosing SSLv2 as the protocol version.
332
333 .. versionadded:: 3.2
334
335.. data:: OP_NO_SSLv3
336
337 Prevents an SSLv3 connection. This option is only applicable in
338 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
339 choosing SSLv3 as the protocol version.
340
341 .. versionadded:: 3.2
342
343.. data:: OP_NO_TLSv1
344
345 Prevents a TLSv1 connection. This option is only applicable in
346 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
347 choosing TLSv1 as the protocol version.
348
349 .. versionadded:: 3.2
350
Antoine Pitroud5323212010-10-22 18:19:07 +0000351.. data:: HAS_SNI
352
353 Whether the OpenSSL library has built-in support for the *Server Name
354 Indication* extension to the SSLv3 and TLSv1 protocols (as defined in
355 :rfc:`4366`). When true, you can use the *server_hostname* argument to
356 :meth:`SSLContext.wrap_socket`.
357
358 .. versionadded:: 3.2
359
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000360.. data:: OPENSSL_VERSION
361
362 The version string of the OpenSSL library loaded by the interpreter::
363
364 >>> ssl.OPENSSL_VERSION
365 'OpenSSL 0.9.8k 25 Mar 2009'
366
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000367 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000368
369.. data:: OPENSSL_VERSION_INFO
370
371 A tuple of five integers representing version information about the
372 OpenSSL library::
373
374 >>> ssl.OPENSSL_VERSION_INFO
375 (0, 9, 8, 11, 15)
376
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000377 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000378
379.. data:: OPENSSL_VERSION_NUMBER
380
381 The raw version number of the OpenSSL library, as a single integer::
382
383 >>> ssl.OPENSSL_VERSION_NUMBER
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000384 9470143
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000385 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000386 '0x9080bf'
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000387
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000388 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000389
Thomas Woutersed03b412007-08-28 21:37:11 +0000390
Antoine Pitrou152efa22010-05-16 18:19:27 +0000391SSL Sockets
392-----------
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000393
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000394SSL sockets provide the following methods of :ref:`socket-objects`:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000395
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000396- :meth:`~socket.socket.accept()`
397- :meth:`~socket.socket.bind()`
398- :meth:`~socket.socket.close()`
399- :meth:`~socket.socket.connect()`
400- :meth:`~socket.socket.detach()`
401- :meth:`~socket.socket.fileno()`
402- :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`
403- :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`
404- :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`,
405 :meth:`~socket.socket.setblocking()`
406- :meth:`~socket.socket.listen()`
407- :meth:`~socket.socket.makefile()`
408- :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()`
409 (but passing a non-zero ``flags`` argument is not allowed)
410- :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with
411 the same limitation)
412- :meth:`~socket.socket.shutdown()`
413
414They also have the following additional methods and attributes:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000415
Bill Janssen48dc27c2007-12-05 03:38:10 +0000416.. method:: SSLSocket.do_handshake()
417
Georg Brandl7f01a132009-09-16 15:58:14 +0000418 Performs the SSL setup handshake. If the socket is non-blocking, this method
419 may raise :exc:`SSLError` with the value of the exception instance's
420 ``args[0]`` being either :const:`SSL_ERROR_WANT_READ` or
421 :const:`SSL_ERROR_WANT_WRITE`, and should be called again until it stops
422 raising those exceptions. Here's an example of how to do that::
Bill Janssen48dc27c2007-12-05 03:38:10 +0000423
424 while True:
425 try:
426 sock.do_handshake()
427 break
428 except ssl.SSLError as err:
429 if err.args[0] == ssl.SSL_ERROR_WANT_READ:
430 select.select([sock], [], [])
431 elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
432 select.select([], [sock], [])
433 else:
434 raise
435
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000436.. method:: SSLSocket.getpeercert(binary_form=False)
437
Georg Brandl7f01a132009-09-16 15:58:14 +0000438 If there is no certificate for the peer on the other end of the connection,
439 returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000440
Georg Brandl7f01a132009-09-16 15:58:14 +0000441 If the parameter ``binary_form`` is :const:`False`, and a certificate was
442 received from the peer, this method returns a :class:`dict` instance. If the
443 certificate was not validated, the dict is empty. If the certificate was
444 validated, it returns a dict with the keys ``subject`` (the principal for
445 which the certificate was issued), and ``notAfter`` (the time after which the
Antoine Pitroufb046912010-11-09 20:21:19 +0000446 certificate should not be trusted). If a certificate contains an instance
447 of the *Subject Alternative Name* extension (see :rfc:`3280`), there will
448 also be a ``subjectAltName`` key in the dictionary.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000449
450 The "subject" field is a tuple containing the sequence of relative
Georg Brandl7f01a132009-09-16 15:58:14 +0000451 distinguished names (RDNs) given in the certificate's data structure for the
452 principal, and each RDN is a sequence of name-value pairs::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000453
454 {'notAfter': 'Feb 16 16:54:50 2013 GMT',
Ezio Melotti985e24d2009-09-13 07:54:02 +0000455 'subject': ((('countryName', 'US'),),
456 (('stateOrProvinceName', 'Delaware'),),
457 (('localityName', 'Wilmington'),),
458 (('organizationName', 'Python Software Foundation'),),
459 (('organizationalUnitName', 'SSL'),),
460 (('commonName', 'somemachine.python.org'),))}
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000461
Georg Brandl7f01a132009-09-16 15:58:14 +0000462 If the ``binary_form`` parameter is :const:`True`, and a certificate was
463 provided, this method returns the DER-encoded form of the entire certificate
464 as a sequence of bytes, or :const:`None` if the peer did not provide a
465 certificate. This return value is independent of validation; if validation
466 was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000467 been validated, but if :const:`CERT_NONE` was used to establish the
468 connection, the certificate, if present, will not have been validated.
469
Antoine Pitroufb046912010-11-09 20:21:19 +0000470 .. versionchanged:: 3.2
471 The returned dictionary includes additional items such as ``issuer``
472 and ``notBefore``.
473
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000474.. method:: SSLSocket.cipher()
475
Georg Brandl7f01a132009-09-16 15:58:14 +0000476 Returns a three-value tuple containing the name of the cipher being used, the
477 version of the SSL protocol that defines its use, and the number of secret
478 bits being used. If no connection has been established, returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000479
480
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000481.. method:: SSLSocket.unwrap()
482
Georg Brandl7f01a132009-09-16 15:58:14 +0000483 Performs the SSL shutdown handshake, which removes the TLS layer from the
484 underlying socket, and returns the underlying socket object. This can be
485 used to go from encrypted operation over a connection to unencrypted. The
486 returned socket should always be used for further communication with the
487 other side of the connection, rather than the original socket.
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000488
Antoine Pitrou152efa22010-05-16 18:19:27 +0000489
Antoine Pitrouec883db2010-05-24 21:20:20 +0000490.. attribute:: SSLSocket.context
491
492 The :class:`SSLContext` object this SSL socket is tied to. If the SSL
493 socket was created using the top-level :func:`wrap_socket` function
494 (rather than :meth:`SSLContext.wrap_socket`), this is a custom context
495 object created for this SSL socket.
496
497 .. versionadded:: 3.2
498
499
Antoine Pitrou152efa22010-05-16 18:19:27 +0000500SSL Contexts
501------------
502
Antoine Pitroucafaad42010-05-24 15:58:43 +0000503.. versionadded:: 3.2
504
Antoine Pitroub0182c82010-10-12 20:09:02 +0000505An SSL context holds various data longer-lived than single SSL connections,
506such as SSL configuration options, certificate(s) and private key(s).
507It also manages a cache of SSL sessions for server-side sockets, in order
508to speed up repeated connections from the same clients.
509
Antoine Pitrou152efa22010-05-16 18:19:27 +0000510.. class:: SSLContext(protocol)
511
Antoine Pitroub0182c82010-10-12 20:09:02 +0000512 Create a new SSL context. You must pass *protocol* which must be one
513 of the ``PROTOCOL_*`` constants defined in this module.
514 :data:`PROTOCOL_SSLv23` is recommended for maximum interoperability.
515
Antoine Pitrou152efa22010-05-16 18:19:27 +0000516
517:class:`SSLContext` objects have the following methods and attributes:
518
519.. method:: SSLContext.load_cert_chain(certfile, keyfile=None)
520
521 Load a private key and the corresponding certificate. The *certfile*
522 string must be the path to a single file in PEM format containing the
523 certificate as well as any number of CA certificates needed to establish
524 the certificate's authenticity. The *keyfile* string, if present, must
525 point to a file containing the private key in. Otherwise the private
526 key will be taken from *certfile* as well. See the discussion of
527 :ref:`ssl-certificates` for more information on how the certificate
528 is stored in the *certfile*.
529
530 An :class:`SSLError` is raised if the private key doesn't
531 match with the certificate.
532
533.. method:: SSLContext.load_verify_locations(cafile=None, capath=None)
534
535 Load a set of "certification authority" (CA) certificates used to validate
536 other peers' certificates when :data:`verify_mode` is other than
537 :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified.
538
539 The *cafile* string, if present, is the path to a file of concatenated
540 CA certificates in PEM format. See the discussion of
541 :ref:`ssl-certificates` for more information about how to arrange the
542 certificates in this file.
543
544 The *capath* string, if present, is
545 the path to a directory containing several CA certificates in PEM format,
546 following an `OpenSSL specific layout
547 <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
548
Antoine Pitrou664c2d12010-11-17 20:29:42 +0000549.. method:: SSLContext.set_default_verify_paths()
550
551 Load a set of default "certification authority" (CA) certificates from
552 a filesystem path defined when building the OpenSSL library. Unfortunately,
553 there's no easy way to know whether this method succeeds: no error is
554 returned if no certificates are to be found. When the OpenSSL library is
555 provided as part of the operating system, though, it is likely to be
556 configured properly.
557
Antoine Pitrou152efa22010-05-16 18:19:27 +0000558.. method:: SSLContext.set_ciphers(ciphers)
559
560 Set the available ciphers for sockets created with this context.
561 It should be a string in the `OpenSSL cipher list format
562 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
563 If no cipher can be selected (because compile-time options or other
564 configuration forbids use of all the specified ciphers), an
565 :class:`SSLError` will be raised.
566
567 .. note::
568 when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
569 give the currently selected cipher.
570
Antoine Pitroud5323212010-10-22 18:19:07 +0000571.. method:: SSLContext.wrap_socket(sock, server_side=False, \
572 do_handshake_on_connect=True, suppress_ragged_eofs=True, \
573 server_hostname=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000574
575 Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
576 object. The SSL socket is tied to the context, its settings and
577 certificates. The parameters *server_side*, *do_handshake_on_connect*
578 and *suppress_ragged_eofs* have the same meaning as in the top-level
579 :func:`wrap_socket` function.
580
Antoine Pitroud5323212010-10-22 18:19:07 +0000581 On client connections, the optional parameter *server_hostname* specifies
582 the hostname of the service which we are connecting to. This allows a
583 single server to host multiple SSL-based services with distinct certificates,
584 quite similarly to HTTP virtual hosts. Specifying *server_hostname*
585 will raise a :exc:`ValueError` if the OpenSSL library doesn't have support
586 for it (that is, if :data:`HAS_SNI` is :const:`False`). Specifying
587 *server_hostname* will also raise a :exc:`ValueError` if *server_side*
588 is true.
589
Antoine Pitroub0182c82010-10-12 20:09:02 +0000590.. method:: SSLContext.session_stats()
591
592 Get statistics about the SSL sessions created or managed by this context.
593 A dictionary is returned which maps the names of each `piece of information
594 <http://www.openssl.org/docs/ssl/SSL_CTX_sess_number.html>`_ to their
595 numeric values. For example, here is the total number of hits and misses
596 in the session cache since the context was created::
597
598 >>> stats = context.session_stats()
599 >>> stats['hits'], stats['misses']
600 (0, 0)
601
Antoine Pitroub5218772010-05-21 09:56:06 +0000602.. attribute:: SSLContext.options
603
604 An integer representing the set of SSL options enabled on this context.
605 The default value is :data:`OP_ALL`, but you can specify other options
606 such as :data:`OP_NO_SSLv2` by ORing them together.
607
608 .. note::
609 With versions of OpenSSL older than 0.9.8m, it is only possible
610 to set options, not to clear them. Attempting to clear an option
611 (by resetting the corresponding bits) will raise a ``ValueError``.
612
Antoine Pitrou152efa22010-05-16 18:19:27 +0000613.. attribute:: SSLContext.protocol
614
615 The protocol version chosen when constructing the context. This attribute
616 is read-only.
617
618.. attribute:: SSLContext.verify_mode
619
620 Whether to try to verify other peers' certificates and how to behave
621 if verification fails. This attribute must be one of
622 :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.
623
624
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000625.. index:: single: certificates
626
627.. index:: single: X509 certificate
628
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000629.. _ssl-certificates:
630
Thomas Woutersed03b412007-08-28 21:37:11 +0000631Certificates
632------------
633
Georg Brandl7f01a132009-09-16 15:58:14 +0000634Certificates in general are part of a public-key / private-key system. In this
635system, each *principal*, (which may be a machine, or a person, or an
636organization) is assigned a unique two-part encryption key. One part of the key
637is public, and is called the *public key*; the other part is kept secret, and is
638called the *private key*. The two parts are related, in that if you encrypt a
639message with one of the parts, you can decrypt it with the other part, and
640**only** with the other part.
Thomas Woutersed03b412007-08-28 21:37:11 +0000641
Georg Brandl7f01a132009-09-16 15:58:14 +0000642A certificate contains information about two principals. It contains the name
643of a *subject*, and the subject's public key. It also contains a statement by a
644second principal, the *issuer*, that the subject is who he claims to be, and
645that this is indeed the subject's public key. The issuer's statement is signed
646with the issuer's private key, which only the issuer knows. However, anyone can
647verify the issuer's statement by finding the issuer's public key, decrypting the
648statement with it, and comparing it to the other information in the certificate.
649The certificate also contains information about the time period over which it is
650valid. This is expressed as two fields, called "notBefore" and "notAfter".
Thomas Woutersed03b412007-08-28 21:37:11 +0000651
Georg Brandl7f01a132009-09-16 15:58:14 +0000652In the Python use of certificates, a client or server can use a certificate to
653prove who they are. The other side of a network connection can also be required
654to produce a certificate, and that certificate can be validated to the
655satisfaction of the client or server that requires such validation. The
656connection attempt can be set to raise an exception if the validation fails.
657Validation is done automatically, by the underlying OpenSSL framework; the
658application need not concern itself with its mechanics. But the application
659does usually need to provide sets of certificates to allow this process to take
660place.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000661
Georg Brandl7f01a132009-09-16 15:58:14 +0000662Python uses files to contain certificates. They should be formatted as "PEM"
663(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
664and a footer line::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000665
666 -----BEGIN CERTIFICATE-----
667 ... (certificate in base64 PEM encoding) ...
668 -----END CERTIFICATE-----
669
Antoine Pitrou152efa22010-05-16 18:19:27 +0000670Certificate chains
671^^^^^^^^^^^^^^^^^^
672
Georg Brandl7f01a132009-09-16 15:58:14 +0000673The Python files which contain certificates can contain a sequence of
674certificates, sometimes called a *certificate chain*. This chain should start
675with the specific certificate for the principal who "is" the client or server,
676and then the certificate for the issuer of that certificate, and then the
677certificate for the issuer of *that* certificate, and so on up the chain till
678you get to a certificate which is *self-signed*, that is, a certificate which
679has the same subject and issuer, sometimes called a *root certificate*. The
680certificates should just be concatenated together in the certificate file. For
681example, suppose we had a three certificate chain, from our server certificate
682to the certificate of the certification authority that signed our server
683certificate, to the root certificate of the agency which issued the
684certification authority's certificate::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000685
686 -----BEGIN CERTIFICATE-----
687 ... (certificate for your server)...
688 -----END CERTIFICATE-----
689 -----BEGIN CERTIFICATE-----
690 ... (the certificate for the CA)...
691 -----END CERTIFICATE-----
692 -----BEGIN CERTIFICATE-----
693 ... (the root certificate for the CA's issuer)...
694 -----END CERTIFICATE-----
695
Antoine Pitrou152efa22010-05-16 18:19:27 +0000696CA certificates
697^^^^^^^^^^^^^^^
698
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000699If you are going to require validation of the other side of the connection's
700certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandl7f01a132009-09-16 15:58:14 +0000701chains for each issuer you are willing to trust. Again, this file just contains
702these chains concatenated together. For validation, Python will use the first
703chain it finds in the file which matches. Some "standard" root certificates are
704available from various certification authorities: `CACert.org
705<http://www.cacert.org/index.php?id=3>`_, `Thawte
706<http://www.thawte.com/roots/>`_, `Verisign
707<http://www.verisign.com/support/roots.html>`_, `Positive SSL
708<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
709(used by python.org), `Equifax and GeoTrust
710<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000711
Georg Brandl7f01a132009-09-16 15:58:14 +0000712In general, if you are using SSL3 or TLS1, you don't need to put the full chain
713in your "CA certs" file; you only need the root certificates, and the remote
714peer is supposed to furnish the other certificates necessary to chain from its
715certificate to a root certificate. See :rfc:`4158` for more discussion of the
716way in which certification chains can be built.
Thomas Woutersed03b412007-08-28 21:37:11 +0000717
Antoine Pitrou152efa22010-05-16 18:19:27 +0000718Combined key and certificate
719^^^^^^^^^^^^^^^^^^^^^^^^^^^^
720
721Often the private key is stored in the same file as the certificate; in this
722case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain`
723and :func:`wrap_socket` needs to be passed. If the private key is stored
724with the certificate, it should come before the first certificate in
725the certificate chain::
726
727 -----BEGIN RSA PRIVATE KEY-----
728 ... (private key in base64 encoding) ...
729 -----END RSA PRIVATE KEY-----
730 -----BEGIN CERTIFICATE-----
731 ... (certificate in base64 PEM encoding) ...
732 -----END CERTIFICATE-----
733
734Self-signed certificates
735^^^^^^^^^^^^^^^^^^^^^^^^
736
Georg Brandl7f01a132009-09-16 15:58:14 +0000737If you are going to create a server that provides SSL-encrypted connection
738services, you will need to acquire a certificate for that service. There are
739many ways of acquiring appropriate certificates, such as buying one from a
740certification authority. Another common practice is to generate a self-signed
741certificate. The simplest way to do this is with the OpenSSL package, using
742something like the following::
Thomas Woutersed03b412007-08-28 21:37:11 +0000743
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000744 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
745 Generating a 1024 bit RSA private key
746 .......++++++
747 .............................++++++
748 writing new private key to 'cert.pem'
749 -----
750 You are about to be asked to enter information that will be incorporated
751 into your certificate request.
752 What you are about to enter is what is called a Distinguished Name or a DN.
753 There are quite a few fields but you can leave some blank
754 For some fields there will be a default value,
755 If you enter '.', the field will be left blank.
756 -----
757 Country Name (2 letter code) [AU]:US
758 State or Province Name (full name) [Some-State]:MyState
759 Locality Name (eg, city) []:Some City
760 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
761 Organizational Unit Name (eg, section) []:My Group
762 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
763 Email Address []:ops@myserver.mygroup.myorganization.com
764 %
Thomas Woutersed03b412007-08-28 21:37:11 +0000765
Georg Brandl7f01a132009-09-16 15:58:14 +0000766The disadvantage of a self-signed certificate is that it is its own root
767certificate, and no one else will have it in their cache of known (and trusted)
768root certificates.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000769
770
Thomas Woutersed03b412007-08-28 21:37:11 +0000771Examples
772--------
773
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000774Testing for SSL support
775^^^^^^^^^^^^^^^^^^^^^^^
776
Georg Brandl7f01a132009-09-16 15:58:14 +0000777To test for the presence of SSL support in a Python installation, user code
778should use the following idiom::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000779
780 try:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000781 import ssl
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000782 except ImportError:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000783 pass
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000784 else:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000785 ... # do something that requires SSL support
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000786
787Client-side operation
788^^^^^^^^^^^^^^^^^^^^^
789
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000790This example connects to an SSL server and prints the server's certificate::
Thomas Woutersed03b412007-08-28 21:37:11 +0000791
792 import socket, ssl, pprint
793
794 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000795 # require a certificate from the server
796 ssl_sock = ssl.wrap_socket(s,
797 ca_certs="/etc/ca_certs_file",
798 cert_reqs=ssl.CERT_REQUIRED)
Thomas Woutersed03b412007-08-28 21:37:11 +0000799 ssl_sock.connect(('www.verisign.com', 443))
800
Georg Brandl6911e3c2007-09-04 07:15:32 +0000801 pprint.pprint(ssl_sock.getpeercert())
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802 # note that closing the SSLSocket will also close the underlying socket
Thomas Woutersed03b412007-08-28 21:37:11 +0000803 ssl_sock.close()
804
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000805As of October 6, 2010, the certificate printed by this program looks like
Georg Brandl7f01a132009-09-16 15:58:14 +0000806this::
Thomas Woutersed03b412007-08-28 21:37:11 +0000807
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000808 {'notAfter': 'May 25 23:59:59 2012 GMT',
809 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
810 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
811 (('businessCategory', 'V1.0, Clause 5.(b)'),),
812 (('serialNumber', '2497886'),),
813 (('countryName', 'US'),),
814 (('postalCode', '94043'),),
815 (('stateOrProvinceName', 'California'),),
816 (('localityName', 'Mountain View'),),
817 (('streetAddress', '487 East Middlefield Road'),),
818 (('organizationName', 'VeriSign, Inc.'),),
819 (('organizationalUnitName', ' Production Security Services'),),
820 (('commonName', 'www.verisign.com'),))}
Thomas Woutersed03b412007-08-28 21:37:11 +0000821
Antoine Pitrou152efa22010-05-16 18:19:27 +0000822This other example first creates an SSL context, instructs it to verify
823certificates sent by peers, and feeds it a set of recognized certificate
824authorities (CA)::
825
826 >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000827 >>> context.verify_mode = ssl.CERT_REQUIRED
Antoine Pitrou152efa22010-05-16 18:19:27 +0000828 >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
829
830(it is assumed your operating system places a bundle of all CA certificates
831in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have
832to adjust the location)
833
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000834When you use the context to connect to a server, :const:`CERT_REQUIRED`
Antoine Pitrou152efa22010-05-16 18:19:27 +0000835validates the server certificate: it ensures that the server certificate
836was signed with one of the CA certificates, and checks the signature for
837correctness::
838
839 >>> conn = context.wrap_socket(socket.socket(socket.AF_INET))
840 >>> conn.connect(("linuxfr.org", 443))
841
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000842You should then fetch the certificate and check its fields for conformity::
Antoine Pitrou152efa22010-05-16 18:19:27 +0000843
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000844 >>> cert = conn.getpeercert()
845 >>> ssl.match_hostname(cert, "linuxfr.org")
846
847Visual inspection shows that the certificate does identify the desired service
848(that is, the HTTPS host ``linuxfr.org``)::
849
850 >>> pprint.pprint(cert)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000851 {'notAfter': 'Jun 26 21:41:46 2011 GMT',
852 'subject': ((('commonName', 'linuxfr.org'),),),
853 'subjectAltName': (('DNS', 'linuxfr.org'), ('othername', '<unsupported>'))}
854
855Now that you are assured of its authenticity, you can proceed to talk with
856the server::
857
Antoine Pitroudab64262010-09-19 13:31:06 +0000858 >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
859 >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
Antoine Pitrou152efa22010-05-16 18:19:27 +0000860 [b'HTTP/1.1 302 Found',
861 b'Date: Sun, 16 May 2010 13:43:28 GMT',
862 b'Server: Apache/2.2',
863 b'Location: https://linuxfr.org/pub/',
864 b'Vary: Accept-Encoding',
865 b'Connection: close',
866 b'Content-Type: text/html; charset=iso-8859-1',
867 b'',
868 b'']
869
Antoine Pitrou152efa22010-05-16 18:19:27 +0000870See the discussion of :ref:`ssl-security` below.
871
872
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000873Server-side operation
874^^^^^^^^^^^^^^^^^^^^^
875
Antoine Pitrou152efa22010-05-16 18:19:27 +0000876For server operation, typically you'll need to have a server certificate, and
877private key, each in a file. You'll first create a context holding the key
878and the certificate, so that clients can check your authenticity. Then
879you'll open a socket, bind it to a port, call :meth:`listen` on it, and start
880waiting for clients to connect::
Thomas Woutersed03b412007-08-28 21:37:11 +0000881
882 import socket, ssl
883
Antoine Pitrou152efa22010-05-16 18:19:27 +0000884 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
885 context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")
886
Thomas Woutersed03b412007-08-28 21:37:11 +0000887 bindsocket = socket.socket()
888 bindsocket.bind(('myaddr.mydomain.com', 10023))
889 bindsocket.listen(5)
890
Antoine Pitrou152efa22010-05-16 18:19:27 +0000891When a client connects, you'll call :meth:`accept` on the socket to get the
892new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket`
893method to create a server-side SSL socket for the connection::
Thomas Woutersed03b412007-08-28 21:37:11 +0000894
895 while True:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000896 newsocket, fromaddr = bindsocket.accept()
897 connstream = context.wrap_socket(newsocket, server_side=True)
898 try:
899 deal_with_client(connstream)
900 finally:
Antoine Pitroub205d582011-01-02 22:09:27 +0000901 connstream.shutdown(socket.SHUT_RDWR)
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000902 connstream.close()
Thomas Woutersed03b412007-08-28 21:37:11 +0000903
Antoine Pitrou152efa22010-05-16 18:19:27 +0000904Then you'll read data from the ``connstream`` and do something with it till you
Georg Brandl7f01a132009-09-16 15:58:14 +0000905are finished with the client (or the client is finished with you)::
Thomas Woutersed03b412007-08-28 21:37:11 +0000906
907 def deal_with_client(connstream):
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000908 data = connstream.recv(1024)
909 # empty data means the client is finished with us
910 while data:
911 if not do_something(connstream, data):
912 # we'll assume do_something returns False
913 # when we're finished with client
914 break
915 data = connstream.recv(1024)
916 # finished with client
Thomas Woutersed03b412007-08-28 21:37:11 +0000917
Antoine Pitrou152efa22010-05-16 18:19:27 +0000918And go back to listening for new client connections (of course, a real server
919would probably handle each client connection in a separate thread, or put
920the sockets in non-blocking mode and use an event loop).
921
922
923.. _ssl-security:
924
925Security considerations
926-----------------------
927
928Verifying certificates
929^^^^^^^^^^^^^^^^^^^^^^
930
931:const:`CERT_NONE` is the default. Since it does not authenticate the other
932peer, it can be insecure, especially in client mode where most of time you
933would like to ensure the authenticity of the server you're talking to.
934Therefore, when in client mode, it is highly recommended to use
935:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000936have to check that the server certificate, which can be obtained by calling
937:meth:`SSLSocket.getpeercert`, matches the desired service. For many
938protocols and applications, the service can be identified by the hostname;
939in this case, the :func:`match_hostname` function can be used.
Antoine Pitrou152efa22010-05-16 18:19:27 +0000940
941In server mode, if you want to authenticate your clients using the SSL layer
942(rather than using a higher-level authentication mechanism), you'll also have
943to specify :const:`CERT_REQUIRED` and similarly check the client certificate.
944
945 .. note::
946
947 In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are
948 equivalent unless anonymous ciphers are enabled (they are disabled
949 by default).
Thomas Woutersed03b412007-08-28 21:37:11 +0000950
Antoine Pitroub5218772010-05-21 09:56:06 +0000951Protocol versions
952^^^^^^^^^^^^^^^^^
953
954SSL version 2 is considered insecure and is therefore dangerous to use. If
955you want maximum compatibility between clients and servers, it is recommended
956to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable
957SSLv2 explicitly using the :data:`SSLContext.options` attribute::
958
959 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
960 context.options |= ssl.OP_NO_SSLv2
961
962The SSL context created above will allow SSLv3 and TLSv1 connections, but
963not SSLv2.
964
Georg Brandl48310cd2009-01-03 21:18:54 +0000965
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000966.. seealso::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000967
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000968 Class :class:`socket.socket`
969 Documentation of underlying :mod:`socket` class
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000970
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000971 `Introducing SSL and Certificates using OpenSSL <http://old.pseudonym.org/ssl/wwwj-index.html>`_
972 Frederick J. Hirsch
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000973
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000974 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
975 Steve Kent
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000976
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000977 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
978 D. Eastlake et. al.
Thomas Wouters89d996e2007-09-08 17:39:28 +0000979
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000980 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
981 Housley et. al.
Antoine Pitroud5323212010-10-22 18:19:07 +0000982
983 `RFC 4366: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc4366>`_
984 Blake-Wilson et. al.