2 :mod:`ssl` --- SSL wrapper for socket objects
3 ====================================================================
6 :synopsis: SSL wrapper for socket objects
8 .. moduleauthor:: Bill Janssen <bill.janssen@gmail.com>
12 .. sectionauthor:: Bill Janssen <bill.janssen@gmail.com>
15 .. index:: single: OpenSSL; (use in module ssl)
17 .. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
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.
28 Some behavior may be platform dependent, since calls are made to the operating
29 system socket APIs. The installed version of OpenSSL may also cause
30 variations in behavior.
32 This section documents the objects and functions in the ``ssl`` module;
33 for more general information about TLS, SSL, and certificates, the
34 reader is referred to the documents in the "See Also" section at
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
41 :meth:`read` and :meth:`write` methods, along with a method, :meth:`getpeercert`,
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
46 Functions, Constants, and Exceptions
47 ------------------------------------
49 .. exception:: SSLError
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`.
57 .. 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)
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
65 on client connections accepted via the :meth:`accept` method. :func:`wrap_socket` may
66 raise :exc:`SSLError`.
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``.
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::
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-----
85 The parameter ``server_side`` is a boolean which identifies whether server-side or client-side
86 behavior is desired from this socket.
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.
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.
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.
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):
113 ======================== ========= ========= ========== =========
114 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1**
115 ------------------------ --------- --------- ---------- ---------
116 *SSLv2* yes no yes* no
117 *SSLv3* yes yes yes no
118 *SSLv23* yes no yes no
119 *TLSv1* no no yes yes
120 ======================== ========= ========= ========== =========
122 In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4),
123 an SSLv2 client could not connect to an SSLv23 server.
125 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
126 handshake automatically after doing a :meth:`socket.connect`, or whether the
127 application program will call it explicitly, by invoking the :meth:`SSLSocket.do_handshake`
128 method. Calling :meth:`SSLSocket.do_handshake` explicitly gives the program control over
129 the blocking behavior of the socket I/O involved in the handshake.
131 The parameter ``suppress_ragged_eofs`` specifies how the :meth:`SSLSocket.read`
132 method should signal unexpected EOF from the other end of the connection. If specified
133 as :const:`True` (the default), it returns a normal EOF in response to unexpected
134 EOF errors raised from the underlying socket; if :const:`False`, it will raise
135 the exceptions back to the caller.
137 .. function:: RAND_status()
139 Returns True if the SSL pseudo-random number generator has been
140 seeded with 'enough' randomness, and False otherwise. You can use
141 :func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness
142 of the pseudo-random number generator.
144 .. function:: RAND_egd(path)
146 If you are running an entropy-gathering daemon (EGD) somewhere, and ``path``
147 is the pathname of a socket connection open to it, this will read
148 256 bytes of randomness from the socket, and add it to the SSL pseudo-random number generator
149 to increase the security of generated secret keys. This is typically only
150 necessary on systems without better sources of randomness.
152 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for
153 sources of entropy-gathering daemons.
155 .. function:: RAND_add(bytes, entropy)
157 Mixes the given ``bytes`` into the SSL pseudo-random number generator.
158 The parameter ``entropy`` (a float) is a lower bound on the entropy
159 contained in string (so you can always use :const:`0.0`).
160 See :rfc:`1750` for more information on sources of entropy.
162 .. function:: cert_time_to_seconds(timestring)
164 Returns a floating-point value containing a normal seconds-after-the-epoch time
165 value, given the time-string representing the "notBefore" or "notAfter" date
171 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
174 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
175 'Wed May 9 00:00:00 2007'
178 .. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
180 Given the address ``addr`` of an SSL-protected server, as a
181 (*hostname*, *port-number*) pair, fetches the server's certificate,
182 and returns it as a PEM-encoded string. If ``ssl_version`` is
183 specified, uses that version of the SSL protocol to attempt to
184 connect to the server. If ``ca_certs`` is specified, it should be
185 a file containing a list of root certificates, the same format as
186 used for the same parameter in :func:`wrap_socket`. The call will
187 attempt to validate the server certificate against that set of root
188 certificates, and will fail if the validation attempt fails.
190 .. function:: DER_cert_to_PEM_cert (DER_cert_bytes)
192 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
193 string version of the same certificate.
195 .. function:: PEM_cert_to_DER_cert (PEM_cert_string)
197 Given a certificate as an ASCII PEM string, returns a DER-encoded
198 sequence of bytes for that same certificate.
202 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
203 when no certificates will be required or validated from the other
204 side of the socket connection.
206 .. data:: CERT_OPTIONAL
208 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
209 when no certificates will be required from the other side of the
210 socket connection, but if they are provided, will be validated.
211 Note that use of this setting requires a valid certificate
212 validation file also be passed as a value of the ``ca_certs``
215 .. data:: CERT_REQUIRED
217 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
218 when certificates will be required from the other side of the
219 socket connection. Note that use of this setting requires a valid certificate
220 validation file also be passed as a value of the ``ca_certs``
223 .. data:: PROTOCOL_SSLv2
225 Selects SSL version 2 as the channel encryption protocol.
227 .. data:: PROTOCOL_SSLv23
229 Selects SSL version 2 or 3 as the channel encryption protocol.
230 This is a setting to use with servers for maximum compatibility
231 with the other end of an SSL connection, but it may cause the
232 specific ciphers chosen for the encryption to be of fairly low
235 .. data:: PROTOCOL_SSLv3
237 Selects SSL version 3 as the channel encryption protocol.
238 For clients, this is the maximally compatible SSL variant.
240 .. data:: PROTOCOL_TLSv1
242 Selects TLS version 1 as the channel encryption protocol. This is
243 the most modern version, and probably the best choice for maximum
244 protection, if both sides can speak it.
250 .. method:: SSLSocket.read([nbytes=1024])
252 Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them.
254 .. method:: SSLSocket.write(data)
256 Writes the ``data`` to the other side of the connection, using the
257 SSL channel to encrypt. Returns the number of bytes written.
259 .. method:: SSLSocket.getpeercert(binary_form=False)
261 If there is no certificate for the peer on the other end of the
262 connection, returns ``None``.
264 If the parameter ``binary_form`` is :const:`False`, and a
265 certificate was received from the peer, this method returns a
266 :class:`dict` instance. If the certificate was not validated, the
267 dict is empty. If the certificate was validated, it returns a dict
268 with the keys ``subject`` (the principal for which the certificate
269 was issued), and ``notAfter`` (the time after which the certificate
270 should not be trusted). The certificate was already validated, so
271 the ``notBefore`` and ``issuer`` fields are not returned. If a
272 certificate contains an instance of the *Subject Alternative Name*
273 extension (see :rfc:`3280`), there will also be a
274 ``subjectAltName`` key in the dictionary.
276 The "subject" field is a tuple containing the sequence of relative
277 distinguished names (RDNs) given in the certificate's data
278 structure for the principal, and each RDN is a sequence of
281 {'notAfter': 'Feb 16 16:54:50 2013 GMT',
282 'subject': ((('countryName', u'US'),),
283 (('stateOrProvinceName', u'Delaware'),),
284 (('localityName', u'Wilmington'),),
285 (('organizationName', u'Python Software Foundation'),),
286 (('organizationalUnitName', u'SSL'),),
287 (('commonName', u'somemachine.python.org'),))}
289 If the ``binary_form`` parameter is :const:`True`, and a
290 certificate was provided, this method returns the DER-encoded form
291 of the entire certificate as a sequence of bytes, or :const:`None` if the
292 peer did not provide a certificate. This return
293 value is independent of validation; if validation was required
294 (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
295 been validated, but if :const:`CERT_NONE` was used to establish the
296 connection, the certificate, if present, will not have been validated.
298 .. method:: SSLSocket.cipher()
300 Returns a three-value tuple containing the name of the cipher being
301 used, the version of the SSL protocol that defines its use, and the
302 number of secret bits being used. If no connection has been
303 established, returns ``None``.
305 .. method:: SSLSocket.do_handshake()
307 Perform a TLS/SSL handshake. If this is used with a non-blocking socket,
308 it may raise :exc:`SSLError` with an ``arg[0]`` of :const:`SSL_ERROR_WANT_READ`
309 or :const:`SSL_ERROR_WANT_WRITE`, in which case it must be called again until it
310 completes successfully. For example, to simulate the behavior of a blocking socket,
317 except ssl.SSLError, err:
318 if err.args[0] == ssl.SSL_ERROR_WANT_READ:
319 select.select([s], [], [])
320 elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
321 select.select([], [s], [])
325 .. method:: SSLSocket.unwrap()
327 Performs the SSL shutdown handshake, which removes the TLS layer
328 from the underlying socket, and returns the underlying socket
329 object. This can be used to go from encrypted operation over a
330 connection to unencrypted. The socket instance returned should always be
331 used for further communication with the other side of the
332 connection, rather than the original socket instance (which may
333 not function properly after the unwrap).
335 .. index:: single: certificates
337 .. index:: single: X509 certificate
339 .. _ssl-certificates:
344 Certificates in general are part of a public-key / private-key system. In this system, each *principal*,
345 (which may be a machine, or a person, or an organization) is assigned a unique two-part encryption key.
346 One part of the key is public, and is called the *public key*; the other part is kept secret, and is called
347 the *private key*. The two parts are related, in that if you encrypt a message with one of the parts, you can
348 decrypt it with the other part, and **only** with the other part.
350 A certificate contains information about two principals. It contains
351 the name of a *subject*, and the subject's public key. It also
352 contains a statement by a second principal, the *issuer*, that the
353 subject is who he claims to be, and that this is indeed the subject's
354 public key. The issuer's statement is signed with the issuer's
355 private key, which only the issuer knows. However, anyone can verify
356 the issuer's statement by finding the issuer's public key, decrypting
357 the statement with it, and comparing it to the other information in
358 the certificate. The certificate also contains information about the
359 time period over which it is valid. This is expressed as two fields,
360 called "notBefore" and "notAfter".
362 In the Python use of certificates, a client or server
363 can use a certificate to prove who they are. The other
364 side of a network connection can also be required to produce a certificate,
365 and that certificate can be validated to the satisfaction
366 of the client or server that requires such validation.
367 The connection attempt can be set to raise an exception if
368 the validation fails. Validation is done
369 automatically, by the underlying OpenSSL framework; the
370 application need not concern itself with its mechanics.
371 But the application does usually need to provide
372 sets of certificates to allow this process to take place.
374 Python uses files to contain certificates. They should be formatted
375 as "PEM" (see :rfc:`1422`), which is a base-64 encoded form wrapped
376 with a header line and a footer line::
378 -----BEGIN CERTIFICATE-----
379 ... (certificate in base64 PEM encoding) ...
380 -----END CERTIFICATE-----
382 The Python files which contain certificates can contain a sequence
383 of certificates, sometimes called a *certificate chain*. This chain
384 should start with the specific certificate for the principal who "is"
385 the client or server, and then the certificate for the issuer of that
386 certificate, and then the certificate for the issuer of *that* certificate,
387 and so on up the chain till you get to a certificate which is *self-signed*,
388 that is, a certificate which has the same subject and issuer,
389 sometimes called a *root certificate*. The certificates should just
390 be concatenated together in the certificate file. For example, suppose
391 we had a three certificate chain, from our server certificate to the
392 certificate of the certification authority that signed our server certificate,
393 to the root certificate of the agency which issued the certification authority's
396 -----BEGIN CERTIFICATE-----
397 ... (certificate for your server)...
398 -----END CERTIFICATE-----
399 -----BEGIN CERTIFICATE-----
400 ... (the certificate for the CA)...
401 -----END CERTIFICATE-----
402 -----BEGIN CERTIFICATE-----
403 ... (the root certificate for the CA's issuer)...
404 -----END CERTIFICATE-----
406 If you are going to require validation of the other side of the connection's
407 certificate, you need to provide a "CA certs" file, filled with the certificate
408 chains for each issuer you are willing to trust. Again, this file just
409 contains these chains concatenated together. For validation, Python will
410 use the first chain it finds in the file which matches.
412 Some "standard" root certificates are available from various certification
414 `CACert.org <http://www.cacert.org/index.php?id=3>`_,
415 `Thawte <http://www.thawte.com/roots/>`_,
416 `Verisign <http://www.verisign.com/support/roots.html>`_,
417 `Positive SSL <http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_ (used by python.org),
418 `Equifax and GeoTrust <http://www.geotrust.com/resources/root_certificates/index.asp>`_.
420 In general, if you are using
421 SSL3 or TLS1, you don't need to put the full chain in your "CA certs" file;
422 you only need the root certificates, and the remote peer is supposed to
423 furnish the other certificates necessary to chain from its certificate to
425 See :rfc:`4158` for more discussion of the way in which
426 certification chains can be built.
428 If you are going to create a server that provides SSL-encrypted
429 connection services, you will need to acquire a certificate for that
430 service. There are many ways of acquiring appropriate certificates,
431 such as buying one from a certification authority. Another common
432 practice is to generate a self-signed certificate. The simplest
433 way to do this is with the OpenSSL package, using something like
436 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
437 Generating a 1024 bit RSA private key
439 .............................++++++
440 writing new private key to 'cert.pem'
442 You are about to be asked to enter information that will be incorporated
443 into your certificate request.
444 What you are about to enter is what is called a Distinguished Name or a DN.
445 There are quite a few fields but you can leave some blank
446 For some fields there will be a default value,
447 If you enter '.', the field will be left blank.
449 Country Name (2 letter code) [AU]:US
450 State or Province Name (full name) [Some-State]:MyState
451 Locality Name (eg, city) []:Some City
452 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
453 Organizational Unit Name (eg, section) []:My Group
454 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
455 Email Address []:ops@myserver.mygroup.myorganization.com
458 The disadvantage of a self-signed certificate is that it is its
459 own root certificate, and no one else will have it in their cache
460 of known (and trusted) root certificates.
466 Testing for SSL support
467 ^^^^^^^^^^^^^^^^^^^^^^^
469 To test for the presence of SSL support in a Python installation, user code should use the following idiom::
476 [ do something that requires SSL support ]
478 Client-side operation
479 ^^^^^^^^^^^^^^^^^^^^^
481 This example connects to an SSL server, prints the server's address and certificate,
482 sends some bytes, and reads part of the response::
484 import socket, ssl, pprint
486 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
488 # require a certificate from the server
489 ssl_sock = ssl.wrap_socket(s,
490 ca_certs="/etc/ca_certs_file",
491 cert_reqs=ssl.CERT_REQUIRED)
493 ssl_sock.connect(('www.verisign.com', 443))
495 print repr(ssl_sock.getpeername())
496 print ssl_sock.cipher()
497 print pprint.pformat(ssl_sock.getpeercert())
499 # Set a simple HTTP request -- use httplib in actual code.
500 ssl_sock.write("""GET / HTTP/1.0\r
501 Host: www.verisign.com\r\n\r\n""")
503 # Read a chunk of data. Will not necessarily
504 # read all the data returned by the server.
505 data = ssl_sock.read()
507 # note that closing the SSLSocket will also close the underlying socket
510 As of September 6, 2007, the certificate printed by this program
513 {'notAfter': 'May 8 23:59:59 2009 GMT',
514 'subject': ((('serialNumber', u'2497886'),),
515 (('1.3.6.1.4.1.311.60.2.1.3', u'US'),),
516 (('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),),
517 (('countryName', u'US'),),
518 (('postalCode', u'94043'),),
519 (('stateOrProvinceName', u'California'),),
520 (('localityName', u'Mountain View'),),
521 (('streetAddress', u'487 East Middlefield Road'),),
522 (('organizationName', u'VeriSign, Inc.'),),
523 (('organizationalUnitName',
524 u'Production Security Services'),),
525 (('organizationalUnitName',
526 u'Terms of use at www.verisign.com/rpa (c)06'),),
527 (('commonName', u'www.verisign.com'),))}
529 which is a fairly poorly-formed ``subject`` field.
531 Server-side operation
532 ^^^^^^^^^^^^^^^^^^^^^
534 For server operation, typically you'd need to have a server certificate, and private key, each in a file.
535 You'd open a socket, bind it to a port, call :meth:`listen` on it, then start waiting for clients
540 bindsocket = socket.socket()
541 bindsocket.bind(('myaddr.mydomain.com', 10023))
544 When one did, you'd call :meth:`accept` on the socket to get the new socket from the other
545 end, and use :func:`wrap_socket` to create a server-side SSL context for it::
548 newsocket, fromaddr = bindsocket.accept()
549 connstream = ssl.wrap_socket(newsocket,
551 certfile="mycertfile",
553 ssl_version=ssl.PROTOCOL_TLSv1)
554 deal_with_client(connstream)
556 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)::
558 def deal_with_client(connstream):
560 data = connstream.read()
561 # null data means the client is finished with us
563 if not do_something(connstream, data):
564 # we'll assume do_something returns False
565 # when we're finished with client
567 data = connstream.read()
568 # finished with client
571 And go back to listening for new client connections.
576 Class :class:`socket.socket`
577 Documentation of underlying :mod:`socket` class
579 `Introducing SSL and Certificates using OpenSSL <http://old.pseudonym.org/ssl/wwwj-index.html>`_
582 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
585 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
588 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_