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