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