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