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