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