Antoine Pitrou | e1bc898 | 2011-01-02 22:12:22 +0000 | [diff] [blame] | 1 | :mod:`ssl` --- TLS/SSL wrapper for socket objects |
| 2 | ================================================= |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 3 | |
| 4 | .. module:: ssl |
Antoine Pitrou | e1bc898 | 2011-01-02 22:12:22 +0000 | [diff] [blame] | 5 | :synopsis: TLS/SSL wrapper for socket objects |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 6 | |
| 7 | .. moduleauthor:: Bill Janssen <bill.janssen@gmail.com> |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 8 | .. sectionauthor:: Bill Janssen <bill.janssen@gmail.com> |
| 9 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 10 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 11 | .. index:: single: OpenSSL; (use in module ssl) |
| 12 | |
| 13 | .. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer |
| 14 | |
Raymond Hettinger | 469271d | 2011-01-27 20:38:46 +0000 | [diff] [blame] | 15 | **Source code:** :source:`Lib/ssl.py` |
| 16 | |
| 17 | -------------- |
| 18 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 19 | This module provides access to Transport Layer Security (often known as "Secure |
| 20 | Sockets Layer") encryption and peer authentication facilities for network |
| 21 | sockets, both client-side and server-side. This module uses the OpenSSL |
| 22 | library. It is available on all modern Unix systems, Windows, Mac OS X, and |
| 23 | probably additional platforms, as long as OpenSSL is installed on that platform. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 24 | |
| 25 | .. note:: |
| 26 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 27 | 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 Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 30 | |
Christian Heimes | 3046fe4 | 2013-10-29 21:08:56 +0100 | [diff] [blame] | 31 | .. warning:: |
Antoine Pitrou | 9eefe91 | 2013-11-17 15:35:33 +0100 | [diff] [blame] | 32 | Don't use this module without reading the :ref:`ssl-security`. Doing so |
| 33 | may lead to a false sense of security, as the default settings of the |
| 34 | ssl module are not necessarily appropriate for your application. |
Christian Heimes | 3046fe4 | 2013-10-29 21:08:56 +0100 | [diff] [blame] | 35 | |
Christian Heimes | 3046fe4 | 2013-10-29 21:08:56 +0100 | [diff] [blame] | 36 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 37 | This section documents the objects and functions in the ``ssl`` module; for more |
| 38 | general information about TLS, SSL, and certificates, the reader is referred to |
| 39 | the documents in the "See Also" section at the bottom. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 40 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 41 | This module provides a class, :class:`ssl.SSLSocket`, which is derived from the |
| 42 | :class:`socket.socket` type, and provides a socket-like wrapper that also |
| 43 | encrypts and decrypts the data going over the socket with SSL. It supports |
Antoine Pitrou | dab6426 | 2010-09-19 13:31:06 +0000 | [diff] [blame] | 44 | additional methods such as :meth:`getpeercert`, which retrieves the |
| 45 | certificate of the other side of the connection, and :meth:`cipher`,which |
| 46 | retrieves the cipher being used for the secure connection. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 47 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 48 | For more sophisticated applications, the :class:`ssl.SSLContext` class |
| 49 | helps manage settings and certificates, which can then be inherited |
| 50 | by SSL sockets created through the :meth:`SSLContext.wrap_socket` method. |
| 51 | |
| 52 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 53 | Functions, Constants, and Exceptions |
| 54 | ------------------------------------ |
| 55 | |
| 56 | .. exception:: SSLError |
| 57 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 58 | Raised to signal an error from the underlying SSL implementation |
| 59 | (currently provided by the OpenSSL library). This signifies some |
| 60 | problem in the higher-level encryption and authentication layer that's |
| 61 | superimposed on the underlying network connection. This error |
Antoine Pitrou | 5574c30 | 2011-10-12 17:53:43 +0200 | [diff] [blame] | 62 | is a subtype of :exc:`OSError`. The error code and message of |
| 63 | :exc:`SSLError` instances are provided by the OpenSSL library. |
| 64 | |
| 65 | .. versionchanged:: 3.3 |
| 66 | :exc:`SSLError` used to be a subtype of :exc:`socket.error`. |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 67 | |
Antoine Pitrou | 3b36fb1 | 2012-06-22 21:11:52 +0200 | [diff] [blame] | 68 | .. attribute:: library |
| 69 | |
| 70 | A string mnemonic designating the OpenSSL submodule in which the error |
| 71 | occurred, such as ``SSL``, ``PEM`` or ``X509``. The range of possible |
| 72 | values depends on the OpenSSL version. |
| 73 | |
| 74 | .. versionadded:: 3.3 |
| 75 | |
| 76 | .. attribute:: reason |
| 77 | |
| 78 | A string mnemonic designating the reason this error occurred, for |
| 79 | example ``CERTIFICATE_VERIFY_FAILED``. The range of possible |
| 80 | values depends on the OpenSSL version. |
| 81 | |
| 82 | .. versionadded:: 3.3 |
| 83 | |
Antoine Pitrou | 41032a6 | 2011-10-27 23:56:55 +0200 | [diff] [blame] | 84 | .. exception:: SSLZeroReturnError |
| 85 | |
| 86 | A subclass of :exc:`SSLError` raised when trying to read or write and |
| 87 | the SSL connection has been closed cleanly. Note that this doesn't |
| 88 | mean that the underlying transport (read TCP) has been closed. |
| 89 | |
| 90 | .. versionadded:: 3.3 |
| 91 | |
| 92 | .. exception:: SSLWantReadError |
| 93 | |
| 94 | A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket |
| 95 | <ssl-nonblocking>` when trying to read or write data, but more data needs |
| 96 | to be received on the underlying TCP transport before the request can be |
| 97 | fulfilled. |
| 98 | |
| 99 | .. versionadded:: 3.3 |
| 100 | |
| 101 | .. exception:: SSLWantWriteError |
| 102 | |
| 103 | A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket |
| 104 | <ssl-nonblocking>` when trying to read or write data, but more data needs |
| 105 | to be sent on the underlying TCP transport before the request can be |
| 106 | fulfilled. |
| 107 | |
| 108 | .. versionadded:: 3.3 |
| 109 | |
| 110 | .. exception:: SSLSyscallError |
| 111 | |
| 112 | A subclass of :exc:`SSLError` raised when a system error was encountered |
| 113 | while trying to fulfill an operation on a SSL socket. Unfortunately, |
| 114 | there is no easy way to inspect the original errno number. |
| 115 | |
| 116 | .. versionadded:: 3.3 |
| 117 | |
| 118 | .. exception:: SSLEOFError |
| 119 | |
| 120 | A subclass of :exc:`SSLError` raised when the SSL connection has been |
Antoine Pitrou | f3dc2d7 | 2011-10-28 00:01:03 +0200 | [diff] [blame] | 121 | terminated abruptly. Generally, you shouldn't try to reuse the underlying |
Antoine Pitrou | 41032a6 | 2011-10-27 23:56:55 +0200 | [diff] [blame] | 122 | transport when this error is encountered. |
| 123 | |
| 124 | .. versionadded:: 3.3 |
| 125 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 126 | .. exception:: CertificateError |
| 127 | |
| 128 | Raised to signal an error with a certificate (such as mismatching |
| 129 | hostname). Certificate errors detected by OpenSSL, though, raise |
| 130 | an :exc:`SSLError`. |
| 131 | |
| 132 | |
| 133 | Socket creation |
| 134 | ^^^^^^^^^^^^^^^ |
| 135 | |
| 136 | The following function allows for standalone socket creation. Starting from |
| 137 | Python 3.2, it can be more flexible to use :meth:`SSLContext.wrap_socket` |
| 138 | instead. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 139 | |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 140 | .. 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 Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 141 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 142 | Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance |
| 143 | of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps |
Antoine Pitrou | 3e86ba4 | 2013-12-28 17:26:33 +0100 | [diff] [blame] | 144 | the underlying socket in an SSL context. ``sock`` must be a |
| 145 | :data:`~socket.SOCK_STREAM` socket; other socket types are unsupported. |
| 146 | |
| 147 | For client-side sockets, the context construction is lazy; if the |
| 148 | underlying socket isn't connected yet, the context construction will be |
| 149 | performed after :meth:`connect` is called on the socket. For |
| 150 | server-side sockets, if the socket has no remote peer, it is assumed |
| 151 | to be a listening socket, and the server-side SSL wrapping is |
| 152 | automatically performed on client connections accepted via the |
| 153 | :meth:`accept` method. :func:`wrap_socket` may raise :exc:`SSLError`. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 154 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 155 | The ``keyfile`` and ``certfile`` parameters specify optional files which |
| 156 | contain a certificate to be used to identify the local side of the |
| 157 | connection. See the discussion of :ref:`ssl-certificates` for more |
| 158 | information on how the certificate is stored in the ``certfile``. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 159 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 160 | The parameter ``server_side`` is a boolean which identifies whether |
| 161 | server-side or client-side behavior is desired from this socket. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 162 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 163 | The parameter ``cert_reqs`` specifies whether a certificate is required from |
| 164 | the other side of the connection, and whether it will be validated if |
| 165 | provided. It must be one of the three values :const:`CERT_NONE` |
| 166 | (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated |
| 167 | if provided), or :const:`CERT_REQUIRED` (required and validated). If the |
| 168 | value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs`` |
| 169 | parameter must point to a file of CA certificates. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 170 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 171 | The ``ca_certs`` file contains a set of concatenated "certification |
| 172 | authority" certificates, which are used to validate certificates passed from |
| 173 | the other end of the connection. See the discussion of |
| 174 | :ref:`ssl-certificates` for more information about how to arrange the |
| 175 | certificates in this file. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 176 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 177 | The parameter ``ssl_version`` specifies which version of the SSL protocol to |
| 178 | use. Typically, the server chooses a particular protocol version, and the |
| 179 | client must adapt to the server's choice. Most of the versions are not |
Antoine Pitrou | 84a2edc | 2012-01-09 21:35:11 +0100 | [diff] [blame] | 180 | interoperable with the other versions. If not specified, the default is |
| 181 | :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 182 | versions. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 183 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 184 | Here's a table showing which versions in a client (down the side) can connect |
| 185 | to which versions in a server (along the top): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 186 | |
| 187 | .. table:: |
| 188 | |
| 189 | ======================== ========= ========= ========== ========= |
| 190 | *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1** |
Christian Heimes | 255f53b | 2007-12-08 15:33:56 +0000 | [diff] [blame] | 191 | ------------------------ --------- --------- ---------- --------- |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 192 | *SSLv2* yes no yes no |
Antoine Pitrou | ac8bfca | 2012-01-09 21:43:18 +0100 | [diff] [blame] | 193 | *SSLv3* no yes yes no |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 194 | *SSLv23* yes no yes no |
| 195 | *TLSv1* no no yes yes |
| 196 | ======================== ========= ========= ========== ========= |
| 197 | |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 198 | .. note:: |
| 199 | |
Benjamin Peterson | d7c3ed5 | 2010-06-27 22:32:30 +0000 | [diff] [blame] | 200 | Which connections succeed will vary depending on the version of |
| 201 | OpenSSL. For instance, in some older versions of OpenSSL (such |
| 202 | as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an |
| 203 | SSLv23 server. Another example: beginning with OpenSSL 1.0.0, |
| 204 | an SSLv23 client will not actually attempt SSLv2 connections |
| 205 | unless you explicitly enable SSLv2 ciphers; for example, you |
| 206 | might specify ``"ALL"`` or ``"SSLv2"`` as the *ciphers* parameter |
| 207 | to enable them. |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 208 | |
Benjamin Peterson | d7c3ed5 | 2010-06-27 22:32:30 +0000 | [diff] [blame] | 209 | The *ciphers* parameter sets the available ciphers for this SSL object. |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 210 | It should be a string in the `OpenSSL cipher list format |
| 211 | <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 212 | |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 213 | The parameter ``do_handshake_on_connect`` specifies whether to do the SSL |
| 214 | handshake automatically after doing a :meth:`socket.connect`, or whether the |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 215 | application program will call it explicitly, by invoking the |
| 216 | :meth:`SSLSocket.do_handshake` method. Calling |
| 217 | :meth:`SSLSocket.do_handshake` explicitly gives the program control over the |
| 218 | blocking behavior of the socket I/O involved in the handshake. |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 219 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 220 | The parameter ``suppress_ragged_eofs`` specifies how the |
Antoine Pitrou | dab6426 | 2010-09-19 13:31:06 +0000 | [diff] [blame] | 221 | :meth:`SSLSocket.recv` method should signal unexpected EOF from the other end |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 222 | of the connection. If specified as :const:`True` (the default), it returns a |
Antoine Pitrou | dab6426 | 2010-09-19 13:31:06 +0000 | [diff] [blame] | 223 | normal EOF (an empty bytes object) in response to unexpected EOF errors |
| 224 | raised from the underlying socket; if :const:`False`, it will raise the |
| 225 | exceptions back to the caller. |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 226 | |
Ezio Melotti | 4d5195b | 2010-04-20 10:57:44 +0000 | [diff] [blame] | 227 | .. versionchanged:: 3.2 |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 228 | New optional argument *ciphers*. |
| 229 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 230 | Random generation |
| 231 | ^^^^^^^^^^^^^^^^^ |
| 232 | |
Victor Stinner | 99c8b16 | 2011-05-24 12:05:19 +0200 | [diff] [blame] | 233 | .. function:: RAND_bytes(num) |
| 234 | |
Victor Stinner | a675206 | 2011-05-25 11:27:40 +0200 | [diff] [blame] | 235 | Returns *num* cryptographically strong pseudo-random bytes. Raises an |
| 236 | :class:`SSLError` if the PRNG has not been seeded with enough data or if the |
| 237 | operation is not supported by the current RAND method. :func:`RAND_status` |
| 238 | can be used to check the status of the PRNG and :func:`RAND_add` can be used |
| 239 | to seed the PRNG. |
Victor Stinner | 99c8b16 | 2011-05-24 12:05:19 +0200 | [diff] [blame] | 240 | |
Victor Stinner | 19fb53c | 2011-05-24 21:32:40 +0200 | [diff] [blame] | 241 | Read the Wikipedia article, `Cryptographically secure pseudorandom number |
Victor Stinner | a675206 | 2011-05-25 11:27:40 +0200 | [diff] [blame] | 242 | generator (CSPRNG) |
Victor Stinner | 19fb53c | 2011-05-24 21:32:40 +0200 | [diff] [blame] | 243 | <http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator>`_, |
| 244 | to get the requirements of a cryptographically generator. |
| 245 | |
Victor Stinner | 99c8b16 | 2011-05-24 12:05:19 +0200 | [diff] [blame] | 246 | .. versionadded:: 3.3 |
| 247 | |
| 248 | .. function:: RAND_pseudo_bytes(num) |
| 249 | |
| 250 | Returns (bytes, is_cryptographic): bytes are *num* pseudo-random bytes, |
Serhiy Storchaka | fbc1c26 | 2013-11-29 12:17:13 +0200 | [diff] [blame] | 251 | is_cryptographic is ``True`` if the bytes generated are cryptographically |
Victor Stinner | a675206 | 2011-05-25 11:27:40 +0200 | [diff] [blame] | 252 | strong. Raises an :class:`SSLError` if the operation is not supported by the |
| 253 | current RAND method. |
Victor Stinner | 99c8b16 | 2011-05-24 12:05:19 +0200 | [diff] [blame] | 254 | |
Victor Stinner | 19fb53c | 2011-05-24 21:32:40 +0200 | [diff] [blame] | 255 | Generated pseudo-random byte sequences will be unique if they are of |
| 256 | sufficient length, but are not necessarily unpredictable. They can be used |
| 257 | for non-cryptographic purposes and for certain purposes in cryptographic |
| 258 | protocols, but usually not for key generation etc. |
| 259 | |
Victor Stinner | 99c8b16 | 2011-05-24 12:05:19 +0200 | [diff] [blame] | 260 | .. versionadded:: 3.3 |
| 261 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 262 | .. function:: RAND_status() |
| 263 | |
Serhiy Storchaka | fbc1c26 | 2013-11-29 12:17:13 +0200 | [diff] [blame] | 264 | Returns ``True`` if the SSL pseudo-random number generator has been seeded with |
| 265 | 'enough' randomness, and ``False`` otherwise. You can use :func:`ssl.RAND_egd` |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 266 | and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random |
| 267 | number generator. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 268 | |
| 269 | .. function:: RAND_egd(path) |
| 270 | |
Victor Stinner | 99c8b16 | 2011-05-24 12:05:19 +0200 | [diff] [blame] | 271 | If you are running an entropy-gathering daemon (EGD) somewhere, and *path* |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 272 | is the pathname of a socket connection open to it, this will read 256 bytes |
| 273 | of randomness from the socket, and add it to the SSL pseudo-random number |
| 274 | generator to increase the security of generated secret keys. This is |
| 275 | typically only necessary on systems without better sources of randomness. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 276 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 277 | See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources |
| 278 | of entropy-gathering daemons. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 279 | |
| 280 | .. function:: RAND_add(bytes, entropy) |
| 281 | |
Victor Stinner | 99c8b16 | 2011-05-24 12:05:19 +0200 | [diff] [blame] | 282 | Mixes the given *bytes* into the SSL pseudo-random number generator. The |
| 283 | parameter *entropy* (a float) is a lower bound on the entropy contained in |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 284 | string (so you can always use :const:`0.0`). See :rfc:`1750` for more |
| 285 | information on sources of entropy. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 286 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 287 | Certificate handling |
| 288 | ^^^^^^^^^^^^^^^^^^^^ |
| 289 | |
| 290 | .. function:: match_hostname(cert, hostname) |
| 291 | |
| 292 | Verify that *cert* (in decoded format as returned by |
| 293 | :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules |
| 294 | applied are those for checking the identity of HTTPS servers as outlined |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 295 | in :rfc:`2818` and :rfc:`6125`, except that IP addresses are not currently |
| 296 | supported. In addition to HTTPS, this function should be suitable for |
| 297 | checking the identity of servers in various SSL-based protocols such as |
| 298 | FTPS, IMAPS, POPS and others. |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 299 | |
| 300 | :exc:`CertificateError` is raised on failure. On success, the function |
| 301 | returns nothing:: |
| 302 | |
| 303 | >>> cert = {'subject': ((('commonName', 'example.com'),),)} |
| 304 | >>> ssl.match_hostname(cert, "example.com") |
| 305 | >>> ssl.match_hostname(cert, "example.org") |
| 306 | Traceback (most recent call last): |
| 307 | File "<stdin>", line 1, in <module> |
| 308 | File "/home/py3k/Lib/ssl.py", line 130, in match_hostname |
| 309 | ssl.CertificateError: hostname 'example.org' doesn't match 'example.com' |
| 310 | |
| 311 | .. versionadded:: 3.2 |
| 312 | |
Georg Brandl | 72c98d3 | 2013-10-27 07:16:53 +0100 | [diff] [blame] | 313 | .. versionchanged:: 3.3.3 |
| 314 | The function now follows :rfc:`6125`, section 6.4.3 and does neither |
| 315 | match multiple wildcards (e.g. ``*.*.com`` or ``*a*.example.org``) nor |
| 316 | a wildcard inside an internationalized domain names (IDN) fragment. |
| 317 | IDN A-labels such as ``www*.xn--pthon-kva.org`` are still supported, |
| 318 | but ``x*.python.org`` no longer matches ``xn--tda.python.org``. |
| 319 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 320 | .. function:: cert_time_to_seconds(timestring) |
| 321 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 322 | Returns a floating-point value containing a normal seconds-after-the-epoch |
| 323 | time value, given the time-string representing the "notBefore" or "notAfter" |
| 324 | date from a certificate. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 325 | |
| 326 | Here's an example:: |
| 327 | |
| 328 | >>> import ssl |
| 329 | >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT") |
| 330 | 1178694000.0 |
| 331 | >>> import time |
| 332 | >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")) |
| 333 | 'Wed May 9 00:00:00 2007' |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 334 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 335 | .. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 336 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 337 | Given the address ``addr`` of an SSL-protected server, as a (*hostname*, |
| 338 | *port-number*) pair, fetches the server's certificate, and returns it as a |
| 339 | PEM-encoded string. If ``ssl_version`` is specified, uses that version of |
| 340 | the SSL protocol to attempt to connect to the server. If ``ca_certs`` is |
| 341 | specified, it should be a file containing a list of root certificates, the |
| 342 | same format as used for the same parameter in :func:`wrap_socket`. The call |
| 343 | will attempt to validate the server certificate against that set of root |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 344 | certificates, and will fail if the validation attempt fails. |
| 345 | |
Antoine Pitrou | 15399c3 | 2011-04-28 19:23:55 +0200 | [diff] [blame] | 346 | .. versionchanged:: 3.3 |
| 347 | This function is now IPv6-compatible. |
| 348 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 349 | .. function:: DER_cert_to_PEM_cert(DER_cert_bytes) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 350 | |
| 351 | Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded |
| 352 | string version of the same certificate. |
| 353 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 354 | .. function:: PEM_cert_to_DER_cert(PEM_cert_string) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 355 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 356 | Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of |
| 357 | bytes for that same certificate. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 358 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 359 | Constants |
| 360 | ^^^^^^^^^ |
| 361 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 362 | .. data:: CERT_NONE |
| 363 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 364 | Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` |
| 365 | parameter to :func:`wrap_socket`. In this mode (the default), no |
| 366 | certificates will be required from the other side of the socket connection. |
| 367 | If a certificate is received from the other end, no attempt to validate it |
| 368 | is made. |
| 369 | |
| 370 | See the discussion of :ref:`ssl-security` below. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 371 | |
| 372 | .. data:: CERT_OPTIONAL |
| 373 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 374 | Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` |
| 375 | parameter to :func:`wrap_socket`. In this mode no certificates will be |
| 376 | required from the other side of the socket connection; but if they |
| 377 | are provided, validation will be attempted and an :class:`SSLError` |
| 378 | will be raised on failure. |
| 379 | |
| 380 | Use of this setting requires a valid set of CA certificates to |
| 381 | be passed, either to :meth:`SSLContext.load_verify_locations` or as a |
| 382 | value of the ``ca_certs`` parameter to :func:`wrap_socket`. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 383 | |
| 384 | .. data:: CERT_REQUIRED |
| 385 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 386 | Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` |
| 387 | parameter to :func:`wrap_socket`. In this mode, certificates are |
| 388 | required from the other side of the socket connection; an :class:`SSLError` |
| 389 | will be raised if no certificate is provided, or if its validation fails. |
| 390 | |
| 391 | Use of this setting requires a valid set of CA certificates to |
| 392 | be passed, either to :meth:`SSLContext.load_verify_locations` or as a |
| 393 | value of the ``ca_certs`` parameter to :func:`wrap_socket`. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 394 | |
| 395 | .. data:: PROTOCOL_SSLv2 |
| 396 | |
| 397 | Selects SSL version 2 as the channel encryption protocol. |
| 398 | |
Victor Stinner | 3de4919 | 2011-05-09 00:42:58 +0200 | [diff] [blame] | 399 | This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2 |
| 400 | flag. |
| 401 | |
Antoine Pitrou | 8eac60d | 2010-05-16 14:19:41 +0000 | [diff] [blame] | 402 | .. warning:: |
| 403 | |
| 404 | SSL version 2 is insecure. Its use is highly discouraged. |
| 405 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 406 | .. data:: PROTOCOL_SSLv23 |
| 407 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 408 | Selects SSL version 2 or 3 as the channel encryption protocol. This is a |
| 409 | setting to use with servers for maximum compatibility with the other end of |
| 410 | an SSL connection, but it may cause the specific ciphers chosen for the |
| 411 | encryption to be of fairly low quality. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 412 | |
| 413 | .. data:: PROTOCOL_SSLv3 |
| 414 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 415 | Selects SSL version 3 as the channel encryption protocol. For clients, this |
| 416 | is the maximally compatible SSL variant. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 417 | |
| 418 | .. data:: PROTOCOL_TLSv1 |
| 419 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 420 | Selects TLS version 1 as the channel encryption protocol. This is the most |
| 421 | modern version, and probably the best choice for maximum protection, if both |
| 422 | sides can speak it. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 423 | |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 424 | .. data:: OP_ALL |
| 425 | |
| 426 | Enables workarounds for various bugs present in other SSL implementations. |
Antoine Pitrou | 9f6b02e | 2012-01-27 10:02:55 +0100 | [diff] [blame] | 427 | This option is set by default. It does not necessarily set the same |
| 428 | flags as OpenSSL's ``SSL_OP_ALL`` constant. |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 429 | |
| 430 | .. versionadded:: 3.2 |
| 431 | |
| 432 | .. data:: OP_NO_SSLv2 |
| 433 | |
| 434 | Prevents an SSLv2 connection. This option is only applicable in |
| 435 | conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from |
| 436 | choosing SSLv2 as the protocol version. |
| 437 | |
| 438 | .. versionadded:: 3.2 |
| 439 | |
| 440 | .. data:: OP_NO_SSLv3 |
| 441 | |
| 442 | Prevents an SSLv3 connection. This option is only applicable in |
| 443 | conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from |
| 444 | choosing SSLv3 as the protocol version. |
| 445 | |
| 446 | .. versionadded:: 3.2 |
| 447 | |
| 448 | .. data:: OP_NO_TLSv1 |
| 449 | |
| 450 | Prevents a TLSv1 connection. This option is only applicable in |
| 451 | conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from |
| 452 | choosing TLSv1 as the protocol version. |
| 453 | |
| 454 | .. versionadded:: 3.2 |
| 455 | |
Antoine Pitrou | 6db4944 | 2011-12-19 13:27:11 +0100 | [diff] [blame] | 456 | .. data:: OP_CIPHER_SERVER_PREFERENCE |
| 457 | |
| 458 | Use the server's cipher ordering preference, rather than the client's. |
| 459 | This option has no effect on client sockets and SSLv2 server sockets. |
| 460 | |
| 461 | .. versionadded:: 3.3 |
| 462 | |
Antoine Pitrou | 0e576f1 | 2011-12-22 10:03:38 +0100 | [diff] [blame] | 463 | .. data:: OP_SINGLE_DH_USE |
| 464 | |
| 465 | Prevents re-use of the same DH key for distinct SSL sessions. This |
| 466 | improves forward secrecy but requires more computational resources. |
| 467 | This option only applies to server sockets. |
| 468 | |
| 469 | .. versionadded:: 3.3 |
| 470 | |
Antoine Pitrou | 923df6f | 2011-12-19 17:16:51 +0100 | [diff] [blame] | 471 | .. data:: OP_SINGLE_ECDH_USE |
| 472 | |
Antoine Pitrou | 0e576f1 | 2011-12-22 10:03:38 +0100 | [diff] [blame] | 473 | Prevents re-use of the same ECDH key for distinct SSL sessions. This |
Antoine Pitrou | 923df6f | 2011-12-19 17:16:51 +0100 | [diff] [blame] | 474 | improves forward secrecy but requires more computational resources. |
| 475 | This option only applies to server sockets. |
| 476 | |
| 477 | .. versionadded:: 3.3 |
| 478 | |
Antoine Pitrou | 8abdb8a | 2011-12-20 10:13:40 +0100 | [diff] [blame] | 479 | .. data:: OP_NO_COMPRESSION |
| 480 | |
| 481 | Disable compression on the SSL channel. This is useful if the application |
| 482 | protocol supports its own compression scheme. |
| 483 | |
| 484 | This option is only available with OpenSSL 1.0.0 and later. |
| 485 | |
| 486 | .. versionadded:: 3.3 |
| 487 | |
Antoine Pitrou | 501da61 | 2011-12-21 09:27:41 +0100 | [diff] [blame] | 488 | .. data:: HAS_ECDH |
| 489 | |
| 490 | Whether the OpenSSL library has built-in support for Elliptic Curve-based |
| 491 | Diffie-Hellman key exchange. This should be true unless the feature was |
| 492 | explicitly disabled by the distributor. |
| 493 | |
| 494 | .. versionadded:: 3.3 |
| 495 | |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 496 | .. data:: HAS_SNI |
| 497 | |
| 498 | Whether the OpenSSL library has built-in support for the *Server Name |
| 499 | Indication* extension to the SSLv3 and TLSv1 protocols (as defined in |
| 500 | :rfc:`4366`). When true, you can use the *server_hostname* argument to |
| 501 | :meth:`SSLContext.wrap_socket`. |
| 502 | |
| 503 | .. versionadded:: 3.2 |
| 504 | |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 505 | .. data:: HAS_NPN |
| 506 | |
| 507 | Whether the OpenSSL library has built-in support for *Next Protocol |
| 508 | Negotiation* as described in the `NPN draft specification |
| 509 | <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. When true, |
| 510 | you can use the :meth:`SSLContext.set_npn_protocols` method to advertise |
| 511 | which protocols you want to support. |
| 512 | |
| 513 | .. versionadded:: 3.3 |
| 514 | |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 515 | .. data:: CHANNEL_BINDING_TYPES |
| 516 | |
| 517 | List of supported TLS channel binding types. Strings in this list |
| 518 | can be used as arguments to :meth:`SSLSocket.get_channel_binding`. |
| 519 | |
| 520 | .. versionadded:: 3.3 |
| 521 | |
Antoine Pitrou | 04f6a32 | 2010-04-05 21:40:07 +0000 | [diff] [blame] | 522 | .. data:: OPENSSL_VERSION |
| 523 | |
| 524 | The version string of the OpenSSL library loaded by the interpreter:: |
| 525 | |
| 526 | >>> ssl.OPENSSL_VERSION |
| 527 | 'OpenSSL 0.9.8k 25 Mar 2009' |
| 528 | |
Antoine Pitrou | 43a94c31 | 2010-04-05 21:44:48 +0000 | [diff] [blame] | 529 | .. versionadded:: 3.2 |
Antoine Pitrou | 04f6a32 | 2010-04-05 21:40:07 +0000 | [diff] [blame] | 530 | |
| 531 | .. data:: OPENSSL_VERSION_INFO |
| 532 | |
| 533 | A tuple of five integers representing version information about the |
| 534 | OpenSSL library:: |
| 535 | |
| 536 | >>> ssl.OPENSSL_VERSION_INFO |
| 537 | (0, 9, 8, 11, 15) |
| 538 | |
Antoine Pitrou | 43a94c31 | 2010-04-05 21:44:48 +0000 | [diff] [blame] | 539 | .. versionadded:: 3.2 |
Antoine Pitrou | 04f6a32 | 2010-04-05 21:40:07 +0000 | [diff] [blame] | 540 | |
| 541 | .. data:: OPENSSL_VERSION_NUMBER |
| 542 | |
| 543 | The raw version number of the OpenSSL library, as a single integer:: |
| 544 | |
| 545 | >>> ssl.OPENSSL_VERSION_NUMBER |
Antoine Pitrou | 43a94c31 | 2010-04-05 21:44:48 +0000 | [diff] [blame] | 546 | 9470143 |
Antoine Pitrou | 04f6a32 | 2010-04-05 21:40:07 +0000 | [diff] [blame] | 547 | >>> hex(ssl.OPENSSL_VERSION_NUMBER) |
Antoine Pitrou | 43a94c31 | 2010-04-05 21:44:48 +0000 | [diff] [blame] | 548 | '0x9080bf' |
Antoine Pitrou | 04f6a32 | 2010-04-05 21:40:07 +0000 | [diff] [blame] | 549 | |
Antoine Pitrou | 43a94c31 | 2010-04-05 21:44:48 +0000 | [diff] [blame] | 550 | .. versionadded:: 3.2 |
Antoine Pitrou | 04f6a32 | 2010-04-05 21:40:07 +0000 | [diff] [blame] | 551 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 552 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 553 | SSL Sockets |
| 554 | ----------- |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 555 | |
Antoine Pitrou | e1f2f30 | 2010-09-19 13:56:11 +0000 | [diff] [blame] | 556 | SSL sockets provide the following methods of :ref:`socket-objects`: |
Antoine Pitrou | 792ff3e | 2010-09-19 13:19:21 +0000 | [diff] [blame] | 557 | |
Antoine Pitrou | e1f2f30 | 2010-09-19 13:56:11 +0000 | [diff] [blame] | 558 | - :meth:`~socket.socket.accept()` |
| 559 | - :meth:`~socket.socket.bind()` |
| 560 | - :meth:`~socket.socket.close()` |
| 561 | - :meth:`~socket.socket.connect()` |
| 562 | - :meth:`~socket.socket.detach()` |
| 563 | - :meth:`~socket.socket.fileno()` |
| 564 | - :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()` |
| 565 | - :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()` |
| 566 | - :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`, |
| 567 | :meth:`~socket.socket.setblocking()` |
| 568 | - :meth:`~socket.socket.listen()` |
| 569 | - :meth:`~socket.socket.makefile()` |
| 570 | - :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()` |
| 571 | (but passing a non-zero ``flags`` argument is not allowed) |
| 572 | - :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with |
| 573 | the same limitation) |
| 574 | - :meth:`~socket.socket.shutdown()` |
| 575 | |
Antoine Pitrou | 6f5dcb1 | 2011-07-11 01:35:48 +0200 | [diff] [blame] | 576 | However, since the SSL (and TLS) protocol has its own framing atop |
| 577 | of TCP, the SSL sockets abstraction can, in certain respects, diverge from |
| 578 | the specification of normal, OS-level sockets. See especially the |
| 579 | :ref:`notes on non-blocking sockets <ssl-nonblocking>`. |
| 580 | |
| 581 | SSL sockets also have the following additional methods and attributes: |
Antoine Pitrou | 792ff3e | 2010-09-19 13:19:21 +0000 | [diff] [blame] | 582 | |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 583 | .. method:: SSLSocket.do_handshake() |
| 584 | |
Antoine Pitrou | b3593ca | 2011-07-11 01:39:19 +0200 | [diff] [blame] | 585 | Perform the SSL setup handshake. |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 586 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 587 | .. method:: SSLSocket.getpeercert(binary_form=False) |
| 588 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 589 | If there is no certificate for the peer on the other end of the connection, |
| 590 | returns ``None``. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 591 | |
Antoine Pitrou | d34941a | 2013-04-16 20:27:17 +0200 | [diff] [blame] | 592 | If the ``binary_form`` parameter is :const:`False`, and a certificate was |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 593 | received from the peer, this method returns a :class:`dict` instance. If the |
| 594 | certificate was not validated, the dict is empty. If the certificate was |
Antoine Pitrou | b7c6c81 | 2012-08-16 22:14:43 +0200 | [diff] [blame] | 595 | validated, it returns a dict with several keys, amongst them ``subject`` |
| 596 | (the principal for which the certificate was issued) and ``issuer`` |
| 597 | (the principal issuing the certificate). If a certificate contains an |
| 598 | instance of the *Subject Alternative Name* extension (see :rfc:`3280`), |
| 599 | there will also be a ``subjectAltName`` key in the dictionary. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 600 | |
Antoine Pitrou | b7c6c81 | 2012-08-16 22:14:43 +0200 | [diff] [blame] | 601 | The ``subject`` and ``issuer`` fields are tuples containing the sequence |
| 602 | of relative distinguished names (RDNs) given in the certificate's data |
| 603 | structure for the respective fields, and each RDN is a sequence of |
| 604 | name-value pairs. Here is a real-world example:: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 605 | |
Antoine Pitrou | b7c6c81 | 2012-08-16 22:14:43 +0200 | [diff] [blame] | 606 | {'issuer': ((('countryName', 'IL'),), |
| 607 | (('organizationName', 'StartCom Ltd.'),), |
| 608 | (('organizationalUnitName', |
| 609 | 'Secure Digital Certificate Signing'),), |
| 610 | (('commonName', |
| 611 | 'StartCom Class 2 Primary Intermediate Server CA'),)), |
| 612 | 'notAfter': 'Nov 22 08:15:19 2013 GMT', |
| 613 | 'notBefore': 'Nov 21 03:09:52 2011 GMT', |
| 614 | 'serialNumber': '95F0', |
| 615 | 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),), |
| 616 | (('countryName', 'US'),), |
| 617 | (('stateOrProvinceName', 'California'),), |
| 618 | (('localityName', 'San Francisco'),), |
| 619 | (('organizationName', 'Electronic Frontier Foundation, Inc.'),), |
| 620 | (('commonName', '*.eff.org'),), |
| 621 | (('emailAddress', 'hostmaster@eff.org'),)), |
| 622 | 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')), |
| 623 | 'version': 3} |
| 624 | |
| 625 | .. note:: |
Éric Araujo | fa5e6e4 | 2014-03-12 19:51:00 -0400 | [diff] [blame] | 626 | |
Antoine Pitrou | b7c6c81 | 2012-08-16 22:14:43 +0200 | [diff] [blame] | 627 | To validate a certificate for a particular service, you can use the |
| 628 | :func:`match_hostname` function. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 629 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 630 | If the ``binary_form`` parameter is :const:`True`, and a certificate was |
| 631 | provided, this method returns the DER-encoded form of the entire certificate |
| 632 | as a sequence of bytes, or :const:`None` if the peer did not provide a |
Antoine Pitrou | d34941a | 2013-04-16 20:27:17 +0200 | [diff] [blame] | 633 | certificate. Whether the peer provides a certificate depends on the SSL |
| 634 | socket's role: |
| 635 | |
| 636 | * for a client SSL socket, the server will always provide a certificate, |
| 637 | regardless of whether validation was required; |
| 638 | |
| 639 | * for a server SSL socket, the client will only provide a certificate |
| 640 | when requested by the server; therefore :meth:`getpeercert` will return |
| 641 | :const:`None` if you used :const:`CERT_NONE` (rather than |
| 642 | :const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`). |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 643 | |
Antoine Pitrou | fb04691 | 2010-11-09 20:21:19 +0000 | [diff] [blame] | 644 | .. versionchanged:: 3.2 |
| 645 | The returned dictionary includes additional items such as ``issuer`` |
| 646 | and ``notBefore``. |
| 647 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 648 | .. method:: SSLSocket.cipher() |
| 649 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 650 | Returns a three-value tuple containing the name of the cipher being used, the |
| 651 | version of the SSL protocol that defines its use, and the number of secret |
| 652 | bits being used. If no connection has been established, returns ``None``. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 653 | |
Antoine Pitrou | 8abdb8a | 2011-12-20 10:13:40 +0100 | [diff] [blame] | 654 | .. method:: SSLSocket.compression() |
| 655 | |
| 656 | Return the compression algorithm being used as a string, or ``None`` |
| 657 | if the connection isn't compressed. |
| 658 | |
| 659 | If the higher-level protocol supports its own compression mechanism, |
| 660 | you can use :data:`OP_NO_COMPRESSION` to disable SSL-level compression. |
| 661 | |
| 662 | .. versionadded:: 3.3 |
| 663 | |
Antoine Pitrou | d649480 | 2011-07-21 01:11:30 +0200 | [diff] [blame] | 664 | .. method:: SSLSocket.get_channel_binding(cb_type="tls-unique") |
| 665 | |
| 666 | Get channel binding data for current connection, as a bytes object. Returns |
| 667 | ``None`` if not connected or the handshake has not been completed. |
| 668 | |
| 669 | The *cb_type* parameter allow selection of the desired channel binding |
| 670 | type. Valid channel binding types are listed in the |
| 671 | :data:`CHANNEL_BINDING_TYPES` list. Currently only the 'tls-unique' channel |
| 672 | binding, defined by :rfc:`5929`, is supported. :exc:`ValueError` will be |
| 673 | raised if an unsupported channel binding type is requested. |
| 674 | |
| 675 | .. versionadded:: 3.3 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 676 | |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 677 | .. method:: SSLSocket.selected_npn_protocol() |
| 678 | |
| 679 | Returns the protocol that was selected during the TLS/SSL handshake. If |
| 680 | :meth:`SSLContext.set_npn_protocols` was not called, or if the other party |
| 681 | does not support NPN, or if the handshake has not yet happened, this will |
| 682 | return ``None``. |
| 683 | |
| 684 | .. versionadded:: 3.3 |
| 685 | |
Benjamin Peterson | 4aeec04 | 2008-08-19 21:42:13 +0000 | [diff] [blame] | 686 | .. method:: SSLSocket.unwrap() |
| 687 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 688 | Performs the SSL shutdown handshake, which removes the TLS layer from the |
| 689 | underlying socket, and returns the underlying socket object. This can be |
| 690 | used to go from encrypted operation over a connection to unencrypted. The |
| 691 | returned socket should always be used for further communication with the |
| 692 | other side of the connection, rather than the original socket. |
Benjamin Peterson | 4aeec04 | 2008-08-19 21:42:13 +0000 | [diff] [blame] | 693 | |
Antoine Pitrou | ec883db | 2010-05-24 21:20:20 +0000 | [diff] [blame] | 694 | .. attribute:: SSLSocket.context |
| 695 | |
| 696 | The :class:`SSLContext` object this SSL socket is tied to. If the SSL |
| 697 | socket was created using the top-level :func:`wrap_socket` function |
| 698 | (rather than :meth:`SSLContext.wrap_socket`), this is a custom context |
| 699 | object created for this SSL socket. |
| 700 | |
| 701 | .. versionadded:: 3.2 |
| 702 | |
| 703 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 704 | SSL Contexts |
| 705 | ------------ |
| 706 | |
Antoine Pitrou | cafaad4 | 2010-05-24 15:58:43 +0000 | [diff] [blame] | 707 | .. versionadded:: 3.2 |
| 708 | |
Antoine Pitrou | b0182c8 | 2010-10-12 20:09:02 +0000 | [diff] [blame] | 709 | An SSL context holds various data longer-lived than single SSL connections, |
| 710 | such as SSL configuration options, certificate(s) and private key(s). |
| 711 | It also manages a cache of SSL sessions for server-side sockets, in order |
| 712 | to speed up repeated connections from the same clients. |
| 713 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 714 | .. class:: SSLContext(protocol) |
| 715 | |
Antoine Pitrou | b0182c8 | 2010-10-12 20:09:02 +0000 | [diff] [blame] | 716 | Create a new SSL context. You must pass *protocol* which must be one |
| 717 | of the ``PROTOCOL_*`` constants defined in this module. |
| 718 | :data:`PROTOCOL_SSLv23` is recommended for maximum interoperability. |
| 719 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 720 | |
| 721 | :class:`SSLContext` objects have the following methods and attributes: |
| 722 | |
Antoine Pitrou | 4fd1e6a | 2011-08-25 14:39:44 +0200 | [diff] [blame] | 723 | .. method:: SSLContext.load_cert_chain(certfile, keyfile=None, password=None) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 724 | |
| 725 | Load a private key and the corresponding certificate. The *certfile* |
| 726 | string must be the path to a single file in PEM format containing the |
| 727 | certificate as well as any number of CA certificates needed to establish |
| 728 | the certificate's authenticity. The *keyfile* string, if present, must |
| 729 | point to a file containing the private key in. Otherwise the private |
| 730 | key will be taken from *certfile* as well. See the discussion of |
| 731 | :ref:`ssl-certificates` for more information on how the certificate |
| 732 | is stored in the *certfile*. |
| 733 | |
Antoine Pitrou | 4fd1e6a | 2011-08-25 14:39:44 +0200 | [diff] [blame] | 734 | The *password* argument may be a function to call to get the password for |
| 735 | decrypting the private key. It will only be called if the private key is |
| 736 | encrypted and a password is necessary. It will be called with no arguments, |
| 737 | and it should return a string, bytes, or bytearray. If the return value is |
| 738 | a string it will be encoded as UTF-8 before using it to decrypt the key. |
| 739 | Alternatively a string, bytes, or bytearray value may be supplied directly |
| 740 | as the *password* argument. It will be ignored if the private key is not |
| 741 | encrypted and no password is needed. |
| 742 | |
| 743 | If the *password* argument is not specified and a password is required, |
| 744 | OpenSSL's built-in password prompting mechanism will be used to |
| 745 | interactively prompt the user for a password. |
| 746 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 747 | An :class:`SSLError` is raised if the private key doesn't |
| 748 | match with the certificate. |
| 749 | |
Antoine Pitrou | 4fd1e6a | 2011-08-25 14:39:44 +0200 | [diff] [blame] | 750 | .. versionchanged:: 3.3 |
| 751 | New optional argument *password*. |
| 752 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 753 | .. method:: SSLContext.load_verify_locations(cafile=None, capath=None) |
| 754 | |
| 755 | Load a set of "certification authority" (CA) certificates used to validate |
| 756 | other peers' certificates when :data:`verify_mode` is other than |
| 757 | :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified. |
| 758 | |
| 759 | The *cafile* string, if present, is the path to a file of concatenated |
| 760 | CA certificates in PEM format. See the discussion of |
| 761 | :ref:`ssl-certificates` for more information about how to arrange the |
| 762 | certificates in this file. |
| 763 | |
| 764 | The *capath* string, if present, is |
| 765 | the path to a directory containing several CA certificates in PEM format, |
| 766 | following an `OpenSSL specific layout |
| 767 | <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_. |
| 768 | |
Antoine Pitrou | 664c2d1 | 2010-11-17 20:29:42 +0000 | [diff] [blame] | 769 | .. method:: SSLContext.set_default_verify_paths() |
| 770 | |
| 771 | Load a set of default "certification authority" (CA) certificates from |
| 772 | a filesystem path defined when building the OpenSSL library. Unfortunately, |
| 773 | there's no easy way to know whether this method succeeds: no error is |
| 774 | returned if no certificates are to be found. When the OpenSSL library is |
| 775 | provided as part of the operating system, though, it is likely to be |
| 776 | configured properly. |
| 777 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 778 | .. method:: SSLContext.set_ciphers(ciphers) |
| 779 | |
| 780 | Set the available ciphers for sockets created with this context. |
| 781 | It should be a string in the `OpenSSL cipher list format |
| 782 | <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_. |
| 783 | If no cipher can be selected (because compile-time options or other |
| 784 | configuration forbids use of all the specified ciphers), an |
| 785 | :class:`SSLError` will be raised. |
| 786 | |
| 787 | .. note:: |
| 788 | when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will |
| 789 | give the currently selected cipher. |
| 790 | |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 791 | .. method:: SSLContext.set_npn_protocols(protocols) |
| 792 | |
R David Murray | c7f7579 | 2013-06-26 15:11:12 -0400 | [diff] [blame] | 793 | Specify which protocols the socket should advertise during the SSL/TLS |
Antoine Pitrou | d5d17eb | 2012-03-22 00:23:03 +0100 | [diff] [blame] | 794 | handshake. It should be a list of strings, like ``['http/1.1', 'spdy/2']``, |
| 795 | ordered by preference. The selection of a protocol will happen during the |
| 796 | handshake, and will play out according to the `NPN draft specification |
| 797 | <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. After a |
| 798 | successful handshake, the :meth:`SSLSocket.selected_npn_protocol` method will |
| 799 | return the agreed-upon protocol. |
| 800 | |
| 801 | This method will raise :exc:`NotImplementedError` if :data:`HAS_NPN` is |
| 802 | False. |
| 803 | |
| 804 | .. versionadded:: 3.3 |
| 805 | |
Antoine Pitrou | 0e576f1 | 2011-12-22 10:03:38 +0100 | [diff] [blame] | 806 | .. method:: SSLContext.load_dh_params(dhfile) |
| 807 | |
| 808 | Load the key generation parameters for Diffie-Helman (DH) key exchange. |
| 809 | Using DH key exchange improves forward secrecy at the expense of |
| 810 | computational resources (both on the server and on the client). |
| 811 | The *dhfile* parameter should be the path to a file containing DH |
| 812 | parameters in PEM format. |
| 813 | |
| 814 | This setting doesn't apply to client sockets. You can also use the |
| 815 | :data:`OP_SINGLE_DH_USE` option to further improve security. |
| 816 | |
| 817 | .. versionadded:: 3.3 |
| 818 | |
Antoine Pitrou | 923df6f | 2011-12-19 17:16:51 +0100 | [diff] [blame] | 819 | .. method:: SSLContext.set_ecdh_curve(curve_name) |
| 820 | |
Antoine Pitrou | 0e576f1 | 2011-12-22 10:03:38 +0100 | [diff] [blame] | 821 | Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key |
| 822 | exchange. ECDH is significantly faster than regular DH while arguably |
| 823 | as secure. The *curve_name* parameter should be a string describing |
Antoine Pitrou | 923df6f | 2011-12-19 17:16:51 +0100 | [diff] [blame] | 824 | a well-known elliptic curve, for example ``prime256v1`` for a widely |
| 825 | supported curve. |
| 826 | |
| 827 | This setting doesn't apply to client sockets. You can also use the |
| 828 | :data:`OP_SINGLE_ECDH_USE` option to further improve security. |
| 829 | |
Antoine Pitrou | 501da61 | 2011-12-21 09:27:41 +0100 | [diff] [blame] | 830 | This method is not available if :data:`HAS_ECDH` is False. |
| 831 | |
Antoine Pitrou | 923df6f | 2011-12-19 17:16:51 +0100 | [diff] [blame] | 832 | .. versionadded:: 3.3 |
| 833 | |
| 834 | .. seealso:: |
| 835 | `SSL/TLS & Perfect Forward Secrecy <http://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy.html>`_ |
| 836 | Vincent Bernat. |
| 837 | |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 838 | .. method:: SSLContext.wrap_socket(sock, server_side=False, \ |
| 839 | do_handshake_on_connect=True, suppress_ragged_eofs=True, \ |
| 840 | server_hostname=None) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 841 | |
| 842 | Wrap an existing Python socket *sock* and return an :class:`SSLSocket` |
Antoine Pitrou | 3e86ba4 | 2013-12-28 17:26:33 +0100 | [diff] [blame] | 843 | object. *sock* must be a :data:`~socket.SOCK_STREAM` socket; other socket |
| 844 | types are unsupported. |
| 845 | |
| 846 | The returned SSL socket is tied to the context, its settings and |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 847 | certificates. The parameters *server_side*, *do_handshake_on_connect* |
| 848 | and *suppress_ragged_eofs* have the same meaning as in the top-level |
| 849 | :func:`wrap_socket` function. |
| 850 | |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 851 | On client connections, the optional parameter *server_hostname* specifies |
| 852 | the hostname of the service which we are connecting to. This allows a |
| 853 | single server to host multiple SSL-based services with distinct certificates, |
| 854 | quite similarly to HTTP virtual hosts. Specifying *server_hostname* |
| 855 | will raise a :exc:`ValueError` if the OpenSSL library doesn't have support |
| 856 | for it (that is, if :data:`HAS_SNI` is :const:`False`). Specifying |
| 857 | *server_hostname* will also raise a :exc:`ValueError` if *server_side* |
| 858 | is true. |
| 859 | |
Antoine Pitrou | b0182c8 | 2010-10-12 20:09:02 +0000 | [diff] [blame] | 860 | .. method:: SSLContext.session_stats() |
| 861 | |
| 862 | Get statistics about the SSL sessions created or managed by this context. |
| 863 | A dictionary is returned which maps the names of each `piece of information |
| 864 | <http://www.openssl.org/docs/ssl/SSL_CTX_sess_number.html>`_ to their |
| 865 | numeric values. For example, here is the total number of hits and misses |
| 866 | in the session cache since the context was created:: |
| 867 | |
| 868 | >>> stats = context.session_stats() |
| 869 | >>> stats['hits'], stats['misses'] |
| 870 | (0, 0) |
| 871 | |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 872 | .. attribute:: SSLContext.options |
| 873 | |
| 874 | An integer representing the set of SSL options enabled on this context. |
| 875 | The default value is :data:`OP_ALL`, but you can specify other options |
| 876 | such as :data:`OP_NO_SSLv2` by ORing them together. |
| 877 | |
| 878 | .. note:: |
| 879 | With versions of OpenSSL older than 0.9.8m, it is only possible |
| 880 | to set options, not to clear them. Attempting to clear an option |
| 881 | (by resetting the corresponding bits) will raise a ``ValueError``. |
| 882 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 883 | .. attribute:: SSLContext.protocol |
| 884 | |
| 885 | The protocol version chosen when constructing the context. This attribute |
| 886 | is read-only. |
| 887 | |
| 888 | .. attribute:: SSLContext.verify_mode |
| 889 | |
| 890 | Whether to try to verify other peers' certificates and how to behave |
| 891 | if verification fails. This attribute must be one of |
| 892 | :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`. |
| 893 | |
| 894 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 895 | .. index:: single: certificates |
| 896 | |
| 897 | .. index:: single: X509 certificate |
| 898 | |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 899 | .. _ssl-certificates: |
| 900 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 901 | Certificates |
| 902 | ------------ |
| 903 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 904 | Certificates in general are part of a public-key / private-key system. In this |
| 905 | system, each *principal*, (which may be a machine, or a person, or an |
| 906 | organization) is assigned a unique two-part encryption key. One part of the key |
| 907 | is public, and is called the *public key*; the other part is kept secret, and is |
| 908 | called the *private key*. The two parts are related, in that if you encrypt a |
| 909 | message with one of the parts, you can decrypt it with the other part, and |
| 910 | **only** with the other part. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 911 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 912 | A certificate contains information about two principals. It contains the name |
| 913 | of a *subject*, and the subject's public key. It also contains a statement by a |
| 914 | second principal, the *issuer*, that the subject is who he claims to be, and |
| 915 | that this is indeed the subject's public key. The issuer's statement is signed |
| 916 | with the issuer's private key, which only the issuer knows. However, anyone can |
| 917 | verify the issuer's statement by finding the issuer's public key, decrypting the |
| 918 | statement with it, and comparing it to the other information in the certificate. |
| 919 | The certificate also contains information about the time period over which it is |
| 920 | valid. This is expressed as two fields, called "notBefore" and "notAfter". |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 921 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 922 | In the Python use of certificates, a client or server can use a certificate to |
| 923 | prove who they are. The other side of a network connection can also be required |
| 924 | to produce a certificate, and that certificate can be validated to the |
| 925 | satisfaction of the client or server that requires such validation. The |
| 926 | connection attempt can be set to raise an exception if the validation fails. |
| 927 | Validation is done automatically, by the underlying OpenSSL framework; the |
| 928 | application need not concern itself with its mechanics. But the application |
| 929 | does usually need to provide sets of certificates to allow this process to take |
| 930 | place. |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 931 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 932 | Python uses files to contain certificates. They should be formatted as "PEM" |
| 933 | (see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line |
| 934 | and a footer line:: |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 935 | |
| 936 | -----BEGIN CERTIFICATE----- |
| 937 | ... (certificate in base64 PEM encoding) ... |
| 938 | -----END CERTIFICATE----- |
| 939 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 940 | Certificate chains |
| 941 | ^^^^^^^^^^^^^^^^^^ |
| 942 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 943 | The Python files which contain certificates can contain a sequence of |
| 944 | certificates, sometimes called a *certificate chain*. This chain should start |
| 945 | with the specific certificate for the principal who "is" the client or server, |
| 946 | and then the certificate for the issuer of that certificate, and then the |
| 947 | certificate for the issuer of *that* certificate, and so on up the chain till |
| 948 | you get to a certificate which is *self-signed*, that is, a certificate which |
| 949 | has the same subject and issuer, sometimes called a *root certificate*. The |
| 950 | certificates should just be concatenated together in the certificate file. For |
| 951 | example, suppose we had a three certificate chain, from our server certificate |
| 952 | to the certificate of the certification authority that signed our server |
| 953 | certificate, to the root certificate of the agency which issued the |
| 954 | certification authority's certificate:: |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 955 | |
| 956 | -----BEGIN CERTIFICATE----- |
| 957 | ... (certificate for your server)... |
| 958 | -----END CERTIFICATE----- |
| 959 | -----BEGIN CERTIFICATE----- |
| 960 | ... (the certificate for the CA)... |
| 961 | -----END CERTIFICATE----- |
| 962 | -----BEGIN CERTIFICATE----- |
| 963 | ... (the root certificate for the CA's issuer)... |
| 964 | -----END CERTIFICATE----- |
| 965 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 966 | CA certificates |
| 967 | ^^^^^^^^^^^^^^^ |
| 968 | |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 969 | If you are going to require validation of the other side of the connection's |
| 970 | certificate, you need to provide a "CA certs" file, filled with the certificate |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 971 | chains for each issuer you are willing to trust. Again, this file just contains |
| 972 | these chains concatenated together. For validation, Python will use the first |
| 973 | chain it finds in the file which matches. Some "standard" root certificates are |
| 974 | available from various certification authorities: `CACert.org |
| 975 | <http://www.cacert.org/index.php?id=3>`_, `Thawte |
| 976 | <http://www.thawte.com/roots/>`_, `Verisign |
| 977 | <http://www.verisign.com/support/roots.html>`_, `Positive SSL |
| 978 | <http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_ |
| 979 | (used by python.org), `Equifax and GeoTrust |
| 980 | <http://www.geotrust.com/resources/root_certificates/index.asp>`_. |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 981 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 982 | In general, if you are using SSL3 or TLS1, you don't need to put the full chain |
| 983 | in your "CA certs" file; you only need the root certificates, and the remote |
| 984 | peer is supposed to furnish the other certificates necessary to chain from its |
| 985 | certificate to a root certificate. See :rfc:`4158` for more discussion of the |
| 986 | way in which certification chains can be built. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 987 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 988 | Combined key and certificate |
| 989 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 990 | |
| 991 | Often the private key is stored in the same file as the certificate; in this |
| 992 | case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain` |
| 993 | and :func:`wrap_socket` needs to be passed. If the private key is stored |
| 994 | with the certificate, it should come before the first certificate in |
| 995 | the certificate chain:: |
| 996 | |
| 997 | -----BEGIN RSA PRIVATE KEY----- |
| 998 | ... (private key in base64 encoding) ... |
| 999 | -----END RSA PRIVATE KEY----- |
| 1000 | -----BEGIN CERTIFICATE----- |
| 1001 | ... (certificate in base64 PEM encoding) ... |
| 1002 | -----END CERTIFICATE----- |
| 1003 | |
| 1004 | Self-signed certificates |
| 1005 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1006 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 1007 | If you are going to create a server that provides SSL-encrypted connection |
| 1008 | services, you will need to acquire a certificate for that service. There are |
| 1009 | many ways of acquiring appropriate certificates, such as buying one from a |
| 1010 | certification authority. Another common practice is to generate a self-signed |
| 1011 | certificate. The simplest way to do this is with the OpenSSL package, using |
| 1012 | something like the following:: |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1013 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1014 | % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem |
| 1015 | Generating a 1024 bit RSA private key |
| 1016 | .......++++++ |
| 1017 | .............................++++++ |
| 1018 | writing new private key to 'cert.pem' |
| 1019 | ----- |
| 1020 | You are about to be asked to enter information that will be incorporated |
| 1021 | into your certificate request. |
| 1022 | What you are about to enter is what is called a Distinguished Name or a DN. |
| 1023 | There are quite a few fields but you can leave some blank |
| 1024 | For some fields there will be a default value, |
| 1025 | If you enter '.', the field will be left blank. |
| 1026 | ----- |
| 1027 | Country Name (2 letter code) [AU]:US |
| 1028 | State or Province Name (full name) [Some-State]:MyState |
| 1029 | Locality Name (eg, city) []:Some City |
| 1030 | Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc. |
| 1031 | Organizational Unit Name (eg, section) []:My Group |
| 1032 | Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com |
| 1033 | Email Address []:ops@myserver.mygroup.myorganization.com |
| 1034 | % |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1035 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 1036 | The disadvantage of a self-signed certificate is that it is its own root |
| 1037 | certificate, and no one else will have it in their cache of known (and trusted) |
| 1038 | root certificates. |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1039 | |
| 1040 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1041 | Examples |
| 1042 | -------- |
| 1043 | |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1044 | Testing for SSL support |
| 1045 | ^^^^^^^^^^^^^^^^^^^^^^^ |
| 1046 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 1047 | To test for the presence of SSL support in a Python installation, user code |
| 1048 | should use the following idiom:: |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1049 | |
| 1050 | try: |
Georg Brandl | 8a7e5da | 2011-01-02 19:07:51 +0000 | [diff] [blame] | 1051 | import ssl |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1052 | except ImportError: |
Georg Brandl | 8a7e5da | 2011-01-02 19:07:51 +0000 | [diff] [blame] | 1053 | pass |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1054 | else: |
Georg Brandl | 8a7e5da | 2011-01-02 19:07:51 +0000 | [diff] [blame] | 1055 | ... # do something that requires SSL support |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1056 | |
| 1057 | Client-side operation |
| 1058 | ^^^^^^^^^^^^^^^^^^^^^ |
| 1059 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 1060 | This example connects to an SSL server and prints the server's certificate:: |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1061 | |
| 1062 | import socket, ssl, pprint |
| 1063 | |
| 1064 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1065 | # require a certificate from the server |
| 1066 | ssl_sock = ssl.wrap_socket(s, |
| 1067 | ca_certs="/etc/ca_certs_file", |
| 1068 | cert_reqs=ssl.CERT_REQUIRED) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1069 | ssl_sock.connect(('www.verisign.com', 443)) |
| 1070 | |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 1071 | pprint.pprint(ssl_sock.getpeercert()) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1072 | # note that closing the SSLSocket will also close the underlying socket |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1073 | ssl_sock.close() |
| 1074 | |
Antoine Pitrou | 441ae04 | 2012-01-06 20:06:15 +0100 | [diff] [blame] | 1075 | As of January 6, 2012, the certificate printed by this program looks like |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 1076 | this:: |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1077 | |
Antoine Pitrou | 441ae04 | 2012-01-06 20:06:15 +0100 | [diff] [blame] | 1078 | {'issuer': ((('countryName', 'US'),), |
| 1079 | (('organizationName', 'VeriSign, Inc.'),), |
| 1080 | (('organizationalUnitName', 'VeriSign Trust Network'),), |
| 1081 | (('organizationalUnitName', |
| 1082 | 'Terms of use at https://www.verisign.com/rpa (c)06'),), |
| 1083 | (('commonName', |
| 1084 | 'VeriSign Class 3 Extended Validation SSL SGC CA'),)), |
| 1085 | 'notAfter': 'May 25 23:59:59 2012 GMT', |
| 1086 | 'notBefore': 'May 26 00:00:00 2010 GMT', |
| 1087 | 'serialNumber': '53D2BEF924A7245E83CA01E46CAA2477', |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 1088 | 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),), |
| 1089 | (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),), |
| 1090 | (('businessCategory', 'V1.0, Clause 5.(b)'),), |
| 1091 | (('serialNumber', '2497886'),), |
| 1092 | (('countryName', 'US'),), |
| 1093 | (('postalCode', '94043'),), |
| 1094 | (('stateOrProvinceName', 'California'),), |
| 1095 | (('localityName', 'Mountain View'),), |
| 1096 | (('streetAddress', '487 East Middlefield Road'),), |
| 1097 | (('organizationName', 'VeriSign, Inc.'),), |
| 1098 | (('organizationalUnitName', ' Production Security Services'),), |
Antoine Pitrou | 441ae04 | 2012-01-06 20:06:15 +0100 | [diff] [blame] | 1099 | (('commonName', 'www.verisign.com'),)), |
| 1100 | 'subjectAltName': (('DNS', 'www.verisign.com'), |
| 1101 | ('DNS', 'verisign.com'), |
| 1102 | ('DNS', 'www.verisign.net'), |
| 1103 | ('DNS', 'verisign.net'), |
| 1104 | ('DNS', 'www.verisign.mobi'), |
| 1105 | ('DNS', 'verisign.mobi'), |
| 1106 | ('DNS', 'www.verisign.eu'), |
| 1107 | ('DNS', 'verisign.eu')), |
| 1108 | 'version': 3} |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1109 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1110 | This other example first creates an SSL context, instructs it to verify |
| 1111 | certificates sent by peers, and feeds it a set of recognized certificate |
| 1112 | authorities (CA):: |
| 1113 | |
| 1114 | >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 1115 | >>> context.verify_mode = ssl.CERT_REQUIRED |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1116 | >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt") |
| 1117 | |
| 1118 | (it is assumed your operating system places a bundle of all CA certificates |
| 1119 | in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have |
| 1120 | to adjust the location) |
| 1121 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 1122 | When you use the context to connect to a server, :const:`CERT_REQUIRED` |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1123 | validates the server certificate: it ensures that the server certificate |
| 1124 | was signed with one of the CA certificates, and checks the signature for |
| 1125 | correctness:: |
| 1126 | |
| 1127 | >>> conn = context.wrap_socket(socket.socket(socket.AF_INET)) |
| 1128 | >>> conn.connect(("linuxfr.org", 443)) |
| 1129 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 1130 | You should then fetch the certificate and check its fields for conformity:: |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1131 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 1132 | >>> cert = conn.getpeercert() |
| 1133 | >>> ssl.match_hostname(cert, "linuxfr.org") |
| 1134 | |
| 1135 | Visual inspection shows that the certificate does identify the desired service |
| 1136 | (that is, the HTTPS host ``linuxfr.org``):: |
| 1137 | |
| 1138 | >>> pprint.pprint(cert) |
Antoine Pitrou | 441ae04 | 2012-01-06 20:06:15 +0100 | [diff] [blame] | 1139 | {'issuer': ((('organizationName', 'CAcert Inc.'),), |
| 1140 | (('organizationalUnitName', 'http://www.CAcert.org'),), |
| 1141 | (('commonName', 'CAcert Class 3 Root'),)), |
| 1142 | 'notAfter': 'Jun 7 21:02:24 2013 GMT', |
| 1143 | 'notBefore': 'Jun 8 21:02:24 2011 GMT', |
| 1144 | 'serialNumber': 'D3E9', |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1145 | 'subject': ((('commonName', 'linuxfr.org'),),), |
Antoine Pitrou | 441ae04 | 2012-01-06 20:06:15 +0100 | [diff] [blame] | 1146 | 'subjectAltName': (('DNS', 'linuxfr.org'), |
| 1147 | ('othername', '<unsupported>'), |
| 1148 | ('DNS', 'linuxfr.org'), |
| 1149 | ('othername', '<unsupported>'), |
| 1150 | ('DNS', 'dev.linuxfr.org'), |
| 1151 | ('othername', '<unsupported>'), |
| 1152 | ('DNS', 'prod.linuxfr.org'), |
| 1153 | ('othername', '<unsupported>'), |
| 1154 | ('DNS', 'alpha.linuxfr.org'), |
| 1155 | ('othername', '<unsupported>'), |
| 1156 | ('DNS', '*.linuxfr.org'), |
| 1157 | ('othername', '<unsupported>')), |
| 1158 | 'version': 3} |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1159 | |
| 1160 | Now that you are assured of its authenticity, you can proceed to talk with |
| 1161 | the server:: |
| 1162 | |
Antoine Pitrou | dab6426 | 2010-09-19 13:31:06 +0000 | [diff] [blame] | 1163 | >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n") |
| 1164 | >>> pprint.pprint(conn.recv(1024).split(b"\r\n")) |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1165 | [b'HTTP/1.1 302 Found', |
| 1166 | b'Date: Sun, 16 May 2010 13:43:28 GMT', |
| 1167 | b'Server: Apache/2.2', |
| 1168 | b'Location: https://linuxfr.org/pub/', |
| 1169 | b'Vary: Accept-Encoding', |
| 1170 | b'Connection: close', |
| 1171 | b'Content-Type: text/html; charset=iso-8859-1', |
| 1172 | b'', |
| 1173 | b''] |
| 1174 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1175 | See the discussion of :ref:`ssl-security` below. |
| 1176 | |
| 1177 | |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1178 | Server-side operation |
| 1179 | ^^^^^^^^^^^^^^^^^^^^^ |
| 1180 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1181 | For server operation, typically you'll need to have a server certificate, and |
| 1182 | private key, each in a file. You'll first create a context holding the key |
| 1183 | and the certificate, so that clients can check your authenticity. Then |
| 1184 | you'll open a socket, bind it to a port, call :meth:`listen` on it, and start |
| 1185 | waiting for clients to connect:: |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1186 | |
| 1187 | import socket, ssl |
| 1188 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1189 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 1190 | context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile") |
| 1191 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1192 | bindsocket = socket.socket() |
| 1193 | bindsocket.bind(('myaddr.mydomain.com', 10023)) |
| 1194 | bindsocket.listen(5) |
| 1195 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1196 | When a client connects, you'll call :meth:`accept` on the socket to get the |
| 1197 | new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket` |
| 1198 | method to create a server-side SSL socket for the connection:: |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1199 | |
| 1200 | while True: |
Georg Brandl | 8a7e5da | 2011-01-02 19:07:51 +0000 | [diff] [blame] | 1201 | newsocket, fromaddr = bindsocket.accept() |
| 1202 | connstream = context.wrap_socket(newsocket, server_side=True) |
| 1203 | try: |
| 1204 | deal_with_client(connstream) |
| 1205 | finally: |
Antoine Pitrou | b205d58 | 2011-01-02 22:09:27 +0000 | [diff] [blame] | 1206 | connstream.shutdown(socket.SHUT_RDWR) |
Georg Brandl | 8a7e5da | 2011-01-02 19:07:51 +0000 | [diff] [blame] | 1207 | connstream.close() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1208 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1209 | Then you'll read data from the ``connstream`` and do something with it till you |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 1210 | are finished with the client (or the client is finished with you):: |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1211 | |
| 1212 | def deal_with_client(connstream): |
Georg Brandl | 8a7e5da | 2011-01-02 19:07:51 +0000 | [diff] [blame] | 1213 | data = connstream.recv(1024) |
| 1214 | # empty data means the client is finished with us |
| 1215 | while data: |
| 1216 | if not do_something(connstream, data): |
| 1217 | # we'll assume do_something returns False |
| 1218 | # when we're finished with client |
| 1219 | break |
| 1220 | data = connstream.recv(1024) |
| 1221 | # finished with client |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1222 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1223 | And go back to listening for new client connections (of course, a real server |
| 1224 | would probably handle each client connection in a separate thread, or put |
| 1225 | the sockets in non-blocking mode and use an event loop). |
| 1226 | |
| 1227 | |
Antoine Pitrou | 6f5dcb1 | 2011-07-11 01:35:48 +0200 | [diff] [blame] | 1228 | .. _ssl-nonblocking: |
| 1229 | |
| 1230 | Notes on non-blocking sockets |
| 1231 | ----------------------------- |
| 1232 | |
| 1233 | When working with non-blocking sockets, there are several things you need |
| 1234 | to be aware of: |
| 1235 | |
| 1236 | - Calling :func:`~select.select` tells you that the OS-level socket can be |
| 1237 | read from (or written to), but it does not imply that there is sufficient |
| 1238 | data at the upper SSL layer. For example, only part of an SSL frame might |
| 1239 | have arrived. Therefore, you must be ready to handle :meth:`SSLSocket.recv` |
| 1240 | and :meth:`SSLSocket.send` failures, and retry after another call to |
| 1241 | :func:`~select.select`. |
| 1242 | |
| 1243 | (of course, similar provisions apply when using other primitives such as |
| 1244 | :func:`~select.poll`) |
| 1245 | |
| 1246 | - The SSL handshake itself will be non-blocking: the |
| 1247 | :meth:`SSLSocket.do_handshake` method has to be retried until it returns |
| 1248 | successfully. Here is a synopsis using :func:`~select.select` to wait for |
| 1249 | the socket's readiness:: |
| 1250 | |
| 1251 | while True: |
| 1252 | try: |
| 1253 | sock.do_handshake() |
| 1254 | break |
Antoine Pitrou | 873bf26 | 2011-10-27 23:59:03 +0200 | [diff] [blame] | 1255 | except ssl.SSLWantReadError: |
| 1256 | select.select([sock], [], []) |
| 1257 | except ssl.SSLWantWriteError: |
| 1258 | select.select([], [sock], []) |
Antoine Pitrou | 6f5dcb1 | 2011-07-11 01:35:48 +0200 | [diff] [blame] | 1259 | |
| 1260 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1261 | .. _ssl-security: |
| 1262 | |
| 1263 | Security considerations |
| 1264 | ----------------------- |
| 1265 | |
| 1266 | Verifying certificates |
| 1267 | ^^^^^^^^^^^^^^^^^^^^^^ |
| 1268 | |
| 1269 | :const:`CERT_NONE` is the default. Since it does not authenticate the other |
| 1270 | peer, it can be insecure, especially in client mode where most of time you |
| 1271 | would like to ensure the authenticity of the server you're talking to. |
| 1272 | Therefore, when in client mode, it is highly recommended to use |
| 1273 | :const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 1274 | have to check that the server certificate, which can be obtained by calling |
| 1275 | :meth:`SSLSocket.getpeercert`, matches the desired service. For many |
| 1276 | protocols and applications, the service can be identified by the hostname; |
| 1277 | in this case, the :func:`match_hostname` function can be used. |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 1278 | |
| 1279 | In server mode, if you want to authenticate your clients using the SSL layer |
| 1280 | (rather than using a higher-level authentication mechanism), you'll also have |
| 1281 | to specify :const:`CERT_REQUIRED` and similarly check the client certificate. |
| 1282 | |
| 1283 | .. note:: |
| 1284 | |
| 1285 | In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are |
| 1286 | equivalent unless anonymous ciphers are enabled (they are disabled |
| 1287 | by default). |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1288 | |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 1289 | Protocol versions |
| 1290 | ^^^^^^^^^^^^^^^^^ |
| 1291 | |
| 1292 | SSL version 2 is considered insecure and is therefore dangerous to use. If |
| 1293 | you want maximum compatibility between clients and servers, it is recommended |
| 1294 | to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable |
| 1295 | SSLv2 explicitly using the :data:`SSLContext.options` attribute:: |
| 1296 | |
| 1297 | context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
| 1298 | context.options |= ssl.OP_NO_SSLv2 |
| 1299 | |
| 1300 | The SSL context created above will allow SSLv3 and TLSv1 connections, but |
| 1301 | not SSLv2. |
| 1302 | |
Antoine Pitrou | b7ffed8 | 2012-01-04 02:53:44 +0100 | [diff] [blame] | 1303 | Cipher selection |
| 1304 | ^^^^^^^^^^^^^^^^ |
| 1305 | |
| 1306 | If you have advanced security requirements, fine-tuning of the ciphers |
| 1307 | enabled when negotiating a SSL session is possible through the |
| 1308 | :meth:`SSLContext.set_ciphers` method. Starting from Python 3.2.3, the |
| 1309 | ssl module disables certain weak ciphers by default, but you may want |
| 1310 | to further restrict the cipher choice. For example:: |
| 1311 | |
| 1312 | context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) |
| 1313 | context.set_ciphers('HIGH:!aNULL:!eNULL') |
| 1314 | |
| 1315 | The ``!aNULL:!eNULL`` part of the cipher spec is necessary to disable ciphers |
| 1316 | which don't provide both encryption and authentication. Be sure to read |
| 1317 | OpenSSL's documentation about the `cipher list |
| 1318 | format <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_. |
| 1319 | If you want to check which ciphers are enabled by a given cipher list, |
| 1320 | use the ``openssl ciphers`` command on your system. |
| 1321 | |
Antoine Pitrou | 9eefe91 | 2013-11-17 15:35:33 +0100 | [diff] [blame] | 1322 | Multi-processing |
| 1323 | ^^^^^^^^^^^^^^^^ |
| 1324 | |
| 1325 | If using this module as part of a multi-processed application (using, |
| 1326 | for example the :mod:`multiprocessing` or :mod:`concurrent.futures` modules), |
| 1327 | be aware that OpenSSL's internal random number generator does not properly |
| 1328 | handle forked processes. Applications must change the PRNG state of the |
| 1329 | parent process if they use any SSL feature with :func:`os.fork`. Any |
| 1330 | successful call of :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or |
| 1331 | :func:`~ssl.RAND_pseudo_bytes` is sufficient. |
| 1332 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1333 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1334 | .. seealso:: |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1335 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1336 | Class :class:`socket.socket` |
Georg Brandl | 4a6cf6c | 2013-10-06 18:20:31 +0200 | [diff] [blame] | 1337 | Documentation of underlying :mod:`socket` class |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1338 | |
Georg Brandl | 4a6cf6c | 2013-10-06 18:20:31 +0200 | [diff] [blame] | 1339 | `SSL/TLS Strong Encryption: An Introduction <http://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html>`_ |
| 1340 | Intro from the Apache webserver documentation |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1341 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1342 | `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_ |
| 1343 | Steve Kent |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 1344 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1345 | `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_ |
| 1346 | D. Eastlake et. al. |
Thomas Wouters | 89d996e | 2007-09-08 17:39:28 +0000 | [diff] [blame] | 1347 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 1348 | `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_ |
| 1349 | Housley et. al. |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 1350 | |
| 1351 | `RFC 4366: Transport Layer Security (TLS) Extensions <http://www.ietf.org/rfc/rfc4366>`_ |
| 1352 | Blake-Wilson et. al. |