Antoine Pitrou | 9e7d6e5 | 2011-01-02 22:39:10 +0000 | [diff] [blame] | 1 | :mod:`ssl` --- TLS/SSL wrapper for socket objects |
| 2 | ================================================= |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 3 | |
| 4 | .. module:: ssl |
Antoine Pitrou | 9e7d6e5 | 2011-01-02 22:39:10 +0000 | [diff] [blame] | 5 | :synopsis: TLS/SSL wrapper for socket objects |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 6 | |
| 7 | .. moduleauthor:: Bill Janssen <bill.janssen@gmail.com> |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 8 | .. sectionauthor:: Bill Janssen <bill.janssen@gmail.com> |
| 9 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 10 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 11 | .. index:: single: OpenSSL; (use in module ssl) |
| 12 | |
| 13 | .. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer |
| 14 | |
Éric Araujo | 29a0b57 | 2011-08-19 02:14:03 +0200 | [diff] [blame] | 15 | .. versionadded:: 2.6 |
| 16 | |
| 17 | **Source code:** :source:`Lib/ssl.py` |
| 18 | |
| 19 | -------------- |
| 20 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 21 | This module provides access to Transport Layer Security (often known as "Secure |
| 22 | Sockets Layer") encryption and peer authentication facilities for network |
| 23 | sockets, both client-side and server-side. This module uses the OpenSSL |
| 24 | library. It is available on all modern Unix systems, Windows, Mac OS X, and |
| 25 | probably additional platforms, as long as OpenSSL is installed on that platform. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 26 | |
| 27 | .. note:: |
| 28 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 29 | Some behavior may be platform dependent, since calls are made to the |
| 30 | operating system socket APIs. The installed version of OpenSSL may also |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 31 | cause variations in behavior. For example, TLSv1.1 and TLSv1.2 come with |
| 32 | openssl version 1.0.1. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 33 | |
Christian Heimes | 88b2220 | 2013-10-29 21:08:56 +0100 | [diff] [blame] | 34 | .. warning:: |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 35 | Don't use this module without reading the :ref:`ssl-security`. Doing so |
| 36 | may lead to a false sense of security, as the default settings of the |
| 37 | ssl module are not necessarily appropriate for your application. |
Antoine Pitrou | f7a5247 | 2013-11-17 15:42:58 +0100 | [diff] [blame] | 38 | |
Christian Heimes | 88b2220 | 2013-10-29 21:08:56 +0100 | [diff] [blame] | 39 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 40 | This section documents the objects and functions in the ``ssl`` module; for more |
| 41 | general information about TLS, SSL, and certificates, the reader is referred to |
| 42 | the documents in the "See Also" section at the bottom. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 43 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 44 | This module provides a class, :class:`ssl.SSLSocket`, which is derived from the |
| 45 | :class:`socket.socket` type, and provides a socket-like wrapper that also |
| 46 | encrypts and decrypts the data going over the socket with SSL. It supports |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 47 | additional methods such as :meth:`getpeercert`, which retrieves the |
| 48 | certificate of the other side of the connection, and :meth:`cipher`,which |
| 49 | retrieves the cipher being used for the secure connection. |
| 50 | |
| 51 | For more sophisticated applications, the :class:`ssl.SSLContext` class |
| 52 | helps manage settings and certificates, which can then be inherited |
| 53 | by SSL sockets created through the :meth:`SSLContext.wrap_socket` method. |
| 54 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 55 | |
Bill Janssen | 93bf9ce | 2007-09-11 02:42:07 +0000 | [diff] [blame] | 56 | Functions, Constants, and Exceptions |
| 57 | ------------------------------------ |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 58 | |
Bill Janssen | 93bf9ce | 2007-09-11 02:42:07 +0000 | [diff] [blame] | 59 | .. exception:: SSLError |
| 60 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 61 | Raised to signal an error from the underlying SSL implementation (currently |
| 62 | provided by the OpenSSL library). This signifies some problem in the |
| 63 | higher-level encryption and authentication layer that's superimposed on the |
| 64 | underlying network connection. This error is a subtype of |
| 65 | :exc:`socket.error`, which in turn is a subtype of :exc:`IOError`. The |
| 66 | error code and message of :exc:`SSLError` instances are provided by the |
| 67 | OpenSSL library. |
Bill Janssen | 93bf9ce | 2007-09-11 02:42:07 +0000 | [diff] [blame] | 68 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 69 | .. attribute:: library |
| 70 | |
| 71 | A string mnemonic designating the OpenSSL submodule in which the error |
| 72 | occurred, such as ``SSL``, ``PEM`` or ``X509``. The range of possible |
| 73 | values depends on the OpenSSL version. |
| 74 | |
| 75 | .. versionadded:: 2.7.9 |
| 76 | |
| 77 | .. attribute:: reason |
| 78 | |
| 79 | A string mnemonic designating the reason this error occurred, for |
| 80 | example ``CERTIFICATE_VERIFY_FAILED``. The range of possible |
| 81 | values depends on the OpenSSL version. |
| 82 | |
| 83 | .. versionadded:: 2.7.9 |
| 84 | |
| 85 | .. exception:: SSLZeroReturnError |
| 86 | |
| 87 | A subclass of :exc:`SSLError` raised when trying to read or write and |
| 88 | the SSL connection has been closed cleanly. Note that this doesn't |
| 89 | mean that the underlying transport (read TCP) has been closed. |
| 90 | |
| 91 | .. versionadded:: 2.7.9 |
| 92 | |
| 93 | .. exception:: SSLWantReadError |
| 94 | |
| 95 | A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket |
| 96 | <ssl-nonblocking>` when trying to read or write data, but more data needs |
| 97 | to be received on the underlying TCP transport before the request can be |
| 98 | fulfilled. |
| 99 | |
| 100 | .. versionadded:: 2.7.9 |
| 101 | |
| 102 | .. exception:: SSLWantWriteError |
| 103 | |
| 104 | A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket |
| 105 | <ssl-nonblocking>` when trying to read or write data, but more data needs |
| 106 | to be sent on the underlying TCP transport before the request can be |
| 107 | fulfilled. |
| 108 | |
| 109 | .. versionadded:: 2.7.9 |
| 110 | |
| 111 | .. exception:: SSLSyscallError |
| 112 | |
| 113 | A subclass of :exc:`SSLError` raised when a system error was encountered |
| 114 | while trying to fulfill an operation on a SSL socket. Unfortunately, |
| 115 | there is no easy way to inspect the original errno number. |
| 116 | |
| 117 | .. versionadded:: 2.7.9 |
| 118 | |
| 119 | .. exception:: SSLEOFError |
| 120 | |
| 121 | A subclass of :exc:`SSLError` raised when the SSL connection has been |
| 122 | terminated abruptly. Generally, you shouldn't try to reuse the underlying |
| 123 | transport when this error is encountered. |
| 124 | |
| 125 | .. versionadded:: 2.7.9 |
| 126 | |
| 127 | .. exception:: CertificateError |
| 128 | |
| 129 | Raised to signal an error with a certificate (such as mismatching |
| 130 | hostname). Certificate errors detected by OpenSSL, though, raise |
| 131 | an :exc:`SSLError`. |
| 132 | |
| 133 | |
| 134 | Socket creation |
| 135 | ^^^^^^^^^^^^^^^ |
| 136 | |
| 137 | The following function allows for standalone socket creation. Starting from |
| 138 | Python 2.7.9, it can be more flexible to use :meth:`SSLContext.wrap_socket` |
| 139 | instead. |
| 140 | |
| 141 | .. 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) |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 142 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 143 | Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance |
| 144 | of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps |
Antoine Pitrou | 63cc99d | 2013-12-28 17:26:33 +0100 | [diff] [blame] | 145 | the underlying socket in an SSL context. ``sock`` must be a |
| 146 | :data:`~socket.SOCK_STREAM` socket; other socket types are unsupported. |
| 147 | |
| 148 | For client-side sockets, the context construction is lazy; if the |
| 149 | underlying socket isn't connected yet, the context construction will be |
| 150 | performed after :meth:`connect` is called on the socket. For |
| 151 | server-side sockets, if the socket has no remote peer, it is assumed |
| 152 | to be a listening socket, and the server-side SSL wrapping is |
| 153 | automatically performed on client connections accepted via the |
| 154 | :meth:`accept` method. :func:`wrap_socket` may raise :exc:`SSLError`. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 155 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 156 | The ``keyfile`` and ``certfile`` parameters specify optional files which |
| 157 | contain a certificate to be used to identify the local side of the |
| 158 | connection. See the discussion of :ref:`ssl-certificates` for more |
| 159 | information on how the certificate is stored in the ``certfile``. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 160 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 161 | The parameter ``server_side`` is a boolean which identifies whether |
| 162 | server-side or client-side behavior is desired from this socket. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 163 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 164 | The parameter ``cert_reqs`` specifies whether a certificate is required from |
| 165 | the other side of the connection, and whether it will be validated if |
| 166 | provided. It must be one of the three values :const:`CERT_NONE` |
| 167 | (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated |
| 168 | if provided), or :const:`CERT_REQUIRED` (required and validated). If the |
| 169 | value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs`` |
| 170 | parameter must point to a file of CA certificates. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 171 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 172 | The ``ca_certs`` file contains a set of concatenated "certification |
| 173 | authority" certificates, which are used to validate certificates passed from |
| 174 | the other end of the connection. See the discussion of |
| 175 | :ref:`ssl-certificates` for more information about how to arrange the |
| 176 | certificates in this file. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 177 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 178 | The parameter ``ssl_version`` specifies which version of the SSL protocol to |
| 179 | use. Typically, the server chooses a particular protocol version, and the |
| 180 | client must adapt to the server's choice. Most of the versions are not |
Antoine Pitrou | 4a7e0c89 | 2012-01-09 21:35:11 +0100 | [diff] [blame] | 181 | interoperable with the other versions. If not specified, the default is |
| 182 | :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 183 | versions. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 184 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 185 | Here's a table showing which versions in a client (down the side) can connect |
| 186 | to which versions in a server (along the top): |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 187 | |
| 188 | .. table:: |
| 189 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 190 | ======================== ========= ========= ========== ========= =========== =========== |
| 191 | *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1** **TLSv1.1** **TLSv1.2** |
| 192 | ------------------------ --------- --------- ---------- --------- ----------- ----------- |
| 193 | *SSLv2* yes no yes no no no |
| 194 | *SSLv3* no yes yes no no no |
Christian Heimes | b9a860f | 2017-09-07 22:31:17 -0700 | [diff] [blame] | 195 | *SSLv23* [1]_ no yes yes yes yes yes |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 196 | *TLSv1* no no yes yes no no |
| 197 | *TLSv1.1* no no yes no yes no |
| 198 | *TLSv1.2* no no yes no no yes |
| 199 | ======================== ========= ========= ========== ========= =========== =========== |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 200 | |
Christian Heimes | b9a860f | 2017-09-07 22:31:17 -0700 | [diff] [blame] | 201 | .. rubric:: Footnotes |
| 202 | .. [1] TLS 1.3 protocol will be available with :data:`PROTOCOL_SSLv23` in |
| 203 | OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for just |
| 204 | TLS 1.3. |
| 205 | |
Antoine Pitrou | 0a6373c | 2010-04-17 17:10:38 +0000 | [diff] [blame] | 206 | .. note:: |
| 207 | |
Andrew M. Kuchling | 3ded421 | 2010-04-30 00:52:31 +0000 | [diff] [blame] | 208 | Which connections succeed will vary depending on the version of |
Antoine Pitrou | bf9eb35 | 2014-12-03 20:00:56 +0100 | [diff] [blame] | 209 | OpenSSL. For example, before OpenSSL 1.0.0, an SSLv23 client |
| 210 | would always attempt SSLv2 connections. |
Antoine Pitrou | 0a6373c | 2010-04-17 17:10:38 +0000 | [diff] [blame] | 211 | |
Andrew M. Kuchling | 3ded421 | 2010-04-30 00:52:31 +0000 | [diff] [blame] | 212 | The *ciphers* parameter sets the available ciphers for this SSL object. |
Antoine Pitrou | 0a6373c | 2010-04-17 17:10:38 +0000 | [diff] [blame] | 213 | It should be a string in the `OpenSSL cipher list format |
Christian Heimes | 5b6452d | 2017-09-20 22:23:09 +0200 | [diff] [blame] | 214 | <https://wiki.openssl.org/index.php/Manual:Ciphers(1)#CIPHER_LIST_FORMAT>`_. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 215 | |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 216 | The parameter ``do_handshake_on_connect`` specifies whether to do the SSL |
| 217 | handshake automatically after doing a :meth:`socket.connect`, or whether the |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 218 | application program will call it explicitly, by invoking the |
| 219 | :meth:`SSLSocket.do_handshake` method. Calling |
| 220 | :meth:`SSLSocket.do_handshake` explicitly gives the program control over the |
| 221 | blocking behavior of the socket I/O involved in the handshake. |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 222 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 223 | The parameter ``suppress_ragged_eofs`` specifies how the |
| 224 | :meth:`SSLSocket.read` method should signal unexpected EOF from the other end |
| 225 | of the connection. If specified as :const:`True` (the default), it returns a |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 226 | normal EOF (an empty bytes object) in response to unexpected EOF errors |
| 227 | raised from the underlying socket; if :const:`False`, it will raise the |
| 228 | exceptions back to the caller. |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 229 | |
Antoine Pitrou | 0a6373c | 2010-04-17 17:10:38 +0000 | [diff] [blame] | 230 | .. versionchanged:: 2.7 |
| 231 | New optional argument *ciphers*. |
| 232 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 233 | |
| 234 | Context creation |
| 235 | ^^^^^^^^^^^^^^^^ |
| 236 | |
| 237 | A convenience function helps create :class:`SSLContext` objects for common |
| 238 | purposes. |
| 239 | |
| 240 | .. function:: create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None) |
| 241 | |
| 242 | Return a new :class:`SSLContext` object with default settings for |
| 243 | the given *purpose*. The settings are chosen by the :mod:`ssl` module, |
| 244 | and usually represent a higher security level than when calling the |
| 245 | :class:`SSLContext` constructor directly. |
| 246 | |
| 247 | *cafile*, *capath*, *cadata* represent optional CA certificates to |
| 248 | trust for certificate verification, as in |
| 249 | :meth:`SSLContext.load_verify_locations`. If all three are |
| 250 | :const:`None`, this function can choose to trust the system's default |
| 251 | CA certificates instead. |
| 252 | |
Benjamin Peterson | 5151838 | 2015-03-16 12:43:38 -0500 | [diff] [blame] | 253 | The settings are: :data:`PROTOCOL_SSLv23`, :data:`OP_NO_SSLv2`, and |
| 254 | :data:`OP_NO_SSLv3` with high encryption cipher suites without RC4 and |
| 255 | without unauthenticated cipher suites. Passing :data:`~Purpose.SERVER_AUTH` |
| 256 | as *purpose* sets :data:`~SSLContext.verify_mode` to :data:`CERT_REQUIRED` |
| 257 | and either loads CA certificates (when at least one of *cafile*, *capath* or |
| 258 | *cadata* is given) or uses :meth:`SSLContext.load_default_certs` to load |
| 259 | default CA certificates. |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 260 | |
| 261 | .. note:: |
| 262 | The protocol, options, cipher and other settings may change to more |
| 263 | restrictive values anytime without prior deprecation. The values |
| 264 | represent a fair balance between compatibility and security. |
| 265 | |
| 266 | If your application needs specific settings, you should create a |
| 267 | :class:`SSLContext` and apply the settings yourself. |
| 268 | |
| 269 | .. note:: |
| 270 | If you find that when certain older clients or servers attempt to connect |
Benjamin Peterson | ce29e87 | 2015-04-08 11:11:00 -0400 | [diff] [blame] | 271 | with a :class:`SSLContext` created by this function that they get an error |
| 272 | stating "Protocol or cipher suite mismatch", it may be that they only |
| 273 | support SSL3.0 which this function excludes using the |
| 274 | :data:`OP_NO_SSLv3`. SSL3.0 is widely considered to be `completely broken |
| 275 | <https://en.wikipedia.org/wiki/POODLE>`_. If you still wish to continue to |
| 276 | use this function but still allow SSL 3.0 connections you can re-enable |
| 277 | them using:: |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 278 | |
| 279 | ctx = ssl.create_default_context(Purpose.CLIENT_AUTH) |
| 280 | ctx.options &= ~ssl.OP_NO_SSLv3 |
| 281 | |
| 282 | .. versionadded:: 2.7.9 |
| 283 | |
Benjamin Peterson | 5151838 | 2015-03-16 12:43:38 -0500 | [diff] [blame] | 284 | .. versionchanged:: 2.7.10 |
| 285 | |
| 286 | RC4 was dropped from the default cipher string. |
| 287 | |
Christian Heimes | d988f42 | 2016-09-06 20:06:47 +0200 | [diff] [blame] | 288 | .. versionchanged:: 2.7.13 |
| 289 | |
| 290 | ChaCha20/Poly1305 was added to the default cipher string. |
| 291 | |
| 292 | 3DES was dropped from the default cipher string. |
| 293 | |
Christian Heimes | b9a860f | 2017-09-07 22:31:17 -0700 | [diff] [blame] | 294 | .. versionchanged:: 2.7.15 |
| 295 | |
| 296 | TLS 1.3 cipher suites TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, |
| 297 | and TLS_CHACHA20_POLY1305_SHA256 were added to the default cipher string. |
| 298 | |
Nick Coghlan | dbcd457 | 2016-03-20 22:39:15 +1000 | [diff] [blame] | 299 | .. function:: _https_verify_certificates(enable=True) |
| 300 | |
| 301 | Specifies whether or not server certificates are verified when creating |
| 302 | client HTTPS connections without specifying a particular SSL context. |
| 303 | |
| 304 | Starting with Python 2.7.9, :mod:`httplib` and modules which use it, such as |
| 305 | :mod:`urllib2` and :mod:`xmlrpclib`, default to verifying remote server |
| 306 | certificates received when establishing client HTTPS connections. This |
| 307 | default verification checks that the certificate is signed by a Certificate |
| 308 | Authority in the system trust store and that the Common Name (or Subject |
| 309 | Alternate Name) on the presented certificate matches the requested host. |
| 310 | |
| 311 | Setting *enable* to :const:`True` ensures this default behaviour is in |
| 312 | effect. |
| 313 | |
| 314 | Setting *enable* to :const:`False` reverts the default HTTPS certificate |
| 315 | handling to that of Python 2.7.8 and earlier, allowing connections to |
| 316 | servers using self-signed certificates, servers using certificates signed |
| 317 | by a Certicate Authority not present in the system trust store, and servers |
| 318 | where the hostname does not match the presented server certificate. |
| 319 | |
| 320 | The leading underscore on this function denotes that it intentionally does |
| 321 | not exist in any implementation of Python 3 and may not be present in all |
| 322 | Python 2.7 implementations. The portable approach to bypassing certificate |
| 323 | checks or the system trust store when necessary is for tools to enable that |
| 324 | on a case-by-case basis by explicitly passing in a suitably configured SSL |
| 325 | context, rather than reverting the default behaviour of the standard library |
| 326 | client modules. |
| 327 | |
| 328 | .. versionadded:: 2.7.12 |
| 329 | |
| 330 | .. seealso:: |
| 331 | |
| 332 | * `CVE-2014-9365 <http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-9365>`_ |
| 333 | -- HTTPS man-in-the-middle attack against Python clients using default settings |
| 334 | * :pep:`476` -- Enabling certificate verification by default for HTTPS |
| 335 | * :pep:`493` -- HTTPS verification migration tools for Python 2.7 |
| 336 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 337 | |
| 338 | Random generation |
| 339 | ^^^^^^^^^^^^^^^^^ |
| 340 | |
Christian Heimes | 4e64c2c | 2016-09-06 23:41:37 +0200 | [diff] [blame] | 341 | .. deprecated:: 2.7.13 |
Christian Heimes | c2fc7c4 | 2016-09-05 23:37:13 +0200 | [diff] [blame] | 342 | |
Christian Heimes | 4e64c2c | 2016-09-06 23:41:37 +0200 | [diff] [blame] | 343 | OpenSSL has deprecated :func:`ssl.RAND_pseudo_bytes`, use |
Christian Heimes | c2fc7c4 | 2016-09-05 23:37:13 +0200 | [diff] [blame] | 344 | :func:`ssl.RAND_bytes` instead. |
| 345 | |
Christian Heimes | c2fc7c4 | 2016-09-05 23:37:13 +0200 | [diff] [blame] | 346 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 347 | .. function:: RAND_status() |
| 348 | |
Benjamin Peterson | 721c86e | 2015-04-11 07:42:42 -0400 | [diff] [blame] | 349 | Return ``True`` if the SSL pseudo-random number generator has been seeded |
| 350 | with 'enough' randomness, and ``False`` otherwise. You can use |
| 351 | :func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness of |
| 352 | the pseudo-random number generator. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 353 | |
| 354 | .. function:: RAND_egd(path) |
| 355 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 356 | If you are running an entropy-gathering daemon (EGD) somewhere, and *path* |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 357 | is the pathname of a socket connection open to it, this will read 256 bytes |
| 358 | of randomness from the socket, and add it to the SSL pseudo-random number |
| 359 | generator to increase the security of generated secret keys. This is |
| 360 | typically only necessary on systems without better sources of randomness. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 361 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 362 | See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources |
| 363 | of entropy-gathering daemons. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 364 | |
Christian Heimes | c2fc7c4 | 2016-09-05 23:37:13 +0200 | [diff] [blame] | 365 | Availability: not available with LibreSSL and OpenSSL > 1.1.0 |
Victor Stinner | 7c90667 | 2015-01-06 13:53:37 +0100 | [diff] [blame] | 366 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 367 | .. function:: RAND_add(bytes, entropy) |
| 368 | |
Benjamin Peterson | 721c86e | 2015-04-11 07:42:42 -0400 | [diff] [blame] | 369 | Mix the given *bytes* into the SSL pseudo-random number generator. The |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 370 | parameter *entropy* (a float) is a lower bound on the entropy contained in |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 371 | string (so you can always use :const:`0.0`). See :rfc:`1750` for more |
| 372 | information on sources of entropy. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 373 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 374 | Certificate handling |
| 375 | ^^^^^^^^^^^^^^^^^^^^ |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 376 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 377 | .. function:: match_hostname(cert, hostname) |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 378 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 379 | Verify that *cert* (in decoded format as returned by |
| 380 | :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules |
| 381 | applied are those for checking the identity of HTTPS servers as outlined |
| 382 | in :rfc:`2818` and :rfc:`6125`, except that IP addresses are not currently |
| 383 | supported. In addition to HTTPS, this function should be suitable for |
| 384 | checking the identity of servers in various SSL-based protocols such as |
| 385 | FTPS, IMAPS, POPS and others. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 386 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 387 | :exc:`CertificateError` is raised on failure. On success, the function |
| 388 | returns nothing:: |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 389 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 390 | >>> cert = {'subject': ((('commonName', 'example.com'),),)} |
| 391 | >>> ssl.match_hostname(cert, "example.com") |
| 392 | >>> ssl.match_hostname(cert, "example.org") |
| 393 | Traceback (most recent call last): |
| 394 | File "<stdin>", line 1, in <module> |
| 395 | File "/home/py3k/Lib/ssl.py", line 130, in match_hostname |
| 396 | ssl.CertificateError: hostname 'example.org' doesn't match 'example.com' |
| 397 | |
| 398 | .. versionadded:: 2.7.9 |
| 399 | |
| 400 | |
| 401 | .. function:: cert_time_to_seconds(cert_time) |
| 402 | |
| 403 | Return the time in seconds since the Epoch, given the ``cert_time`` |
| 404 | string representing the "notBefore" or "notAfter" date from a |
| 405 | certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C |
| 406 | locale). |
| 407 | |
| 408 | Here's an example: |
| 409 | |
| 410 | .. doctest:: newcontext |
| 411 | |
| 412 | >>> import ssl |
| 413 | >>> timestamp = ssl.cert_time_to_seconds("Jan 5 09:34:43 2018 GMT") |
| 414 | >>> timestamp |
| 415 | 1515144883 |
| 416 | >>> from datetime import datetime |
| 417 | >>> print(datetime.utcfromtimestamp(timestamp)) |
| 418 | 2018-01-05 09:34:43 |
| 419 | |
| 420 | "notBefore" or "notAfter" dates must use GMT (:rfc:`5280`). |
| 421 | |
| 422 | .. versionchanged:: 2.7.9 |
| 423 | Interpret the input time as a time in UTC as specified by 'GMT' |
| 424 | timezone in the input string. Local timezone was used |
| 425 | previously. Return an integer (no fractions of a second in the |
| 426 | input format) |
| 427 | |
| 428 | .. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None) |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 429 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 430 | Given the address ``addr`` of an SSL-protected server, as a (*hostname*, |
| 431 | *port-number*) pair, fetches the server's certificate, and returns it as a |
| 432 | PEM-encoded string. If ``ssl_version`` is specified, uses that version of |
| 433 | the SSL protocol to attempt to connect to the server. If ``ca_certs`` is |
| 434 | specified, it should be a file containing a list of root certificates, the |
| 435 | same format as used for the same parameter in :func:`wrap_socket`. The call |
| 436 | will attempt to validate the server certificate against that set of root |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 437 | certificates, and will fail if the validation attempt fails. |
| 438 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 439 | .. versionchanged:: 2.7.9 |
| 440 | |
| 441 | This function is now IPv6-compatible, and the default *ssl_version* is |
| 442 | changed from :data:`PROTOCOL_SSLv3` to :data:`PROTOCOL_SSLv23` for |
| 443 | maximum compatibility with modern servers. |
| 444 | |
| 445 | .. function:: DER_cert_to_PEM_cert(DER_cert_bytes) |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 446 | |
| 447 | Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded |
| 448 | string version of the same certificate. |
| 449 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 450 | .. function:: PEM_cert_to_DER_cert(PEM_cert_string) |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 451 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 452 | Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of |
| 453 | bytes for that same certificate. |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 454 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 455 | .. function:: get_default_verify_paths() |
| 456 | |
| 457 | Returns a named tuple with paths to OpenSSL's default cafile and capath. |
| 458 | The paths are the same as used by |
| 459 | :meth:`SSLContext.set_default_verify_paths`. The return value is a |
| 460 | :term:`named tuple` ``DefaultVerifyPaths``: |
| 461 | |
Serhiy Storchaka | ad13f33 | 2016-10-19 16:29:10 +0300 | [diff] [blame] | 462 | * :attr:`cafile` - resolved path to cafile or ``None`` if the file doesn't exist, |
| 463 | * :attr:`capath` - resolved path to capath or ``None`` if the directory doesn't exist, |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 464 | * :attr:`openssl_cafile_env` - OpenSSL's environment key that points to a cafile, |
| 465 | * :attr:`openssl_cafile` - hard coded path to a cafile, |
| 466 | * :attr:`openssl_capath_env` - OpenSSL's environment key that points to a capath, |
| 467 | * :attr:`openssl_capath` - hard coded path to a capath directory |
| 468 | |
Christian Heimes | c2fc7c4 | 2016-09-05 23:37:13 +0200 | [diff] [blame] | 469 | Availability: LibreSSL ignores the environment vars |
| 470 | :attr:`openssl_cafile_env` and :attr:`openssl_capath_env` |
| 471 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 472 | .. versionadded:: 2.7.9 |
| 473 | |
| 474 | .. function:: enum_certificates(store_name) |
| 475 | |
| 476 | Retrieve certificates from Windows' system cert store. *store_name* may be |
| 477 | one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert |
| 478 | stores, too. |
| 479 | |
| 480 | The function returns a list of (cert_bytes, encoding_type, trust) tuples. |
| 481 | The encoding_type specifies the encoding of cert_bytes. It is either |
| 482 | :const:`x509_asn` for X.509 ASN.1 data or :const:`pkcs_7_asn` for |
| 483 | PKCS#7 ASN.1 data. Trust specifies the purpose of the certificate as a set |
| 484 | of OIDS or exactly ``True`` if the certificate is trustworthy for all |
| 485 | purposes. |
| 486 | |
| 487 | Example:: |
| 488 | |
| 489 | >>> ssl.enum_certificates("CA") |
| 490 | [(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}), |
| 491 | (b'data...', 'x509_asn', True)] |
| 492 | |
| 493 | Availability: Windows. |
| 494 | |
| 495 | .. versionadded:: 2.7.9 |
| 496 | |
| 497 | .. function:: enum_crls(store_name) |
| 498 | |
| 499 | Retrieve CRLs from Windows' system cert store. *store_name* may be |
| 500 | one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert |
| 501 | stores, too. |
| 502 | |
| 503 | The function returns a list of (cert_bytes, encoding_type, trust) tuples. |
| 504 | The encoding_type specifies the encoding of cert_bytes. It is either |
| 505 | :const:`x509_asn` for X.509 ASN.1 data or :const:`pkcs_7_asn` for |
| 506 | PKCS#7 ASN.1 data. |
| 507 | |
| 508 | Availability: Windows. |
| 509 | |
| 510 | .. versionadded:: 2.7.9 |
| 511 | |
| 512 | |
| 513 | Constants |
| 514 | ^^^^^^^^^ |
| 515 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 516 | .. data:: CERT_NONE |
| 517 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 518 | Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` |
| 519 | parameter to :func:`wrap_socket`. In this mode (the default), no |
| 520 | certificates will be required from the other side of the socket connection. |
| 521 | If a certificate is received from the other end, no attempt to validate it |
| 522 | is made. |
| 523 | |
| 524 | See the discussion of :ref:`ssl-security` below. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 525 | |
| 526 | .. data:: CERT_OPTIONAL |
| 527 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 528 | Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` |
| 529 | parameter to :func:`wrap_socket`. In this mode no certificates will be |
| 530 | required from the other side of the socket connection; but if they |
| 531 | are provided, validation will be attempted and an :class:`SSLError` |
| 532 | will be raised on failure. |
| 533 | |
| 534 | Use of this setting requires a valid set of CA certificates to |
| 535 | be passed, either to :meth:`SSLContext.load_verify_locations` or as a |
| 536 | value of the ``ca_certs`` parameter to :func:`wrap_socket`. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 537 | |
| 538 | .. data:: CERT_REQUIRED |
| 539 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 540 | Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs`` |
| 541 | parameter to :func:`wrap_socket`. In this mode, certificates are |
| 542 | required from the other side of the socket connection; an :class:`SSLError` |
| 543 | will be raised if no certificate is provided, or if its validation fails. |
| 544 | |
| 545 | Use of this setting requires a valid set of CA certificates to |
| 546 | be passed, either to :meth:`SSLContext.load_verify_locations` or as a |
| 547 | value of the ``ca_certs`` parameter to :func:`wrap_socket`. |
| 548 | |
| 549 | .. data:: VERIFY_DEFAULT |
| 550 | |
Benjamin Peterson | 72ef961 | 2015-03-04 22:49:41 -0500 | [diff] [blame] | 551 | Possible value for :attr:`SSLContext.verify_flags`. In this mode, certificate |
| 552 | revocation lists (CRLs) are not checked. By default OpenSSL does neither |
| 553 | require nor verify CRLs. |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 554 | |
| 555 | .. versionadded:: 2.7.9 |
| 556 | |
| 557 | .. data:: VERIFY_CRL_CHECK_LEAF |
| 558 | |
| 559 | Possible value for :attr:`SSLContext.verify_flags`. In this mode, only the |
| 560 | peer cert is check but non of the intermediate CA certificates. The mode |
| 561 | requires a valid CRL that is signed by the peer cert's issuer (its direct |
| 562 | ancestor CA). If no proper has been loaded |
| 563 | :attr:`SSLContext.load_verify_locations`, validation will fail. |
| 564 | |
| 565 | .. versionadded:: 2.7.9 |
| 566 | |
| 567 | .. data:: VERIFY_CRL_CHECK_CHAIN |
| 568 | |
| 569 | Possible value for :attr:`SSLContext.verify_flags`. In this mode, CRLs of |
| 570 | all certificates in the peer cert chain are checked. |
| 571 | |
| 572 | .. versionadded:: 2.7.9 |
| 573 | |
| 574 | .. data:: VERIFY_X509_STRICT |
| 575 | |
| 576 | Possible value for :attr:`SSLContext.verify_flags` to disable workarounds |
| 577 | for broken X.509 certificates. |
| 578 | |
| 579 | .. versionadded:: 2.7.9 |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 580 | |
Benjamin Peterson | 72ef961 | 2015-03-04 22:49:41 -0500 | [diff] [blame] | 581 | .. data:: VERIFY_X509_TRUSTED_FIRST |
| 582 | |
| 583 | Possible value for :attr:`SSLContext.verify_flags`. It instructs OpenSSL to |
| 584 | prefer trusted certificates when building the trust chain to validate a |
| 585 | certificate. This flag is enabled by default. |
| 586 | |
| 587 | .. versionadded:: 2.7.10 |
| 588 | |
Christian Heimes | c2fc7c4 | 2016-09-05 23:37:13 +0200 | [diff] [blame] | 589 | .. data:: PROTOCOL_TLS |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 590 | |
| 591 | Selects the highest protocol version that both the client and server support. |
| 592 | Despite the name, this option can select "TLS" protocols as well as "SSL". |
| 593 | |
Christian Heimes | c2fc7c4 | 2016-09-05 23:37:13 +0200 | [diff] [blame] | 594 | .. versionadded:: 2.7.13 |
| 595 | |
| 596 | .. data:: PROTOCOL_SSLv23 |
| 597 | |
| 598 | Alias for ``PROTOCOL_TLS``. |
| 599 | |
| 600 | .. deprecated:: 2.7.13 Use ``PROTOCOL_TLS`` instead. |
| 601 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 602 | .. data:: PROTOCOL_SSLv2 |
| 603 | |
| 604 | Selects SSL version 2 as the channel encryption protocol. |
| 605 | |
Benjamin Peterson | fd0c92f | 2014-12-06 11:36:32 -0500 | [diff] [blame] | 606 | This protocol is not available if OpenSSL is compiled with the |
| 607 | ``OPENSSL_NO_SSL2`` flag. |
Victor Stinner | b1241f9 | 2011-05-10 01:52:03 +0200 | [diff] [blame] | 608 | |
Antoine Pitrou | 308c2af | 2010-05-16 14:16:56 +0000 | [diff] [blame] | 609 | .. warning:: |
| 610 | |
| 611 | SSL version 2 is insecure. Its use is highly discouraged. |
| 612 | |
Christian Heimes | c2fc7c4 | 2016-09-05 23:37:13 +0200 | [diff] [blame] | 613 | .. deprecated:: 2.7.13 OpenSSL has removed support for SSLv2. |
| 614 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 615 | .. data:: PROTOCOL_SSLv3 |
| 616 | |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 617 | Selects SSL version 3 as the channel encryption protocol. |
| 618 | |
Benjamin Peterson | fd0c92f | 2014-12-06 11:36:32 -0500 | [diff] [blame] | 619 | This protocol is not be available if OpenSSL is compiled with the |
| 620 | ``OPENSSL_NO_SSLv3`` flag. |
| 621 | |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 622 | .. warning:: |
| 623 | |
| 624 | SSL version 3 is insecure. Its use is highly discouraged. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 625 | |
Christian Heimes | c2fc7c4 | 2016-09-05 23:37:13 +0200 | [diff] [blame] | 626 | .. deprecated:: 2.7.13 |
| 627 | |
| 628 | OpenSSL has deprecated all version specific protocols. Use the default |
| 629 | protocol with flags like ``OP_NO_SSLv3`` instead. |
| 630 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 631 | .. data:: PROTOCOL_TLSv1 |
| 632 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 633 | Selects TLS version 1.0 as the channel encryption protocol. |
| 634 | |
Christian Heimes | c2fc7c4 | 2016-09-05 23:37:13 +0200 | [diff] [blame] | 635 | .. deprecated:: 2.7.13 |
| 636 | |
| 637 | OpenSSL has deprecated all version specific protocols. Use the default |
| 638 | protocol with flags like ``OP_NO_SSLv3`` instead. |
| 639 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 640 | .. data:: PROTOCOL_TLSv1_1 |
| 641 | |
| 642 | Selects TLS version 1.1 as the channel encryption protocol. |
| 643 | Available only with openssl version 1.0.1+. |
| 644 | |
| 645 | .. versionadded:: 2.7.9 |
| 646 | |
Christian Heimes | c2fc7c4 | 2016-09-05 23:37:13 +0200 | [diff] [blame] | 647 | .. deprecated:: 2.7.13 |
| 648 | |
| 649 | OpenSSL has deprecated all version specific protocols. Use the default |
| 650 | protocol with flags like ``OP_NO_SSLv3`` instead. |
| 651 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 652 | .. data:: PROTOCOL_TLSv1_2 |
| 653 | |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 654 | Selects TLS version 1.2 as the channel encryption protocol. This is the |
| 655 | most modern version, and probably the best choice for maximum protection, |
| 656 | if both sides can speak it. Available only with openssl version 1.0.1+. |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 657 | |
| 658 | .. versionadded:: 2.7.9 |
| 659 | |
Christian Heimes | c2fc7c4 | 2016-09-05 23:37:13 +0200 | [diff] [blame] | 660 | .. deprecated:: 2.7.13 |
| 661 | |
| 662 | OpenSSL has deprecated all version specific protocols. Use the default |
| 663 | protocol with flags like ``OP_NO_SSLv3`` instead. |
| 664 | |
| 665 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 666 | .. data:: OP_ALL |
| 667 | |
| 668 | Enables workarounds for various bugs present in other SSL implementations. |
| 669 | This option is set by default. It does not necessarily set the same |
| 670 | flags as OpenSSL's ``SSL_OP_ALL`` constant. |
| 671 | |
| 672 | .. versionadded:: 2.7.9 |
| 673 | |
| 674 | .. data:: OP_NO_SSLv2 |
| 675 | |
| 676 | Prevents an SSLv2 connection. This option is only applicable in |
| 677 | conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from |
| 678 | choosing SSLv2 as the protocol version. |
| 679 | |
| 680 | .. versionadded:: 2.7.9 |
| 681 | |
| 682 | .. data:: OP_NO_SSLv3 |
| 683 | |
| 684 | Prevents an SSLv3 connection. This option is only applicable in |
| 685 | conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from |
| 686 | choosing SSLv3 as the protocol version. |
| 687 | |
| 688 | .. versionadded:: 2.7.9 |
| 689 | |
| 690 | .. data:: OP_NO_TLSv1 |
| 691 | |
| 692 | Prevents a TLSv1 connection. This option is only applicable in |
| 693 | conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from |
| 694 | choosing TLSv1 as the protocol version. |
| 695 | |
| 696 | .. versionadded:: 2.7.9 |
| 697 | |
| 698 | .. data:: OP_NO_TLSv1_1 |
| 699 | |
| 700 | Prevents a TLSv1.1 connection. This option is only applicable in conjunction |
| 701 | with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.1 as |
| 702 | the protocol version. Available only with openssl version 1.0.1+. |
| 703 | |
| 704 | .. versionadded:: 2.7.9 |
| 705 | |
| 706 | .. data:: OP_NO_TLSv1_2 |
| 707 | |
| 708 | Prevents a TLSv1.2 connection. This option is only applicable in conjunction |
| 709 | with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.2 as |
| 710 | the protocol version. Available only with openssl version 1.0.1+. |
| 711 | |
| 712 | .. versionadded:: 2.7.9 |
| 713 | |
Christian Heimes | b9a860f | 2017-09-07 22:31:17 -0700 | [diff] [blame] | 714 | .. data:: OP_NO_TLSv1_3 |
| 715 | |
| 716 | Prevents a TLSv1.3 connection. This option is only applicable in conjunction |
| 717 | with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.3 as |
| 718 | the protocol version. TLS 1.3 is available with OpenSSL 1.1.1 or later. |
| 719 | When Python has been compiled against an older version of OpenSSL, the |
| 720 | flag defaults to *0*. |
| 721 | |
| 722 | .. versionadded:: 2.7.15 |
| 723 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 724 | .. data:: OP_CIPHER_SERVER_PREFERENCE |
| 725 | |
| 726 | Use the server's cipher ordering preference, rather than the client's. |
| 727 | This option has no effect on client sockets and SSLv2 server sockets. |
| 728 | |
| 729 | .. versionadded:: 2.7.9 |
| 730 | |
| 731 | .. data:: OP_SINGLE_DH_USE |
| 732 | |
| 733 | Prevents re-use of the same DH key for distinct SSL sessions. This |
| 734 | improves forward secrecy but requires more computational resources. |
| 735 | This option only applies to server sockets. |
| 736 | |
| 737 | .. versionadded:: 2.7.9 |
| 738 | |
| 739 | .. data:: OP_SINGLE_ECDH_USE |
| 740 | |
| 741 | Prevents re-use of the same ECDH key for distinct SSL sessions. This |
| 742 | improves forward secrecy but requires more computational resources. |
| 743 | This option only applies to server sockets. |
| 744 | |
| 745 | .. versionadded:: 2.7.9 |
| 746 | |
| 747 | .. data:: OP_NO_COMPRESSION |
| 748 | |
| 749 | Disable compression on the SSL channel. This is useful if the application |
| 750 | protocol supports its own compression scheme. |
| 751 | |
| 752 | This option is only available with OpenSSL 1.0.0 and later. |
| 753 | |
| 754 | .. versionadded:: 2.7.9 |
| 755 | |
Benjamin Peterson | b10bfbe | 2015-01-23 16:35:37 -0500 | [diff] [blame] | 756 | .. data:: HAS_ALPN |
| 757 | |
| 758 | Whether the OpenSSL library has built-in support for the *Application-Layer |
| 759 | Protocol Negotiation* TLS extension as described in :rfc:`7301`. |
| 760 | |
Benjamin Peterson | 65aa261 | 2015-01-23 16:47:52 -0500 | [diff] [blame] | 761 | .. versionadded:: 2.7.10 |
Benjamin Peterson | b10bfbe | 2015-01-23 16:35:37 -0500 | [diff] [blame] | 762 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 763 | .. data:: HAS_ECDH |
| 764 | |
| 765 | Whether the OpenSSL library has built-in support for Elliptic Curve-based |
| 766 | Diffie-Hellman key exchange. This should be true unless the feature was |
| 767 | explicitly disabled by the distributor. |
| 768 | |
| 769 | .. versionadded:: 2.7.9 |
| 770 | |
| 771 | .. data:: HAS_SNI |
| 772 | |
| 773 | Whether the OpenSSL library has built-in support for the *Server Name |
Benjamin Peterson | 31aa69e | 2014-11-23 20:13:31 -0600 | [diff] [blame] | 774 | Indication* extension (as defined in :rfc:`4366`). |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 775 | |
| 776 | .. versionadded:: 2.7.9 |
| 777 | |
| 778 | .. data:: HAS_NPN |
| 779 | |
| 780 | Whether the OpenSSL library has built-in support for *Next Protocol |
| 781 | Negotiation* as described in the `NPN draft specification |
Georg Brandl | 6e0b44e | 2016-02-26 19:37:12 +0100 | [diff] [blame] | 782 | <https://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. When true, |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 783 | you can use the :meth:`SSLContext.set_npn_protocols` method to advertise |
| 784 | which protocols you want to support. |
| 785 | |
| 786 | .. versionadded:: 2.7.9 |
| 787 | |
Christian Heimes | b9a860f | 2017-09-07 22:31:17 -0700 | [diff] [blame] | 788 | .. data:: HAS_TLSv1_3 |
| 789 | |
| 790 | Whether the OpenSSL library has built-in support for the TLS 1.3 protocol. |
| 791 | |
| 792 | .. versionadded:: 2.7.15 |
| 793 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 794 | .. data:: CHANNEL_BINDING_TYPES |
| 795 | |
| 796 | List of supported TLS channel binding types. Strings in this list |
| 797 | can be used as arguments to :meth:`SSLSocket.get_channel_binding`. |
| 798 | |
| 799 | .. versionadded:: 2.7.9 |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 800 | |
Antoine Pitrou | f9de534 | 2010-04-05 21:35:07 +0000 | [diff] [blame] | 801 | .. data:: OPENSSL_VERSION |
| 802 | |
| 803 | The version string of the OpenSSL library loaded by the interpreter:: |
| 804 | |
| 805 | >>> ssl.OPENSSL_VERSION |
| 806 | 'OpenSSL 0.9.8k 25 Mar 2009' |
| 807 | |
| 808 | .. versionadded:: 2.7 |
| 809 | |
| 810 | .. data:: OPENSSL_VERSION_INFO |
| 811 | |
| 812 | A tuple of five integers representing version information about the |
| 813 | OpenSSL library:: |
| 814 | |
| 815 | >>> ssl.OPENSSL_VERSION_INFO |
| 816 | (0, 9, 8, 11, 15) |
| 817 | |
| 818 | .. versionadded:: 2.7 |
| 819 | |
| 820 | .. data:: OPENSSL_VERSION_NUMBER |
| 821 | |
| 822 | The raw version number of the OpenSSL library, as a single integer:: |
| 823 | |
| 824 | >>> ssl.OPENSSL_VERSION_NUMBER |
| 825 | 9470143L |
| 826 | >>> hex(ssl.OPENSSL_VERSION_NUMBER) |
| 827 | '0x9080bfL' |
| 828 | |
| 829 | .. versionadded:: 2.7 |
| 830 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 831 | .. data:: ALERT_DESCRIPTION_HANDSHAKE_FAILURE |
| 832 | ALERT_DESCRIPTION_INTERNAL_ERROR |
| 833 | ALERT_DESCRIPTION_* |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 834 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 835 | Alert Descriptions from :rfc:`5246` and others. The `IANA TLS Alert Registry |
Serhiy Storchaka | b4905ef | 2016-05-07 10:50:12 +0300 | [diff] [blame] | 836 | <https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6>`_ |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 837 | contains this list and references to the RFCs where their meaning is defined. |
| 838 | |
| 839 | Used as the return value of the callback function in |
| 840 | :meth:`SSLContext.set_servername_callback`. |
| 841 | |
| 842 | .. versionadded:: 2.7.9 |
| 843 | |
| 844 | .. data:: Purpose.SERVER_AUTH |
| 845 | |
| 846 | Option for :func:`create_default_context` and |
| 847 | :meth:`SSLContext.load_default_certs`. This value indicates that the |
| 848 | context may be used to authenticate Web servers (therefore, it will |
| 849 | be used to create client-side sockets). |
| 850 | |
| 851 | .. versionadded:: 2.7.9 |
| 852 | |
| 853 | .. data:: Purpose.CLIENT_AUTH |
| 854 | |
| 855 | Option for :func:`create_default_context` and |
| 856 | :meth:`SSLContext.load_default_certs`. This value indicates that the |
| 857 | context may be used to authenticate Web clients (therefore, it will |
| 858 | be used to create server-side sockets). |
| 859 | |
| 860 | .. versionadded:: 2.7.9 |
| 861 | |
| 862 | |
| 863 | SSL Sockets |
| 864 | ----------- |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 865 | |
Giampaolo Rodola' | 7679413 | 2013-04-06 03:46:47 +0200 | [diff] [blame] | 866 | SSL sockets provide the following methods of :ref:`socket-objects`: |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 867 | |
Giampaolo Rodola' | 7679413 | 2013-04-06 03:46:47 +0200 | [diff] [blame] | 868 | - :meth:`~socket.socket.accept()` |
| 869 | - :meth:`~socket.socket.bind()` |
| 870 | - :meth:`~socket.socket.close()` |
| 871 | - :meth:`~socket.socket.connect()` |
| 872 | - :meth:`~socket.socket.fileno()` |
| 873 | - :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()` |
| 874 | - :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()` |
| 875 | - :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`, |
| 876 | :meth:`~socket.socket.setblocking()` |
| 877 | - :meth:`~socket.socket.listen()` |
| 878 | - :meth:`~socket.socket.makefile()` |
| 879 | - :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()` |
| 880 | (but passing a non-zero ``flags`` argument is not allowed) |
| 881 | - :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with |
| 882 | the same limitation) |
| 883 | - :meth:`~socket.socket.shutdown()` |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 884 | |
Giampaolo Rodola' | 7679413 | 2013-04-06 03:46:47 +0200 | [diff] [blame] | 885 | However, since the SSL (and TLS) protocol has its own framing atop |
| 886 | of TCP, the SSL sockets abstraction can, in certain respects, diverge from |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 887 | the specification of normal, OS-level sockets. See especially the |
| 888 | :ref:`notes on non-blocking sockets <ssl-nonblocking>`. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 889 | |
Giampaolo Rodola' | 7679413 | 2013-04-06 03:46:47 +0200 | [diff] [blame] | 890 | SSL sockets also have the following additional methods and attributes: |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 891 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 892 | .. method:: SSLSocket.do_handshake() |
| 893 | |
| 894 | Perform the SSL setup handshake. |
| 895 | |
| 896 | .. versionchanged:: 2.7.9 |
| 897 | |
| 898 | The handshake method also performs :func:`match_hostname` when the |
| 899 | :attr:`~SSLContext.check_hostname` attribute of the socket's |
| 900 | :attr:`~SSLSocket.context` is true. |
| 901 | |
Bill Janssen | 93bf9ce | 2007-09-11 02:42:07 +0000 | [diff] [blame] | 902 | .. method:: SSLSocket.getpeercert(binary_form=False) |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 903 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 904 | If there is no certificate for the peer on the other end of the connection, |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 905 | return ``None``. If the SSL handshake hasn't been done yet, raise |
| 906 | :exc:`ValueError`. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 907 | |
Antoine Pitrou | f12f391 | 2013-04-16 20:27:17 +0200 | [diff] [blame] | 908 | If the ``binary_form`` parameter is :const:`False`, and a certificate was |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 909 | received from the peer, this method returns a :class:`dict` instance. If the |
| 910 | certificate was not validated, the dict is empty. If the certificate was |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 911 | validated, it returns a dict with several keys, amongst them ``subject`` |
| 912 | (the principal for which the certificate was issued) and ``issuer`` |
| 913 | (the principal issuing the certificate). If a certificate contains an |
| 914 | instance of the *Subject Alternative Name* extension (see :rfc:`3280`), |
| 915 | there will also be a ``subjectAltName`` key in the dictionary. |
Bill Janssen | 93bf9ce | 2007-09-11 02:42:07 +0000 | [diff] [blame] | 916 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 917 | The ``subject`` and ``issuer`` fields are tuples containing the sequence |
| 918 | of relative distinguished names (RDNs) given in the certificate's data |
| 919 | structure for the respective fields, and each RDN is a sequence of |
| 920 | name-value pairs. Here is a real-world example:: |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 921 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 922 | {'issuer': ((('countryName', 'IL'),), |
| 923 | (('organizationName', 'StartCom Ltd.'),), |
| 924 | (('organizationalUnitName', |
| 925 | 'Secure Digital Certificate Signing'),), |
| 926 | (('commonName', |
| 927 | 'StartCom Class 2 Primary Intermediate Server CA'),)), |
| 928 | 'notAfter': 'Nov 22 08:15:19 2013 GMT', |
| 929 | 'notBefore': 'Nov 21 03:09:52 2011 GMT', |
| 930 | 'serialNumber': '95F0', |
| 931 | 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),), |
| 932 | (('countryName', 'US'),), |
| 933 | (('stateOrProvinceName', 'California'),), |
| 934 | (('localityName', 'San Francisco'),), |
| 935 | (('organizationName', 'Electronic Frontier Foundation, Inc.'),), |
| 936 | (('commonName', '*.eff.org'),), |
| 937 | (('emailAddress', 'hostmaster@eff.org'),)), |
| 938 | 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')), |
| 939 | 'version': 3} |
| 940 | |
| 941 | .. note:: |
| 942 | |
| 943 | To validate a certificate for a particular service, you can use the |
| 944 | :func:`match_hostname` function. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 945 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 946 | If the ``binary_form`` parameter is :const:`True`, and a certificate was |
| 947 | provided, this method returns the DER-encoded form of the entire certificate |
| 948 | as a sequence of bytes, or :const:`None` if the peer did not provide a |
Antoine Pitrou | f12f391 | 2013-04-16 20:27:17 +0200 | [diff] [blame] | 949 | certificate. Whether the peer provides a certificate depends on the SSL |
| 950 | socket's role: |
| 951 | |
| 952 | * for a client SSL socket, the server will always provide a certificate, |
| 953 | regardless of whether validation was required; |
| 954 | |
| 955 | * for a server SSL socket, the client will only provide a certificate |
| 956 | when requested by the server; therefore :meth:`getpeercert` will return |
| 957 | :const:`None` if you used :const:`CERT_NONE` (rather than |
| 958 | :const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`). |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 959 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 960 | .. versionchanged:: 2.7.9 |
| 961 | The returned dictionary includes additional items such as ``issuer`` and |
| 962 | ``notBefore``. Additionall :exc:`ValueError` is raised when the handshake |
| 963 | isn't done. The returned dictionary includes additional X509v3 extension |
| 964 | items such as ``crlDistributionPoints``, ``caIssuers`` and ``OCSP`` URIs. |
| 965 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 966 | .. method:: SSLSocket.cipher() |
| 967 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 968 | Returns a three-value tuple containing the name of the cipher being used, the |
| 969 | version of the SSL protocol that defines its use, and the number of secret |
| 970 | bits being used. If no connection has been established, returns ``None``. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 971 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 972 | .. method:: SSLSocket.compression() |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 973 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 974 | Return the compression algorithm being used as a string, or ``None`` |
| 975 | if the connection isn't compressed. |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 976 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 977 | If the higher-level protocol supports its own compression mechanism, |
| 978 | you can use :data:`OP_NO_COMPRESSION` to disable SSL-level compression. |
| 979 | |
| 980 | .. versionadded:: 2.7.9 |
| 981 | |
| 982 | .. method:: SSLSocket.get_channel_binding(cb_type="tls-unique") |
| 983 | |
| 984 | Get channel binding data for current connection, as a bytes object. Returns |
| 985 | ``None`` if not connected or the handshake has not been completed. |
| 986 | |
| 987 | The *cb_type* parameter allow selection of the desired channel binding |
| 988 | type. Valid channel binding types are listed in the |
| 989 | :data:`CHANNEL_BINDING_TYPES` list. Currently only the 'tls-unique' channel |
| 990 | binding, defined by :rfc:`5929`, is supported. :exc:`ValueError` will be |
| 991 | raised if an unsupported channel binding type is requested. |
| 992 | |
| 993 | .. versionadded:: 2.7.9 |
| 994 | |
Benjamin Peterson | b10bfbe | 2015-01-23 16:35:37 -0500 | [diff] [blame] | 995 | .. method:: SSLSocket.selected_alpn_protocol() |
| 996 | |
| 997 | Return the protocol that was selected during the TLS handshake. If |
| 998 | :meth:`SSLContext.set_alpn_protocols` was not called, if the other party does |
Benjamin Peterson | aa70758 | 2015-01-23 17:30:26 -0500 | [diff] [blame] | 999 | not support ALPN, if this socket does not support any of the client's |
| 1000 | proposed protocols, or if the handshake has not happened yet, ``None`` is |
Benjamin Peterson | b10bfbe | 2015-01-23 16:35:37 -0500 | [diff] [blame] | 1001 | returned. |
| 1002 | |
Benjamin Peterson | 65aa261 | 2015-01-23 16:47:52 -0500 | [diff] [blame] | 1003 | .. versionadded:: 2.7.10 |
Benjamin Peterson | b10bfbe | 2015-01-23 16:35:37 -0500 | [diff] [blame] | 1004 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1005 | .. method:: SSLSocket.selected_npn_protocol() |
| 1006 | |
Benjamin Peterson | b10bfbe | 2015-01-23 16:35:37 -0500 | [diff] [blame] | 1007 | Return the higher-level protocol that was selected during the TLS/SSL |
Alex Gaynor | e98205d | 2014-09-04 13:33:22 -0700 | [diff] [blame] | 1008 | handshake. If :meth:`SSLContext.set_npn_protocols` was not called, or |
| 1009 | if the other party does not support NPN, or if the handshake has not yet |
| 1010 | happened, this will return ``None``. |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1011 | |
| 1012 | .. versionadded:: 2.7.9 |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 1013 | |
Bill Janssen | 5bfbd76 | 2008-08-12 17:09:57 +0000 | [diff] [blame] | 1014 | .. method:: SSLSocket.unwrap() |
| 1015 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 1016 | Performs the SSL shutdown handshake, which removes the TLS layer from the |
| 1017 | underlying socket, and returns the underlying socket object. This can be |
| 1018 | used to go from encrypted operation over a connection to unencrypted. The |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1019 | returned socket should always be used for further communication with the |
| 1020 | other side of the connection, rather than the original socket. |
| 1021 | |
Alex Gaynor | e98205d | 2014-09-04 13:33:22 -0700 | [diff] [blame] | 1022 | .. method:: SSLSocket.version() |
| 1023 | |
| 1024 | Return the actual SSL protocol version negotiated by the connection |
| 1025 | as a string, or ``None`` is no secure connection is established. |
| 1026 | As of this writing, possible return values include ``"SSLv2"``, |
| 1027 | ``"SSLv3"``, ``"TLSv1"``, ``"TLSv1.1"`` and ``"TLSv1.2"``. |
| 1028 | Recent OpenSSL versions may define more return values. |
| 1029 | |
Alex Gaynor | 162126d | 2014-09-04 13:37:07 -0700 | [diff] [blame] | 1030 | .. versionadded:: 2.7.9 |
Alex Gaynor | e98205d | 2014-09-04 13:33:22 -0700 | [diff] [blame] | 1031 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1032 | .. attribute:: SSLSocket.context |
| 1033 | |
| 1034 | The :class:`SSLContext` object this SSL socket is tied to. If the SSL |
| 1035 | socket was created using the top-level :func:`wrap_socket` function |
| 1036 | (rather than :meth:`SSLContext.wrap_socket`), this is a custom context |
| 1037 | object created for this SSL socket. |
| 1038 | |
| 1039 | .. versionadded:: 2.7.9 |
| 1040 | |
| 1041 | |
| 1042 | SSL Contexts |
| 1043 | ------------ |
| 1044 | |
| 1045 | .. versionadded:: 2.7.9 |
| 1046 | |
| 1047 | An SSL context holds various data longer-lived than single SSL connections, |
| 1048 | such as SSL configuration options, certificate(s) and private key(s). |
| 1049 | It also manages a cache of SSL sessions for server-side sockets, in order |
| 1050 | to speed up repeated connections from the same clients. |
| 1051 | |
| 1052 | .. class:: SSLContext(protocol) |
| 1053 | |
| 1054 | Create a new SSL context. You must pass *protocol* which must be one |
| 1055 | of the ``PROTOCOL_*`` constants defined in this module. |
| 1056 | :data:`PROTOCOL_SSLv23` is currently recommended for maximum |
| 1057 | interoperability. |
| 1058 | |
| 1059 | .. seealso:: |
| 1060 | :func:`create_default_context` lets the :mod:`ssl` module choose |
| 1061 | security settings for a given purpose. |
| 1062 | |
| 1063 | |
| 1064 | :class:`SSLContext` objects have the following methods and attributes: |
| 1065 | |
| 1066 | .. method:: SSLContext.cert_store_stats() |
| 1067 | |
| 1068 | Get statistics about quantities of loaded X.509 certificates, count of |
| 1069 | X.509 certificates flagged as CA certificates and certificate revocation |
| 1070 | lists as dictionary. |
| 1071 | |
| 1072 | Example for a context with one CA cert and one other cert:: |
| 1073 | |
| 1074 | >>> context.cert_store_stats() |
| 1075 | {'crl': 0, 'x509_ca': 1, 'x509': 2} |
| 1076 | |
| 1077 | |
| 1078 | .. method:: SSLContext.load_cert_chain(certfile, keyfile=None, password=None) |
| 1079 | |
| 1080 | Load a private key and the corresponding certificate. The *certfile* |
| 1081 | string must be the path to a single file in PEM format containing the |
| 1082 | certificate as well as any number of CA certificates needed to establish |
| 1083 | the certificate's authenticity. The *keyfile* string, if present, must |
| 1084 | point to a file containing the private key in. Otherwise the private |
| 1085 | key will be taken from *certfile* as well. See the discussion of |
| 1086 | :ref:`ssl-certificates` for more information on how the certificate |
| 1087 | is stored in the *certfile*. |
| 1088 | |
| 1089 | The *password* argument may be a function to call to get the password for |
| 1090 | decrypting the private key. It will only be called if the private key is |
| 1091 | encrypted and a password is necessary. It will be called with no arguments, |
| 1092 | and it should return a string, bytes, or bytearray. If the return value is |
| 1093 | a string it will be encoded as UTF-8 before using it to decrypt the key. |
| 1094 | Alternatively a string, bytes, or bytearray value may be supplied directly |
| 1095 | as the *password* argument. It will be ignored if the private key is not |
| 1096 | encrypted and no password is needed. |
| 1097 | |
| 1098 | If the *password* argument is not specified and a password is required, |
| 1099 | OpenSSL's built-in password prompting mechanism will be used to |
| 1100 | interactively prompt the user for a password. |
| 1101 | |
| 1102 | An :class:`SSLError` is raised if the private key doesn't |
| 1103 | match with the certificate. |
| 1104 | |
| 1105 | .. method:: SSLContext.load_default_certs(purpose=Purpose.SERVER_AUTH) |
| 1106 | |
| 1107 | Load a set of default "certification authority" (CA) certificates from |
| 1108 | default locations. On Windows it loads CA certs from the ``CA`` and |
| 1109 | ``ROOT`` system stores. On other systems it calls |
| 1110 | :meth:`SSLContext.set_default_verify_paths`. In the future the method may |
| 1111 | load CA certificates from other locations, too. |
| 1112 | |
| 1113 | The *purpose* flag specifies what kind of CA certificates are loaded. The |
| 1114 | default settings :data:`Purpose.SERVER_AUTH` loads certificates, that are |
| 1115 | flagged and trusted for TLS web server authentication (client side |
| 1116 | sockets). :data:`Purpose.CLIENT_AUTH` loads CA certificates for client |
| 1117 | certificate verification on the server side. |
| 1118 | |
| 1119 | .. method:: SSLContext.load_verify_locations(cafile=None, capath=None, cadata=None) |
| 1120 | |
| 1121 | Load a set of "certification authority" (CA) certificates used to validate |
| 1122 | other peers' certificates when :data:`verify_mode` is other than |
| 1123 | :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified. |
| 1124 | |
| 1125 | This method can also load certification revocation lists (CRLs) in PEM or |
| 1126 | DER format. In order to make use of CRLs, :attr:`SSLContext.verify_flags` |
| 1127 | must be configured properly. |
| 1128 | |
| 1129 | The *cafile* string, if present, is the path to a file of concatenated |
| 1130 | CA certificates in PEM format. See the discussion of |
| 1131 | :ref:`ssl-certificates` for more information about how to arrange the |
| 1132 | certificates in this file. |
| 1133 | |
| 1134 | The *capath* string, if present, is |
| 1135 | the path to a directory containing several CA certificates in PEM format, |
| 1136 | following an `OpenSSL specific layout |
Miss Islington (bot) | 3ff488c | 2017-12-13 04:45:13 -0800 | [diff] [blame] | 1137 | <https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_load_verify_locations.html>`_. |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1138 | |
| 1139 | The *cadata* object, if present, is either an ASCII string of one or more |
| 1140 | PEM-encoded certificates or a bytes-like object of DER-encoded |
| 1141 | certificates. Like with *capath* extra lines around PEM-encoded |
| 1142 | certificates are ignored but at least one certificate must be present. |
| 1143 | |
| 1144 | .. method:: SSLContext.get_ca_certs(binary_form=False) |
| 1145 | |
| 1146 | Get a list of loaded "certification authority" (CA) certificates. If the |
| 1147 | ``binary_form`` parameter is :const:`False` each list |
| 1148 | entry is a dict like the output of :meth:`SSLSocket.getpeercert`. Otherwise |
| 1149 | the method returns a list of DER-encoded certificates. The returned list |
| 1150 | does not contain certificates from *capath* unless a certificate was |
| 1151 | requested and loaded by a SSL connection. |
| 1152 | |
Xiang Zhang | c4f91ba | 2016-12-23 11:10:19 +0800 | [diff] [blame] | 1153 | .. note:: |
| 1154 | Certificates in a capath directory aren't loaded unless they have |
| 1155 | been used at least once. |
| 1156 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1157 | .. method:: SSLContext.set_default_verify_paths() |
| 1158 | |
| 1159 | Load a set of default "certification authority" (CA) certificates from |
| 1160 | a filesystem path defined when building the OpenSSL library. Unfortunately, |
| 1161 | there's no easy way to know whether this method succeeds: no error is |
| 1162 | returned if no certificates are to be found. When the OpenSSL library is |
| 1163 | provided as part of the operating system, though, it is likely to be |
| 1164 | configured properly. |
| 1165 | |
| 1166 | .. method:: SSLContext.set_ciphers(ciphers) |
| 1167 | |
| 1168 | Set the available ciphers for sockets created with this context. |
| 1169 | It should be a string in the `OpenSSL cipher list format |
Christian Heimes | 5b6452d | 2017-09-20 22:23:09 +0200 | [diff] [blame] | 1170 | <https://wiki.openssl.org/index.php/Manual:Ciphers(1)#CIPHER_LIST_FORMAT>`_. |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1171 | If no cipher can be selected (because compile-time options or other |
| 1172 | configuration forbids use of all the specified ciphers), an |
| 1173 | :class:`SSLError` will be raised. |
| 1174 | |
| 1175 | .. note:: |
| 1176 | when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will |
| 1177 | give the currently selected cipher. |
| 1178 | |
Benjamin Peterson | b10bfbe | 2015-01-23 16:35:37 -0500 | [diff] [blame] | 1179 | .. method:: SSLContext.set_alpn_protocols(protocols) |
| 1180 | |
| 1181 | Specify which protocols the socket should advertise during the SSL/TLS |
| 1182 | handshake. It should be a list of ASCII strings, like ``['http/1.1', |
| 1183 | 'spdy/2']``, ordered by preference. The selection of a protocol will happen |
| 1184 | during the handshake, and will play out according to :rfc:`7301`. After a |
| 1185 | successful handshake, the :meth:`SSLSocket.selected_alpn_protocol` method will |
| 1186 | return the agreed-upon protocol. |
| 1187 | |
| 1188 | This method will raise :exc:`NotImplementedError` if :data:`HAS_ALPN` is |
| 1189 | False. |
| 1190 | |
Christian Heimes | 05b7d9c | 2017-08-15 10:55:03 +0200 | [diff] [blame] | 1191 | OpenSSL 1.1.0 to 1.1.0e will abort the handshake and raise :exc:`SSLError` |
| 1192 | when both sides support ALPN but cannot agree on a protocol. 1.1.0f+ |
| 1193 | behaves like 1.0.2, :meth:`SSLSocket.selected_alpn_protocol` returns None. |
Christian Heimes | c2fc7c4 | 2016-09-05 23:37:13 +0200 | [diff] [blame] | 1194 | |
Benjamin Peterson | 65aa261 | 2015-01-23 16:47:52 -0500 | [diff] [blame] | 1195 | .. versionadded:: 2.7.10 |
Benjamin Peterson | b10bfbe | 2015-01-23 16:35:37 -0500 | [diff] [blame] | 1196 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1197 | .. method:: SSLContext.set_npn_protocols(protocols) |
| 1198 | |
| 1199 | Specify which protocols the socket should advertise during the SSL/TLS |
| 1200 | handshake. It should be a list of strings, like ``['http/1.1', 'spdy/2']``, |
| 1201 | ordered by preference. The selection of a protocol will happen during the |
| 1202 | handshake, and will play out according to the `NPN draft specification |
Georg Brandl | 6e0b44e | 2016-02-26 19:37:12 +0100 | [diff] [blame] | 1203 | <https://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. After a |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1204 | successful handshake, the :meth:`SSLSocket.selected_npn_protocol` method will |
| 1205 | return the agreed-upon protocol. |
| 1206 | |
| 1207 | This method will raise :exc:`NotImplementedError` if :data:`HAS_NPN` is |
| 1208 | False. |
| 1209 | |
| 1210 | .. method:: SSLContext.set_servername_callback(server_name_callback) |
| 1211 | |
| 1212 | Register a callback function that will be called after the TLS Client Hello |
| 1213 | handshake message has been received by the SSL/TLS server when the TLS client |
| 1214 | specifies a server name indication. The server name indication mechanism |
| 1215 | is specified in :rfc:`6066` section 3 - Server Name Indication. |
| 1216 | |
| 1217 | Only one callback can be set per ``SSLContext``. If *server_name_callback* |
| 1218 | is ``None`` then the callback is disabled. Calling this function a |
| 1219 | subsequent time will disable the previously registered callback. |
| 1220 | |
| 1221 | The callback function, *server_name_callback*, will be called with three |
| 1222 | arguments; the first being the :class:`ssl.SSLSocket`, the second is a string |
| 1223 | that represents the server name that the client is intending to communicate |
| 1224 | (or :const:`None` if the TLS Client Hello does not contain a server name) |
| 1225 | and the third argument is the original :class:`SSLContext`. The server name |
| 1226 | argument is the IDNA decoded server name. |
| 1227 | |
| 1228 | A typical use of this callback is to change the :class:`ssl.SSLSocket`'s |
| 1229 | :attr:`SSLSocket.context` attribute to a new object of type |
| 1230 | :class:`SSLContext` representing a certificate chain that matches the server |
| 1231 | name. |
| 1232 | |
| 1233 | Due to the early negotiation phase of the TLS connection, only limited |
| 1234 | methods and attributes are usable like |
Benjamin Peterson | b10bfbe | 2015-01-23 16:35:37 -0500 | [diff] [blame] | 1235 | :meth:`SSLSocket.selected_alpn_protocol` and :attr:`SSLSocket.context`. |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1236 | :meth:`SSLSocket.getpeercert`, :meth:`SSLSocket.getpeercert`, |
| 1237 | :meth:`SSLSocket.cipher` and :meth:`SSLSocket.compress` methods require that |
| 1238 | the TLS connection has progressed beyond the TLS Client Hello and therefore |
| 1239 | will not contain return meaningful values nor can they be called safely. |
| 1240 | |
| 1241 | The *server_name_callback* function must return ``None`` to allow the |
| 1242 | TLS negotiation to continue. If a TLS failure is required, a constant |
| 1243 | :const:`ALERT_DESCRIPTION_* <ALERT_DESCRIPTION_INTERNAL_ERROR>` can be |
| 1244 | returned. Other return values will result in a TLS fatal error with |
| 1245 | :const:`ALERT_DESCRIPTION_INTERNAL_ERROR`. |
| 1246 | |
| 1247 | If there is an IDNA decoding error on the server name, the TLS connection |
| 1248 | will terminate with an :const:`ALERT_DESCRIPTION_INTERNAL_ERROR` fatal TLS |
| 1249 | alert message to the client. |
| 1250 | |
| 1251 | If an exception is raised from the *server_name_callback* function the TLS |
| 1252 | connection will terminate with a fatal TLS alert message |
| 1253 | :const:`ALERT_DESCRIPTION_HANDSHAKE_FAILURE`. |
| 1254 | |
| 1255 | This method will raise :exc:`NotImplementedError` if the OpenSSL library |
| 1256 | had OPENSSL_NO_TLSEXT defined when it was built. |
| 1257 | |
| 1258 | .. method:: SSLContext.load_dh_params(dhfile) |
| 1259 | |
| 1260 | Load the key generation parameters for Diffie-Helman (DH) key exchange. |
| 1261 | Using DH key exchange improves forward secrecy at the expense of |
| 1262 | computational resources (both on the server and on the client). |
| 1263 | The *dhfile* parameter should be the path to a file containing DH |
| 1264 | parameters in PEM format. |
| 1265 | |
| 1266 | This setting doesn't apply to client sockets. You can also use the |
| 1267 | :data:`OP_SINGLE_DH_USE` option to further improve security. |
| 1268 | |
| 1269 | .. method:: SSLContext.set_ecdh_curve(curve_name) |
| 1270 | |
| 1271 | Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key |
| 1272 | exchange. ECDH is significantly faster than regular DH while arguably |
| 1273 | as secure. The *curve_name* parameter should be a string describing |
| 1274 | a well-known elliptic curve, for example ``prime256v1`` for a widely |
| 1275 | supported curve. |
| 1276 | |
| 1277 | This setting doesn't apply to client sockets. You can also use the |
| 1278 | :data:`OP_SINGLE_ECDH_USE` option to further improve security. |
| 1279 | |
Serhiy Storchaka | dc0e3a8 | 2016-10-19 18:30:16 +0300 | [diff] [blame] | 1280 | This method is not available if :data:`HAS_ECDH` is ``False``. |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1281 | |
| 1282 | .. seealso:: |
| 1283 | `SSL/TLS & Perfect Forward Secrecy <http://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy.html>`_ |
| 1284 | Vincent Bernat. |
| 1285 | |
| 1286 | .. method:: SSLContext.wrap_socket(sock, server_side=False, \ |
| 1287 | do_handshake_on_connect=True, suppress_ragged_eofs=True, \ |
| 1288 | server_hostname=None) |
| 1289 | |
| 1290 | Wrap an existing Python socket *sock* and return an :class:`SSLSocket` |
| 1291 | object. *sock* must be a :data:`~socket.SOCK_STREAM` socket; other socket |
| 1292 | types are unsupported. |
| 1293 | |
| 1294 | The returned SSL socket is tied to the context, its settings and |
| 1295 | certificates. The parameters *server_side*, *do_handshake_on_connect* |
| 1296 | and *suppress_ragged_eofs* have the same meaning as in the top-level |
| 1297 | :func:`wrap_socket` function. |
| 1298 | |
| 1299 | On client connections, the optional parameter *server_hostname* specifies |
| 1300 | the hostname of the service which we are connecting to. This allows a |
| 1301 | single server to host multiple SSL-based services with distinct certificates, |
Benjamin Peterson | 31aa69e | 2014-11-23 20:13:31 -0600 | [diff] [blame] | 1302 | quite similarly to HTTP virtual hosts. Specifying *server_hostname* will |
| 1303 | raise a :exc:`ValueError` if *server_side* is true. |
| 1304 | |
Benjamin Peterson | 6fa40c4 | 2014-11-23 20:13:55 -0600 | [diff] [blame] | 1305 | .. versionchanged:: 2.7.9 |
Benjamin Peterson | 31aa69e | 2014-11-23 20:13:31 -0600 | [diff] [blame] | 1306 | Always allow a server_hostname to be passed, even if OpenSSL does not |
| 1307 | have SNI. |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1308 | |
| 1309 | .. method:: SSLContext.session_stats() |
| 1310 | |
| 1311 | Get statistics about the SSL sessions created or managed by this context. |
| 1312 | A dictionary is returned which maps the names of each `piece of information |
Miss Islington (bot) | 3ff488c | 2017-12-13 04:45:13 -0800 | [diff] [blame] | 1313 | <https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_sess_number.html>`_ to their |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1314 | numeric values. For example, here is the total number of hits and misses |
| 1315 | in the session cache since the context was created:: |
| 1316 | |
| 1317 | >>> stats = context.session_stats() |
| 1318 | >>> stats['hits'], stats['misses'] |
| 1319 | (0, 0) |
| 1320 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1321 | .. attribute:: SSLContext.check_hostname |
| 1322 | |
| 1323 | Wether to match the peer cert's hostname with :func:`match_hostname` in |
| 1324 | :meth:`SSLSocket.do_handshake`. The context's |
| 1325 | :attr:`~SSLContext.verify_mode` must be set to :data:`CERT_OPTIONAL` or |
| 1326 | :data:`CERT_REQUIRED`, and you must pass *server_hostname* to |
| 1327 | :meth:`~SSLContext.wrap_socket` in order to match the hostname. |
| 1328 | |
| 1329 | Example:: |
| 1330 | |
| 1331 | import socket, ssl |
| 1332 | |
Benjamin Peterson | 6c7edba | 2018-02-20 22:17:10 -0800 | [diff] [blame] | 1333 | context = ssl.SSLContext(ssl.PROTOCOL_TLS) |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1334 | context.verify_mode = ssl.CERT_REQUIRED |
| 1335 | context.check_hostname = True |
| 1336 | context.load_default_certs() |
| 1337 | |
| 1338 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1339 | ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com') |
| 1340 | ssl_sock.connect(('www.verisign.com', 443)) |
| 1341 | |
| 1342 | .. note:: |
| 1343 | |
| 1344 | This features requires OpenSSL 0.9.8f or newer. |
| 1345 | |
| 1346 | .. attribute:: SSLContext.options |
| 1347 | |
| 1348 | An integer representing the set of SSL options enabled on this context. |
| 1349 | The default value is :data:`OP_ALL`, but you can specify other options |
| 1350 | such as :data:`OP_NO_SSLv2` by ORing them together. |
| 1351 | |
| 1352 | .. note:: |
| 1353 | With versions of OpenSSL older than 0.9.8m, it is only possible |
| 1354 | to set options, not to clear them. Attempting to clear an option |
| 1355 | (by resetting the corresponding bits) will raise a ``ValueError``. |
| 1356 | |
| 1357 | .. attribute:: SSLContext.protocol |
| 1358 | |
| 1359 | The protocol version chosen when constructing the context. This attribute |
| 1360 | is read-only. |
| 1361 | |
| 1362 | .. attribute:: SSLContext.verify_flags |
| 1363 | |
| 1364 | The flags for certificate verification operations. You can set flags like |
| 1365 | :data:`VERIFY_CRL_CHECK_LEAF` by ORing them together. By default OpenSSL |
| 1366 | does neither require nor verify certificate revocation lists (CRLs). |
| 1367 | Available only with openssl version 0.9.8+. |
| 1368 | |
| 1369 | .. attribute:: SSLContext.verify_mode |
| 1370 | |
| 1371 | Whether to try to verify other peers' certificates and how to behave |
| 1372 | if verification fails. This attribute must be one of |
| 1373 | :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`. |
| 1374 | |
Bill Janssen | 5bfbd76 | 2008-08-12 17:09:57 +0000 | [diff] [blame] | 1375 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 1376 | .. index:: single: certificates |
| 1377 | |
| 1378 | .. index:: single: X509 certificate |
| 1379 | |
Bill Janssen | 93bf9ce | 2007-09-11 02:42:07 +0000 | [diff] [blame] | 1380 | .. _ssl-certificates: |
| 1381 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1382 | Certificates |
| 1383 | ------------ |
| 1384 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 1385 | Certificates in general are part of a public-key / private-key system. In this |
| 1386 | system, each *principal*, (which may be a machine, or a person, or an |
| 1387 | organization) is assigned a unique two-part encryption key. One part of the key |
| 1388 | is public, and is called the *public key*; the other part is kept secret, and is |
| 1389 | called the *private key*. The two parts are related, in that if you encrypt a |
| 1390 | message with one of the parts, you can decrypt it with the other part, and |
| 1391 | **only** with the other part. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1392 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 1393 | A certificate contains information about two principals. It contains the name |
| 1394 | of a *subject*, and the subject's public key. It also contains a statement by a |
| 1395 | second principal, the *issuer*, that the subject is who he claims to be, and |
| 1396 | that this is indeed the subject's public key. The issuer's statement is signed |
| 1397 | with the issuer's private key, which only the issuer knows. However, anyone can |
| 1398 | verify the issuer's statement by finding the issuer's public key, decrypting the |
| 1399 | statement with it, and comparing it to the other information in the certificate. |
| 1400 | The certificate also contains information about the time period over which it is |
| 1401 | valid. This is expressed as two fields, called "notBefore" and "notAfter". |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1402 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 1403 | In the Python use of certificates, a client or server can use a certificate to |
| 1404 | prove who they are. The other side of a network connection can also be required |
| 1405 | to produce a certificate, and that certificate can be validated to the |
| 1406 | satisfaction of the client or server that requires such validation. The |
| 1407 | connection attempt can be set to raise an exception if the validation fails. |
| 1408 | Validation is done automatically, by the underlying OpenSSL framework; the |
| 1409 | application need not concern itself with its mechanics. But the application |
| 1410 | does usually need to provide sets of certificates to allow this process to take |
| 1411 | place. |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1412 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 1413 | Python uses files to contain certificates. They should be formatted as "PEM" |
| 1414 | (see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line |
| 1415 | and a footer line:: |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1416 | |
| 1417 | -----BEGIN CERTIFICATE----- |
| 1418 | ... (certificate in base64 PEM encoding) ... |
| 1419 | -----END CERTIFICATE----- |
| 1420 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1421 | Certificate chains |
| 1422 | ^^^^^^^^^^^^^^^^^^ |
| 1423 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 1424 | The Python files which contain certificates can contain a sequence of |
| 1425 | certificates, sometimes called a *certificate chain*. This chain should start |
| 1426 | with the specific certificate for the principal who "is" the client or server, |
| 1427 | and then the certificate for the issuer of that certificate, and then the |
| 1428 | certificate for the issuer of *that* certificate, and so on up the chain till |
| 1429 | you get to a certificate which is *self-signed*, that is, a certificate which |
| 1430 | has the same subject and issuer, sometimes called a *root certificate*. The |
| 1431 | certificates should just be concatenated together in the certificate file. For |
| 1432 | example, suppose we had a three certificate chain, from our server certificate |
| 1433 | to the certificate of the certification authority that signed our server |
| 1434 | certificate, to the root certificate of the agency which issued the |
| 1435 | certification authority's certificate:: |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1436 | |
| 1437 | -----BEGIN CERTIFICATE----- |
| 1438 | ... (certificate for your server)... |
| 1439 | -----END CERTIFICATE----- |
| 1440 | -----BEGIN CERTIFICATE----- |
| 1441 | ... (the certificate for the CA)... |
| 1442 | -----END CERTIFICATE----- |
| 1443 | -----BEGIN CERTIFICATE----- |
| 1444 | ... (the root certificate for the CA's issuer)... |
| 1445 | -----END CERTIFICATE----- |
| 1446 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1447 | CA certificates |
| 1448 | ^^^^^^^^^^^^^^^ |
| 1449 | |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1450 | If you are going to require validation of the other side of the connection's |
| 1451 | certificate, you need to provide a "CA certs" file, filled with the certificate |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 1452 | chains for each issuer you are willing to trust. Again, this file just contains |
| 1453 | these chains concatenated together. For validation, Python will use the first |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1454 | chain it finds in the file which matches. The platform's certificates file can |
| 1455 | be used by calling :meth:`SSLContext.load_default_certs`, this is done |
| 1456 | automatically with :func:`.create_default_context`. |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 1457 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1458 | Combined key and certificate |
| 1459 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 1460 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1461 | Often the private key is stored in the same file as the certificate; in this |
| 1462 | case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain` |
| 1463 | and :func:`wrap_socket` needs to be passed. If the private key is stored |
| 1464 | with the certificate, it should come before the first certificate in |
| 1465 | the certificate chain:: |
| 1466 | |
| 1467 | -----BEGIN RSA PRIVATE KEY----- |
| 1468 | ... (private key in base64 encoding) ... |
| 1469 | -----END RSA PRIVATE KEY----- |
| 1470 | -----BEGIN CERTIFICATE----- |
| 1471 | ... (certificate in base64 PEM encoding) ... |
| 1472 | -----END CERTIFICATE----- |
| 1473 | |
| 1474 | Self-signed certificates |
| 1475 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1476 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 1477 | If you are going to create a server that provides SSL-encrypted connection |
| 1478 | services, you will need to acquire a certificate for that service. There are |
| 1479 | many ways of acquiring appropriate certificates, such as buying one from a |
| 1480 | certification authority. Another common practice is to generate a self-signed |
| 1481 | certificate. The simplest way to do this is with the OpenSSL package, using |
| 1482 | something like the following:: |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1483 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 1484 | % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem |
| 1485 | Generating a 1024 bit RSA private key |
| 1486 | .......++++++ |
| 1487 | .............................++++++ |
| 1488 | writing new private key to 'cert.pem' |
| 1489 | ----- |
| 1490 | You are about to be asked to enter information that will be incorporated |
| 1491 | into your certificate request. |
| 1492 | What you are about to enter is what is called a Distinguished Name or a DN. |
| 1493 | There are quite a few fields but you can leave some blank |
| 1494 | For some fields there will be a default value, |
| 1495 | If you enter '.', the field will be left blank. |
| 1496 | ----- |
| 1497 | Country Name (2 letter code) [AU]:US |
| 1498 | State or Province Name (full name) [Some-State]:MyState |
| 1499 | Locality Name (eg, city) []:Some City |
| 1500 | Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc. |
| 1501 | Organizational Unit Name (eg, section) []:My Group |
| 1502 | Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com |
| 1503 | Email Address []:ops@myserver.mygroup.myorganization.com |
| 1504 | % |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1505 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 1506 | The disadvantage of a self-signed certificate is that it is its own root |
| 1507 | certificate, and no one else will have it in their cache of known (and trusted) |
| 1508 | root certificates. |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1509 | |
| 1510 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1511 | Examples |
| 1512 | -------- |
| 1513 | |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1514 | Testing for SSL support |
| 1515 | ^^^^^^^^^^^^^^^^^^^^^^^ |
| 1516 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 1517 | To test for the presence of SSL support in a Python installation, user code |
| 1518 | should use the following idiom:: |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1519 | |
| 1520 | try: |
Georg Brandl | 2804602 | 2011-02-25 11:01:04 +0000 | [diff] [blame] | 1521 | import ssl |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1522 | except ImportError: |
Georg Brandl | 2804602 | 2011-02-25 11:01:04 +0000 | [diff] [blame] | 1523 | pass |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1524 | else: |
Serhiy Storchaka | 12d547a | 2016-05-10 13:45:32 +0300 | [diff] [blame] | 1525 | ... # do something that requires SSL support |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1526 | |
| 1527 | Client-side operation |
| 1528 | ^^^^^^^^^^^^^^^^^^^^^ |
| 1529 | |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1530 | This example creates a SSL context with the recommended security settings |
| 1531 | for client sockets, including automatic certificate verification:: |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1532 | |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1533 | >>> context = ssl.create_default_context() |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1534 | |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1535 | If you prefer to tune security settings yourself, you might create |
| 1536 | a context from scratch (but beware that you might not get the settings |
| 1537 | right):: |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1538 | |
Benjamin Peterson | 6c7edba | 2018-02-20 22:17:10 -0800 | [diff] [blame] | 1539 | >>> context = ssl.SSLContext(ssl.PROTOCOL_TLS) |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1540 | >>> context.verify_mode = ssl.CERT_REQUIRED |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1541 | >>> context.check_hostname = True |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1542 | >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt") |
| 1543 | |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1544 | (this snippet assumes your operating system places a bundle of all CA |
| 1545 | certificates in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an |
| 1546 | error and have to adjust the location) |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1547 | |
| 1548 | When you use the context to connect to a server, :const:`CERT_REQUIRED` |
| 1549 | validates the server certificate: it ensures that the server certificate |
| 1550 | was signed with one of the CA certificates, and checks the signature for |
| 1551 | correctness:: |
| 1552 | |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1553 | >>> conn = context.wrap_socket(socket.socket(socket.AF_INET), |
| 1554 | ... server_hostname="www.python.org") |
| 1555 | >>> conn.connect(("www.python.org", 443)) |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1556 | |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1557 | You may then fetch the certificate:: |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1558 | |
| 1559 | >>> cert = conn.getpeercert() |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1560 | |
| 1561 | Visual inspection shows that the certificate does identify the desired service |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1562 | (that is, the HTTPS host ``www.python.org``):: |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1563 | |
| 1564 | >>> pprint.pprint(cert) |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1565 | {'OCSP': ('http://ocsp.digicert.com',), |
| 1566 | 'caIssuers': ('http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt',), |
| 1567 | 'crlDistributionPoints': ('http://crl3.digicert.com/sha2-ev-server-g1.crl', |
| 1568 | 'http://crl4.digicert.com/sha2-ev-server-g1.crl'), |
| 1569 | 'issuer': ((('countryName', 'US'),), |
| 1570 | (('organizationName', 'DigiCert Inc'),), |
| 1571 | (('organizationalUnitName', 'www.digicert.com'),), |
| 1572 | (('commonName', 'DigiCert SHA2 Extended Validation Server CA'),)), |
| 1573 | 'notAfter': 'Sep 9 12:00:00 2016 GMT', |
| 1574 | 'notBefore': 'Sep 5 00:00:00 2014 GMT', |
| 1575 | 'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26', |
| 1576 | 'subject': ((('businessCategory', 'Private Organization'),), |
| 1577 | (('1.3.6.1.4.1.311.60.2.1.3', 'US'),), |
| 1578 | (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),), |
| 1579 | (('serialNumber', '3359300'),), |
| 1580 | (('streetAddress', '16 Allen Rd'),), |
| 1581 | (('postalCode', '03894-4801'),), |
| 1582 | (('countryName', 'US'),), |
| 1583 | (('stateOrProvinceName', 'NH'),), |
| 1584 | (('localityName', 'Wolfeboro,'),), |
| 1585 | (('organizationName', 'Python Software Foundation'),), |
| 1586 | (('commonName', 'www.python.org'),)), |
| 1587 | 'subjectAltName': (('DNS', 'www.python.org'), |
| 1588 | ('DNS', 'python.org'), |
| 1589 | ('DNS', 'pypi.python.org'), |
| 1590 | ('DNS', 'docs.python.org'), |
| 1591 | ('DNS', 'testpypi.python.org'), |
| 1592 | ('DNS', 'bugs.python.org'), |
| 1593 | ('DNS', 'wiki.python.org'), |
| 1594 | ('DNS', 'hg.python.org'), |
| 1595 | ('DNS', 'mail.python.org'), |
| 1596 | ('DNS', 'packaging.python.org'), |
| 1597 | ('DNS', 'pythonhosted.org'), |
| 1598 | ('DNS', 'www.pythonhosted.org'), |
| 1599 | ('DNS', 'test.pythonhosted.org'), |
| 1600 | ('DNS', 'us.pycon.org'), |
| 1601 | ('DNS', 'id.python.org')), |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1602 | 'version': 3} |
| 1603 | |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1604 | Now the SSL channel is established and the certificate verified, you can |
| 1605 | proceed to talk with the server:: |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1606 | |
| 1607 | >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n") |
| 1608 | >>> pprint.pprint(conn.recv(1024).split(b"\r\n")) |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1609 | [b'HTTP/1.1 200 OK', |
| 1610 | b'Date: Sat, 18 Oct 2014 18:27:20 GMT', |
| 1611 | b'Server: nginx', |
| 1612 | b'Content-Type: text/html; charset=utf-8', |
| 1613 | b'X-Frame-Options: SAMEORIGIN', |
| 1614 | b'Content-Length: 45679', |
| 1615 | b'Accept-Ranges: bytes', |
| 1616 | b'Via: 1.1 varnish', |
| 1617 | b'Age: 2188', |
| 1618 | b'X-Served-By: cache-lcy1134-LCY', |
| 1619 | b'X-Cache: HIT', |
| 1620 | b'X-Cache-Hits: 11', |
| 1621 | b'Vary: Cookie', |
| 1622 | b'Strict-Transport-Security: max-age=63072000; includeSubDomains', |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1623 | b'Connection: close', |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1624 | b'', |
| 1625 | b''] |
| 1626 | |
| 1627 | See the discussion of :ref:`ssl-security` below. |
| 1628 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1629 | |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1630 | Server-side operation |
| 1631 | ^^^^^^^^^^^^^^^^^^^^^ |
| 1632 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1633 | For server operation, typically you'll need to have a server certificate, and |
| 1634 | private key, each in a file. You'll first create a context holding the key |
| 1635 | and the certificate, so that clients can check your authenticity. Then |
| 1636 | you'll open a socket, bind it to a port, call :meth:`listen` on it, and start |
| 1637 | waiting for clients to connect:: |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1638 | |
Benjamin Peterson | a7b55a3 | 2009-02-20 03:31:23 +0000 | [diff] [blame] | 1639 | import socket, ssl |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1640 | |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1641 | context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1642 | context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile") |
| 1643 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1644 | bindsocket = socket.socket() |
| 1645 | bindsocket.bind(('myaddr.mydomain.com', 10023)) |
| 1646 | bindsocket.listen(5) |
| 1647 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1648 | When a client connects, you'll call :meth:`accept` on the socket to get the |
| 1649 | new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket` |
| 1650 | method to create a server-side SSL socket for the connection:: |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1651 | |
| 1652 | while True: |
Antoine Pitrou | 9e7d6e5 | 2011-01-02 22:39:10 +0000 | [diff] [blame] | 1653 | newsocket, fromaddr = bindsocket.accept() |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1654 | connstream = context.wrap_socket(newsocket, server_side=True) |
Antoine Pitrou | 9e7d6e5 | 2011-01-02 22:39:10 +0000 | [diff] [blame] | 1655 | try: |
| 1656 | deal_with_client(connstream) |
| 1657 | finally: |
| 1658 | connstream.shutdown(socket.SHUT_RDWR) |
| 1659 | connstream.close() |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1660 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1661 | Then you'll read data from the ``connstream`` and do something with it till you |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 1662 | are finished with the client (or the client is finished with you):: |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1663 | |
| 1664 | def deal_with_client(connstream): |
Georg Brandl | 2804602 | 2011-02-25 11:01:04 +0000 | [diff] [blame] | 1665 | data = connstream.read() |
| 1666 | # null data means the client is finished with us |
| 1667 | while data: |
| 1668 | if not do_something(connstream, data): |
| 1669 | # we'll assume do_something returns False |
| 1670 | # when we're finished with client |
| 1671 | break |
| 1672 | data = connstream.read() |
| 1673 | # finished with client |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1674 | |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1675 | And go back to listening for new client connections (of course, a real server |
| 1676 | would probably handle each client connection in a separate thread, or put |
| 1677 | the sockets in non-blocking mode and use an event loop). |
| 1678 | |
| 1679 | |
| 1680 | .. _ssl-nonblocking: |
| 1681 | |
| 1682 | Notes on non-blocking sockets |
| 1683 | ----------------------------- |
| 1684 | |
| 1685 | When working with non-blocking sockets, there are several things you need |
| 1686 | to be aware of: |
| 1687 | |
| 1688 | - Calling :func:`~select.select` tells you that the OS-level socket can be |
| 1689 | read from (or written to), but it does not imply that there is sufficient |
| 1690 | data at the upper SSL layer. For example, only part of an SSL frame might |
| 1691 | have arrived. Therefore, you must be ready to handle :meth:`SSLSocket.recv` |
| 1692 | and :meth:`SSLSocket.send` failures, and retry after another call to |
| 1693 | :func:`~select.select`. |
| 1694 | |
| 1695 | - Conversely, since the SSL layer has its own framing, a SSL socket may |
| 1696 | still have data available for reading without :func:`~select.select` |
| 1697 | being aware of it. Therefore, you should first call |
| 1698 | :meth:`SSLSocket.recv` to drain any potentially available data, and then |
| 1699 | only block on a :func:`~select.select` call if still necessary. |
| 1700 | |
| 1701 | (of course, similar provisions apply when using other primitives such as |
| 1702 | :func:`~select.poll`, or those in the :mod:`selectors` module) |
| 1703 | |
| 1704 | - The SSL handshake itself will be non-blocking: the |
| 1705 | :meth:`SSLSocket.do_handshake` method has to be retried until it returns |
| 1706 | successfully. Here is a synopsis using :func:`~select.select` to wait for |
| 1707 | the socket's readiness:: |
| 1708 | |
| 1709 | while True: |
| 1710 | try: |
| 1711 | sock.do_handshake() |
| 1712 | break |
| 1713 | except ssl.SSLWantReadError: |
| 1714 | select.select([sock], [], []) |
| 1715 | except ssl.SSLWantWriteError: |
| 1716 | select.select([], [sock], []) |
| 1717 | |
| 1718 | |
| 1719 | .. _ssl-security: |
| 1720 | |
| 1721 | Security considerations |
| 1722 | ----------------------- |
| 1723 | |
| 1724 | Best defaults |
| 1725 | ^^^^^^^^^^^^^ |
| 1726 | |
| 1727 | For **client use**, if you don't have any special requirements for your |
| 1728 | security policy, it is highly recommended that you use the |
| 1729 | :func:`create_default_context` function to create your SSL context. |
| 1730 | It will load the system's trusted CA certificates, enable certificate |
| 1731 | validation and hostname checking, and try to choose reasonably secure |
| 1732 | protocol and cipher settings. |
| 1733 | |
| 1734 | If a client certificate is needed for the connection, it can be added with |
| 1735 | :meth:`SSLContext.load_cert_chain`. |
| 1736 | |
| 1737 | By contrast, if you create the SSL context by calling the :class:`SSLContext` |
| 1738 | constructor yourself, it will not have certificate validation nor hostname |
| 1739 | checking enabled by default. If you do so, please read the paragraphs below |
| 1740 | to achieve a good security level. |
| 1741 | |
| 1742 | Manual settings |
| 1743 | ^^^^^^^^^^^^^^^ |
| 1744 | |
| 1745 | Verifying certificates |
| 1746 | '''''''''''''''''''''' |
| 1747 | |
| 1748 | When calling the :class:`SSLContext` constructor directly, |
| 1749 | :const:`CERT_NONE` is the default. Since it does not authenticate the other |
| 1750 | peer, it can be insecure, especially in client mode where most of time you |
| 1751 | would like to ensure the authenticity of the server you're talking to. |
| 1752 | Therefore, when in client mode, it is highly recommended to use |
| 1753 | :const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also |
| 1754 | have to check that the server certificate, which can be obtained by calling |
| 1755 | :meth:`SSLSocket.getpeercert`, matches the desired service. For many |
| 1756 | protocols and applications, the service can be identified by the hostname; |
| 1757 | in this case, the :func:`match_hostname` function can be used. This common |
| 1758 | check is automatically performed when :attr:`SSLContext.check_hostname` is |
| 1759 | enabled. |
| 1760 | |
| 1761 | In server mode, if you want to authenticate your clients using the SSL layer |
| 1762 | (rather than using a higher-level authentication mechanism), you'll also have |
| 1763 | to specify :const:`CERT_REQUIRED` and similarly check the client certificate. |
| 1764 | |
| 1765 | .. note:: |
| 1766 | |
| 1767 | In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are |
| 1768 | equivalent unless anonymous ciphers are enabled (they are disabled |
| 1769 | by default). |
| 1770 | |
| 1771 | Protocol versions |
| 1772 | ''''''''''''''''' |
| 1773 | |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1774 | SSL versions 2 and 3 are considered insecure and are therefore dangerous to |
| 1775 | use. If you want maximum compatibility between clients and servers, it is |
| 1776 | recommended to use :const:`PROTOCOL_SSLv23` as the protocol version and then |
| 1777 | disable SSLv2 and SSLv3 explicitly using the :data:`SSLContext.options` |
| 1778 | attribute:: |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1779 | |
| 1780 | context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
| 1781 | context.options |= ssl.OP_NO_SSLv2 |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1782 | context.options |= ssl.OP_NO_SSLv3 |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1783 | |
Antoine Pitrou | 9e4a933 | 2014-10-21 00:14:39 +0200 | [diff] [blame] | 1784 | The SSL context created above will only allow TLSv1 and later (if |
| 1785 | supported by your system) connections. |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1786 | |
| 1787 | Cipher selection |
| 1788 | '''''''''''''''' |
| 1789 | |
| 1790 | If you have advanced security requirements, fine-tuning of the ciphers |
| 1791 | enabled when negotiating a SSL session is possible through the |
| 1792 | :meth:`SSLContext.set_ciphers` method. Starting from Python 2.7.9, the |
| 1793 | ssl module disables certain weak ciphers by default, but you may want |
| 1794 | to further restrict the cipher choice. Be sure to read OpenSSL's documentation |
Serhiy Storchaka | b4905ef | 2016-05-07 10:50:12 +0300 | [diff] [blame] | 1795 | about the `cipher list format <https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT>`_. |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1796 | If you want to check which ciphers are enabled by a given cipher list, use the |
| 1797 | ``openssl ciphers`` command on your system. |
| 1798 | |
| 1799 | Multi-processing |
| 1800 | ^^^^^^^^^^^^^^^^ |
| 1801 | |
| 1802 | If using this module as part of a multi-processed application (using, |
| 1803 | for example the :mod:`multiprocessing` or :mod:`concurrent.futures` modules), |
| 1804 | be aware that OpenSSL's internal random number generator does not properly |
| 1805 | handle forked processes. Applications must change the PRNG state of the |
| 1806 | parent process if they use any SSL feature with :func:`os.fork`. Any |
| 1807 | successful call of :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or |
| 1808 | :func:`~ssl.RAND_pseudo_bytes` is sufficient. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 1809 | |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 1810 | |
Christian Heimes | 3d87f4c | 2018-02-25 10:21:03 +0100 | [diff] [blame^] | 1811 | .. ssl-libressl: |
| 1812 | |
| 1813 | LibreSSL support |
| 1814 | ---------------- |
| 1815 | |
| 1816 | LibreSSL is a fork of OpenSSL 1.0.1. The ssl module has limited support for |
| 1817 | LibreSSL. Some features are not available when the ssl module is compiled |
| 1818 | with LibreSSL. |
| 1819 | |
| 1820 | * LibreSSL >= 2.6.1 no longer supports NPN. The methods |
| 1821 | :meth:`SSLContext.set_npn_protocols` and |
| 1822 | :meth:`SSLSocket.selected_npn_protocol` are not available. |
| 1823 | * :meth:`SSLContext.set_default_verify_paths` ignores the env vars |
| 1824 | :envvar:`SSL_CERT_FILE` and :envvar:`SSL_CERT_PATH` although |
| 1825 | :func:`get_default_verify_paths` still reports them. |
| 1826 | |
| 1827 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 1828 | .. seealso:: |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1829 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 1830 | Class :class:`socket.socket` |
Georg Brandl | 4e8534e | 2013-10-06 18:20:31 +0200 | [diff] [blame] | 1831 | Documentation of underlying :mod:`socket` class |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1832 | |
Georg Brandl | 6e0b44e | 2016-02-26 19:37:12 +0100 | [diff] [blame] | 1833 | `SSL/TLS Strong Encryption: An Introduction <https://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html>`_ |
Georg Brandl | 4e8534e | 2013-10-06 18:20:31 +0200 | [diff] [blame] | 1834 | Intro from the Apache webserver documentation |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1835 | |
Georg Brandl | 6e0b44e | 2016-02-26 19:37:12 +0100 | [diff] [blame] | 1836 | `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <https://www.ietf.org/rfc/rfc1422>`_ |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 1837 | Steve Kent |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 1838 | |
Georg Brandl | 6e0b44e | 2016-02-26 19:37:12 +0100 | [diff] [blame] | 1839 | `RFC 1750: Randomness Recommendations for Security <https://www.ietf.org/rfc/rfc1750>`_ |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 1840 | D. Eastlake et. al. |
Bill Janssen | ffe576d | 2007-09-05 00:46:27 +0000 | [diff] [blame] | 1841 | |
Georg Brandl | 6e0b44e | 2016-02-26 19:37:12 +0100 | [diff] [blame] | 1842 | `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <https://www.ietf.org/rfc/rfc3280>`_ |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 1843 | Housley et. al. |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1844 | |
Georg Brandl | 6e0b44e | 2016-02-26 19:37:12 +0100 | [diff] [blame] | 1845 | `RFC 4366: Transport Layer Security (TLS) Extensions <https://www.ietf.org/rfc/rfc4366>`_ |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1846 | Blake-Wilson et. al. |
| 1847 | |
Georg Brandl | 6e0b44e | 2016-02-26 19:37:12 +0100 | [diff] [blame] | 1848 | `RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2 <https://tools.ietf.org/html/rfc5246>`_ |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1849 | T. Dierks et. al. |
| 1850 | |
Georg Brandl | 6e0b44e | 2016-02-26 19:37:12 +0100 | [diff] [blame] | 1851 | `RFC 6066: Transport Layer Security (TLS) Extensions <https://tools.ietf.org/html/rfc6066>`_ |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1852 | D. Eastlake |
| 1853 | |
Serhiy Storchaka | b4905ef | 2016-05-07 10:50:12 +0300 | [diff] [blame] | 1854 | `IANA TLS: Transport Layer Security (TLS) Parameters <https://www.iana.org/assignments/tls-parameters/tls-parameters.xml>`_ |
Benjamin Peterson | daeb925 | 2014-08-20 14:14:50 -0500 | [diff] [blame] | 1855 | IANA |
Miss Islington (bot) | ab4894b | 2017-09-06 17:31:48 -0700 | [diff] [blame] | 1856 | |
| 1857 | `RFC 7525: Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS) <https://tools.ietf.org/html/rfc7525>`_ |
| 1858 | IETF |
| 1859 | |
| 1860 | `Mozilla's Server Side TLS recommendations <https://wiki.mozilla.org/Security/Server_Side_TLS>`_ |
| 1861 | Mozilla |