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 |
| 31 | cause variations in behavior. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 32 | |
Christian Heimes | 88b2220 | 2013-10-29 21:08:56 +0100 | [diff] [blame] | 33 | .. warning:: |
Antoine Pitrou | f7a5247 | 2013-11-17 15:42:58 +0100 | [diff] [blame] | 34 | The ssl module won't validate certificates by default. When used in |
| 35 | client mode, this means you are vulnerable to man-in-the-middle attacks. |
| 36 | |
| 37 | .. warning:: |
Christian Heimes | 88b2220 | 2013-10-29 21:08:56 +0100 | [diff] [blame] | 38 | |
| 39 | OpenSSL's internal random number generator does not properly handle fork. |
| 40 | Applications must change the PRNG state of the parent process if they use |
Christian Heimes | db78e43 | 2013-10-29 22:19:39 +0100 | [diff] [blame] | 41 | any SSL feature with :func:`os.fork`. Any successful call of |
Christian Heimes | 88b2220 | 2013-10-29 21:08:56 +0100 | [diff] [blame] | 42 | :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or |
| 43 | :func:`~ssl.RAND_pseudo_bytes` is sufficient. |
| 44 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 45 | This section documents the objects and functions in the ``ssl`` module; for more |
| 46 | general information about TLS, SSL, and certificates, the reader is referred to |
| 47 | the documents in the "See Also" section at the bottom. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 48 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 49 | This module provides a class, :class:`ssl.SSLSocket`, which is derived from the |
| 50 | :class:`socket.socket` type, and provides a socket-like wrapper that also |
| 51 | encrypts and decrypts the data going over the socket with SSL. It supports |
| 52 | additional :meth:`read` and :meth:`write` methods, along with a method, |
| 53 | :meth:`getpeercert`, to retrieve the certificate of the other side of the |
| 54 | connection, and a method, :meth:`cipher`, to retrieve the cipher being used for |
| 55 | the secure connection. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 56 | |
Bill Janssen | 93bf9ce | 2007-09-11 02:42:07 +0000 | [diff] [blame] | 57 | Functions, Constants, and Exceptions |
| 58 | ------------------------------------ |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 59 | |
Bill Janssen | 93bf9ce | 2007-09-11 02:42:07 +0000 | [diff] [blame] | 60 | .. exception:: SSLError |
| 61 | |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 62 | Raised to signal an error from the underlying SSL implementation. This |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 63 | signifies some problem in the higher-level encryption and authentication |
| 64 | layer that's superimposed on the underlying network connection. This error |
| 65 | is a subtype of :exc:`socket.error`, which in turn is a subtype of |
| 66 | :exc:`IOError`. |
Bill Janssen | 93bf9ce | 2007-09-11 02:42:07 +0000 | [diff] [blame] | 67 | |
Antoine Pitrou | 0a6373c | 2010-04-17 17:10:38 +0000 | [diff] [blame] | 68 | .. 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] | 69 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 70 | Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance |
| 71 | of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps |
| 72 | the underlying socket in an SSL context. For client-side sockets, the |
| 73 | context construction is lazy; if the underlying socket isn't connected yet, |
| 74 | the context construction will be performed after :meth:`connect` is called on |
| 75 | the socket. For server-side sockets, if the socket has no remote peer, it is |
| 76 | assumed to be a listening socket, and the server-side SSL wrapping is |
| 77 | automatically performed on client connections accepted via the :meth:`accept` |
| 78 | method. :func:`wrap_socket` may raise :exc:`SSLError`. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 79 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 80 | The ``keyfile`` and ``certfile`` parameters specify optional files which |
| 81 | contain a certificate to be used to identify the local side of the |
| 82 | connection. See the discussion of :ref:`ssl-certificates` for more |
| 83 | information on how the certificate is stored in the ``certfile``. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 84 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 85 | Often the private key is stored in the same file as the certificate; in this |
| 86 | case, only the ``certfile`` parameter need be passed. If the private key is |
| 87 | stored in a separate file, both parameters must be used. If the private key |
| 88 | is stored in the ``certfile``, it should come before the first certificate in |
| 89 | the certificate chain:: |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 90 | |
| 91 | -----BEGIN RSA PRIVATE KEY----- |
| 92 | ... (private key in base64 encoding) ... |
| 93 | -----END RSA PRIVATE KEY----- |
| 94 | -----BEGIN CERTIFICATE----- |
| 95 | ... (certificate in base64 PEM encoding) ... |
| 96 | -----END CERTIFICATE----- |
| 97 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 98 | The parameter ``server_side`` is a boolean which identifies whether |
| 99 | server-side or client-side behavior is desired from this socket. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 100 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 101 | The parameter ``cert_reqs`` specifies whether a certificate is required from |
| 102 | the other side of the connection, and whether it will be validated if |
| 103 | provided. It must be one of the three values :const:`CERT_NONE` |
| 104 | (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated |
| 105 | if provided), or :const:`CERT_REQUIRED` (required and validated). If the |
| 106 | value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs`` |
| 107 | parameter must point to a file of CA certificates. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 108 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 109 | The ``ca_certs`` file contains a set of concatenated "certification |
| 110 | authority" certificates, which are used to validate certificates passed from |
| 111 | the other end of the connection. See the discussion of |
| 112 | :ref:`ssl-certificates` for more information about how to arrange the |
| 113 | certificates in this file. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 114 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 115 | The parameter ``ssl_version`` specifies which version of the SSL protocol to |
| 116 | use. Typically, the server chooses a particular protocol version, and the |
| 117 | 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] | 118 | interoperable with the other versions. If not specified, the default is |
| 119 | :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 120 | versions. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 121 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 122 | Here's a table showing which versions in a client (down the side) can connect |
| 123 | to which versions in a server (along the top): |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 124 | |
| 125 | .. table:: |
| 126 | |
| 127 | ======================== ========= ========= ========== ========= |
| 128 | *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1** |
Georg Brandl | 2b92f6b | 2007-12-06 01:52:24 +0000 | [diff] [blame] | 129 | ------------------------ --------- --------- ---------- --------- |
Antoine Pitrou | 0a6373c | 2010-04-17 17:10:38 +0000 | [diff] [blame] | 130 | *SSLv2* yes no yes no |
Antoine Pitrou | df4c986 | 2012-01-09 21:43:18 +0100 | [diff] [blame] | 131 | *SSLv3* no yes yes no |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 132 | *SSLv23* yes no yes no |
| 133 | *TLSv1* no no yes yes |
| 134 | ======================== ========= ========= ========== ========= |
| 135 | |
Antoine Pitrou | 0a6373c | 2010-04-17 17:10:38 +0000 | [diff] [blame] | 136 | .. note:: |
| 137 | |
Andrew M. Kuchling | 3ded421 | 2010-04-30 00:52:31 +0000 | [diff] [blame] | 138 | Which connections succeed will vary depending on the version of |
| 139 | OpenSSL. For instance, in some older versions of OpenSSL (such |
| 140 | as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an |
| 141 | SSLv23 server. Another example: beginning with OpenSSL 1.0.0, |
| 142 | an SSLv23 client will not actually attempt SSLv2 connections |
| 143 | unless you explicitly enable SSLv2 ciphers; for example, you |
| 144 | might specify ``"ALL"`` or ``"SSLv2"`` as the *ciphers* parameter |
| 145 | to enable them. |
Antoine Pitrou | 0a6373c | 2010-04-17 17:10:38 +0000 | [diff] [blame] | 146 | |
Andrew M. Kuchling | 3ded421 | 2010-04-30 00:52:31 +0000 | [diff] [blame] | 147 | The *ciphers* parameter sets the available ciphers for this SSL object. |
Antoine Pitrou | 0a6373c | 2010-04-17 17:10:38 +0000 | [diff] [blame] | 148 | It should be a string in the `OpenSSL cipher list format |
| 149 | <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 150 | |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 151 | The parameter ``do_handshake_on_connect`` specifies whether to do the SSL |
| 152 | handshake automatically after doing a :meth:`socket.connect`, or whether the |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 153 | application program will call it explicitly, by invoking the |
| 154 | :meth:`SSLSocket.do_handshake` method. Calling |
| 155 | :meth:`SSLSocket.do_handshake` explicitly gives the program control over the |
| 156 | blocking behavior of the socket I/O involved in the handshake. |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 157 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 158 | The parameter ``suppress_ragged_eofs`` specifies how the |
| 159 | :meth:`SSLSocket.read` method should signal unexpected EOF from the other end |
| 160 | of the connection. If specified as :const:`True` (the default), it returns a |
| 161 | normal EOF in response to unexpected EOF errors raised from the underlying |
| 162 | socket; if :const:`False`, it will raise the exceptions back to the caller. |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 163 | |
Antoine Pitrou | 0a6373c | 2010-04-17 17:10:38 +0000 | [diff] [blame] | 164 | .. versionchanged:: 2.7 |
| 165 | New optional argument *ciphers*. |
| 166 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 167 | .. function:: RAND_status() |
| 168 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 169 | Returns True if the SSL pseudo-random number generator has been seeded with |
| 170 | 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd` |
| 171 | and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random |
| 172 | number generator. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 173 | |
| 174 | .. function:: RAND_egd(path) |
| 175 | |
| 176 | If you are running an entropy-gathering daemon (EGD) somewhere, and ``path`` |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 177 | is the pathname of a socket connection open to it, this will read 256 bytes |
| 178 | of randomness from the socket, and add it to the SSL pseudo-random number |
| 179 | generator to increase the security of generated secret keys. This is |
| 180 | typically only necessary on systems without better sources of randomness. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 181 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 182 | See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources |
| 183 | of entropy-gathering daemons. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 184 | |
| 185 | .. function:: RAND_add(bytes, entropy) |
| 186 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 187 | Mixes the given ``bytes`` into the SSL pseudo-random number generator. The |
| 188 | parameter ``entropy`` (a float) is a lower bound on the entropy contained in |
| 189 | string (so you can always use :const:`0.0`). See :rfc:`1750` for more |
| 190 | information on sources of entropy. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 191 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 192 | .. function:: cert_time_to_seconds(timestring) |
| 193 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 194 | Returns a floating-point value containing a normal seconds-after-the-epoch |
| 195 | time value, given the time-string representing the "notBefore" or "notAfter" |
| 196 | date from a certificate. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 197 | |
| 198 | Here's an example:: |
| 199 | |
| 200 | >>> import ssl |
| 201 | >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT") |
| 202 | 1178694000.0 |
| 203 | >>> import time |
| 204 | >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")) |
| 205 | 'Wed May 9 00:00:00 2007' |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 206 | >>> |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 207 | |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 208 | .. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None) |
| 209 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 210 | Given the address ``addr`` of an SSL-protected server, as a (*hostname*, |
| 211 | *port-number*) pair, fetches the server's certificate, and returns it as a |
| 212 | PEM-encoded string. If ``ssl_version`` is specified, uses that version of |
| 213 | the SSL protocol to attempt to connect to the server. If ``ca_certs`` is |
| 214 | specified, it should be a file containing a list of root certificates, the |
| 215 | same format as used for the same parameter in :func:`wrap_socket`. The call |
| 216 | will attempt to validate the server certificate against that set of root |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 217 | certificates, and will fail if the validation attempt fails. |
| 218 | |
| 219 | .. function:: DER_cert_to_PEM_cert (DER_cert_bytes) |
| 220 | |
| 221 | Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded |
| 222 | string version of the same certificate. |
| 223 | |
| 224 | .. function:: PEM_cert_to_DER_cert (PEM_cert_string) |
| 225 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 226 | Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of |
| 227 | bytes for that same certificate. |
Bill Janssen | 296a59d | 2007-09-16 22:06:00 +0000 | [diff] [blame] | 228 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 229 | .. data:: CERT_NONE |
| 230 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 231 | Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no |
| 232 | certificates will be required or validated from the other side of the socket |
| 233 | connection. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 234 | |
| 235 | .. data:: CERT_OPTIONAL |
| 236 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 237 | Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no |
| 238 | certificates will be required from the other side of the socket connection, |
| 239 | but if they are provided, will be validated. Note that use of this setting |
| 240 | requires a valid certificate validation file also be passed as a value of the |
| 241 | ``ca_certs`` parameter. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 242 | |
| 243 | .. data:: CERT_REQUIRED |
| 244 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 245 | Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when |
| 246 | certificates will be required from the other side of the socket connection. |
| 247 | Note that use of this setting requires a valid certificate validation file |
| 248 | also be passed as a value of the ``ca_certs`` parameter. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 249 | |
| 250 | .. data:: PROTOCOL_SSLv2 |
| 251 | |
| 252 | Selects SSL version 2 as the channel encryption protocol. |
| 253 | |
Victor Stinner | b1241f9 | 2011-05-10 01:52:03 +0200 | [diff] [blame] | 254 | This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2 |
| 255 | flag. |
| 256 | |
Antoine Pitrou | 308c2af | 2010-05-16 14:16:56 +0000 | [diff] [blame] | 257 | .. warning:: |
| 258 | |
| 259 | SSL version 2 is insecure. Its use is highly discouraged. |
| 260 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 261 | .. data:: PROTOCOL_SSLv23 |
| 262 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 263 | Selects SSL version 2 or 3 as the channel encryption protocol. This is a |
| 264 | setting to use with servers for maximum compatibility with the other end of |
| 265 | an SSL connection, but it may cause the specific ciphers chosen for the |
| 266 | encryption to be of fairly low quality. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 267 | |
| 268 | .. data:: PROTOCOL_SSLv3 |
| 269 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 270 | Selects SSL version 3 as the channel encryption protocol. For clients, this |
| 271 | is the maximally compatible SSL variant. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 272 | |
| 273 | .. data:: PROTOCOL_TLSv1 |
| 274 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 275 | Selects TLS version 1 as the channel encryption protocol. This is the most |
| 276 | modern version, and probably the best choice for maximum protection, if both |
| 277 | sides can speak it. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 278 | |
Antoine Pitrou | f9de534 | 2010-04-05 21:35:07 +0000 | [diff] [blame] | 279 | .. data:: OPENSSL_VERSION |
| 280 | |
| 281 | The version string of the OpenSSL library loaded by the interpreter:: |
| 282 | |
| 283 | >>> ssl.OPENSSL_VERSION |
| 284 | 'OpenSSL 0.9.8k 25 Mar 2009' |
| 285 | |
| 286 | .. versionadded:: 2.7 |
| 287 | |
| 288 | .. data:: OPENSSL_VERSION_INFO |
| 289 | |
| 290 | A tuple of five integers representing version information about the |
| 291 | OpenSSL library:: |
| 292 | |
| 293 | >>> ssl.OPENSSL_VERSION_INFO |
| 294 | (0, 9, 8, 11, 15) |
| 295 | |
| 296 | .. versionadded:: 2.7 |
| 297 | |
| 298 | .. data:: OPENSSL_VERSION_NUMBER |
| 299 | |
| 300 | The raw version number of the OpenSSL library, as a single integer:: |
| 301 | |
| 302 | >>> ssl.OPENSSL_VERSION_NUMBER |
| 303 | 9470143L |
| 304 | >>> hex(ssl.OPENSSL_VERSION_NUMBER) |
| 305 | '0x9080bfL' |
| 306 | |
| 307 | .. versionadded:: 2.7 |
| 308 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 309 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 310 | SSLSocket Objects |
| 311 | ----------------- |
| 312 | |
Giampaolo Rodola' | 7679413 | 2013-04-06 03:46:47 +0200 | [diff] [blame] | 313 | SSL sockets provide the following methods of :ref:`socket-objects`: |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 314 | |
Giampaolo Rodola' | 7679413 | 2013-04-06 03:46:47 +0200 | [diff] [blame] | 315 | - :meth:`~socket.socket.accept()` |
| 316 | - :meth:`~socket.socket.bind()` |
| 317 | - :meth:`~socket.socket.close()` |
| 318 | - :meth:`~socket.socket.connect()` |
| 319 | - :meth:`~socket.socket.fileno()` |
| 320 | - :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()` |
| 321 | - :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()` |
| 322 | - :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`, |
| 323 | :meth:`~socket.socket.setblocking()` |
| 324 | - :meth:`~socket.socket.listen()` |
| 325 | - :meth:`~socket.socket.makefile()` |
| 326 | - :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()` |
| 327 | (but passing a non-zero ``flags`` argument is not allowed) |
| 328 | - :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with |
| 329 | the same limitation) |
| 330 | - :meth:`~socket.socket.shutdown()` |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 331 | |
Giampaolo Rodola' | 7679413 | 2013-04-06 03:46:47 +0200 | [diff] [blame] | 332 | However, since the SSL (and TLS) protocol has its own framing atop |
| 333 | of TCP, the SSL sockets abstraction can, in certain respects, diverge from |
| 334 | the specification of normal, OS-level sockets. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 335 | |
Giampaolo Rodola' | 7679413 | 2013-04-06 03:46:47 +0200 | [diff] [blame] | 336 | SSL sockets also have the following additional methods and attributes: |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 337 | |
Bill Janssen | 93bf9ce | 2007-09-11 02:42:07 +0000 | [diff] [blame] | 338 | .. method:: SSLSocket.getpeercert(binary_form=False) |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 339 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 340 | If there is no certificate for the peer on the other end of the connection, |
| 341 | returns ``None``. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 342 | |
Antoine Pitrou | f12f391 | 2013-04-16 20:27:17 +0200 | [diff] [blame] | 343 | If the ``binary_form`` parameter is :const:`False`, and a certificate was |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 344 | received from the peer, this method returns a :class:`dict` instance. If the |
| 345 | certificate was not validated, the dict is empty. If the certificate was |
| 346 | validated, it returns a dict with the keys ``subject`` (the principal for |
| 347 | which the certificate was issued), and ``notAfter`` (the time after which the |
| 348 | certificate should not be trusted). The certificate was already validated, |
| 349 | so the ``notBefore`` and ``issuer`` fields are not returned. If a |
| 350 | certificate contains an instance of the *Subject Alternative Name* extension |
| 351 | (see :rfc:`3280`), there will also be a ``subjectAltName`` key in the |
| 352 | dictionary. |
Bill Janssen | 93bf9ce | 2007-09-11 02:42:07 +0000 | [diff] [blame] | 353 | |
| 354 | The "subject" field is a tuple containing the sequence of relative |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 355 | distinguished names (RDNs) given in the certificate's data structure for the |
| 356 | principal, and each RDN is a sequence of name-value pairs:: |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 357 | |
| 358 | {'notAfter': 'Feb 16 16:54:50 2013 GMT', |
| 359 | 'subject': ((('countryName', u'US'),), |
| 360 | (('stateOrProvinceName', u'Delaware'),), |
| 361 | (('localityName', u'Wilmington'),), |
| 362 | (('organizationName', u'Python Software Foundation'),), |
| 363 | (('organizationalUnitName', u'SSL'),), |
| 364 | (('commonName', u'somemachine.python.org'),))} |
| 365 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 366 | If the ``binary_form`` parameter is :const:`True`, and a certificate was |
| 367 | provided, this method returns the DER-encoded form of the entire certificate |
| 368 | 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] | 369 | certificate. Whether the peer provides a certificate depends on the SSL |
| 370 | socket's role: |
| 371 | |
| 372 | * for a client SSL socket, the server will always provide a certificate, |
| 373 | regardless of whether validation was required; |
| 374 | |
| 375 | * for a server SSL socket, the client will only provide a certificate |
| 376 | when requested by the server; therefore :meth:`getpeercert` will return |
| 377 | :const:`None` if you used :const:`CERT_NONE` (rather than |
| 378 | :const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`). |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 379 | |
| 380 | .. method:: SSLSocket.cipher() |
| 381 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 382 | Returns a three-value tuple containing the name of the cipher being used, the |
| 383 | version of the SSL protocol that defines its use, and the number of secret |
| 384 | bits being used. If no connection has been established, returns ``None``. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 385 | |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 386 | .. method:: SSLSocket.do_handshake() |
| 387 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 388 | Perform a TLS/SSL handshake. If this is used with a non-blocking socket, it |
| 389 | may raise :exc:`SSLError` with an ``arg[0]`` of :const:`SSL_ERROR_WANT_READ` |
| 390 | or :const:`SSL_ERROR_WANT_WRITE`, in which case it must be called again until |
| 391 | it completes successfully. For example, to simulate the behavior of a |
| 392 | blocking socket, one might write:: |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 393 | |
| 394 | while True: |
| 395 | try: |
| 396 | s.do_handshake() |
| 397 | break |
Andrew Svetlov | 1625d88 | 2012-10-30 21:56:43 +0200 | [diff] [blame] | 398 | except ssl.SSLError as err: |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 399 | if err.args[0] == ssl.SSL_ERROR_WANT_READ: |
| 400 | select.select([s], [], []) |
| 401 | elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE: |
| 402 | select.select([], [s], []) |
| 403 | else: |
| 404 | raise |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 405 | |
Bill Janssen | 5bfbd76 | 2008-08-12 17:09:57 +0000 | [diff] [blame] | 406 | .. method:: SSLSocket.unwrap() |
| 407 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 408 | Performs the SSL shutdown handshake, which removes the TLS layer from the |
| 409 | underlying socket, and returns the underlying socket object. This can be |
| 410 | used to go from encrypted operation over a connection to unencrypted. The |
| 411 | socket instance returned should always be used for further communication with |
| 412 | the other side of the connection, rather than the original socket instance |
| 413 | (which may not function properly after the unwrap). |
Bill Janssen | 5bfbd76 | 2008-08-12 17:09:57 +0000 | [diff] [blame] | 414 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 415 | .. index:: single: certificates |
| 416 | |
| 417 | .. index:: single: X509 certificate |
| 418 | |
Bill Janssen | 93bf9ce | 2007-09-11 02:42:07 +0000 | [diff] [blame] | 419 | .. _ssl-certificates: |
| 420 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 421 | Certificates |
| 422 | ------------ |
| 423 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 424 | Certificates in general are part of a public-key / private-key system. In this |
| 425 | system, each *principal*, (which may be a machine, or a person, or an |
| 426 | organization) is assigned a unique two-part encryption key. One part of the key |
| 427 | is public, and is called the *public key*; the other part is kept secret, and is |
| 428 | called the *private key*. The two parts are related, in that if you encrypt a |
| 429 | message with one of the parts, you can decrypt it with the other part, and |
| 430 | **only** with the other part. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 431 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 432 | A certificate contains information about two principals. It contains the name |
| 433 | of a *subject*, and the subject's public key. It also contains a statement by a |
| 434 | second principal, the *issuer*, that the subject is who he claims to be, and |
| 435 | that this is indeed the subject's public key. The issuer's statement is signed |
| 436 | with the issuer's private key, which only the issuer knows. However, anyone can |
| 437 | verify the issuer's statement by finding the issuer's public key, decrypting the |
| 438 | statement with it, and comparing it to the other information in the certificate. |
| 439 | The certificate also contains information about the time period over which it is |
| 440 | valid. This is expressed as two fields, called "notBefore" and "notAfter". |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 441 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 442 | In the Python use of certificates, a client or server can use a certificate to |
| 443 | prove who they are. The other side of a network connection can also be required |
| 444 | to produce a certificate, and that certificate can be validated to the |
| 445 | satisfaction of the client or server that requires such validation. The |
| 446 | connection attempt can be set to raise an exception if the validation fails. |
| 447 | Validation is done automatically, by the underlying OpenSSL framework; the |
| 448 | application need not concern itself with its mechanics. But the application |
| 449 | does usually need to provide sets of certificates to allow this process to take |
| 450 | place. |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 451 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 452 | Python uses files to contain certificates. They should be formatted as "PEM" |
| 453 | (see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line |
| 454 | and a footer line:: |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 455 | |
| 456 | -----BEGIN CERTIFICATE----- |
| 457 | ... (certificate in base64 PEM encoding) ... |
| 458 | -----END CERTIFICATE----- |
| 459 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 460 | The Python files which contain certificates can contain a sequence of |
| 461 | certificates, sometimes called a *certificate chain*. This chain should start |
| 462 | with the specific certificate for the principal who "is" the client or server, |
| 463 | and then the certificate for the issuer of that certificate, and then the |
| 464 | certificate for the issuer of *that* certificate, and so on up the chain till |
| 465 | you get to a certificate which is *self-signed*, that is, a certificate which |
| 466 | has the same subject and issuer, sometimes called a *root certificate*. The |
| 467 | certificates should just be concatenated together in the certificate file. For |
| 468 | example, suppose we had a three certificate chain, from our server certificate |
| 469 | to the certificate of the certification authority that signed our server |
| 470 | certificate, to the root certificate of the agency which issued the |
| 471 | certification authority's certificate:: |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 472 | |
| 473 | -----BEGIN CERTIFICATE----- |
| 474 | ... (certificate for your server)... |
| 475 | -----END CERTIFICATE----- |
| 476 | -----BEGIN CERTIFICATE----- |
| 477 | ... (the certificate for the CA)... |
| 478 | -----END CERTIFICATE----- |
| 479 | -----BEGIN CERTIFICATE----- |
| 480 | ... (the root certificate for the CA's issuer)... |
| 481 | -----END CERTIFICATE----- |
| 482 | |
| 483 | If you are going to require validation of the other side of the connection's |
| 484 | 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] | 485 | chains for each issuer you are willing to trust. Again, this file just contains |
| 486 | these chains concatenated together. For validation, Python will use the first |
| 487 | chain it finds in the file which matches. |
Bill Janssen | 934b16d | 2008-06-28 22:19:33 +0000 | [diff] [blame] | 488 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 489 | Some "standard" root certificates are available from various certification |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 490 | authorities: `CACert.org <http://www.cacert.org/index.php?id=3>`_, `Thawte |
| 491 | <http://www.thawte.com/roots/>`_, `Verisign |
| 492 | <http://www.verisign.com/support/roots.html>`_, `Positive SSL |
| 493 | <http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_ |
| 494 | (used by python.org), `Equifax and GeoTrust |
| 495 | <http://www.geotrust.com/resources/root_certificates/index.asp>`_. |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 496 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 497 | In general, if you are using SSL3 or TLS1, you don't need to put the full chain |
| 498 | in your "CA certs" file; you only need the root certificates, and the remote |
| 499 | peer is supposed to furnish the other certificates necessary to chain from its |
| 500 | certificate to a root certificate. See :rfc:`4158` for more discussion of the |
| 501 | way in which certification chains can be built. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 502 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 503 | If you are going to create a server that provides SSL-encrypted connection |
| 504 | services, you will need to acquire a certificate for that service. There are |
| 505 | many ways of acquiring appropriate certificates, such as buying one from a |
| 506 | certification authority. Another common practice is to generate a self-signed |
| 507 | certificate. The simplest way to do this is with the OpenSSL package, using |
| 508 | something like the following:: |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 509 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 510 | % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem |
| 511 | Generating a 1024 bit RSA private key |
| 512 | .......++++++ |
| 513 | .............................++++++ |
| 514 | writing new private key to 'cert.pem' |
| 515 | ----- |
| 516 | You are about to be asked to enter information that will be incorporated |
| 517 | into your certificate request. |
| 518 | What you are about to enter is what is called a Distinguished Name or a DN. |
| 519 | There are quite a few fields but you can leave some blank |
| 520 | For some fields there will be a default value, |
| 521 | If you enter '.', the field will be left blank. |
| 522 | ----- |
| 523 | Country Name (2 letter code) [AU]:US |
| 524 | State or Province Name (full name) [Some-State]:MyState |
| 525 | Locality Name (eg, city) []:Some City |
| 526 | Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc. |
| 527 | Organizational Unit Name (eg, section) []:My Group |
| 528 | Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com |
| 529 | Email Address []:ops@myserver.mygroup.myorganization.com |
| 530 | % |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 531 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 532 | The disadvantage of a self-signed certificate is that it is its own root |
| 533 | certificate, and no one else will have it in their cache of known (and trusted) |
| 534 | root certificates. |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 535 | |
| 536 | |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 537 | Examples |
| 538 | -------- |
| 539 | |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 540 | Testing for SSL support |
| 541 | ^^^^^^^^^^^^^^^^^^^^^^^ |
| 542 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 543 | To test for the presence of SSL support in a Python installation, user code |
| 544 | should use the following idiom:: |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 545 | |
| 546 | try: |
Georg Brandl | 2804602 | 2011-02-25 11:01:04 +0000 | [diff] [blame] | 547 | import ssl |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 548 | except ImportError: |
Georg Brandl | 2804602 | 2011-02-25 11:01:04 +0000 | [diff] [blame] | 549 | pass |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 550 | else: |
Georg Brandl | 2804602 | 2011-02-25 11:01:04 +0000 | [diff] [blame] | 551 | ... # do something that requires SSL support |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 552 | |
| 553 | Client-side operation |
| 554 | ^^^^^^^^^^^^^^^^^^^^^ |
| 555 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 556 | This example connects to an SSL server, prints the server's address and |
| 557 | certificate, sends some bytes, and reads part of the response:: |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 558 | |
Benjamin Peterson | a7b55a3 | 2009-02-20 03:31:23 +0000 | [diff] [blame] | 559 | import socket, ssl, pprint |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 560 | |
| 561 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 562 | |
| 563 | # require a certificate from the server |
| 564 | ssl_sock = ssl.wrap_socket(s, |
| 565 | ca_certs="/etc/ca_certs_file", |
| 566 | cert_reqs=ssl.CERT_REQUIRED) |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 567 | |
| 568 | ssl_sock.connect(('www.verisign.com', 443)) |
| 569 | |
| 570 | print repr(ssl_sock.getpeername()) |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 571 | print ssl_sock.cipher() |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 572 | print pprint.pformat(ssl_sock.getpeercert()) |
| 573 | |
| 574 | # Set a simple HTTP request -- use httplib in actual code. |
| 575 | ssl_sock.write("""GET / HTTP/1.0\r |
| 576 | Host: www.verisign.com\r\n\r\n""") |
| 577 | |
| 578 | # Read a chunk of data. Will not necessarily |
| 579 | # read all the data returned by the server. |
| 580 | data = ssl_sock.read() |
| 581 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 582 | # note that closing the SSLSocket will also close the underlying socket |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 583 | ssl_sock.close() |
| 584 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 585 | As of September 6, 2007, the certificate printed by this program looked like |
| 586 | this:: |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 587 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 588 | {'notAfter': 'May 8 23:59:59 2009 GMT', |
| 589 | 'subject': ((('serialNumber', u'2497886'),), |
| 590 | (('1.3.6.1.4.1.311.60.2.1.3', u'US'),), |
| 591 | (('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),), |
| 592 | (('countryName', u'US'),), |
| 593 | (('postalCode', u'94043'),), |
| 594 | (('stateOrProvinceName', u'California'),), |
| 595 | (('localityName', u'Mountain View'),), |
| 596 | (('streetAddress', u'487 East Middlefield Road'),), |
| 597 | (('organizationName', u'VeriSign, Inc.'),), |
| 598 | (('organizationalUnitName', |
| 599 | u'Production Security Services'),), |
| 600 | (('organizationalUnitName', |
| 601 | u'Terms of use at www.verisign.com/rpa (c)06'),), |
| 602 | (('commonName', u'www.verisign.com'),))} |
| 603 | |
| 604 | which is a fairly poorly-formed ``subject`` field. |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 605 | |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 606 | Server-side operation |
| 607 | ^^^^^^^^^^^^^^^^^^^^^ |
| 608 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 609 | For server operation, typically you'd need to have a server certificate, and |
| 610 | private key, each in a file. You'd open a socket, bind it to a port, call |
| 611 | :meth:`listen` on it, then start waiting for clients to connect:: |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 612 | |
Benjamin Peterson | a7b55a3 | 2009-02-20 03:31:23 +0000 | [diff] [blame] | 613 | import socket, ssl |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 614 | |
| 615 | bindsocket = socket.socket() |
| 616 | bindsocket.bind(('myaddr.mydomain.com', 10023)) |
| 617 | bindsocket.listen(5) |
| 618 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 619 | When one did, you'd call :meth:`accept` on the socket to get the new socket from |
| 620 | the other end, and use :func:`wrap_socket` to create a server-side SSL context |
| 621 | for it:: |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 622 | |
| 623 | while True: |
Antoine Pitrou | 9e7d6e5 | 2011-01-02 22:39:10 +0000 | [diff] [blame] | 624 | newsocket, fromaddr = bindsocket.accept() |
| 625 | connstream = ssl.wrap_socket(newsocket, |
| 626 | server_side=True, |
| 627 | certfile="mycertfile", |
| 628 | keyfile="mykeyfile", |
| 629 | ssl_version=ssl.PROTOCOL_TLSv1) |
| 630 | try: |
| 631 | deal_with_client(connstream) |
| 632 | finally: |
| 633 | connstream.shutdown(socket.SHUT_RDWR) |
| 634 | connstream.close() |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 635 | |
Georg Brandl | a50d20a | 2009-09-16 15:57:46 +0000 | [diff] [blame] | 636 | Then you'd read data from the ``connstream`` and do something with it till you |
| 637 | 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] | 638 | |
| 639 | def deal_with_client(connstream): |
Georg Brandl | 2804602 | 2011-02-25 11:01:04 +0000 | [diff] [blame] | 640 | data = connstream.read() |
| 641 | # null data means the client is finished with us |
| 642 | while data: |
| 643 | if not do_something(connstream, data): |
| 644 | # we'll assume do_something returns False |
| 645 | # when we're finished with client |
| 646 | break |
| 647 | data = connstream.read() |
| 648 | # finished with client |
Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame] | 649 | |
| 650 | And go back to listening for new client connections. |
| 651 | |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 652 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 653 | .. seealso:: |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 654 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 655 | Class :class:`socket.socket` |
Georg Brandl | 4e8534e | 2013-10-06 18:20:31 +0200 | [diff] [blame] | 656 | Documentation of underlying :mod:`socket` class |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 657 | |
Georg Brandl | 4e8534e | 2013-10-06 18:20:31 +0200 | [diff] [blame] | 658 | `SSL/TLS Strong Encryption: An Introduction <http://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html>`_ |
| 659 | Intro from the Apache webserver documentation |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 660 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 661 | `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_ |
| 662 | Steve Kent |
Bill Janssen | 426ea0a | 2007-08-29 22:35:05 +0000 | [diff] [blame] | 663 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 664 | `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_ |
| 665 | D. Eastlake et. al. |
Bill Janssen | ffe576d | 2007-09-05 00:46:27 +0000 | [diff] [blame] | 666 | |
Bill Janssen | 98d19da | 2007-09-10 21:51:02 +0000 | [diff] [blame] | 667 | `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_ |
| 668 | Housley et. al. |