blob: 69eaf8b9302bbdb03cdb312efcd9059accfa2fc3 [file] [log] [blame]
Antoine Pitroue1bc8982011-01-02 22:12:22 +00001:mod:`ssl` --- TLS/SSL wrapper for socket objects
2=================================================
Thomas Woutersed03b412007-08-28 21:37:11 +00003
4.. module:: ssl
Antoine Pitroue1bc8982011-01-02 22:12:22 +00005 :synopsis: TLS/SSL wrapper for socket objects
Thomas Wouters47b49bf2007-08-30 22:15:33 +00006
7.. moduleauthor:: Bill Janssen <bill.janssen@gmail.com>
Thomas Wouters47b49bf2007-08-30 22:15:33 +00008.. sectionauthor:: Bill Janssen <bill.janssen@gmail.com>
9
Thomas Woutersed03b412007-08-28 21:37:11 +000010
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011.. index:: single: OpenSSL; (use in module ssl)
12
13.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
14
Raymond Hettinger469271d2011-01-27 20:38:46 +000015**Source code:** :source:`Lib/ssl.py`
16
17--------------
18
Georg Brandl7f01a132009-09-16 15:58:14 +000019This module provides access to Transport Layer Security (often known as "Secure
20Sockets Layer") encryption and peer authentication facilities for network
21sockets, both client-side and server-side. This module uses the OpenSSL
22library. It is available on all modern Unix systems, Windows, Mac OS X, and
23probably additional platforms, as long as OpenSSL is installed on that platform.
Thomas Woutersed03b412007-08-28 21:37:11 +000024
25.. note::
26
Georg Brandl7f01a132009-09-16 15:58:14 +000027 Some behavior may be platform dependent, since calls are made to the
28 operating system socket APIs. The installed version of OpenSSL may also
29 cause variations in behavior.
Thomas Woutersed03b412007-08-28 21:37:11 +000030
Georg Brandl7f01a132009-09-16 15:58:14 +000031This section documents the objects and functions in the ``ssl`` module; for more
32general information about TLS, SSL, and certificates, the reader is referred to
33the documents in the "See Also" section at the bottom.
Thomas Woutersed03b412007-08-28 21:37:11 +000034
Georg Brandl7f01a132009-09-16 15:58:14 +000035This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
36:class:`socket.socket` type, and provides a socket-like wrapper that also
37encrypts and decrypts the data going over the socket with SSL. It supports
Antoine Pitroudab64262010-09-19 13:31:06 +000038additional methods such as :meth:`getpeercert`, which retrieves the
39certificate of the other side of the connection, and :meth:`cipher`,which
40retrieves the cipher being used for the secure connection.
Thomas Woutersed03b412007-08-28 21:37:11 +000041
Antoine Pitrou152efa22010-05-16 18:19:27 +000042For more sophisticated applications, the :class:`ssl.SSLContext` class
43helps manage settings and certificates, which can then be inherited
44by SSL sockets created through the :meth:`SSLContext.wrap_socket` method.
45
46
Thomas Wouters1b7f8912007-09-19 03:06:30 +000047Functions, Constants, and Exceptions
48------------------------------------
49
50.. exception:: SSLError
51
Antoine Pitrou59fdd672010-10-08 10:37:08 +000052 Raised to signal an error from the underlying SSL implementation
53 (currently provided by the OpenSSL library). This signifies some
54 problem in the higher-level encryption and authentication layer that's
55 superimposed on the underlying network connection. This error
Antoine Pitrou5574c302011-10-12 17:53:43 +020056 is a subtype of :exc:`OSError`. The error code and message of
57 :exc:`SSLError` instances are provided by the OpenSSL library.
58
59 .. versionchanged:: 3.3
60 :exc:`SSLError` used to be a subtype of :exc:`socket.error`.
Antoine Pitrou59fdd672010-10-08 10:37:08 +000061
Antoine Pitrou41032a62011-10-27 23:56:55 +020062.. exception:: SSLZeroReturnError
63
64 A subclass of :exc:`SSLError` raised when trying to read or write and
65 the SSL connection has been closed cleanly. Note that this doesn't
66 mean that the underlying transport (read TCP) has been closed.
67
68 .. versionadded:: 3.3
69
70.. exception:: SSLWantReadError
71
72 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
73 <ssl-nonblocking>` when trying to read or write data, but more data needs
74 to be received on the underlying TCP transport before the request can be
75 fulfilled.
76
77 .. versionadded:: 3.3
78
79.. exception:: SSLWantWriteError
80
81 A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
82 <ssl-nonblocking>` when trying to read or write data, but more data needs
83 to be sent on the underlying TCP transport before the request can be
84 fulfilled.
85
86 .. versionadded:: 3.3
87
88.. exception:: SSLSyscallError
89
90 A subclass of :exc:`SSLError` raised when a system error was encountered
91 while trying to fulfill an operation on a SSL socket. Unfortunately,
92 there is no easy way to inspect the original errno number.
93
94 .. versionadded:: 3.3
95
96.. exception:: SSLEOFError
97
98 A subclass of :exc:`SSLError` raised when the SSL connection has been
Antoine Pitrouf3dc2d72011-10-28 00:01:03 +020099 terminated abruptly. Generally, you shouldn't try to reuse the underlying
Antoine Pitrou41032a62011-10-27 23:56:55 +0200100 transport when this error is encountered.
101
102 .. versionadded:: 3.3
103
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000104.. exception:: CertificateError
105
106 Raised to signal an error with a certificate (such as mismatching
107 hostname). Certificate errors detected by OpenSSL, though, raise
108 an :exc:`SSLError`.
109
110
111Socket creation
112^^^^^^^^^^^^^^^
113
114The following function allows for standalone socket creation. Starting from
115Python 3.2, it can be more flexible to use :meth:`SSLContext.wrap_socket`
116instead.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000117
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000118.. 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 +0000119
Georg Brandl7f01a132009-09-16 15:58:14 +0000120 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
121 of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
122 the underlying socket in an SSL context. For client-side sockets, the
123 context construction is lazy; if the underlying socket isn't connected yet,
124 the context construction will be performed after :meth:`connect` is called on
125 the socket. For server-side sockets, if the socket has no remote peer, it is
126 assumed to be a listening socket, and the server-side SSL wrapping is
127 automatically performed on client connections accepted via the :meth:`accept`
128 method. :func:`wrap_socket` may raise :exc:`SSLError`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000129
Georg Brandl7f01a132009-09-16 15:58:14 +0000130 The ``keyfile`` and ``certfile`` parameters specify optional files which
131 contain a certificate to be used to identify the local side of the
132 connection. See the discussion of :ref:`ssl-certificates` for more
133 information on how the certificate is stored in the ``certfile``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000134
Georg Brandl7f01a132009-09-16 15:58:14 +0000135 The parameter ``server_side`` is a boolean which identifies whether
136 server-side or client-side behavior is desired from this socket.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000137
Georg Brandl7f01a132009-09-16 15:58:14 +0000138 The parameter ``cert_reqs`` specifies whether a certificate is required from
139 the other side of the connection, and whether it will be validated if
140 provided. It must be one of the three values :const:`CERT_NONE`
141 (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
142 if provided), or :const:`CERT_REQUIRED` (required and validated). If the
143 value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
144 parameter must point to a file of CA certificates.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000145
Georg Brandl7f01a132009-09-16 15:58:14 +0000146 The ``ca_certs`` file contains a set of concatenated "certification
147 authority" certificates, which are used to validate certificates passed from
148 the other end of the connection. See the discussion of
149 :ref:`ssl-certificates` for more information about how to arrange the
150 certificates in this file.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000151
Georg Brandl7f01a132009-09-16 15:58:14 +0000152 The parameter ``ssl_version`` specifies which version of the SSL protocol to
153 use. Typically, the server chooses a particular protocol version, and the
154 client must adapt to the server's choice. Most of the versions are not
155 interoperable with the other versions. If not specified, for client-side
156 operation, the default SSL version is SSLv3; for server-side operation,
157 SSLv23. These version selections provide the most compatibility with other
158 versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000159
Georg Brandl7f01a132009-09-16 15:58:14 +0000160 Here's a table showing which versions in a client (down the side) can connect
161 to which versions in a server (along the top):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000162
163 .. table::
164
165 ======================== ========= ========= ========== =========
166 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1**
Christian Heimes255f53b2007-12-08 15:33:56 +0000167 ------------------------ --------- --------- ---------- ---------
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000168 *SSLv2* yes no yes no
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000169 *SSLv3* yes yes yes no
170 *SSLv23* yes no yes no
171 *TLSv1* no no yes yes
172 ======================== ========= ========= ========== =========
173
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000174 .. note::
175
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000176 Which connections succeed will vary depending on the version of
177 OpenSSL. For instance, in some older versions of OpenSSL (such
178 as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an
179 SSLv23 server. Another example: beginning with OpenSSL 1.0.0,
180 an SSLv23 client will not actually attempt SSLv2 connections
181 unless you explicitly enable SSLv2 ciphers; for example, you
182 might specify ``"ALL"`` or ``"SSLv2"`` as the *ciphers* parameter
183 to enable them.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000184
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000185 The *ciphers* parameter sets the available ciphers for this SSL object.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000186 It should be a string in the `OpenSSL cipher list format
187 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000188
Bill Janssen48dc27c2007-12-05 03:38:10 +0000189 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
190 handshake automatically after doing a :meth:`socket.connect`, or whether the
Georg Brandl7f01a132009-09-16 15:58:14 +0000191 application program will call it explicitly, by invoking the
192 :meth:`SSLSocket.do_handshake` method. Calling
193 :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
194 blocking behavior of the socket I/O involved in the handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000195
Georg Brandl7f01a132009-09-16 15:58:14 +0000196 The parameter ``suppress_ragged_eofs`` specifies how the
Antoine Pitroudab64262010-09-19 13:31:06 +0000197 :meth:`SSLSocket.recv` method should signal unexpected EOF from the other end
Georg Brandl7f01a132009-09-16 15:58:14 +0000198 of the connection. If specified as :const:`True` (the default), it returns a
Antoine Pitroudab64262010-09-19 13:31:06 +0000199 normal EOF (an empty bytes object) in response to unexpected EOF errors
200 raised from the underlying socket; if :const:`False`, it will raise the
201 exceptions back to the caller.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000202
Ezio Melotti4d5195b2010-04-20 10:57:44 +0000203 .. versionchanged:: 3.2
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000204 New optional argument *ciphers*.
205
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000206Random generation
207^^^^^^^^^^^^^^^^^
208
Victor Stinner99c8b162011-05-24 12:05:19 +0200209.. function:: RAND_bytes(num)
210
Victor Stinnera6752062011-05-25 11:27:40 +0200211 Returns *num* cryptographically strong pseudo-random bytes. Raises an
212 :class:`SSLError` if the PRNG has not been seeded with enough data or if the
213 operation is not supported by the current RAND method. :func:`RAND_status`
214 can be used to check the status of the PRNG and :func:`RAND_add` can be used
215 to seed the PRNG.
Victor Stinner99c8b162011-05-24 12:05:19 +0200216
Victor Stinner19fb53c2011-05-24 21:32:40 +0200217 Read the Wikipedia article, `Cryptographically secure pseudorandom number
Victor Stinnera6752062011-05-25 11:27:40 +0200218 generator (CSPRNG)
Victor Stinner19fb53c2011-05-24 21:32:40 +0200219 <http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator>`_,
220 to get the requirements of a cryptographically generator.
221
Victor Stinner99c8b162011-05-24 12:05:19 +0200222 .. versionadded:: 3.3
223
224.. function:: RAND_pseudo_bytes(num)
225
226 Returns (bytes, is_cryptographic): bytes are *num* pseudo-random bytes,
227 is_cryptographic is True if the bytes generated are cryptographically
Victor Stinnera6752062011-05-25 11:27:40 +0200228 strong. Raises an :class:`SSLError` if the operation is not supported by the
229 current RAND method.
Victor Stinner99c8b162011-05-24 12:05:19 +0200230
Victor Stinner19fb53c2011-05-24 21:32:40 +0200231 Generated pseudo-random byte sequences will be unique if they are of
232 sufficient length, but are not necessarily unpredictable. They can be used
233 for non-cryptographic purposes and for certain purposes in cryptographic
234 protocols, but usually not for key generation etc.
235
Victor Stinner99c8b162011-05-24 12:05:19 +0200236 .. versionadded:: 3.3
237
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000238.. function:: RAND_status()
239
Georg Brandl7f01a132009-09-16 15:58:14 +0000240 Returns True if the SSL pseudo-random number generator has been seeded with
241 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
242 and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
243 number generator.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000244
245.. function:: RAND_egd(path)
246
Victor Stinner99c8b162011-05-24 12:05:19 +0200247 If you are running an entropy-gathering daemon (EGD) somewhere, and *path*
Georg Brandl7f01a132009-09-16 15:58:14 +0000248 is the pathname of a socket connection open to it, this will read 256 bytes
249 of randomness from the socket, and add it to the SSL pseudo-random number
250 generator to increase the security of generated secret keys. This is
251 typically only necessary on systems without better sources of randomness.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000252
Georg Brandl7f01a132009-09-16 15:58:14 +0000253 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
254 of entropy-gathering daemons.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000255
256.. function:: RAND_add(bytes, entropy)
257
Victor Stinner99c8b162011-05-24 12:05:19 +0200258 Mixes the given *bytes* into the SSL pseudo-random number generator. The
259 parameter *entropy* (a float) is a lower bound on the entropy contained in
Georg Brandl7f01a132009-09-16 15:58:14 +0000260 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
261 information on sources of entropy.
Thomas Woutersed03b412007-08-28 21:37:11 +0000262
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000263Certificate handling
264^^^^^^^^^^^^^^^^^^^^
265
266.. function:: match_hostname(cert, hostname)
267
268 Verify that *cert* (in decoded format as returned by
269 :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules
270 applied are those for checking the identity of HTTPS servers as outlined
271 in :rfc:`2818`, except that IP addresses are not currently supported.
272 In addition to HTTPS, this function should be suitable for checking the
273 identity of servers in various SSL-based protocols such as FTPS, IMAPS,
274 POPS and others.
275
276 :exc:`CertificateError` is raised on failure. On success, the function
277 returns nothing::
278
279 >>> cert = {'subject': ((('commonName', 'example.com'),),)}
280 >>> ssl.match_hostname(cert, "example.com")
281 >>> ssl.match_hostname(cert, "example.org")
282 Traceback (most recent call last):
283 File "<stdin>", line 1, in <module>
284 File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
285 ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'
286
287 .. versionadded:: 3.2
288
Thomas Woutersed03b412007-08-28 21:37:11 +0000289.. function:: cert_time_to_seconds(timestring)
290
Georg Brandl7f01a132009-09-16 15:58:14 +0000291 Returns a floating-point value containing a normal seconds-after-the-epoch
292 time value, given the time-string representing the "notBefore" or "notAfter"
293 date from a certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000294
295 Here's an example::
296
297 >>> import ssl
298 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
299 1178694000.0
300 >>> import time
301 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
302 'Wed May 9 00:00:00 2007'
Thomas Woutersed03b412007-08-28 21:37:11 +0000303
Georg Brandl7f01a132009-09-16 15:58:14 +0000304.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000305
Georg Brandl7f01a132009-09-16 15:58:14 +0000306 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
307 *port-number*) pair, fetches the server's certificate, and returns it as a
308 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
309 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
310 specified, it should be a file containing a list of root certificates, the
311 same format as used for the same parameter in :func:`wrap_socket`. The call
312 will attempt to validate the server certificate against that set of root
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000313 certificates, and will fail if the validation attempt fails.
314
Antoine Pitrou15399c32011-04-28 19:23:55 +0200315 .. versionchanged:: 3.3
316 This function is now IPv6-compatible.
317
Georg Brandl7f01a132009-09-16 15:58:14 +0000318.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000319
320 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
321 string version of the same certificate.
322
Georg Brandl7f01a132009-09-16 15:58:14 +0000323.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000324
Georg Brandl7f01a132009-09-16 15:58:14 +0000325 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
326 bytes for that same certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000327
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000328Constants
329^^^^^^^^^
330
Thomas Woutersed03b412007-08-28 21:37:11 +0000331.. data:: CERT_NONE
332
Antoine Pitrou152efa22010-05-16 18:19:27 +0000333 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
334 parameter to :func:`wrap_socket`. In this mode (the default), no
335 certificates will be required from the other side of the socket connection.
336 If a certificate is received from the other end, no attempt to validate it
337 is made.
338
339 See the discussion of :ref:`ssl-security` below.
Thomas Woutersed03b412007-08-28 21:37:11 +0000340
341.. data:: CERT_OPTIONAL
342
Antoine Pitrou152efa22010-05-16 18:19:27 +0000343 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
344 parameter to :func:`wrap_socket`. In this mode no certificates will be
345 required from the other side of the socket connection; but if they
346 are provided, validation will be attempted and an :class:`SSLError`
347 will be raised on failure.
348
349 Use of this setting requires a valid set of CA certificates to
350 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
351 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000352
353.. data:: CERT_REQUIRED
354
Antoine Pitrou152efa22010-05-16 18:19:27 +0000355 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
356 parameter to :func:`wrap_socket`. In this mode, certificates are
357 required from the other side of the socket connection; an :class:`SSLError`
358 will be raised if no certificate is provided, or if its validation fails.
359
360 Use of this setting requires a valid set of CA certificates to
361 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
362 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000363
364.. data:: PROTOCOL_SSLv2
365
366 Selects SSL version 2 as the channel encryption protocol.
367
Victor Stinner3de49192011-05-09 00:42:58 +0200368 This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
369 flag.
370
Antoine Pitrou8eac60d2010-05-16 14:19:41 +0000371 .. warning::
372
373 SSL version 2 is insecure. Its use is highly discouraged.
374
Thomas Woutersed03b412007-08-28 21:37:11 +0000375.. data:: PROTOCOL_SSLv23
376
Georg Brandl7f01a132009-09-16 15:58:14 +0000377 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
378 setting to use with servers for maximum compatibility with the other end of
379 an SSL connection, but it may cause the specific ciphers chosen for the
380 encryption to be of fairly low quality.
Thomas Woutersed03b412007-08-28 21:37:11 +0000381
382.. data:: PROTOCOL_SSLv3
383
Georg Brandl7f01a132009-09-16 15:58:14 +0000384 Selects SSL version 3 as the channel encryption protocol. For clients, this
385 is the maximally compatible SSL variant.
Thomas Woutersed03b412007-08-28 21:37:11 +0000386
387.. data:: PROTOCOL_TLSv1
388
Georg Brandl7f01a132009-09-16 15:58:14 +0000389 Selects TLS version 1 as the channel encryption protocol. This is the most
390 modern version, and probably the best choice for maximum protection, if both
391 sides can speak it.
Thomas Woutersed03b412007-08-28 21:37:11 +0000392
Antoine Pitroub5218772010-05-21 09:56:06 +0000393.. data:: OP_ALL
394
395 Enables workarounds for various bugs present in other SSL implementations.
396 This option is set by default.
397
398 .. versionadded:: 3.2
399
400.. data:: OP_NO_SSLv2
401
402 Prevents an SSLv2 connection. This option is only applicable in
403 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
404 choosing SSLv2 as the protocol version.
405
406 .. versionadded:: 3.2
407
408.. data:: OP_NO_SSLv3
409
410 Prevents an SSLv3 connection. This option is only applicable in
411 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
412 choosing SSLv3 as the protocol version.
413
414 .. versionadded:: 3.2
415
416.. data:: OP_NO_TLSv1
417
418 Prevents a TLSv1 connection. This option is only applicable in
419 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
420 choosing TLSv1 as the protocol version.
421
422 .. versionadded:: 3.2
423
Antoine Pitrou6db49442011-12-19 13:27:11 +0100424.. data:: OP_CIPHER_SERVER_PREFERENCE
425
426 Use the server's cipher ordering preference, rather than the client's.
427 This option has no effect on client sockets and SSLv2 server sockets.
428
429 .. versionadded:: 3.3
430
Antoine Pitroud5323212010-10-22 18:19:07 +0000431.. data:: HAS_SNI
432
433 Whether the OpenSSL library has built-in support for the *Server Name
434 Indication* extension to the SSLv3 and TLSv1 protocols (as defined in
435 :rfc:`4366`). When true, you can use the *server_hostname* argument to
436 :meth:`SSLContext.wrap_socket`.
437
438 .. versionadded:: 3.2
439
Antoine Pitroud6494802011-07-21 01:11:30 +0200440.. data:: CHANNEL_BINDING_TYPES
441
442 List of supported TLS channel binding types. Strings in this list
443 can be used as arguments to :meth:`SSLSocket.get_channel_binding`.
444
445 .. versionadded:: 3.3
446
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000447.. data:: OPENSSL_VERSION
448
449 The version string of the OpenSSL library loaded by the interpreter::
450
451 >>> ssl.OPENSSL_VERSION
452 'OpenSSL 0.9.8k 25 Mar 2009'
453
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000454 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000455
456.. data:: OPENSSL_VERSION_INFO
457
458 A tuple of five integers representing version information about the
459 OpenSSL library::
460
461 >>> ssl.OPENSSL_VERSION_INFO
462 (0, 9, 8, 11, 15)
463
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000464 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000465
466.. data:: OPENSSL_VERSION_NUMBER
467
468 The raw version number of the OpenSSL library, as a single integer::
469
470 >>> ssl.OPENSSL_VERSION_NUMBER
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000471 9470143
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000472 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000473 '0x9080bf'
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000474
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000475 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000476
Thomas Woutersed03b412007-08-28 21:37:11 +0000477
Antoine Pitrou152efa22010-05-16 18:19:27 +0000478SSL Sockets
479-----------
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000480
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000481SSL sockets provide the following methods of :ref:`socket-objects`:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000482
Antoine Pitroue1f2f302010-09-19 13:56:11 +0000483- :meth:`~socket.socket.accept()`
484- :meth:`~socket.socket.bind()`
485- :meth:`~socket.socket.close()`
486- :meth:`~socket.socket.connect()`
487- :meth:`~socket.socket.detach()`
488- :meth:`~socket.socket.fileno()`
489- :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`
490- :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`
491- :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`,
492 :meth:`~socket.socket.setblocking()`
493- :meth:`~socket.socket.listen()`
494- :meth:`~socket.socket.makefile()`
495- :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()`
496 (but passing a non-zero ``flags`` argument is not allowed)
497- :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with
498 the same limitation)
499- :meth:`~socket.socket.shutdown()`
500
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +0200501However, since the SSL (and TLS) protocol has its own framing atop
502of TCP, the SSL sockets abstraction can, in certain respects, diverge from
503the specification of normal, OS-level sockets. See especially the
504:ref:`notes on non-blocking sockets <ssl-nonblocking>`.
505
506SSL sockets also have the following additional methods and attributes:
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000507
Bill Janssen48dc27c2007-12-05 03:38:10 +0000508.. method:: SSLSocket.do_handshake()
509
Antoine Pitroub3593ca2011-07-11 01:39:19 +0200510 Perform the SSL setup handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000511
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000512.. method:: SSLSocket.getpeercert(binary_form=False)
513
Georg Brandl7f01a132009-09-16 15:58:14 +0000514 If there is no certificate for the peer on the other end of the connection,
515 returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000516
Georg Brandl7f01a132009-09-16 15:58:14 +0000517 If the parameter ``binary_form`` is :const:`False`, and a certificate was
518 received from the peer, this method returns a :class:`dict` instance. If the
519 certificate was not validated, the dict is empty. If the certificate was
520 validated, it returns a dict with the keys ``subject`` (the principal for
521 which the certificate was issued), and ``notAfter`` (the time after which the
Antoine Pitroufb046912010-11-09 20:21:19 +0000522 certificate should not be trusted). If a certificate contains an instance
523 of the *Subject Alternative Name* extension (see :rfc:`3280`), there will
524 also be a ``subjectAltName`` key in the dictionary.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000525
526 The "subject" field is a tuple containing the sequence of relative
Georg Brandl7f01a132009-09-16 15:58:14 +0000527 distinguished names (RDNs) given in the certificate's data structure for the
528 principal, and each RDN is a sequence of name-value pairs::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000529
530 {'notAfter': 'Feb 16 16:54:50 2013 GMT',
Ezio Melotti985e24d2009-09-13 07:54:02 +0000531 'subject': ((('countryName', 'US'),),
532 (('stateOrProvinceName', 'Delaware'),),
533 (('localityName', 'Wilmington'),),
534 (('organizationName', 'Python Software Foundation'),),
535 (('organizationalUnitName', 'SSL'),),
536 (('commonName', 'somemachine.python.org'),))}
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537
Georg Brandl7f01a132009-09-16 15:58:14 +0000538 If the ``binary_form`` parameter is :const:`True`, and a certificate was
539 provided, this method returns the DER-encoded form of the entire certificate
540 as a sequence of bytes, or :const:`None` if the peer did not provide a
541 certificate. This return value is independent of validation; if validation
542 was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000543 been validated, but if :const:`CERT_NONE` was used to establish the
544 connection, the certificate, if present, will not have been validated.
545
Antoine Pitroufb046912010-11-09 20:21:19 +0000546 .. versionchanged:: 3.2
547 The returned dictionary includes additional items such as ``issuer``
548 and ``notBefore``.
549
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000550.. method:: SSLSocket.cipher()
551
Georg Brandl7f01a132009-09-16 15:58:14 +0000552 Returns a three-value tuple containing the name of the cipher being used, the
553 version of the SSL protocol that defines its use, and the number of secret
554 bits being used. If no connection has been established, returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000555
Antoine Pitroud6494802011-07-21 01:11:30 +0200556.. method:: SSLSocket.get_channel_binding(cb_type="tls-unique")
557
558 Get channel binding data for current connection, as a bytes object. Returns
559 ``None`` if not connected or the handshake has not been completed.
560
561 The *cb_type* parameter allow selection of the desired channel binding
562 type. Valid channel binding types are listed in the
563 :data:`CHANNEL_BINDING_TYPES` list. Currently only the 'tls-unique' channel
564 binding, defined by :rfc:`5929`, is supported. :exc:`ValueError` will be
565 raised if an unsupported channel binding type is requested.
566
567 .. versionadded:: 3.3
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000568
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000569.. method:: SSLSocket.unwrap()
570
Georg Brandl7f01a132009-09-16 15:58:14 +0000571 Performs the SSL shutdown handshake, which removes the TLS layer from the
572 underlying socket, and returns the underlying socket object. This can be
573 used to go from encrypted operation over a connection to unencrypted. The
574 returned socket should always be used for further communication with the
575 other side of the connection, rather than the original socket.
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000576
Antoine Pitrou152efa22010-05-16 18:19:27 +0000577
Antoine Pitrouec883db2010-05-24 21:20:20 +0000578.. attribute:: SSLSocket.context
579
580 The :class:`SSLContext` object this SSL socket is tied to. If the SSL
581 socket was created using the top-level :func:`wrap_socket` function
582 (rather than :meth:`SSLContext.wrap_socket`), this is a custom context
583 object created for this SSL socket.
584
585 .. versionadded:: 3.2
586
587
Antoine Pitrou152efa22010-05-16 18:19:27 +0000588SSL Contexts
589------------
590
Antoine Pitroucafaad42010-05-24 15:58:43 +0000591.. versionadded:: 3.2
592
Antoine Pitroub0182c82010-10-12 20:09:02 +0000593An SSL context holds various data longer-lived than single SSL connections,
594such as SSL configuration options, certificate(s) and private key(s).
595It also manages a cache of SSL sessions for server-side sockets, in order
596to speed up repeated connections from the same clients.
597
Antoine Pitrou152efa22010-05-16 18:19:27 +0000598.. class:: SSLContext(protocol)
599
Antoine Pitroub0182c82010-10-12 20:09:02 +0000600 Create a new SSL context. You must pass *protocol* which must be one
601 of the ``PROTOCOL_*`` constants defined in this module.
602 :data:`PROTOCOL_SSLv23` is recommended for maximum interoperability.
603
Antoine Pitrou152efa22010-05-16 18:19:27 +0000604
605:class:`SSLContext` objects have the following methods and attributes:
606
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200607.. method:: SSLContext.load_cert_chain(certfile, keyfile=None, password=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000608
609 Load a private key and the corresponding certificate. The *certfile*
610 string must be the path to a single file in PEM format containing the
611 certificate as well as any number of CA certificates needed to establish
612 the certificate's authenticity. The *keyfile* string, if present, must
613 point to a file containing the private key in. Otherwise the private
614 key will be taken from *certfile* as well. See the discussion of
615 :ref:`ssl-certificates` for more information on how the certificate
616 is stored in the *certfile*.
617
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200618 The *password* argument may be a function to call to get the password for
619 decrypting the private key. It will only be called if the private key is
620 encrypted and a password is necessary. It will be called with no arguments,
621 and it should return a string, bytes, or bytearray. If the return value is
622 a string it will be encoded as UTF-8 before using it to decrypt the key.
623 Alternatively a string, bytes, or bytearray value may be supplied directly
624 as the *password* argument. It will be ignored if the private key is not
625 encrypted and no password is needed.
626
627 If the *password* argument is not specified and a password is required,
628 OpenSSL's built-in password prompting mechanism will be used to
629 interactively prompt the user for a password.
630
Antoine Pitrou152efa22010-05-16 18:19:27 +0000631 An :class:`SSLError` is raised if the private key doesn't
632 match with the certificate.
633
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +0200634 .. versionchanged:: 3.3
635 New optional argument *password*.
636
Antoine Pitrou152efa22010-05-16 18:19:27 +0000637.. method:: SSLContext.load_verify_locations(cafile=None, capath=None)
638
639 Load a set of "certification authority" (CA) certificates used to validate
640 other peers' certificates when :data:`verify_mode` is other than
641 :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified.
642
643 The *cafile* string, if present, is the path to a file of concatenated
644 CA certificates in PEM format. See the discussion of
645 :ref:`ssl-certificates` for more information about how to arrange the
646 certificates in this file.
647
648 The *capath* string, if present, is
649 the path to a directory containing several CA certificates in PEM format,
650 following an `OpenSSL specific layout
651 <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
652
Antoine Pitrou664c2d12010-11-17 20:29:42 +0000653.. method:: SSLContext.set_default_verify_paths()
654
655 Load a set of default "certification authority" (CA) certificates from
656 a filesystem path defined when building the OpenSSL library. Unfortunately,
657 there's no easy way to know whether this method succeeds: no error is
658 returned if no certificates are to be found. When the OpenSSL library is
659 provided as part of the operating system, though, it is likely to be
660 configured properly.
661
Antoine Pitrou152efa22010-05-16 18:19:27 +0000662.. method:: SSLContext.set_ciphers(ciphers)
663
664 Set the available ciphers for sockets created with this context.
665 It should be a string in the `OpenSSL cipher list format
666 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
667 If no cipher can be selected (because compile-time options or other
668 configuration forbids use of all the specified ciphers), an
669 :class:`SSLError` will be raised.
670
671 .. note::
672 when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
673 give the currently selected cipher.
674
Antoine Pitroud5323212010-10-22 18:19:07 +0000675.. method:: SSLContext.wrap_socket(sock, server_side=False, \
676 do_handshake_on_connect=True, suppress_ragged_eofs=True, \
677 server_hostname=None)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000678
679 Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
680 object. The SSL socket is tied to the context, its settings and
681 certificates. The parameters *server_side*, *do_handshake_on_connect*
682 and *suppress_ragged_eofs* have the same meaning as in the top-level
683 :func:`wrap_socket` function.
684
Antoine Pitroud5323212010-10-22 18:19:07 +0000685 On client connections, the optional parameter *server_hostname* specifies
686 the hostname of the service which we are connecting to. This allows a
687 single server to host multiple SSL-based services with distinct certificates,
688 quite similarly to HTTP virtual hosts. Specifying *server_hostname*
689 will raise a :exc:`ValueError` if the OpenSSL library doesn't have support
690 for it (that is, if :data:`HAS_SNI` is :const:`False`). Specifying
691 *server_hostname* will also raise a :exc:`ValueError` if *server_side*
692 is true.
693
Antoine Pitroub0182c82010-10-12 20:09:02 +0000694.. method:: SSLContext.session_stats()
695
696 Get statistics about the SSL sessions created or managed by this context.
697 A dictionary is returned which maps the names of each `piece of information
698 <http://www.openssl.org/docs/ssl/SSL_CTX_sess_number.html>`_ to their
699 numeric values. For example, here is the total number of hits and misses
700 in the session cache since the context was created::
701
702 >>> stats = context.session_stats()
703 >>> stats['hits'], stats['misses']
704 (0, 0)
705
Antoine Pitroub5218772010-05-21 09:56:06 +0000706.. attribute:: SSLContext.options
707
708 An integer representing the set of SSL options enabled on this context.
709 The default value is :data:`OP_ALL`, but you can specify other options
710 such as :data:`OP_NO_SSLv2` by ORing them together.
711
712 .. note::
713 With versions of OpenSSL older than 0.9.8m, it is only possible
714 to set options, not to clear them. Attempting to clear an option
715 (by resetting the corresponding bits) will raise a ``ValueError``.
716
Antoine Pitrou152efa22010-05-16 18:19:27 +0000717.. attribute:: SSLContext.protocol
718
719 The protocol version chosen when constructing the context. This attribute
720 is read-only.
721
722.. attribute:: SSLContext.verify_mode
723
724 Whether to try to verify other peers' certificates and how to behave
725 if verification fails. This attribute must be one of
726 :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.
727
728
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000729.. index:: single: certificates
730
731.. index:: single: X509 certificate
732
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000733.. _ssl-certificates:
734
Thomas Woutersed03b412007-08-28 21:37:11 +0000735Certificates
736------------
737
Georg Brandl7f01a132009-09-16 15:58:14 +0000738Certificates in general are part of a public-key / private-key system. In this
739system, each *principal*, (which may be a machine, or a person, or an
740organization) is assigned a unique two-part encryption key. One part of the key
741is public, and is called the *public key*; the other part is kept secret, and is
742called the *private key*. The two parts are related, in that if you encrypt a
743message with one of the parts, you can decrypt it with the other part, and
744**only** with the other part.
Thomas Woutersed03b412007-08-28 21:37:11 +0000745
Georg Brandl7f01a132009-09-16 15:58:14 +0000746A certificate contains information about two principals. It contains the name
747of a *subject*, and the subject's public key. It also contains a statement by a
748second principal, the *issuer*, that the subject is who he claims to be, and
749that this is indeed the subject's public key. The issuer's statement is signed
750with the issuer's private key, which only the issuer knows. However, anyone can
751verify the issuer's statement by finding the issuer's public key, decrypting the
752statement with it, and comparing it to the other information in the certificate.
753The certificate also contains information about the time period over which it is
754valid. This is expressed as two fields, called "notBefore" and "notAfter".
Thomas Woutersed03b412007-08-28 21:37:11 +0000755
Georg Brandl7f01a132009-09-16 15:58:14 +0000756In the Python use of certificates, a client or server can use a certificate to
757prove who they are. The other side of a network connection can also be required
758to produce a certificate, and that certificate can be validated to the
759satisfaction of the client or server that requires such validation. The
760connection attempt can be set to raise an exception if the validation fails.
761Validation is done automatically, by the underlying OpenSSL framework; the
762application need not concern itself with its mechanics. But the application
763does usually need to provide sets of certificates to allow this process to take
764place.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000765
Georg Brandl7f01a132009-09-16 15:58:14 +0000766Python uses files to contain certificates. They should be formatted as "PEM"
767(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
768and a footer line::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000769
770 -----BEGIN CERTIFICATE-----
771 ... (certificate in base64 PEM encoding) ...
772 -----END CERTIFICATE-----
773
Antoine Pitrou152efa22010-05-16 18:19:27 +0000774Certificate chains
775^^^^^^^^^^^^^^^^^^
776
Georg Brandl7f01a132009-09-16 15:58:14 +0000777The Python files which contain certificates can contain a sequence of
778certificates, sometimes called a *certificate chain*. This chain should start
779with the specific certificate for the principal who "is" the client or server,
780and then the certificate for the issuer of that certificate, and then the
781certificate for the issuer of *that* certificate, and so on up the chain till
782you get to a certificate which is *self-signed*, that is, a certificate which
783has the same subject and issuer, sometimes called a *root certificate*. The
784certificates should just be concatenated together in the certificate file. For
785example, suppose we had a three certificate chain, from our server certificate
786to the certificate of the certification authority that signed our server
787certificate, to the root certificate of the agency which issued the
788certification authority's certificate::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000789
790 -----BEGIN CERTIFICATE-----
791 ... (certificate for your server)...
792 -----END CERTIFICATE-----
793 -----BEGIN CERTIFICATE-----
794 ... (the certificate for the CA)...
795 -----END CERTIFICATE-----
796 -----BEGIN CERTIFICATE-----
797 ... (the root certificate for the CA's issuer)...
798 -----END CERTIFICATE-----
799
Antoine Pitrou152efa22010-05-16 18:19:27 +0000800CA certificates
801^^^^^^^^^^^^^^^
802
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000803If you are going to require validation of the other side of the connection's
804certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandl7f01a132009-09-16 15:58:14 +0000805chains for each issuer you are willing to trust. Again, this file just contains
806these chains concatenated together. For validation, Python will use the first
807chain it finds in the file which matches. Some "standard" root certificates are
808available from various certification authorities: `CACert.org
809<http://www.cacert.org/index.php?id=3>`_, `Thawte
810<http://www.thawte.com/roots/>`_, `Verisign
811<http://www.verisign.com/support/roots.html>`_, `Positive SSL
812<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
813(used by python.org), `Equifax and GeoTrust
814<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000815
Georg Brandl7f01a132009-09-16 15:58:14 +0000816In general, if you are using SSL3 or TLS1, you don't need to put the full chain
817in your "CA certs" file; you only need the root certificates, and the remote
818peer is supposed to furnish the other certificates necessary to chain from its
819certificate to a root certificate. See :rfc:`4158` for more discussion of the
820way in which certification chains can be built.
Thomas Woutersed03b412007-08-28 21:37:11 +0000821
Antoine Pitrou152efa22010-05-16 18:19:27 +0000822Combined key and certificate
823^^^^^^^^^^^^^^^^^^^^^^^^^^^^
824
825Often the private key is stored in the same file as the certificate; in this
826case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain`
827and :func:`wrap_socket` needs to be passed. If the private key is stored
828with the certificate, it should come before the first certificate in
829the certificate chain::
830
831 -----BEGIN RSA PRIVATE KEY-----
832 ... (private key in base64 encoding) ...
833 -----END RSA PRIVATE KEY-----
834 -----BEGIN CERTIFICATE-----
835 ... (certificate in base64 PEM encoding) ...
836 -----END CERTIFICATE-----
837
838Self-signed certificates
839^^^^^^^^^^^^^^^^^^^^^^^^
840
Georg Brandl7f01a132009-09-16 15:58:14 +0000841If you are going to create a server that provides SSL-encrypted connection
842services, you will need to acquire a certificate for that service. There are
843many ways of acquiring appropriate certificates, such as buying one from a
844certification authority. Another common practice is to generate a self-signed
845certificate. The simplest way to do this is with the OpenSSL package, using
846something like the following::
Thomas Woutersed03b412007-08-28 21:37:11 +0000847
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000848 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
849 Generating a 1024 bit RSA private key
850 .......++++++
851 .............................++++++
852 writing new private key to 'cert.pem'
853 -----
854 You are about to be asked to enter information that will be incorporated
855 into your certificate request.
856 What you are about to enter is what is called a Distinguished Name or a DN.
857 There are quite a few fields but you can leave some blank
858 For some fields there will be a default value,
859 If you enter '.', the field will be left blank.
860 -----
861 Country Name (2 letter code) [AU]:US
862 State or Province Name (full name) [Some-State]:MyState
863 Locality Name (eg, city) []:Some City
864 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
865 Organizational Unit Name (eg, section) []:My Group
866 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
867 Email Address []:ops@myserver.mygroup.myorganization.com
868 %
Thomas Woutersed03b412007-08-28 21:37:11 +0000869
Georg Brandl7f01a132009-09-16 15:58:14 +0000870The disadvantage of a self-signed certificate is that it is its own root
871certificate, and no one else will have it in their cache of known (and trusted)
872root certificates.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000873
874
Thomas Woutersed03b412007-08-28 21:37:11 +0000875Examples
876--------
877
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000878Testing for SSL support
879^^^^^^^^^^^^^^^^^^^^^^^
880
Georg Brandl7f01a132009-09-16 15:58:14 +0000881To test for the presence of SSL support in a Python installation, user code
882should use the following idiom::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000883
884 try:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000885 import ssl
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000886 except ImportError:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000887 pass
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000888 else:
Georg Brandl8a7e5da2011-01-02 19:07:51 +0000889 ... # do something that requires SSL support
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000890
891Client-side operation
892^^^^^^^^^^^^^^^^^^^^^
893
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000894This example connects to an SSL server and prints the server's certificate::
Thomas Woutersed03b412007-08-28 21:37:11 +0000895
896 import socket, ssl, pprint
897
898 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000899 # require a certificate from the server
900 ssl_sock = ssl.wrap_socket(s,
901 ca_certs="/etc/ca_certs_file",
902 cert_reqs=ssl.CERT_REQUIRED)
Thomas Woutersed03b412007-08-28 21:37:11 +0000903 ssl_sock.connect(('www.verisign.com', 443))
904
Georg Brandl6911e3c2007-09-04 07:15:32 +0000905 pprint.pprint(ssl_sock.getpeercert())
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000906 # note that closing the SSLSocket will also close the underlying socket
Thomas Woutersed03b412007-08-28 21:37:11 +0000907 ssl_sock.close()
908
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000909As of October 6, 2010, the certificate printed by this program looks like
Georg Brandl7f01a132009-09-16 15:58:14 +0000910this::
Thomas Woutersed03b412007-08-28 21:37:11 +0000911
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000912 {'notAfter': 'May 25 23:59:59 2012 GMT',
913 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
914 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
915 (('businessCategory', 'V1.0, Clause 5.(b)'),),
916 (('serialNumber', '2497886'),),
917 (('countryName', 'US'),),
918 (('postalCode', '94043'),),
919 (('stateOrProvinceName', 'California'),),
920 (('localityName', 'Mountain View'),),
921 (('streetAddress', '487 East Middlefield Road'),),
922 (('organizationName', 'VeriSign, Inc.'),),
923 (('organizationalUnitName', ' Production Security Services'),),
924 (('commonName', 'www.verisign.com'),))}
Thomas Woutersed03b412007-08-28 21:37:11 +0000925
Antoine Pitrou152efa22010-05-16 18:19:27 +0000926This other example first creates an SSL context, instructs it to verify
927certificates sent by peers, and feeds it a set of recognized certificate
928authorities (CA)::
929
930 >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000931 >>> context.verify_mode = ssl.CERT_REQUIRED
Antoine Pitrou152efa22010-05-16 18:19:27 +0000932 >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
933
934(it is assumed your operating system places a bundle of all CA certificates
935in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have
936to adjust the location)
937
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000938When you use the context to connect to a server, :const:`CERT_REQUIRED`
Antoine Pitrou152efa22010-05-16 18:19:27 +0000939validates the server certificate: it ensures that the server certificate
940was signed with one of the CA certificates, and checks the signature for
941correctness::
942
943 >>> conn = context.wrap_socket(socket.socket(socket.AF_INET))
944 >>> conn.connect(("linuxfr.org", 443))
945
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000946You should then fetch the certificate and check its fields for conformity::
Antoine Pitrou152efa22010-05-16 18:19:27 +0000947
Antoine Pitrou59fdd672010-10-08 10:37:08 +0000948 >>> cert = conn.getpeercert()
949 >>> ssl.match_hostname(cert, "linuxfr.org")
950
951Visual inspection shows that the certificate does identify the desired service
952(that is, the HTTPS host ``linuxfr.org``)::
953
954 >>> pprint.pprint(cert)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000955 {'notAfter': 'Jun 26 21:41:46 2011 GMT',
956 'subject': ((('commonName', 'linuxfr.org'),),),
957 'subjectAltName': (('DNS', 'linuxfr.org'), ('othername', '<unsupported>'))}
958
959Now that you are assured of its authenticity, you can proceed to talk with
960the server::
961
Antoine Pitroudab64262010-09-19 13:31:06 +0000962 >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
963 >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
Antoine Pitrou152efa22010-05-16 18:19:27 +0000964 [b'HTTP/1.1 302 Found',
965 b'Date: Sun, 16 May 2010 13:43:28 GMT',
966 b'Server: Apache/2.2',
967 b'Location: https://linuxfr.org/pub/',
968 b'Vary: Accept-Encoding',
969 b'Connection: close',
970 b'Content-Type: text/html; charset=iso-8859-1',
971 b'',
972 b'']
973
Antoine Pitrou152efa22010-05-16 18:19:27 +0000974See the discussion of :ref:`ssl-security` below.
975
976
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000977Server-side operation
978^^^^^^^^^^^^^^^^^^^^^
979
Antoine Pitrou152efa22010-05-16 18:19:27 +0000980For server operation, typically you'll need to have a server certificate, and
981private key, each in a file. You'll first create a context holding the key
982and the certificate, so that clients can check your authenticity. Then
983you'll open a socket, bind it to a port, call :meth:`listen` on it, and start
984waiting for clients to connect::
Thomas Woutersed03b412007-08-28 21:37:11 +0000985
986 import socket, ssl
987
Antoine Pitrou152efa22010-05-16 18:19:27 +0000988 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
989 context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")
990
Thomas Woutersed03b412007-08-28 21:37:11 +0000991 bindsocket = socket.socket()
992 bindsocket.bind(('myaddr.mydomain.com', 10023))
993 bindsocket.listen(5)
994
Antoine Pitrou152efa22010-05-16 18:19:27 +0000995When a client connects, you'll call :meth:`accept` on the socket to get the
996new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket`
997method to create a server-side SSL socket for the connection::
Thomas Woutersed03b412007-08-28 21:37:11 +0000998
999 while True:
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001000 newsocket, fromaddr = bindsocket.accept()
1001 connstream = context.wrap_socket(newsocket, server_side=True)
1002 try:
1003 deal_with_client(connstream)
1004 finally:
Antoine Pitroub205d582011-01-02 22:09:27 +00001005 connstream.shutdown(socket.SHUT_RDWR)
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001006 connstream.close()
Thomas Woutersed03b412007-08-28 21:37:11 +00001007
Antoine Pitrou152efa22010-05-16 18:19:27 +00001008Then you'll read data from the ``connstream`` and do something with it till you
Georg Brandl7f01a132009-09-16 15:58:14 +00001009are finished with the client (or the client is finished with you)::
Thomas Woutersed03b412007-08-28 21:37:11 +00001010
1011 def deal_with_client(connstream):
Georg Brandl8a7e5da2011-01-02 19:07:51 +00001012 data = connstream.recv(1024)
1013 # empty data means the client is finished with us
1014 while data:
1015 if not do_something(connstream, data):
1016 # we'll assume do_something returns False
1017 # when we're finished with client
1018 break
1019 data = connstream.recv(1024)
1020 # finished with client
Thomas Woutersed03b412007-08-28 21:37:11 +00001021
Antoine Pitrou152efa22010-05-16 18:19:27 +00001022And go back to listening for new client connections (of course, a real server
1023would probably handle each client connection in a separate thread, or put
1024the sockets in non-blocking mode and use an event loop).
1025
1026
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001027.. _ssl-nonblocking:
1028
1029Notes on non-blocking sockets
1030-----------------------------
1031
1032When working with non-blocking sockets, there are several things you need
1033to be aware of:
1034
1035- Calling :func:`~select.select` tells you that the OS-level socket can be
1036 read from (or written to), but it does not imply that there is sufficient
1037 data at the upper SSL layer. For example, only part of an SSL frame might
1038 have arrived. Therefore, you must be ready to handle :meth:`SSLSocket.recv`
1039 and :meth:`SSLSocket.send` failures, and retry after another call to
1040 :func:`~select.select`.
1041
1042 (of course, similar provisions apply when using other primitives such as
1043 :func:`~select.poll`)
1044
1045- The SSL handshake itself will be non-blocking: the
1046 :meth:`SSLSocket.do_handshake` method has to be retried until it returns
1047 successfully. Here is a synopsis using :func:`~select.select` to wait for
1048 the socket's readiness::
1049
1050 while True:
1051 try:
1052 sock.do_handshake()
1053 break
Antoine Pitrou873bf262011-10-27 23:59:03 +02001054 except ssl.SSLWantReadError:
1055 select.select([sock], [], [])
1056 except ssl.SSLWantWriteError:
1057 select.select([], [sock], [])
Antoine Pitrou6f5dcb12011-07-11 01:35:48 +02001058
1059
Antoine Pitrou152efa22010-05-16 18:19:27 +00001060.. _ssl-security:
1061
1062Security considerations
1063-----------------------
1064
1065Verifying certificates
1066^^^^^^^^^^^^^^^^^^^^^^
1067
1068:const:`CERT_NONE` is the default. Since it does not authenticate the other
1069peer, it can be insecure, especially in client mode where most of time you
1070would like to ensure the authenticity of the server you're talking to.
1071Therefore, when in client mode, it is highly recommended to use
1072:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also
Antoine Pitrou59fdd672010-10-08 10:37:08 +00001073have to check that the server certificate, which can be obtained by calling
1074:meth:`SSLSocket.getpeercert`, matches the desired service. For many
1075protocols and applications, the service can be identified by the hostname;
1076in this case, the :func:`match_hostname` function can be used.
Antoine Pitrou152efa22010-05-16 18:19:27 +00001077
1078In server mode, if you want to authenticate your clients using the SSL layer
1079(rather than using a higher-level authentication mechanism), you'll also have
1080to specify :const:`CERT_REQUIRED` and similarly check the client certificate.
1081
1082 .. note::
1083
1084 In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are
1085 equivalent unless anonymous ciphers are enabled (they are disabled
1086 by default).
Thomas Woutersed03b412007-08-28 21:37:11 +00001087
Antoine Pitroub5218772010-05-21 09:56:06 +00001088Protocol versions
1089^^^^^^^^^^^^^^^^^
1090
1091SSL version 2 is considered insecure and is therefore dangerous to use. If
1092you want maximum compatibility between clients and servers, it is recommended
1093to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable
1094SSLv2 explicitly using the :data:`SSLContext.options` attribute::
1095
1096 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1097 context.options |= ssl.OP_NO_SSLv2
1098
1099The SSL context created above will allow SSLv3 and TLSv1 connections, but
1100not SSLv2.
1101
Georg Brandl48310cd2009-01-03 21:18:54 +00001102
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001103.. seealso::
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001104
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001105 Class :class:`socket.socket`
1106 Documentation of underlying :mod:`socket` class
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001107
Antoine Pitrouf394e472011-10-07 16:58:07 +02001108 `TLS (Transport Layer Security) and SSL (Secure Socket Layer) <http://www3.rad.com/networks/applications/secure/tls.htm>`_
1109 Debby Koren
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001110
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001111 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
1112 Steve Kent
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001113
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001114 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
1115 D. Eastlake et. al.
Thomas Wouters89d996e2007-09-08 17:39:28 +00001116
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001117 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
1118 Housley et. al.
Antoine Pitroud5323212010-10-22 18:19:07 +00001119
1120 `RFC 4366: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc4366>`_
1121 Blake-Wilson et. al.