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