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