blob: f4cac3a14a5f6b457eaf901fcb5a1e7eb16cf661 [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>
Guido van Rossum8ee23bb2007-08-27 19:11:11 +00008
9.. versionadded:: 2.6
10
Bill Janssen426ea0a2007-08-29 22:35:05 +000011.. sectionauthor:: Bill Janssen <bill.janssen@gmail.com>
12
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000013
Bill Janssen98d19da2007-09-10 21:51:02 +000014.. index:: single: OpenSSL; (use in module ssl)
15
16.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
17
Georg Brandla50d20a2009-09-16 15:57:46 +000018This module provides access to Transport Layer Security (often known as "Secure
19Sockets Layer") encryption and peer authentication facilities for network
20sockets, both client-side and server-side. This module uses the OpenSSL
21library. It is available on all modern Unix systems, Windows, Mac OS X, and
22probably additional platforms, as long as OpenSSL is installed on that platform.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000023
24.. note::
25
Georg Brandla50d20a2009-09-16 15:57:46 +000026 Some behavior may be platform dependent, since calls are made to the
27 operating system socket APIs. The installed version of OpenSSL may also
28 cause variations in behavior.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000029
Georg Brandla50d20a2009-09-16 15:57:46 +000030This section documents the objects and functions in the ``ssl`` module; for more
31general information about TLS, SSL, and certificates, the reader is referred to
32the documents in the "See Also" section at the bottom.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000033
Georg Brandla50d20a2009-09-16 15:57:46 +000034This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
35:class:`socket.socket` type, and provides a socket-like wrapper that also
36encrypts and decrypts the data going over the socket with SSL. It supports
37additional :meth:`read` and :meth:`write` methods, along with a method,
38:meth:`getpeercert`, to retrieve the certificate of the other side of the
39connection, and a method, :meth:`cipher`, to retrieve the cipher being used for
40the secure connection.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000041
Bill Janssen93bf9ce2007-09-11 02:42:07 +000042Functions, Constants, and Exceptions
43------------------------------------
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000044
Bill Janssen93bf9ce2007-09-11 02:42:07 +000045.. exception:: SSLError
46
Georg Brandlc62ef8b2009-01-03 20:55:06 +000047 Raised to signal an error from the underlying SSL implementation. This
Georg Brandla50d20a2009-09-16 15:57:46 +000048 signifies some problem in the higher-level encryption and authentication
49 layer that's superimposed on the underlying network connection. This error
50 is a subtype of :exc:`socket.error`, which in turn is a subtype of
51 :exc:`IOError`.
Bill Janssen93bf9ce2007-09-11 02:42:07 +000052
Antoine Pitrou0a6373c2010-04-17 17:10:38 +000053.. 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 +000054
Georg Brandla50d20a2009-09-16 15:57:46 +000055 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
56 of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
57 the underlying socket in an SSL context. For client-side sockets, the
58 context construction is lazy; if the underlying socket isn't connected yet,
59 the context construction will be performed after :meth:`connect` is called on
60 the socket. For server-side sockets, if the socket has no remote peer, it is
61 assumed to be a listening socket, and the server-side SSL wrapping is
62 automatically performed on client connections accepted via the :meth:`accept`
63 method. :func:`wrap_socket` may raise :exc:`SSLError`.
Bill Janssen98d19da2007-09-10 21:51:02 +000064
Georg Brandla50d20a2009-09-16 15:57:46 +000065 The ``keyfile`` and ``certfile`` parameters specify optional files which
66 contain a certificate to be used to identify the local side of the
67 connection. See the discussion of :ref:`ssl-certificates` for more
68 information on how the certificate is stored in the ``certfile``.
Bill Janssen98d19da2007-09-10 21:51:02 +000069
Georg Brandla50d20a2009-09-16 15:57:46 +000070 Often the private key is stored in the same file as the certificate; in this
71 case, only the ``certfile`` parameter need be passed. If the private key is
72 stored in a separate file, both parameters must be used. If the private key
73 is stored in the ``certfile``, it should come before the first certificate in
74 the certificate chain::
Bill Janssen98d19da2007-09-10 21:51:02 +000075
76 -----BEGIN RSA PRIVATE KEY-----
77 ... (private key in base64 encoding) ...
78 -----END RSA PRIVATE KEY-----
79 -----BEGIN CERTIFICATE-----
80 ... (certificate in base64 PEM encoding) ...
81 -----END CERTIFICATE-----
82
Georg Brandla50d20a2009-09-16 15:57:46 +000083 The parameter ``server_side`` is a boolean which identifies whether
84 server-side or client-side behavior is desired from this socket.
Bill Janssen98d19da2007-09-10 21:51:02 +000085
Georg Brandla50d20a2009-09-16 15:57:46 +000086 The parameter ``cert_reqs`` specifies whether a certificate is required from
87 the other side of the connection, and whether it will be validated if
88 provided. It must be one of the three values :const:`CERT_NONE`
89 (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
90 if provided), or :const:`CERT_REQUIRED` (required and validated). If the
91 value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
92 parameter must point to a file of CA certificates.
Bill Janssen98d19da2007-09-10 21:51:02 +000093
Georg Brandla50d20a2009-09-16 15:57:46 +000094 The ``ca_certs`` file contains a set of concatenated "certification
95 authority" certificates, which are used to validate certificates passed from
96 the other end of the connection. See the discussion of
97 :ref:`ssl-certificates` for more information about how to arrange the
98 certificates in this file.
Bill Janssen98d19da2007-09-10 21:51:02 +000099
Georg Brandla50d20a2009-09-16 15:57:46 +0000100 The parameter ``ssl_version`` specifies which version of the SSL protocol to
101 use. Typically, the server chooses a particular protocol version, and the
102 client must adapt to the server's choice. Most of the versions are not
103 interoperable with the other versions. If not specified, for client-side
104 operation, the default SSL version is SSLv3; for server-side operation,
105 SSLv23. These version selections provide the most compatibility with other
106 versions.
Bill Janssen98d19da2007-09-10 21:51:02 +0000107
Georg Brandla50d20a2009-09-16 15:57:46 +0000108 Here's a table showing which versions in a client (down the side) can connect
109 to which versions in a server (along the top):
Bill Janssen98d19da2007-09-10 21:51:02 +0000110
111 .. table::
112
113 ======================== ========= ========= ========== =========
114 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1**
Georg Brandl2b92f6b2007-12-06 01:52:24 +0000115 ------------------------ --------- --------- ---------- ---------
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000116 *SSLv2* yes no yes no
Bill Janssen98d19da2007-09-10 21:51:02 +0000117 *SSLv3* yes yes yes no
118 *SSLv23* yes no yes no
119 *TLSv1* no no yes yes
120 ======================== ========= ========= ========== =========
121
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000122 .. note::
123
Andrew M. Kuchling3ded4212010-04-30 00:52:31 +0000124 Which connections succeed will vary depending on the version of
125 OpenSSL. For instance, in some older versions of OpenSSL (such
126 as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an
127 SSLv23 server. Another example: beginning with OpenSSL 1.0.0,
128 an SSLv23 client will not actually attempt SSLv2 connections
129 unless you explicitly enable SSLv2 ciphers; for example, you
130 might specify ``"ALL"`` or ``"SSLv2"`` as the *ciphers* parameter
131 to enable them.
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000132
Andrew M. Kuchling3ded4212010-04-30 00:52:31 +0000133 The *ciphers* parameter sets the available ciphers for this SSL object.
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000134 It should be a string in the `OpenSSL cipher list format
135 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
Bill Janssen98d19da2007-09-10 21:51:02 +0000136
Bill Janssen934b16d2008-06-28 22:19:33 +0000137 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
138 handshake automatically after doing a :meth:`socket.connect`, or whether the
Georg Brandla50d20a2009-09-16 15:57:46 +0000139 application program will call it explicitly, by invoking the
140 :meth:`SSLSocket.do_handshake` method. Calling
141 :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
142 blocking behavior of the socket I/O involved in the handshake.
Bill Janssen934b16d2008-06-28 22:19:33 +0000143
Georg Brandla50d20a2009-09-16 15:57:46 +0000144 The parameter ``suppress_ragged_eofs`` specifies how the
145 :meth:`SSLSocket.read` method should signal unexpected EOF from the other end
146 of the connection. If specified as :const:`True` (the default), it returns a
147 normal EOF in response to unexpected EOF errors raised from the underlying
148 socket; if :const:`False`, it will raise the exceptions back to the caller.
Bill Janssen934b16d2008-06-28 22:19:33 +0000149
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000150 .. versionchanged:: 2.7
151 New optional argument *ciphers*.
152
Bill Janssen98d19da2007-09-10 21:51:02 +0000153.. function:: RAND_status()
154
Georg Brandla50d20a2009-09-16 15:57:46 +0000155 Returns True if the SSL pseudo-random number generator has been seeded with
156 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
157 and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
158 number generator.
Bill Janssen98d19da2007-09-10 21:51:02 +0000159
160.. function:: RAND_egd(path)
161
162 If you are running an entropy-gathering daemon (EGD) somewhere, and ``path``
Georg Brandla50d20a2009-09-16 15:57:46 +0000163 is the pathname of a socket connection open to it, this will read 256 bytes
164 of randomness from the socket, and add it to the SSL pseudo-random number
165 generator to increase the security of generated secret keys. This is
166 typically only necessary on systems without better sources of randomness.
Bill Janssen98d19da2007-09-10 21:51:02 +0000167
Georg Brandla50d20a2009-09-16 15:57:46 +0000168 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
169 of entropy-gathering daemons.
Bill Janssen98d19da2007-09-10 21:51:02 +0000170
171.. function:: RAND_add(bytes, entropy)
172
Georg Brandla50d20a2009-09-16 15:57:46 +0000173 Mixes the given ``bytes`` into the SSL pseudo-random number generator. The
174 parameter ``entropy`` (a float) is a lower bound on the entropy contained in
175 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
176 information on sources of entropy.
Bill Janssen98d19da2007-09-10 21:51:02 +0000177
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000178.. function:: cert_time_to_seconds(timestring)
179
Georg Brandla50d20a2009-09-16 15:57:46 +0000180 Returns a floating-point value containing a normal seconds-after-the-epoch
181 time value, given the time-string representing the "notBefore" or "notAfter"
182 date from a certificate.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000183
184 Here's an example::
185
186 >>> import ssl
187 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
188 1178694000.0
189 >>> import time
190 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
191 'Wed May 9 00:00:00 2007'
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000192 >>>
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000193
Bill Janssen296a59d2007-09-16 22:06:00 +0000194.. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
195
Georg Brandla50d20a2009-09-16 15:57:46 +0000196 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
197 *port-number*) pair, fetches the server's certificate, and returns it as a
198 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
199 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
200 specified, it should be a file containing a list of root certificates, the
201 same format as used for the same parameter in :func:`wrap_socket`. The call
202 will attempt to validate the server certificate against that set of root
Bill Janssen296a59d2007-09-16 22:06:00 +0000203 certificates, and will fail if the validation attempt fails.
204
205.. function:: DER_cert_to_PEM_cert (DER_cert_bytes)
206
207 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
208 string version of the same certificate.
209
210.. function:: PEM_cert_to_DER_cert (PEM_cert_string)
211
Georg Brandla50d20a2009-09-16 15:57:46 +0000212 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
213 bytes for that same certificate.
Bill Janssen296a59d2007-09-16 22:06:00 +0000214
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000215.. data:: CERT_NONE
216
Georg Brandla50d20a2009-09-16 15:57:46 +0000217 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
218 certificates will be required or validated from the other side of the socket
219 connection.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000220
221.. data:: CERT_OPTIONAL
222
Georg Brandla50d20a2009-09-16 15:57:46 +0000223 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
224 certificates will be required from the other side of the socket connection,
225 but if they are provided, will be validated. Note that use of this setting
226 requires a valid certificate validation file also be passed as a value of the
227 ``ca_certs`` parameter.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000228
229.. data:: CERT_REQUIRED
230
Georg Brandla50d20a2009-09-16 15:57:46 +0000231 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when
232 certificates will be required from the other side of the socket connection.
233 Note that use of this setting requires a valid certificate validation file
234 also be passed as a value of the ``ca_certs`` parameter.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000235
236.. data:: PROTOCOL_SSLv2
237
238 Selects SSL version 2 as the channel encryption protocol.
239
Victor Stinnerb1241f92011-05-10 01:52:03 +0200240 This protocol is not available if OpenSSL is compiled with OPENSSL_NO_SSL2
241 flag.
242
Antoine Pitrou308c2af2010-05-16 14:16:56 +0000243 .. warning::
244
245 SSL version 2 is insecure. Its use is highly discouraged.
246
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000247.. data:: PROTOCOL_SSLv23
248
Georg Brandla50d20a2009-09-16 15:57:46 +0000249 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
250 setting to use with servers for maximum compatibility with the other end of
251 an SSL connection, but it may cause the specific ciphers chosen for the
252 encryption to be of fairly low quality.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000253
254.. data:: PROTOCOL_SSLv3
255
Georg Brandla50d20a2009-09-16 15:57:46 +0000256 Selects SSL version 3 as the channel encryption protocol. For clients, this
257 is the maximally compatible SSL variant.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000258
259.. data:: PROTOCOL_TLSv1
260
Georg Brandla50d20a2009-09-16 15:57:46 +0000261 Selects TLS version 1 as the channel encryption protocol. This is the most
262 modern version, and probably the best choice for maximum protection, if both
263 sides can speak it.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000264
Antoine Pitrouf9de5342010-04-05 21:35:07 +0000265.. data:: OPENSSL_VERSION
266
267 The version string of the OpenSSL library loaded by the interpreter::
268
269 >>> ssl.OPENSSL_VERSION
270 'OpenSSL 0.9.8k 25 Mar 2009'
271
272 .. versionadded:: 2.7
273
274.. data:: OPENSSL_VERSION_INFO
275
276 A tuple of five integers representing version information about the
277 OpenSSL library::
278
279 >>> ssl.OPENSSL_VERSION_INFO
280 (0, 9, 8, 11, 15)
281
282 .. versionadded:: 2.7
283
284.. data:: OPENSSL_VERSION_NUMBER
285
286 The raw version number of the OpenSSL library, as a single integer::
287
288 >>> ssl.OPENSSL_VERSION_NUMBER
289 9470143L
290 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
291 '0x9080bfL'
292
293 .. versionadded:: 2.7
294
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000295
Bill Janssen98d19da2007-09-10 21:51:02 +0000296SSLSocket Objects
297-----------------
298
299.. method:: SSLSocket.read([nbytes=1024])
300
301 Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them.
302
303.. method:: SSLSocket.write(data)
304
Georg Brandla50d20a2009-09-16 15:57:46 +0000305 Writes the ``data`` to the other side of the connection, using the SSL
306 channel to encrypt. Returns the number of bytes written.
Bill Janssen98d19da2007-09-10 21:51:02 +0000307
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000308.. method:: SSLSocket.getpeercert(binary_form=False)
Bill Janssen98d19da2007-09-10 21:51:02 +0000309
Georg Brandla50d20a2009-09-16 15:57:46 +0000310 If there is no certificate for the peer on the other end of the connection,
311 returns ``None``.
Bill Janssen98d19da2007-09-10 21:51:02 +0000312
Georg Brandla50d20a2009-09-16 15:57:46 +0000313 If the parameter ``binary_form`` is :const:`False`, and a certificate was
314 received from the peer, this method returns a :class:`dict` instance. If the
315 certificate was not validated, the dict is empty. If the certificate was
316 validated, it returns a dict with the keys ``subject`` (the principal for
317 which the certificate was issued), and ``notAfter`` (the time after which the
318 certificate should not be trusted). The certificate was already validated,
319 so the ``notBefore`` and ``issuer`` fields are not returned. If a
320 certificate contains an instance of the *Subject Alternative Name* extension
321 (see :rfc:`3280`), there will also be a ``subjectAltName`` key in the
322 dictionary.
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000323
324 The "subject" field is a tuple containing the sequence of relative
Georg Brandla50d20a2009-09-16 15:57:46 +0000325 distinguished names (RDNs) given in the certificate's data structure for the
326 principal, and each RDN is a sequence of name-value pairs::
Bill Janssen98d19da2007-09-10 21:51:02 +0000327
328 {'notAfter': 'Feb 16 16:54:50 2013 GMT',
329 'subject': ((('countryName', u'US'),),
330 (('stateOrProvinceName', u'Delaware'),),
331 (('localityName', u'Wilmington'),),
332 (('organizationName', u'Python Software Foundation'),),
333 (('organizationalUnitName', u'SSL'),),
334 (('commonName', u'somemachine.python.org'),))}
335
Georg Brandla50d20a2009-09-16 15:57:46 +0000336 If the ``binary_form`` parameter is :const:`True`, and a certificate was
337 provided, this method returns the DER-encoded form of the entire certificate
338 as a sequence of bytes, or :const:`None` if the peer did not provide a
339 certificate. This return value is independent of validation; if validation
340 was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
Bill Janssen296a59d2007-09-16 22:06:00 +0000341 been validated, but if :const:`CERT_NONE` was used to establish the
342 connection, the certificate, if present, will not have been validated.
Bill Janssen98d19da2007-09-10 21:51:02 +0000343
344.. method:: SSLSocket.cipher()
345
Georg Brandla50d20a2009-09-16 15:57:46 +0000346 Returns a three-value tuple containing the name of the cipher being used, the
347 version of the SSL protocol that defines its use, and the number of secret
348 bits being used. If no connection has been established, returns ``None``.
Bill Janssen98d19da2007-09-10 21:51:02 +0000349
Bill Janssen934b16d2008-06-28 22:19:33 +0000350.. method:: SSLSocket.do_handshake()
351
Georg Brandla50d20a2009-09-16 15:57:46 +0000352 Perform a TLS/SSL handshake. If this is used with a non-blocking socket, it
353 may raise :exc:`SSLError` with an ``arg[0]`` of :const:`SSL_ERROR_WANT_READ`
354 or :const:`SSL_ERROR_WANT_WRITE`, in which case it must be called again until
355 it completes successfully. For example, to simulate the behavior of a
356 blocking socket, one might write::
Bill Janssen934b16d2008-06-28 22:19:33 +0000357
358 while True:
359 try:
360 s.do_handshake()
361 break
362 except ssl.SSLError, err:
363 if err.args[0] == ssl.SSL_ERROR_WANT_READ:
364 select.select([s], [], [])
365 elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
366 select.select([], [s], [])
367 else:
368 raise
Bill Janssen98d19da2007-09-10 21:51:02 +0000369
Bill Janssen5bfbd762008-08-12 17:09:57 +0000370.. method:: SSLSocket.unwrap()
371
Georg Brandla50d20a2009-09-16 15:57:46 +0000372 Performs the SSL shutdown handshake, which removes the TLS layer from the
373 underlying socket, and returns the underlying socket object. This can be
374 used to go from encrypted operation over a connection to unencrypted. The
375 socket instance returned should always be used for further communication with
376 the other side of the connection, rather than the original socket instance
377 (which may not function properly after the unwrap).
Bill Janssen5bfbd762008-08-12 17:09:57 +0000378
Bill Janssen98d19da2007-09-10 21:51:02 +0000379.. index:: single: certificates
380
381.. index:: single: X509 certificate
382
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000383.. _ssl-certificates:
384
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000385Certificates
386------------
387
Georg Brandla50d20a2009-09-16 15:57:46 +0000388Certificates in general are part of a public-key / private-key system. In this
389system, each *principal*, (which may be a machine, or a person, or an
390organization) is assigned a unique two-part encryption key. One part of the key
391is public, and is called the *public key*; the other part is kept secret, and is
392called the *private key*. The two parts are related, in that if you encrypt a
393message with one of the parts, you can decrypt it with the other part, and
394**only** with the other part.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000395
Georg Brandla50d20a2009-09-16 15:57:46 +0000396A certificate contains information about two principals. It contains the name
397of a *subject*, and the subject's public key. It also contains a statement by a
398second principal, the *issuer*, that the subject is who he claims to be, and
399that this is indeed the subject's public key. The issuer's statement is signed
400with the issuer's private key, which only the issuer knows. However, anyone can
401verify the issuer's statement by finding the issuer's public key, decrypting the
402statement with it, and comparing it to the other information in the certificate.
403The certificate also contains information about the time period over which it is
404valid. This is expressed as two fields, called "notBefore" and "notAfter".
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000405
Georg Brandla50d20a2009-09-16 15:57:46 +0000406In the Python use of certificates, a client or server can use a certificate to
407prove who they are. The other side of a network connection can also be required
408to produce a certificate, and that certificate can be validated to the
409satisfaction of the client or server that requires such validation. The
410connection attempt can be set to raise an exception if the validation fails.
411Validation is done automatically, by the underlying OpenSSL framework; the
412application need not concern itself with its mechanics. But the application
413does usually need to provide sets of certificates to allow this process to take
414place.
Bill Janssen426ea0a2007-08-29 22:35:05 +0000415
Georg Brandla50d20a2009-09-16 15:57:46 +0000416Python uses files to contain certificates. They should be formatted as "PEM"
417(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
418and a footer line::
Bill Janssen426ea0a2007-08-29 22:35:05 +0000419
420 -----BEGIN CERTIFICATE-----
421 ... (certificate in base64 PEM encoding) ...
422 -----END CERTIFICATE-----
423
Georg Brandla50d20a2009-09-16 15:57:46 +0000424The Python files which contain certificates can contain a sequence of
425certificates, sometimes called a *certificate chain*. This chain should start
426with the specific certificate for the principal who "is" the client or server,
427and then the certificate for the issuer of that certificate, and then the
428certificate for the issuer of *that* certificate, and so on up the chain till
429you get to a certificate which is *self-signed*, that is, a certificate which
430has the same subject and issuer, sometimes called a *root certificate*. The
431certificates should just be concatenated together in the certificate file. For
432example, suppose we had a three certificate chain, from our server certificate
433to the certificate of the certification authority that signed our server
434certificate, to the root certificate of the agency which issued the
435certification authority's certificate::
Bill Janssen426ea0a2007-08-29 22:35:05 +0000436
437 -----BEGIN CERTIFICATE-----
438 ... (certificate for your server)...
439 -----END CERTIFICATE-----
440 -----BEGIN CERTIFICATE-----
441 ... (the certificate for the CA)...
442 -----END CERTIFICATE-----
443 -----BEGIN CERTIFICATE-----
444 ... (the root certificate for the CA's issuer)...
445 -----END CERTIFICATE-----
446
447If you are going to require validation of the other side of the connection's
448certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandla50d20a2009-09-16 15:57:46 +0000449chains for each issuer you are willing to trust. Again, this file just contains
450these chains concatenated together. For validation, Python will use the first
451chain it finds in the file which matches.
Bill Janssen934b16d2008-06-28 22:19:33 +0000452
Bill Janssen98d19da2007-09-10 21:51:02 +0000453Some "standard" root certificates are available from various certification
Georg Brandla50d20a2009-09-16 15:57:46 +0000454authorities: `CACert.org <http://www.cacert.org/index.php?id=3>`_, `Thawte
455<http://www.thawte.com/roots/>`_, `Verisign
456<http://www.verisign.com/support/roots.html>`_, `Positive SSL
457<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
458(used by python.org), `Equifax and GeoTrust
459<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Bill Janssen98d19da2007-09-10 21:51:02 +0000460
Georg Brandla50d20a2009-09-16 15:57:46 +0000461In general, if you are using SSL3 or TLS1, you don't need to put the full chain
462in your "CA certs" file; you only need the root certificates, and the remote
463peer is supposed to furnish the other certificates necessary to chain from its
464certificate to a root certificate. See :rfc:`4158` for more discussion of the
465way in which certification chains can be built.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000466
Georg Brandla50d20a2009-09-16 15:57:46 +0000467If you are going to create a server that provides SSL-encrypted connection
468services, you will need to acquire a certificate for that service. There are
469many ways of acquiring appropriate certificates, such as buying one from a
470certification authority. Another common practice is to generate a self-signed
471certificate. The simplest way to do this is with the OpenSSL package, using
472something like the following::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000473
Bill Janssen98d19da2007-09-10 21:51:02 +0000474 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
475 Generating a 1024 bit RSA private key
476 .......++++++
477 .............................++++++
478 writing new private key to 'cert.pem'
479 -----
480 You are about to be asked to enter information that will be incorporated
481 into your certificate request.
482 What you are about to enter is what is called a Distinguished Name or a DN.
483 There are quite a few fields but you can leave some blank
484 For some fields there will be a default value,
485 If you enter '.', the field will be left blank.
486 -----
487 Country Name (2 letter code) [AU]:US
488 State or Province Name (full name) [Some-State]:MyState
489 Locality Name (eg, city) []:Some City
490 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
491 Organizational Unit Name (eg, section) []:My Group
492 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
493 Email Address []:ops@myserver.mygroup.myorganization.com
494 %
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000495
Georg Brandla50d20a2009-09-16 15:57:46 +0000496The disadvantage of a self-signed certificate is that it is its own root
497certificate, and no one else will have it in their cache of known (and trusted)
498root certificates.
Bill Janssen426ea0a2007-08-29 22:35:05 +0000499
500
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000501Examples
502--------
503
Bill Janssen426ea0a2007-08-29 22:35:05 +0000504Testing for SSL support
505^^^^^^^^^^^^^^^^^^^^^^^
506
Georg Brandla50d20a2009-09-16 15:57:46 +0000507To test for the presence of SSL support in a Python installation, user code
508should use the following idiom::
Bill Janssen426ea0a2007-08-29 22:35:05 +0000509
510 try:
Georg Brandl28046022011-02-25 11:01:04 +0000511 import ssl
Bill Janssen426ea0a2007-08-29 22:35:05 +0000512 except ImportError:
Georg Brandl28046022011-02-25 11:01:04 +0000513 pass
Bill Janssen426ea0a2007-08-29 22:35:05 +0000514 else:
Georg Brandl28046022011-02-25 11:01:04 +0000515 ... # do something that requires SSL support
Bill Janssen426ea0a2007-08-29 22:35:05 +0000516
517Client-side operation
518^^^^^^^^^^^^^^^^^^^^^
519
Georg Brandla50d20a2009-09-16 15:57:46 +0000520This example connects to an SSL server, prints the server's address and
521certificate, sends some bytes, and reads part of the response::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000522
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000523 import socket, ssl, pprint
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000524
525 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Bill Janssen98d19da2007-09-10 21:51:02 +0000526
527 # require a certificate from the server
528 ssl_sock = ssl.wrap_socket(s,
529 ca_certs="/etc/ca_certs_file",
530 cert_reqs=ssl.CERT_REQUIRED)
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000531
532 ssl_sock.connect(('www.verisign.com', 443))
533
534 print repr(ssl_sock.getpeername())
Bill Janssen98d19da2007-09-10 21:51:02 +0000535 print ssl_sock.cipher()
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000536 print pprint.pformat(ssl_sock.getpeercert())
537
538 # Set a simple HTTP request -- use httplib in actual code.
539 ssl_sock.write("""GET / HTTP/1.0\r
540 Host: www.verisign.com\r\n\r\n""")
541
542 # Read a chunk of data. Will not necessarily
543 # read all the data returned by the server.
544 data = ssl_sock.read()
545
Bill Janssen98d19da2007-09-10 21:51:02 +0000546 # note that closing the SSLSocket will also close the underlying socket
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000547 ssl_sock.close()
548
Georg Brandla50d20a2009-09-16 15:57:46 +0000549As of September 6, 2007, the certificate printed by this program looked like
550this::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000551
Bill Janssen98d19da2007-09-10 21:51:02 +0000552 {'notAfter': 'May 8 23:59:59 2009 GMT',
553 'subject': ((('serialNumber', u'2497886'),),
554 (('1.3.6.1.4.1.311.60.2.1.3', u'US'),),
555 (('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),),
556 (('countryName', u'US'),),
557 (('postalCode', u'94043'),),
558 (('stateOrProvinceName', u'California'),),
559 (('localityName', u'Mountain View'),),
560 (('streetAddress', u'487 East Middlefield Road'),),
561 (('organizationName', u'VeriSign, Inc.'),),
562 (('organizationalUnitName',
563 u'Production Security Services'),),
564 (('organizationalUnitName',
565 u'Terms of use at www.verisign.com/rpa (c)06'),),
566 (('commonName', u'www.verisign.com'),))}
567
568which is a fairly poorly-formed ``subject`` field.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000569
Bill Janssen426ea0a2007-08-29 22:35:05 +0000570Server-side operation
571^^^^^^^^^^^^^^^^^^^^^
572
Georg Brandla50d20a2009-09-16 15:57:46 +0000573For server operation, typically you'd need to have a server certificate, and
574private key, each in a file. You'd open a socket, bind it to a port, call
575:meth:`listen` on it, then start waiting for clients to connect::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000576
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000577 import socket, ssl
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000578
579 bindsocket = socket.socket()
580 bindsocket.bind(('myaddr.mydomain.com', 10023))
581 bindsocket.listen(5)
582
Georg Brandla50d20a2009-09-16 15:57:46 +0000583When one did, you'd call :meth:`accept` on the socket to get the new socket from
584the other end, and use :func:`wrap_socket` to create a server-side SSL context
585for it::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000586
587 while True:
Antoine Pitrou9e7d6e52011-01-02 22:39:10 +0000588 newsocket, fromaddr = bindsocket.accept()
589 connstream = ssl.wrap_socket(newsocket,
590 server_side=True,
591 certfile="mycertfile",
592 keyfile="mykeyfile",
593 ssl_version=ssl.PROTOCOL_TLSv1)
594 try:
595 deal_with_client(connstream)
596 finally:
597 connstream.shutdown(socket.SHUT_RDWR)
598 connstream.close()
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000599
Georg Brandla50d20a2009-09-16 15:57:46 +0000600Then you'd read data from the ``connstream`` and do something with it till you
601are finished with the client (or the client is finished with you)::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000602
603 def deal_with_client(connstream):
Georg Brandl28046022011-02-25 11:01:04 +0000604 data = connstream.read()
605 # null data means the client is finished with us
606 while data:
607 if not do_something(connstream, data):
608 # we'll assume do_something returns False
609 # when we're finished with client
610 break
611 data = connstream.read()
612 # finished with client
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000613
614And go back to listening for new client connections.
615
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000616
Bill Janssen98d19da2007-09-10 21:51:02 +0000617.. seealso::
Bill Janssen426ea0a2007-08-29 22:35:05 +0000618
Bill Janssen98d19da2007-09-10 21:51:02 +0000619 Class :class:`socket.socket`
620 Documentation of underlying :mod:`socket` class
Bill Janssen426ea0a2007-08-29 22:35:05 +0000621
Bill Janssen98d19da2007-09-10 21:51:02 +0000622 `Introducing SSL and Certificates using OpenSSL <http://old.pseudonym.org/ssl/wwwj-index.html>`_
623 Frederick J. Hirsch
Bill Janssen426ea0a2007-08-29 22:35:05 +0000624
Bill Janssen98d19da2007-09-10 21:51:02 +0000625 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
626 Steve Kent
Bill Janssen426ea0a2007-08-29 22:35:05 +0000627
Bill Janssen98d19da2007-09-10 21:51:02 +0000628 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
629 D. Eastlake et. al.
Bill Janssenffe576d2007-09-05 00:46:27 +0000630
Bill Janssen98d19da2007-09-10 21:51:02 +0000631 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
632 Housley et. al.