blob: c11597602de0bc95208dae4a66dd4827eeebeb3c [file] [log] [blame]
Antoine Pitrou9e7d6e52011-01-02 22:39:10 +00001:mod:`ssl` --- TLS/SSL wrapper for socket objects
2=================================================
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00003
4.. module:: ssl
Antoine Pitrou9e7d6e52011-01-02 22:39:10 +00005 :synopsis: TLS/SSL wrapper for socket objects
Bill Janssen426ea0a2007-08-29 22:35:05 +00006
7.. moduleauthor:: Bill Janssen <bill.janssen@gmail.com>
Bill Janssen426ea0a2007-08-29 22:35:05 +00008.. sectionauthor:: Bill Janssen <bill.janssen@gmail.com>
9
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000010
Bill Janssen98d19da2007-09-10 21:51:02 +000011.. index:: single: OpenSSL; (use in module ssl)
12
13.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
14
Éric Araujo29a0b572011-08-19 02:14:03 +020015.. versionadded:: 2.6
16
17**Source code:** :source:`Lib/ssl.py`
18
19--------------
20
Georg Brandla50d20a2009-09-16 15:57:46 +000021This module provides access to Transport Layer Security (often known as "Secure
22Sockets Layer") encryption and peer authentication facilities for network
23sockets, both client-side and server-side. This module uses the OpenSSL
24library. It is available on all modern Unix systems, Windows, Mac OS X, and
25probably additional platforms, as long as OpenSSL is installed on that platform.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000026
27.. note::
28
Georg Brandla50d20a2009-09-16 15:57:46 +000029 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.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000032
Christian Heimes88b22202013-10-29 21:08:56 +010033.. warning::
Antoine Pitrouf7a52472013-11-17 15:42:58 +010034 The ssl module won't validate certificates by default. When used in
35 client mode, this means you are vulnerable to man-in-the-middle attacks.
36
37.. warning::
Christian Heimes88b22202013-10-29 21:08:56 +010038
39 OpenSSL's internal random number generator does not properly handle fork.
40 Applications must change the PRNG state of the parent process if they use
Christian Heimesdb78e432013-10-29 22:19:39 +010041 any SSL feature with :func:`os.fork`. Any successful call of
Christian Heimes88b22202013-10-29 21:08:56 +010042 :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or
43 :func:`~ssl.RAND_pseudo_bytes` is sufficient.
44
Georg Brandla50d20a2009-09-16 15:57:46 +000045This section documents the objects and functions in the ``ssl`` module; for more
46general information about TLS, SSL, and certificates, the reader is referred to
47the documents in the "See Also" section at the bottom.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000048
Georg Brandla50d20a2009-09-16 15:57:46 +000049This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
50:class:`socket.socket` type, and provides a socket-like wrapper that also
51encrypts and decrypts the data going over the socket with SSL. It supports
52additional :meth:`read` and :meth:`write` methods, along with a method,
53:meth:`getpeercert`, to retrieve the certificate of the other side of the
54connection, and a method, :meth:`cipher`, to retrieve the cipher being used for
55the secure connection.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000056
Bill Janssen93bf9ce2007-09-11 02:42:07 +000057Functions, Constants, and Exceptions
58------------------------------------
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000059
Bill Janssen93bf9ce2007-09-11 02:42:07 +000060.. exception:: SSLError
61
Georg Brandlc62ef8b2009-01-03 20:55:06 +000062 Raised to signal an error from the underlying SSL implementation. This
Georg Brandla50d20a2009-09-16 15:57:46 +000063 signifies some problem in the higher-level encryption and authentication
64 layer that's superimposed on the underlying network connection. This error
65 is a subtype of :exc:`socket.error`, which in turn is a subtype of
66 :exc:`IOError`.
Bill Janssen93bf9ce2007-09-11 02:42:07 +000067
Antoine Pitrou0a6373c2010-04-17 17:10:38 +000068.. 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)
Bill Janssen98d19da2007-09-10 21:51:02 +000069
Georg Brandla50d20a2009-09-16 15:57:46 +000070 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
71 of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
Antoine Pitrou63cc99d2013-12-28 17:26:33 +010072 the underlying socket in an SSL context. ``sock`` must be a
73 :data:`~socket.SOCK_STREAM` socket; other socket types are unsupported.
74
75 For client-side sockets, the context construction is lazy; if the
76 underlying socket isn't connected yet, the context construction will be
77 performed after :meth:`connect` is called on the socket. For
78 server-side sockets, if the socket has no remote peer, it is assumed
79 to be a listening socket, and the server-side SSL wrapping is
80 automatically performed on client connections accepted via the
81 :meth:`accept` method. :func:`wrap_socket` may raise :exc:`SSLError`.
Bill Janssen98d19da2007-09-10 21:51:02 +000082
Georg Brandla50d20a2009-09-16 15:57:46 +000083 The ``keyfile`` and ``certfile`` parameters specify optional files which
84 contain a certificate to be used to identify the local side of the
85 connection. See the discussion of :ref:`ssl-certificates` for more
86 information on how the certificate is stored in the ``certfile``.
Bill Janssen98d19da2007-09-10 21:51:02 +000087
Georg Brandla50d20a2009-09-16 15:57:46 +000088 Often the private key is stored in the same file as the certificate; in this
89 case, only the ``certfile`` parameter need be passed. If the private key is
90 stored in a separate file, both parameters must be used. If the private key
91 is stored in the ``certfile``, it should come before the first certificate in
92 the certificate chain::
Bill Janssen98d19da2007-09-10 21:51:02 +000093
94 -----BEGIN RSA PRIVATE KEY-----
95 ... (private key in base64 encoding) ...
96 -----END RSA PRIVATE KEY-----
97 -----BEGIN CERTIFICATE-----
98 ... (certificate in base64 PEM encoding) ...
99 -----END CERTIFICATE-----
100
Georg Brandla50d20a2009-09-16 15:57:46 +0000101 The parameter ``server_side`` is a boolean which identifies whether
102 server-side or client-side behavior is desired from this socket.
Bill Janssen98d19da2007-09-10 21:51:02 +0000103
Georg Brandla50d20a2009-09-16 15:57:46 +0000104 The parameter ``cert_reqs`` specifies whether a certificate is required from
105 the other side of the connection, and whether it will be validated if
106 provided. It must be one of the three values :const:`CERT_NONE`
107 (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
108 if provided), or :const:`CERT_REQUIRED` (required and validated). If the
109 value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
110 parameter must point to a file of CA certificates.
Bill Janssen98d19da2007-09-10 21:51:02 +0000111
Georg Brandla50d20a2009-09-16 15:57:46 +0000112 The ``ca_certs`` file contains a set of concatenated "certification
113 authority" certificates, which are used to validate certificates passed from
114 the other end of the connection. See the discussion of
115 :ref:`ssl-certificates` for more information about how to arrange the
116 certificates in this file.
Bill Janssen98d19da2007-09-10 21:51:02 +0000117
Georg Brandla50d20a2009-09-16 15:57:46 +0000118 The parameter ``ssl_version`` specifies which version of the SSL protocol to
119 use. Typically, the server chooses a particular protocol version, and the
120 client must adapt to the server's choice. Most of the versions are not
Antoine Pitrou4a7e0c892012-01-09 21:35:11 +0100121 interoperable with the other versions. If not specified, the default is
122 :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other
Georg Brandla50d20a2009-09-16 15:57:46 +0000123 versions.
Bill Janssen98d19da2007-09-10 21:51:02 +0000124
Georg Brandla50d20a2009-09-16 15:57:46 +0000125 Here's a table showing which versions in a client (down the side) can connect
126 to which versions in a server (along the top):
Bill Janssen98d19da2007-09-10 21:51:02 +0000127
128 .. table::
129
130 ======================== ========= ========= ========== =========
131 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1**
Georg Brandl2b92f6b2007-12-06 01:52:24 +0000132 ------------------------ --------- --------- ---------- ---------
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000133 *SSLv2* yes no yes no
Antoine Pitroudf4c9862012-01-09 21:43:18 +0100134 *SSLv3* no yes yes no
Bill Janssen98d19da2007-09-10 21:51:02 +0000135 *SSLv23* yes no yes no
136 *TLSv1* no no yes yes
137 ======================== ========= ========= ========== =========
138
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000139 .. note::
140
Andrew M. Kuchling3ded4212010-04-30 00:52:31 +0000141 Which connections succeed will vary depending on the version of
142 OpenSSL. For instance, in some older versions of OpenSSL (such
143 as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an
144 SSLv23 server. Another example: beginning with OpenSSL 1.0.0,
145 an SSLv23 client will not actually attempt SSLv2 connections
146 unless you explicitly enable SSLv2 ciphers; for example, you
147 might specify ``"ALL"`` or ``"SSLv2"`` as the *ciphers* parameter
148 to enable them.
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000149
Andrew M. Kuchling3ded4212010-04-30 00:52:31 +0000150 The *ciphers* parameter sets the available ciphers for this SSL object.
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000151 It should be a string in the `OpenSSL cipher list format
152 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
Bill Janssen98d19da2007-09-10 21:51:02 +0000153
Bill Janssen934b16d2008-06-28 22:19:33 +0000154 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
155 handshake automatically after doing a :meth:`socket.connect`, or whether the
Georg Brandla50d20a2009-09-16 15:57:46 +0000156 application program will call it explicitly, by invoking the
157 :meth:`SSLSocket.do_handshake` method. Calling
158 :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
159 blocking behavior of the socket I/O involved in the handshake.
Bill Janssen934b16d2008-06-28 22:19:33 +0000160
Georg Brandla50d20a2009-09-16 15:57:46 +0000161 The parameter ``suppress_ragged_eofs`` specifies how the
162 :meth:`SSLSocket.read` method should signal unexpected EOF from the other end
163 of the connection. If specified as :const:`True` (the default), it returns a
164 normal EOF in response to unexpected EOF errors raised from the underlying
165 socket; if :const:`False`, it will raise the exceptions back to the caller.
Bill Janssen934b16d2008-06-28 22:19:33 +0000166
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000167 .. versionchanged:: 2.7
168 New optional argument *ciphers*.
169
Bill Janssen98d19da2007-09-10 21:51:02 +0000170.. function:: RAND_status()
171
Serhiy Storchaka26d936a2013-11-29 12:16:53 +0200172 Returns ``True`` if the SSL pseudo-random number generator has been seeded with
Georg Brandla50d20a2009-09-16 15:57:46 +0000173 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
174 and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
175 number generator.
Bill Janssen98d19da2007-09-10 21:51:02 +0000176
177.. function:: RAND_egd(path)
178
179 If you are running an entropy-gathering daemon (EGD) somewhere, and ``path``
Georg Brandla50d20a2009-09-16 15:57:46 +0000180 is the pathname of a socket connection open to it, this will read 256 bytes
181 of randomness from the socket, and add it to the SSL pseudo-random number
182 generator to increase the security of generated secret keys. This is
183 typically only necessary on systems without better sources of randomness.
Bill Janssen98d19da2007-09-10 21:51:02 +0000184
Georg Brandla50d20a2009-09-16 15:57:46 +0000185 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
186 of entropy-gathering daemons.
Bill Janssen98d19da2007-09-10 21:51:02 +0000187
188.. function:: RAND_add(bytes, entropy)
189
Georg Brandla50d20a2009-09-16 15:57:46 +0000190 Mixes the given ``bytes`` into the SSL pseudo-random number generator. The
191 parameter ``entropy`` (a float) is a lower bound on the entropy contained in
192 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
193 information on sources of entropy.
Bill Janssen98d19da2007-09-10 21:51:02 +0000194
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000195.. function:: cert_time_to_seconds(timestring)
196
Georg Brandla50d20a2009-09-16 15:57:46 +0000197 Returns a floating-point value containing a normal seconds-after-the-epoch
198 time value, given the time-string representing the "notBefore" or "notAfter"
199 date from a certificate.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000200
201 Here's an example::
202
203 >>> import ssl
204 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
205 1178694000.0
206 >>> import time
207 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
208 'Wed May 9 00:00:00 2007'
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000209 >>>
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000210
Bill Janssen296a59d2007-09-16 22:06:00 +0000211.. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
212
Georg Brandla50d20a2009-09-16 15:57:46 +0000213 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
214 *port-number*) pair, fetches the server's certificate, and returns it as a
215 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
216 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
217 specified, it should be a file containing a list of root certificates, the
218 same format as used for the same parameter in :func:`wrap_socket`. The call
219 will attempt to validate the server certificate against that set of root
Bill Janssen296a59d2007-09-16 22:06:00 +0000220 certificates, and will fail if the validation attempt fails.
221
222.. function:: DER_cert_to_PEM_cert (DER_cert_bytes)
223
224 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
225 string version of the same certificate.
226
227.. function:: PEM_cert_to_DER_cert (PEM_cert_string)
228
Georg Brandla50d20a2009-09-16 15:57:46 +0000229 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
230 bytes for that same certificate.
Bill Janssen296a59d2007-09-16 22:06:00 +0000231
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000232.. data:: CERT_NONE
233
Georg Brandla50d20a2009-09-16 15:57:46 +0000234 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
235 certificates will be required or validated from the other side of the socket
236 connection.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000237
238.. data:: CERT_OPTIONAL
239
Georg Brandla50d20a2009-09-16 15:57:46 +0000240 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
241 certificates will be required from the other side of the socket connection,
242 but if they are provided, will be validated. Note that use of this setting
243 requires a valid certificate validation file also be passed as a value of the
244 ``ca_certs`` parameter.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000245
246.. data:: CERT_REQUIRED
247
Georg Brandla50d20a2009-09-16 15:57:46 +0000248 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when
249 certificates will be required from the other side of the socket connection.
250 Note that use of this setting requires a valid certificate validation file
251 also be passed as a value of the ``ca_certs`` parameter.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000252
253.. data:: PROTOCOL_SSLv2
254
255 Selects SSL version 2 as the channel encryption protocol.
256
Victor Stinnerb1241f92011-05-10 01:52:03 +0200257 This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
258 flag.
259
Antoine Pitrou308c2af2010-05-16 14:16:56 +0000260 .. warning::
261
262 SSL version 2 is insecure. Its use is highly discouraged.
263
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000264.. data:: PROTOCOL_SSLv23
265
Georg Brandla50d20a2009-09-16 15:57:46 +0000266 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
267 setting to use with servers for maximum compatibility with the other end of
268 an SSL connection, but it may cause the specific ciphers chosen for the
269 encryption to be of fairly low quality.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000270
271.. data:: PROTOCOL_SSLv3
272
Georg Brandla50d20a2009-09-16 15:57:46 +0000273 Selects SSL version 3 as the channel encryption protocol. For clients, this
274 is the maximally compatible SSL variant.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000275
276.. data:: PROTOCOL_TLSv1
277
Georg Brandla50d20a2009-09-16 15:57:46 +0000278 Selects TLS version 1 as the channel encryption protocol. This is the most
279 modern version, and probably the best choice for maximum protection, if both
280 sides can speak it.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000281
Antoine Pitrouf9de5342010-04-05 21:35:07 +0000282.. data:: OPENSSL_VERSION
283
284 The version string of the OpenSSL library loaded by the interpreter::
285
286 >>> ssl.OPENSSL_VERSION
287 'OpenSSL 0.9.8k 25 Mar 2009'
288
289 .. versionadded:: 2.7
290
291.. data:: OPENSSL_VERSION_INFO
292
293 A tuple of five integers representing version information about the
294 OpenSSL library::
295
296 >>> ssl.OPENSSL_VERSION_INFO
297 (0, 9, 8, 11, 15)
298
299 .. versionadded:: 2.7
300
301.. data:: OPENSSL_VERSION_NUMBER
302
303 The raw version number of the OpenSSL library, as a single integer::
304
305 >>> ssl.OPENSSL_VERSION_NUMBER
306 9470143L
307 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
308 '0x9080bfL'
309
310 .. versionadded:: 2.7
311
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000312
Bill Janssen98d19da2007-09-10 21:51:02 +0000313SSLSocket Objects
314-----------------
315
Giampaolo Rodola'76794132013-04-06 03:46:47 +0200316SSL sockets provide the following methods of :ref:`socket-objects`:
Bill Janssen98d19da2007-09-10 21:51:02 +0000317
Giampaolo Rodola'76794132013-04-06 03:46:47 +0200318- :meth:`~socket.socket.accept()`
319- :meth:`~socket.socket.bind()`
320- :meth:`~socket.socket.close()`
321- :meth:`~socket.socket.connect()`
322- :meth:`~socket.socket.fileno()`
323- :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`
324- :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`
325- :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`,
326 :meth:`~socket.socket.setblocking()`
327- :meth:`~socket.socket.listen()`
328- :meth:`~socket.socket.makefile()`
329- :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()`
330 (but passing a non-zero ``flags`` argument is not allowed)
331- :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with
332 the same limitation)
333- :meth:`~socket.socket.shutdown()`
Bill Janssen98d19da2007-09-10 21:51:02 +0000334
Giampaolo Rodola'76794132013-04-06 03:46:47 +0200335However, since the SSL (and TLS) protocol has its own framing atop
336of TCP, the SSL sockets abstraction can, in certain respects, diverge from
337the specification of normal, OS-level sockets.
Bill Janssen98d19da2007-09-10 21:51:02 +0000338
Giampaolo Rodola'76794132013-04-06 03:46:47 +0200339SSL sockets also have the following additional methods and attributes:
Bill Janssen98d19da2007-09-10 21:51:02 +0000340
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000341.. method:: SSLSocket.getpeercert(binary_form=False)
Bill Janssen98d19da2007-09-10 21:51:02 +0000342
Georg Brandla50d20a2009-09-16 15:57:46 +0000343 If there is no certificate for the peer on the other end of the connection,
344 returns ``None``.
Bill Janssen98d19da2007-09-10 21:51:02 +0000345
Antoine Pitrouf12f3912013-04-16 20:27:17 +0200346 If the ``binary_form`` parameter is :const:`False`, and a certificate was
Georg Brandla50d20a2009-09-16 15:57:46 +0000347 received from the peer, this method returns a :class:`dict` instance. If the
348 certificate was not validated, the dict is empty. If the certificate was
349 validated, it returns a dict with the keys ``subject`` (the principal for
350 which the certificate was issued), and ``notAfter`` (the time after which the
351 certificate should not be trusted). The certificate was already validated,
352 so the ``notBefore`` and ``issuer`` fields are not returned. If a
353 certificate contains an instance of the *Subject Alternative Name* extension
354 (see :rfc:`3280`), there will also be a ``subjectAltName`` key in the
355 dictionary.
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000356
357 The "subject" field is a tuple containing the sequence of relative
Georg Brandla50d20a2009-09-16 15:57:46 +0000358 distinguished names (RDNs) given in the certificate's data structure for the
359 principal, and each RDN is a sequence of name-value pairs::
Bill Janssen98d19da2007-09-10 21:51:02 +0000360
361 {'notAfter': 'Feb 16 16:54:50 2013 GMT',
362 'subject': ((('countryName', u'US'),),
363 (('stateOrProvinceName', u'Delaware'),),
364 (('localityName', u'Wilmington'),),
365 (('organizationName', u'Python Software Foundation'),),
366 (('organizationalUnitName', u'SSL'),),
367 (('commonName', u'somemachine.python.org'),))}
368
Georg Brandla50d20a2009-09-16 15:57:46 +0000369 If the ``binary_form`` parameter is :const:`True`, and a certificate was
370 provided, this method returns the DER-encoded form of the entire certificate
371 as a sequence of bytes, or :const:`None` if the peer did not provide a
Antoine Pitrouf12f3912013-04-16 20:27:17 +0200372 certificate. Whether the peer provides a certificate depends on the SSL
373 socket's role:
374
375 * for a client SSL socket, the server will always provide a certificate,
376 regardless of whether validation was required;
377
378 * for a server SSL socket, the client will only provide a certificate
379 when requested by the server; therefore :meth:`getpeercert` will return
380 :const:`None` if you used :const:`CERT_NONE` (rather than
381 :const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`).
Bill Janssen98d19da2007-09-10 21:51:02 +0000382
383.. method:: SSLSocket.cipher()
384
Georg Brandla50d20a2009-09-16 15:57:46 +0000385 Returns a three-value tuple containing the name of the cipher being used, the
386 version of the SSL protocol that defines its use, and the number of secret
387 bits being used. If no connection has been established, returns ``None``.
Bill Janssen98d19da2007-09-10 21:51:02 +0000388
Bill Janssen934b16d2008-06-28 22:19:33 +0000389.. method:: SSLSocket.do_handshake()
390
Georg Brandla50d20a2009-09-16 15:57:46 +0000391 Perform a TLS/SSL handshake. If this is used with a non-blocking socket, it
392 may raise :exc:`SSLError` with an ``arg[0]`` of :const:`SSL_ERROR_WANT_READ`
393 or :const:`SSL_ERROR_WANT_WRITE`, in which case it must be called again until
394 it completes successfully. For example, to simulate the behavior of a
395 blocking socket, one might write::
Bill Janssen934b16d2008-06-28 22:19:33 +0000396
397 while True:
398 try:
399 s.do_handshake()
400 break
Andrew Svetlov1625d882012-10-30 21:56:43 +0200401 except ssl.SSLError as err:
Bill Janssen934b16d2008-06-28 22:19:33 +0000402 if err.args[0] == ssl.SSL_ERROR_WANT_READ:
403 select.select([s], [], [])
404 elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
405 select.select([], [s], [])
406 else:
407 raise
Bill Janssen98d19da2007-09-10 21:51:02 +0000408
Bill Janssen5bfbd762008-08-12 17:09:57 +0000409.. method:: SSLSocket.unwrap()
410
Georg Brandla50d20a2009-09-16 15:57:46 +0000411 Performs the SSL shutdown handshake, which removes the TLS layer from the
412 underlying socket, and returns the underlying socket object. This can be
413 used to go from encrypted operation over a connection to unencrypted. The
414 socket instance returned should always be used for further communication with
415 the other side of the connection, rather than the original socket instance
416 (which may not function properly after the unwrap).
Bill Janssen5bfbd762008-08-12 17:09:57 +0000417
Bill Janssen98d19da2007-09-10 21:51:02 +0000418.. index:: single: certificates
419
420.. index:: single: X509 certificate
421
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000422.. _ssl-certificates:
423
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000424Certificates
425------------
426
Georg Brandla50d20a2009-09-16 15:57:46 +0000427Certificates in general are part of a public-key / private-key system. In this
428system, each *principal*, (which may be a machine, or a person, or an
429organization) is assigned a unique two-part encryption key. One part of the key
430is public, and is called the *public key*; the other part is kept secret, and is
431called the *private key*. The two parts are related, in that if you encrypt a
432message with one of the parts, you can decrypt it with the other part, and
433**only** with the other part.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000434
Georg Brandla50d20a2009-09-16 15:57:46 +0000435A certificate contains information about two principals. It contains the name
436of a *subject*, and the subject's public key. It also contains a statement by a
437second principal, the *issuer*, that the subject is who he claims to be, and
438that this is indeed the subject's public key. The issuer's statement is signed
439with the issuer's private key, which only the issuer knows. However, anyone can
440verify the issuer's statement by finding the issuer's public key, decrypting the
441statement with it, and comparing it to the other information in the certificate.
442The certificate also contains information about the time period over which it is
443valid. This is expressed as two fields, called "notBefore" and "notAfter".
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000444
Georg Brandla50d20a2009-09-16 15:57:46 +0000445In the Python use of certificates, a client or server can use a certificate to
446prove who they are. The other side of a network connection can also be required
447to produce a certificate, and that certificate can be validated to the
448satisfaction of the client or server that requires such validation. The
449connection attempt can be set to raise an exception if the validation fails.
450Validation is done automatically, by the underlying OpenSSL framework; the
451application need not concern itself with its mechanics. But the application
452does usually need to provide sets of certificates to allow this process to take
453place.
Bill Janssen426ea0a2007-08-29 22:35:05 +0000454
Georg Brandla50d20a2009-09-16 15:57:46 +0000455Python uses files to contain certificates. They should be formatted as "PEM"
456(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
457and a footer line::
Bill Janssen426ea0a2007-08-29 22:35:05 +0000458
459 -----BEGIN CERTIFICATE-----
460 ... (certificate in base64 PEM encoding) ...
461 -----END CERTIFICATE-----
462
Georg Brandla50d20a2009-09-16 15:57:46 +0000463The Python files which contain certificates can contain a sequence of
464certificates, sometimes called a *certificate chain*. This chain should start
465with the specific certificate for the principal who "is" the client or server,
466and then the certificate for the issuer of that certificate, and then the
467certificate for the issuer of *that* certificate, and so on up the chain till
468you get to a certificate which is *self-signed*, that is, a certificate which
469has the same subject and issuer, sometimes called a *root certificate*. The
470certificates should just be concatenated together in the certificate file. For
471example, suppose we had a three certificate chain, from our server certificate
472to the certificate of the certification authority that signed our server
473certificate, to the root certificate of the agency which issued the
474certification authority's certificate::
Bill Janssen426ea0a2007-08-29 22:35:05 +0000475
476 -----BEGIN CERTIFICATE-----
477 ... (certificate for your server)...
478 -----END CERTIFICATE-----
479 -----BEGIN CERTIFICATE-----
480 ... (the certificate for the CA)...
481 -----END CERTIFICATE-----
482 -----BEGIN CERTIFICATE-----
483 ... (the root certificate for the CA's issuer)...
484 -----END CERTIFICATE-----
485
486If you are going to require validation of the other side of the connection's
487certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandla50d20a2009-09-16 15:57:46 +0000488chains for each issuer you are willing to trust. Again, this file just contains
489these chains concatenated together. For validation, Python will use the first
490chain it finds in the file which matches.
Bill Janssen934b16d2008-06-28 22:19:33 +0000491
Bill Janssen98d19da2007-09-10 21:51:02 +0000492Some "standard" root certificates are available from various certification
Donald Stufft74a4eba2014-03-24 19:49:42 -0400493authorities: `Thawte <http://www.thawte.com/roots/>`_, `Verisign
Georg Brandla50d20a2009-09-16 15:57:46 +0000494<http://www.verisign.com/support/roots.html>`_, `Positive SSL
495<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
496(used by python.org), `Equifax and GeoTrust
497<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Bill Janssen98d19da2007-09-10 21:51:02 +0000498
Georg Brandla50d20a2009-09-16 15:57:46 +0000499In general, if you are using SSL3 or TLS1, you don't need to put the full chain
500in your "CA certs" file; you only need the root certificates, and the remote
501peer is supposed to furnish the other certificates necessary to chain from its
502certificate to a root certificate. See :rfc:`4158` for more discussion of the
503way in which certification chains can be built.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000504
Georg Brandla50d20a2009-09-16 15:57:46 +0000505If you are going to create a server that provides SSL-encrypted connection
506services, you will need to acquire a certificate for that service. There are
507many ways of acquiring appropriate certificates, such as buying one from a
508certification authority. Another common practice is to generate a self-signed
509certificate. The simplest way to do this is with the OpenSSL package, using
510something like the following::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000511
Bill Janssen98d19da2007-09-10 21:51:02 +0000512 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
513 Generating a 1024 bit RSA private key
514 .......++++++
515 .............................++++++
516 writing new private key to 'cert.pem'
517 -----
518 You are about to be asked to enter information that will be incorporated
519 into your certificate request.
520 What you are about to enter is what is called a Distinguished Name or a DN.
521 There are quite a few fields but you can leave some blank
522 For some fields there will be a default value,
523 If you enter '.', the field will be left blank.
524 -----
525 Country Name (2 letter code) [AU]:US
526 State or Province Name (full name) [Some-State]:MyState
527 Locality Name (eg, city) []:Some City
528 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
529 Organizational Unit Name (eg, section) []:My Group
530 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
531 Email Address []:ops@myserver.mygroup.myorganization.com
532 %
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000533
Georg Brandla50d20a2009-09-16 15:57:46 +0000534The disadvantage of a self-signed certificate is that it is its own root
535certificate, and no one else will have it in their cache of known (and trusted)
536root certificates.
Bill Janssen426ea0a2007-08-29 22:35:05 +0000537
538
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000539Examples
540--------
541
Bill Janssen426ea0a2007-08-29 22:35:05 +0000542Testing for SSL support
543^^^^^^^^^^^^^^^^^^^^^^^
544
Georg Brandla50d20a2009-09-16 15:57:46 +0000545To test for the presence of SSL support in a Python installation, user code
546should use the following idiom::
Bill Janssen426ea0a2007-08-29 22:35:05 +0000547
548 try:
Georg Brandl28046022011-02-25 11:01:04 +0000549 import ssl
Bill Janssen426ea0a2007-08-29 22:35:05 +0000550 except ImportError:
Georg Brandl28046022011-02-25 11:01:04 +0000551 pass
Bill Janssen426ea0a2007-08-29 22:35:05 +0000552 else:
Georg Brandl28046022011-02-25 11:01:04 +0000553 ... # do something that requires SSL support
Bill Janssen426ea0a2007-08-29 22:35:05 +0000554
555Client-side operation
556^^^^^^^^^^^^^^^^^^^^^
557
Georg Brandla50d20a2009-09-16 15:57:46 +0000558This example connects to an SSL server, prints the server's address and
559certificate, sends some bytes, and reads part of the response::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000560
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000561 import socket, ssl, pprint
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000562
563 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Bill Janssen98d19da2007-09-10 21:51:02 +0000564
565 # require a certificate from the server
566 ssl_sock = ssl.wrap_socket(s,
567 ca_certs="/etc/ca_certs_file",
568 cert_reqs=ssl.CERT_REQUIRED)
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000569
570 ssl_sock.connect(('www.verisign.com', 443))
571
572 print repr(ssl_sock.getpeername())
Bill Janssen98d19da2007-09-10 21:51:02 +0000573 print ssl_sock.cipher()
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000574 print pprint.pformat(ssl_sock.getpeercert())
575
576 # Set a simple HTTP request -- use httplib in actual code.
577 ssl_sock.write("""GET / HTTP/1.0\r
578 Host: www.verisign.com\r\n\r\n""")
579
580 # Read a chunk of data. Will not necessarily
581 # read all the data returned by the server.
582 data = ssl_sock.read()
583
Bill Janssen98d19da2007-09-10 21:51:02 +0000584 # note that closing the SSLSocket will also close the underlying socket
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000585 ssl_sock.close()
586
Georg Brandla50d20a2009-09-16 15:57:46 +0000587As of September 6, 2007, the certificate printed by this program looked like
588this::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000589
Bill Janssen98d19da2007-09-10 21:51:02 +0000590 {'notAfter': 'May 8 23:59:59 2009 GMT',
591 'subject': ((('serialNumber', u'2497886'),),
592 (('1.3.6.1.4.1.311.60.2.1.3', u'US'),),
593 (('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),),
594 (('countryName', u'US'),),
595 (('postalCode', u'94043'),),
596 (('stateOrProvinceName', u'California'),),
597 (('localityName', u'Mountain View'),),
598 (('streetAddress', u'487 East Middlefield Road'),),
599 (('organizationName', u'VeriSign, Inc.'),),
600 (('organizationalUnitName',
601 u'Production Security Services'),),
602 (('organizationalUnitName',
603 u'Terms of use at www.verisign.com/rpa (c)06'),),
604 (('commonName', u'www.verisign.com'),))}
605
606which is a fairly poorly-formed ``subject`` field.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000607
Bill Janssen426ea0a2007-08-29 22:35:05 +0000608Server-side operation
609^^^^^^^^^^^^^^^^^^^^^
610
Georg Brandla50d20a2009-09-16 15:57:46 +0000611For server operation, typically you'd need to have a server certificate, and
612private key, each in a file. You'd open a socket, bind it to a port, call
613:meth:`listen` on it, then start waiting for clients to connect::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000614
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000615 import socket, ssl
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000616
617 bindsocket = socket.socket()
618 bindsocket.bind(('myaddr.mydomain.com', 10023))
619 bindsocket.listen(5)
620
Georg Brandla50d20a2009-09-16 15:57:46 +0000621When one did, you'd call :meth:`accept` on the socket to get the new socket from
622the other end, and use :func:`wrap_socket` to create a server-side SSL context
623for it::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000624
625 while True:
Antoine Pitrou9e7d6e52011-01-02 22:39:10 +0000626 newsocket, fromaddr = bindsocket.accept()
627 connstream = ssl.wrap_socket(newsocket,
628 server_side=True,
629 certfile="mycertfile",
630 keyfile="mykeyfile",
631 ssl_version=ssl.PROTOCOL_TLSv1)
632 try:
633 deal_with_client(connstream)
634 finally:
635 connstream.shutdown(socket.SHUT_RDWR)
636 connstream.close()
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000637
Georg Brandla50d20a2009-09-16 15:57:46 +0000638Then you'd read data from the ``connstream`` and do something with it till you
639are finished with the client (or the client is finished with you)::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000640
641 def deal_with_client(connstream):
Georg Brandl28046022011-02-25 11:01:04 +0000642 data = connstream.read()
643 # null data means the client is finished with us
644 while data:
645 if not do_something(connstream, data):
646 # we'll assume do_something returns False
647 # when we're finished with client
648 break
649 data = connstream.read()
650 # finished with client
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000651
652And go back to listening for new client connections.
653
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000654
Bill Janssen98d19da2007-09-10 21:51:02 +0000655.. seealso::
Bill Janssen426ea0a2007-08-29 22:35:05 +0000656
Bill Janssen98d19da2007-09-10 21:51:02 +0000657 Class :class:`socket.socket`
Georg Brandl4e8534e2013-10-06 18:20:31 +0200658 Documentation of underlying :mod:`socket` class
Bill Janssen426ea0a2007-08-29 22:35:05 +0000659
Georg Brandl4e8534e2013-10-06 18:20:31 +0200660 `SSL/TLS Strong Encryption: An Introduction <http://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html>`_
661 Intro from the Apache webserver documentation
Bill Janssen426ea0a2007-08-29 22:35:05 +0000662
Bill Janssen98d19da2007-09-10 21:51:02 +0000663 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
664 Steve Kent
Bill Janssen426ea0a2007-08-29 22:35:05 +0000665
Bill Janssen98d19da2007-09-10 21:51:02 +0000666 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
667 D. Eastlake et. al.
Bill Janssenffe576d2007-09-05 00:46:27 +0000668
Bill Janssen98d19da2007-09-10 21:51:02 +0000669 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
670 Housley et. al.