blob: 5f8272b2f2c0b90bf1ffcfb94622a12678ce63ee [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
Georg Brandla50d20a2009-09-16 15:57:46 +000033This section documents the objects and functions in the ``ssl`` module; for more
34general information about TLS, SSL, and certificates, the reader is referred to
35the documents in the "See Also" section at the bottom.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000036
Georg Brandla50d20a2009-09-16 15:57:46 +000037This 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
39encrypts and decrypts the data going over the socket with SSL. It supports
40additional :meth:`read` and :meth:`write` methods, along with a method,
41:meth:`getpeercert`, to retrieve the certificate of the other side of the
42connection, and a method, :meth:`cipher`, to retrieve the cipher being used for
43the secure connection.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000044
Bill Janssen93bf9ce2007-09-11 02:42:07 +000045Functions, Constants, and Exceptions
46------------------------------------
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000047
Bill Janssen93bf9ce2007-09-11 02:42:07 +000048.. exception:: SSLError
49
Georg Brandlc62ef8b2009-01-03 20:55:06 +000050 Raised to signal an error from the underlying SSL implementation. This
Georg Brandla50d20a2009-09-16 15:57:46 +000051 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`.
Bill Janssen93bf9ce2007-09-11 02:42:07 +000055
Antoine Pitrou0a6373c2010-04-17 17:10:38 +000056.. 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 +000057
Georg Brandla50d20a2009-09-16 15:57:46 +000058 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`.
Bill Janssen98d19da2007-09-10 21:51:02 +000067
Georg Brandla50d20a2009-09-16 15:57:46 +000068 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``.
Bill Janssen98d19da2007-09-10 21:51:02 +000072
Georg Brandla50d20a2009-09-16 15:57:46 +000073 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::
Bill Janssen98d19da2007-09-10 21:51:02 +000078
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
Georg Brandla50d20a2009-09-16 15:57:46 +000086 The parameter ``server_side`` is a boolean which identifies whether
87 server-side or client-side behavior is desired from this socket.
Bill Janssen98d19da2007-09-10 21:51:02 +000088
Georg Brandla50d20a2009-09-16 15:57:46 +000089 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.
Bill Janssen98d19da2007-09-10 21:51:02 +000096
Georg Brandla50d20a2009-09-16 15:57:46 +000097 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.
Bill Janssen98d19da2007-09-10 21:51:02 +0000102
Georg Brandla50d20a2009-09-16 15:57:46 +0000103 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
Antoine Pitrou4a7e0c892012-01-09 21:35:11 +0100106 interoperable with the other versions. If not specified, the default is
107 :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other
Georg Brandla50d20a2009-09-16 15:57:46 +0000108 versions.
Bill Janssen98d19da2007-09-10 21:51:02 +0000109
Georg Brandla50d20a2009-09-16 15:57:46 +0000110 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):
Bill Janssen98d19da2007-09-10 21:51:02 +0000112
113 .. table::
114
115 ======================== ========= ========= ========== =========
116 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1**
Georg Brandl2b92f6b2007-12-06 01:52:24 +0000117 ------------------------ --------- --------- ---------- ---------
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000118 *SSLv2* yes no yes no
Bill Janssen98d19da2007-09-10 21:51:02 +0000119 *SSLv3* yes yes yes no
120 *SSLv23* yes no yes no
121 *TLSv1* no no yes yes
122 ======================== ========= ========= ========== =========
123
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000124 .. note::
125
Andrew M. Kuchling3ded4212010-04-30 00:52:31 +0000126 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.
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000134
Andrew M. Kuchling3ded4212010-04-30 00:52:31 +0000135 The *ciphers* parameter sets the available ciphers for this SSL object.
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000136 It should be a string in the `OpenSSL cipher list format
137 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
Bill Janssen98d19da2007-09-10 21:51:02 +0000138
Bill Janssen934b16d2008-06-28 22:19:33 +0000139 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
140 handshake automatically after doing a :meth:`socket.connect`, or whether the
Georg Brandla50d20a2009-09-16 15:57:46 +0000141 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.
Bill Janssen934b16d2008-06-28 22:19:33 +0000145
Georg Brandla50d20a2009-09-16 15:57:46 +0000146 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.
Bill Janssen934b16d2008-06-28 22:19:33 +0000151
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000152 .. versionchanged:: 2.7
153 New optional argument *ciphers*.
154
Bill Janssen98d19da2007-09-10 21:51:02 +0000155.. function:: RAND_status()
156
Georg Brandla50d20a2009-09-16 15:57:46 +0000157 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.
Bill Janssen98d19da2007-09-10 21:51:02 +0000161
162.. function:: RAND_egd(path)
163
164 If you are running an entropy-gathering daemon (EGD) somewhere, and ``path``
Georg Brandla50d20a2009-09-16 15:57:46 +0000165 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.
Bill Janssen98d19da2007-09-10 21:51:02 +0000169
Georg Brandla50d20a2009-09-16 15:57:46 +0000170 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
171 of entropy-gathering daemons.
Bill Janssen98d19da2007-09-10 21:51:02 +0000172
173.. function:: RAND_add(bytes, entropy)
174
Georg Brandla50d20a2009-09-16 15:57:46 +0000175 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.
Bill Janssen98d19da2007-09-10 21:51:02 +0000179
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000180.. function:: cert_time_to_seconds(timestring)
181
Georg Brandla50d20a2009-09-16 15:57:46 +0000182 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.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000185
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'
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000194 >>>
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000195
Bill Janssen296a59d2007-09-16 22:06:00 +0000196.. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
197
Georg Brandla50d20a2009-09-16 15:57:46 +0000198 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
Bill Janssen296a59d2007-09-16 22:06:00 +0000205 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
Georg Brandla50d20a2009-09-16 15:57:46 +0000214 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
215 bytes for that same certificate.
Bill Janssen296a59d2007-09-16 22:06:00 +0000216
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000217.. data:: CERT_NONE
218
Georg Brandla50d20a2009-09-16 15:57:46 +0000219 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.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000222
223.. data:: CERT_OPTIONAL
224
Georg Brandla50d20a2009-09-16 15:57:46 +0000225 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.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000230
231.. data:: CERT_REQUIRED
232
Georg Brandla50d20a2009-09-16 15:57:46 +0000233 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.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000237
238.. data:: PROTOCOL_SSLv2
239
240 Selects SSL version 2 as the channel encryption protocol.
241
Victor Stinnerb1241f92011-05-10 01:52:03 +0200242 This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
243 flag.
244
Antoine Pitrou308c2af2010-05-16 14:16:56 +0000245 .. warning::
246
247 SSL version 2 is insecure. Its use is highly discouraged.
248
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000249.. data:: PROTOCOL_SSLv23
250
Georg Brandla50d20a2009-09-16 15:57:46 +0000251 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.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000255
256.. data:: PROTOCOL_SSLv3
257
Georg Brandla50d20a2009-09-16 15:57:46 +0000258 Selects SSL version 3 as the channel encryption protocol. For clients, this
259 is the maximally compatible SSL variant.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000260
261.. data:: PROTOCOL_TLSv1
262
Georg Brandla50d20a2009-09-16 15:57:46 +0000263 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.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000266
Antoine Pitrouf9de5342010-04-05 21:35:07 +0000267.. data:: OPENSSL_VERSION
268
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
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000297
Bill Janssen98d19da2007-09-10 21:51:02 +0000298SSLSocket Objects
299-----------------
300
301.. method:: SSLSocket.read([nbytes=1024])
302
303 Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them.
304
305.. method:: SSLSocket.write(data)
306
Georg Brandla50d20a2009-09-16 15:57:46 +0000307 Writes the ``data`` to the other side of the connection, using the SSL
308 channel to encrypt. Returns the number of bytes written.
Bill Janssen98d19da2007-09-10 21:51:02 +0000309
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000310.. method:: SSLSocket.getpeercert(binary_form=False)
Bill Janssen98d19da2007-09-10 21:51:02 +0000311
Georg Brandla50d20a2009-09-16 15:57:46 +0000312 If there is no certificate for the peer on the other end of the connection,
313 returns ``None``.
Bill Janssen98d19da2007-09-10 21:51:02 +0000314
Georg Brandla50d20a2009-09-16 15:57:46 +0000315 If the parameter ``binary_form`` is :const:`False`, and a certificate was
316 received from the peer, this method returns a :class:`dict` instance. If the
317 certificate was not validated, the dict is empty. If the certificate was
318 validated, it returns a dict with the keys ``subject`` (the principal for
319 which the certificate was issued), and ``notAfter`` (the time after which the
320 certificate should not be trusted). The certificate was already validated,
321 so the ``notBefore`` and ``issuer`` fields are not returned. If a
322 certificate contains an instance of the *Subject Alternative Name* extension
323 (see :rfc:`3280`), there will also be a ``subjectAltName`` key in the
324 dictionary.
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000325
326 The "subject" field is a tuple containing the sequence of relative
Georg Brandla50d20a2009-09-16 15:57:46 +0000327 distinguished names (RDNs) given in the certificate's data structure for the
328 principal, and each RDN is a sequence of name-value pairs::
Bill Janssen98d19da2007-09-10 21:51:02 +0000329
330 {'notAfter': 'Feb 16 16:54:50 2013 GMT',
331 'subject': ((('countryName', u'US'),),
332 (('stateOrProvinceName', u'Delaware'),),
333 (('localityName', u'Wilmington'),),
334 (('organizationName', u'Python Software Foundation'),),
335 (('organizationalUnitName', u'SSL'),),
336 (('commonName', u'somemachine.python.org'),))}
337
Georg Brandla50d20a2009-09-16 15:57:46 +0000338 If the ``binary_form`` parameter is :const:`True`, and a certificate was
339 provided, this method returns the DER-encoded form of the entire certificate
340 as a sequence of bytes, or :const:`None` if the peer did not provide a
341 certificate. This return value is independent of validation; if validation
342 was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
Bill Janssen296a59d2007-09-16 22:06:00 +0000343 been validated, but if :const:`CERT_NONE` was used to establish the
344 connection, the certificate, if present, will not have been validated.
Bill Janssen98d19da2007-09-10 21:51:02 +0000345
346.. method:: SSLSocket.cipher()
347
Georg Brandla50d20a2009-09-16 15:57:46 +0000348 Returns a three-value tuple containing the name of the cipher being used, the
349 version of the SSL protocol that defines its use, and the number of secret
350 bits being used. If no connection has been established, returns ``None``.
Bill Janssen98d19da2007-09-10 21:51:02 +0000351
Bill Janssen934b16d2008-06-28 22:19:33 +0000352.. method:: SSLSocket.do_handshake()
353
Georg Brandla50d20a2009-09-16 15:57:46 +0000354 Perform a TLS/SSL handshake. If this is used with a non-blocking socket, it
355 may raise :exc:`SSLError` with an ``arg[0]`` of :const:`SSL_ERROR_WANT_READ`
356 or :const:`SSL_ERROR_WANT_WRITE`, in which case it must be called again until
357 it completes successfully. For example, to simulate the behavior of a
358 blocking socket, one might write::
Bill Janssen934b16d2008-06-28 22:19:33 +0000359
360 while True:
361 try:
362 s.do_handshake()
363 break
364 except ssl.SSLError, err:
365 if err.args[0] == ssl.SSL_ERROR_WANT_READ:
366 select.select([s], [], [])
367 elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
368 select.select([], [s], [])
369 else:
370 raise
Bill Janssen98d19da2007-09-10 21:51:02 +0000371
Bill Janssen5bfbd762008-08-12 17:09:57 +0000372.. method:: SSLSocket.unwrap()
373
Georg Brandla50d20a2009-09-16 15:57:46 +0000374 Performs the SSL shutdown handshake, which removes the TLS layer from the
375 underlying socket, and returns the underlying socket object. This can be
376 used to go from encrypted operation over a connection to unencrypted. The
377 socket instance returned should always be used for further communication with
378 the other side of the connection, rather than the original socket instance
379 (which may not function properly after the unwrap).
Bill Janssen5bfbd762008-08-12 17:09:57 +0000380
Bill Janssen98d19da2007-09-10 21:51:02 +0000381.. index:: single: certificates
382
383.. index:: single: X509 certificate
384
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000385.. _ssl-certificates:
386
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000387Certificates
388------------
389
Georg Brandla50d20a2009-09-16 15:57:46 +0000390Certificates in general are part of a public-key / private-key system. In this
391system, each *principal*, (which may be a machine, or a person, or an
392organization) is assigned a unique two-part encryption key. One part of the key
393is public, and is called the *public key*; the other part is kept secret, and is
394called the *private key*. The two parts are related, in that if you encrypt a
395message with one of the parts, you can decrypt it with the other part, and
396**only** with the other part.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000397
Georg Brandla50d20a2009-09-16 15:57:46 +0000398A certificate contains information about two principals. It contains the name
399of a *subject*, and the subject's public key. It also contains a statement by a
400second principal, the *issuer*, that the subject is who he claims to be, and
401that this is indeed the subject's public key. The issuer's statement is signed
402with the issuer's private key, which only the issuer knows. However, anyone can
403verify the issuer's statement by finding the issuer's public key, decrypting the
404statement with it, and comparing it to the other information in the certificate.
405The certificate also contains information about the time period over which it is
406valid. This is expressed as two fields, called "notBefore" and "notAfter".
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000407
Georg Brandla50d20a2009-09-16 15:57:46 +0000408In the Python use of certificates, a client or server can use a certificate to
409prove who they are. The other side of a network connection can also be required
410to produce a certificate, and that certificate can be validated to the
411satisfaction of the client or server that requires such validation. The
412connection attempt can be set to raise an exception if the validation fails.
413Validation is done automatically, by the underlying OpenSSL framework; the
414application need not concern itself with its mechanics. But the application
415does usually need to provide sets of certificates to allow this process to take
416place.
Bill Janssen426ea0a2007-08-29 22:35:05 +0000417
Georg Brandla50d20a2009-09-16 15:57:46 +0000418Python uses files to contain certificates. They should be formatted as "PEM"
419(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
420and a footer line::
Bill Janssen426ea0a2007-08-29 22:35:05 +0000421
422 -----BEGIN CERTIFICATE-----
423 ... (certificate in base64 PEM encoding) ...
424 -----END CERTIFICATE-----
425
Georg Brandla50d20a2009-09-16 15:57:46 +0000426The Python files which contain certificates can contain a sequence of
427certificates, sometimes called a *certificate chain*. This chain should start
428with the specific certificate for the principal who "is" the client or server,
429and then the certificate for the issuer of that certificate, and then the
430certificate for the issuer of *that* certificate, and so on up the chain till
431you get to a certificate which is *self-signed*, that is, a certificate which
432has the same subject and issuer, sometimes called a *root certificate*. The
433certificates should just be concatenated together in the certificate file. For
434example, suppose we had a three certificate chain, from our server certificate
435to the certificate of the certification authority that signed our server
436certificate, to the root certificate of the agency which issued the
437certification authority's certificate::
Bill Janssen426ea0a2007-08-29 22:35:05 +0000438
439 -----BEGIN CERTIFICATE-----
440 ... (certificate for your server)...
441 -----END CERTIFICATE-----
442 -----BEGIN CERTIFICATE-----
443 ... (the certificate for the CA)...
444 -----END CERTIFICATE-----
445 -----BEGIN CERTIFICATE-----
446 ... (the root certificate for the CA's issuer)...
447 -----END CERTIFICATE-----
448
449If you are going to require validation of the other side of the connection's
450certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandla50d20a2009-09-16 15:57:46 +0000451chains for each issuer you are willing to trust. Again, this file just contains
452these chains concatenated together. For validation, Python will use the first
453chain it finds in the file which matches.
Bill Janssen934b16d2008-06-28 22:19:33 +0000454
Bill Janssen98d19da2007-09-10 21:51:02 +0000455Some "standard" root certificates are available from various certification
Georg Brandla50d20a2009-09-16 15:57:46 +0000456authorities: `CACert.org <http://www.cacert.org/index.php?id=3>`_, `Thawte
457<http://www.thawte.com/roots/>`_, `Verisign
458<http://www.verisign.com/support/roots.html>`_, `Positive SSL
459<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
460(used by python.org), `Equifax and GeoTrust
461<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Bill Janssen98d19da2007-09-10 21:51:02 +0000462
Georg Brandla50d20a2009-09-16 15:57:46 +0000463In general, if you are using SSL3 or TLS1, you don't need to put the full chain
464in your "CA certs" file; you only need the root certificates, and the remote
465peer is supposed to furnish the other certificates necessary to chain from its
466certificate to a root certificate. See :rfc:`4158` for more discussion of the
467way in which certification chains can be built.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000468
Georg Brandla50d20a2009-09-16 15:57:46 +0000469If you are going to create a server that provides SSL-encrypted connection
470services, you will need to acquire a certificate for that service. There are
471many ways of acquiring appropriate certificates, such as buying one from a
472certification authority. Another common practice is to generate a self-signed
473certificate. The simplest way to do this is with the OpenSSL package, using
474something like the following::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000475
Bill Janssen98d19da2007-09-10 21:51:02 +0000476 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
477 Generating a 1024 bit RSA private key
478 .......++++++
479 .............................++++++
480 writing new private key to 'cert.pem'
481 -----
482 You are about to be asked to enter information that will be incorporated
483 into your certificate request.
484 What you are about to enter is what is called a Distinguished Name or a DN.
485 There are quite a few fields but you can leave some blank
486 For some fields there will be a default value,
487 If you enter '.', the field will be left blank.
488 -----
489 Country Name (2 letter code) [AU]:US
490 State or Province Name (full name) [Some-State]:MyState
491 Locality Name (eg, city) []:Some City
492 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
493 Organizational Unit Name (eg, section) []:My Group
494 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
495 Email Address []:ops@myserver.mygroup.myorganization.com
496 %
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000497
Georg Brandla50d20a2009-09-16 15:57:46 +0000498The disadvantage of a self-signed certificate is that it is its own root
499certificate, and no one else will have it in their cache of known (and trusted)
500root certificates.
Bill Janssen426ea0a2007-08-29 22:35:05 +0000501
502
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000503Examples
504--------
505
Bill Janssen426ea0a2007-08-29 22:35:05 +0000506Testing for SSL support
507^^^^^^^^^^^^^^^^^^^^^^^
508
Georg Brandla50d20a2009-09-16 15:57:46 +0000509To test for the presence of SSL support in a Python installation, user code
510should use the following idiom::
Bill Janssen426ea0a2007-08-29 22:35:05 +0000511
512 try:
Georg Brandl28046022011-02-25 11:01:04 +0000513 import ssl
Bill Janssen426ea0a2007-08-29 22:35:05 +0000514 except ImportError:
Georg Brandl28046022011-02-25 11:01:04 +0000515 pass
Bill Janssen426ea0a2007-08-29 22:35:05 +0000516 else:
Georg Brandl28046022011-02-25 11:01:04 +0000517 ... # do something that requires SSL support
Bill Janssen426ea0a2007-08-29 22:35:05 +0000518
519Client-side operation
520^^^^^^^^^^^^^^^^^^^^^
521
Georg Brandla50d20a2009-09-16 15:57:46 +0000522This example connects to an SSL server, prints the server's address and
523certificate, sends some bytes, and reads part of the response::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000524
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000525 import socket, ssl, pprint
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000526
527 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Bill Janssen98d19da2007-09-10 21:51:02 +0000528
529 # require a certificate from the server
530 ssl_sock = ssl.wrap_socket(s,
531 ca_certs="/etc/ca_certs_file",
532 cert_reqs=ssl.CERT_REQUIRED)
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000533
534 ssl_sock.connect(('www.verisign.com', 443))
535
536 print repr(ssl_sock.getpeername())
Bill Janssen98d19da2007-09-10 21:51:02 +0000537 print ssl_sock.cipher()
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000538 print pprint.pformat(ssl_sock.getpeercert())
539
540 # Set a simple HTTP request -- use httplib in actual code.
541 ssl_sock.write("""GET / HTTP/1.0\r
542 Host: www.verisign.com\r\n\r\n""")
543
544 # Read a chunk of data. Will not necessarily
545 # read all the data returned by the server.
546 data = ssl_sock.read()
547
Bill Janssen98d19da2007-09-10 21:51:02 +0000548 # note that closing the SSLSocket will also close the underlying socket
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000549 ssl_sock.close()
550
Georg Brandla50d20a2009-09-16 15:57:46 +0000551As of September 6, 2007, the certificate printed by this program looked like
552this::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000553
Bill Janssen98d19da2007-09-10 21:51:02 +0000554 {'notAfter': 'May 8 23:59:59 2009 GMT',
555 'subject': ((('serialNumber', u'2497886'),),
556 (('1.3.6.1.4.1.311.60.2.1.3', u'US'),),
557 (('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),),
558 (('countryName', u'US'),),
559 (('postalCode', u'94043'),),
560 (('stateOrProvinceName', u'California'),),
561 (('localityName', u'Mountain View'),),
562 (('streetAddress', u'487 East Middlefield Road'),),
563 (('organizationName', u'VeriSign, Inc.'),),
564 (('organizationalUnitName',
565 u'Production Security Services'),),
566 (('organizationalUnitName',
567 u'Terms of use at www.verisign.com/rpa (c)06'),),
568 (('commonName', u'www.verisign.com'),))}
569
570which is a fairly poorly-formed ``subject`` field.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000571
Bill Janssen426ea0a2007-08-29 22:35:05 +0000572Server-side operation
573^^^^^^^^^^^^^^^^^^^^^
574
Georg Brandla50d20a2009-09-16 15:57:46 +0000575For server operation, typically you'd need to have a server certificate, and
576private key, each in a file. You'd open a socket, bind it to a port, call
577:meth:`listen` on it, then start waiting for clients to connect::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000578
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000579 import socket, ssl
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000580
581 bindsocket = socket.socket()
582 bindsocket.bind(('myaddr.mydomain.com', 10023))
583 bindsocket.listen(5)
584
Georg Brandla50d20a2009-09-16 15:57:46 +0000585When one did, you'd call :meth:`accept` on the socket to get the new socket from
586the other end, and use :func:`wrap_socket` to create a server-side SSL context
587for it::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000588
589 while True:
Antoine Pitrou9e7d6e52011-01-02 22:39:10 +0000590 newsocket, fromaddr = bindsocket.accept()
591 connstream = ssl.wrap_socket(newsocket,
592 server_side=True,
593 certfile="mycertfile",
594 keyfile="mykeyfile",
595 ssl_version=ssl.PROTOCOL_TLSv1)
596 try:
597 deal_with_client(connstream)
598 finally:
599 connstream.shutdown(socket.SHUT_RDWR)
600 connstream.close()
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000601
Georg Brandla50d20a2009-09-16 15:57:46 +0000602Then you'd read data from the ``connstream`` and do something with it till you
603are finished with the client (or the client is finished with you)::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000604
605 def deal_with_client(connstream):
Georg Brandl28046022011-02-25 11:01:04 +0000606 data = connstream.read()
607 # null data means the client is finished with us
608 while data:
609 if not do_something(connstream, data):
610 # we'll assume do_something returns False
611 # when we're finished with client
612 break
613 data = connstream.read()
614 # finished with client
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000615
616And go back to listening for new client connections.
617
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000618
Bill Janssen98d19da2007-09-10 21:51:02 +0000619.. seealso::
Bill Janssen426ea0a2007-08-29 22:35:05 +0000620
Bill Janssen98d19da2007-09-10 21:51:02 +0000621 Class :class:`socket.socket`
622 Documentation of underlying :mod:`socket` class
Bill Janssen426ea0a2007-08-29 22:35:05 +0000623
Antoine Pitrou5472c1c2011-10-07 17:03:01 +0200624 `TLS (Transport Layer Security) and SSL (Secure Socket Layer) <http://www3.rad.com/networks/applications/secure/tls.htm>`_
625 Debby Koren
Bill Janssen426ea0a2007-08-29 22:35:05 +0000626
Bill Janssen98d19da2007-09-10 21:51:02 +0000627 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
628 Steve Kent
Bill Janssen426ea0a2007-08-29 22:35:05 +0000629
Bill Janssen98d19da2007-09-10 21:51:02 +0000630 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
631 D. Eastlake et. al.
Bill Janssenffe576d2007-09-05 00:46:27 +0000632
Bill Janssen98d19da2007-09-10 21:51:02 +0000633 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
634 Housley et. al.