blob: 5072caf101ff0e7b672d679a77b8911d422d2587 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001
Thomas Wouters47b49bf2007-08-30 22:15:33 +00002:mod:`ssl` --- SSL wrapper for socket objects
Thomas Woutersed03b412007-08-28 21:37:11 +00003====================================================================
4
5.. module:: ssl
Thomas Wouters47b49bf2007-08-30 22:15:33 +00006 :synopsis: SSL wrapper for socket objects
7
8.. moduleauthor:: Bill Janssen <bill.janssen@gmail.com>
Thomas Wouters47b49bf2007-08-30 22:15:33 +00009.. sectionauthor:: Bill Janssen <bill.janssen@gmail.com>
10
Thomas Woutersed03b412007-08-28 21:37:11 +000011
12This module provides access to Transport Layer Security (often known
13as "Secure Sockets Layer") encryption and peer authentication
14facilities for network sockets, both client-side and server-side.
15This module uses the OpenSSL library. It is available on all modern
16Unix systems, Windows, Mac OS X, and probably additional
17platforms, as long as OpenSSL is installed on that platform.
18
19.. note::
20
21 Some behavior may be platform dependent, since calls are made to the operating
22 system socket APIs.
23
Thomas Wouters47b49bf2007-08-30 22:15:33 +000024This section documents the objects and functions in the ``ssl`` module;
Thomas Woutersed03b412007-08-28 21:37:11 +000025for more general information about TLS, SSL, and certificates, the
Thomas Wouters47b49bf2007-08-30 22:15:33 +000026reader is referred to the documents in the :ref:`ssl-references` section.
Thomas Woutersed03b412007-08-28 21:37:11 +000027
28This module defines a class, :class:`ssl.sslsocket`, which is
29derived from the :class:`socket.socket` type, and supports additional
30:meth:`read` and :meth:`write` methods, along with a method, :meth:`getpeercert`,
31to retrieve the certificate of the other side of the connection.
32
33This module defines the following functions, exceptions, and constants:
34
35.. function:: cert_time_to_seconds(timestring)
36
37 Returns a floating-point value containing a normal seconds-after-the-epoch time
38 value, given the time-string representing the "notBefore" or "notAfter" date
39 from a certificate.
40
41 Here's an example::
42
43 >>> import ssl
44 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
45 1178694000.0
46 >>> import time
47 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
48 'Wed May 9 00:00:00 2007'
49 >>>
50
51.. exception:: sslerror
52
53 Raised to signal an error from the underlying SSL implementation. This
54 signifies some problem in the higher-level
55 encryption and authentication layer that's superimposed on the underlying
56 network connection.
57
58.. data:: CERT_NONE
59
Thomas Wouters47b49bf2007-08-30 22:15:33 +000060 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
Thomas Woutersed03b412007-08-28 21:37:11 +000061 when no certificates will be required or validated from the other
62 side of the socket connection.
63
64.. data:: CERT_OPTIONAL
65
Thomas Wouters47b49bf2007-08-30 22:15:33 +000066 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
Thomas Woutersed03b412007-08-28 21:37:11 +000067 when no certificates will be required from the other side of the
68 socket connection, but if they are provided, will be validated.
69 Note that use of this setting requires a valid certificate
Thomas Wouters47b49bf2007-08-30 22:15:33 +000070 validation file also be passed as a value of the ``ca_certs``
Thomas Woutersed03b412007-08-28 21:37:11 +000071 parameter.
72
73.. data:: CERT_REQUIRED
74
Thomas Wouters47b49bf2007-08-30 22:15:33 +000075 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
Thomas Woutersed03b412007-08-28 21:37:11 +000076 when certificates will be required from the other side of the
77 socket connection. Note that use of this setting requires a valid certificate
Thomas Wouters47b49bf2007-08-30 22:15:33 +000078 validation file also be passed as a value of the ``ca_certs``
Thomas Woutersed03b412007-08-28 21:37:11 +000079 parameter.
80
81.. data:: PROTOCOL_SSLv2
82
83 Selects SSL version 2 as the channel encryption protocol.
84
85.. data:: PROTOCOL_SSLv23
86
87 Selects SSL version 2 or 3 as the channel encryption protocol. This is a setting to use for maximum compatibility
88 with the other end of an SSL connection, but it may cause the specific ciphers chosen for the encryption to be
89 of fairly low quality.
90
91.. data:: PROTOCOL_SSLv3
92
93 Selects SSL version 3 as the channel encryption protocol.
94
95.. data:: PROTOCOL_TLSv1
96
97 Selects SSL version 2 as the channel encryption protocol. This is
98 the most modern version, and probably the best choice for maximum
99 protection, if both sides can speak it.
100
101
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000102.. _ssl-certificates:
103
Thomas Woutersed03b412007-08-28 21:37:11 +0000104Certificates
105------------
106
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000107Certificates in general are part of a public-key / private-key system. In this system, each *principal*,
Thomas Woutersed03b412007-08-28 21:37:11 +0000108(which may be a machine, or a person, or an organization) is assigned a unique two-part encryption key.
109One part of the key is public, and is called the *public key*; the other part is kept secret, and is called
110the *private key*. The two parts are related, in that if you encrypt a message with one of the parts, you can
111decrypt it with the other part, and **only** with the other part.
112
113A certificate contains information about two principals. It contains
114the name of a *subject*, and the subject's public key. It also
115contains a statement by a second principal, the *issuer*, that the
116subject is who he claims to be, and that this is indeed the subject's
117public key. The issuer's statement is signed with the issuer's
118private key, which only the issuer knows. However, anyone can verify
119the issuer's statement by finding the issuer's public key, decrypting
120the statement with it, and comparing it to the other information in
121the certificate. The certificate also contains information about the
122time period over which it is valid. This is expressed as two fields,
123called "notBefore" and "notAfter".
124
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000125In the Python use of certificates, a client or server
126can use a certificate to prove who they are. The other
127side of a network connection can also be required to produce a certificate,
128and that certificate can be validated to the satisfaction
129of the client or server that requires such validation.
130The connection can be set to fail automatically if such
131validation is not achieved.
132
133Python uses files to contain certificates. They should be formatted
134as "PEM" (see :rfc:`1422`), which is a base-64 encoded form wrapped
135with a header line and a footer line::
136
137 -----BEGIN CERTIFICATE-----
138 ... (certificate in base64 PEM encoding) ...
139 -----END CERTIFICATE-----
140
141The Python files which contain certificates can contain a sequence
142of certificates, sometimes called a *certificate chain*. This chain
143should start with the specific certificate for the principal who "is"
144the client or server, and then the certificate for the issuer of that
145certificate, and then the certificate for the issuer of *that* certificate,
146and so on up the chain till you get to a certificate which is *self-signed*,
147that is, a certificate which has the same subject and issuer,
148sometimes called a *root certificate*. The certificates should just
149be concatenated together in the certificate file. For example, suppose
150we had a three certificate chain, from our server certificate to the
151certificate of the certification authority that signed our server certificate,
152to the root certificate of the agency which issued the certification authority's
153certificate::
154
155 -----BEGIN CERTIFICATE-----
156 ... (certificate for your server)...
157 -----END CERTIFICATE-----
158 -----BEGIN CERTIFICATE-----
159 ... (the certificate for the CA)...
160 -----END CERTIFICATE-----
161 -----BEGIN CERTIFICATE-----
162 ... (the root certificate for the CA's issuer)...
163 -----END CERTIFICATE-----
164
165If you are going to require validation of the other side of the connection's
166certificate, you need to provide a "CA certs" file, filled with the certificate
167chains for each issuer you are willing to trust. Again, this file just
168contains these chains concatenated together. For validation, Python will
169use the first chain it finds in the file which matches.
170Some "standard" root certificates are available at
171http://www.thawte.com/roots/ (for Thawte roots) and
172http://www.verisign.com/support/roots.html (for Verisign roots).
Thomas Woutersed03b412007-08-28 21:37:11 +0000173
174
175sslsocket Objects
176-----------------
177
178.. class:: sslsocket(sock [, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_SSLv23, ca_certs=None])
179
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000180 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance of a subtype
Thomas Woutersed03b412007-08-28 21:37:11 +0000181 of :class:`socket.socket` which wraps the underlying socket in an SSL context.
182 For client-side sockets, the context construction is lazy; if the underlying socket isn't
183 connected yet, the context construction will be performed after :meth:`connect` is called
184 on the socket.
185
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000186 The ``keyfile`` and ``certfile`` parameters specify optional files which contain a certificate
187 to be used to identify the local side of the connection. See the above discussion of :ref:`ssl-certificates`
188 for more information on how the certificate is stored in the ``certfile``.
Thomas Woutersed03b412007-08-28 21:37:11 +0000189
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000190 Often the private key is stored
191 in the same file as the certificate; in this case, only the ``certfile`` parameter need be
192 passed. If the private key is stored in a separate file, both parameters must be used.
193 If the private key is stored in the ``certfile``, it should come before the first certificate
194 in the certificate chain::
195
196 -----BEGIN RSA PRIVATE KEY-----
197 ... (private key in base64 encoding) ...
198 -----END RSA PRIVATE KEY-----
199 -----BEGIN CERTIFICATE-----
200 ... (certificate in base64 PEM encoding) ...
201 -----END CERTIFICATE-----
202
203 The parameter ``server_side`` is a boolean which identifies whether server-side or client-side
Thomas Woutersed03b412007-08-28 21:37:11 +0000204 behavior is desired from this socket.
205
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000206 The parameter ``cert_reqs`` specifies whether a certificate is
Thomas Woutersed03b412007-08-28 21:37:11 +0000207 required from the other side of the connection, and whether it will
208 be validated if provided. It must be one of the three values
209 :const:`CERT_NONE` (certificates ignored), :const:`CERT_OPTIONAL` (not required,
210 but validated if provided), or :const:`CERT_REQUIRED` (required and
211 validated). If the value of this parameter is not :const:`CERT_NONE`, then
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000212 the ``ca_certs`` parameter must point to a file of CA certificates.
Thomas Woutersed03b412007-08-28 21:37:11 +0000213
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000214 The parameter ``ssl_version`` specifies which version of the SSL protocol to use. Typically,
Thomas Woutersed03b412007-08-28 21:37:11 +0000215 the server specifies this, and a client connecting to it must use the same protocol. An
216 SSL server using :const:`PROTOCOL_SSLv23` can understand a client connecting via SSL2, SSL3, or TLS1,
217 but a client using :const:`PROTOCOL_SSLv23` can only connect to an SSL2 server.
218
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000219 The ``ca_certs`` file contains a set of concatenated "certification authority" certificates,
Thomas Woutersed03b412007-08-28 21:37:11 +0000220 which are used to validate certificates passed from the other end of the connection.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000221 See the above discussion of :ref:`ssl-certificates` for more information about how to arrange
222 the certificates in this file.
Thomas Woutersed03b412007-08-28 21:37:11 +0000223
224.. method:: sslsocket.read([nbytes])
225
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000226 Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them.
Thomas Woutersed03b412007-08-28 21:37:11 +0000227
228.. method:: sslsocket.write(data)
229
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000230 Writes the ``data`` to the other side of the connection, using the SSL channel to encrypt. Returns the number
Thomas Woutersed03b412007-08-28 21:37:11 +0000231 of bytes written.
232
233.. method:: sslsocket.getpeercert()
234
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000235 If there is no certificate for the peer on the other end of the connection, returns ``None``.
236 If a certificate was received from the peer, but not validated, returns an empty ``dict`` instance.
237 If a certificate was received and validated, returns a ``dict`` instance with the fields
238 ``subject`` (the principal for which the certificate was issued), ``issuer`` (the signer of
239 the certificate), ``notBefore`` (the time before which the certificate should not be trusted),
240 and ``notAfter`` (the time after which the certificate should not be trusted) filled in.
Thomas Woutersed03b412007-08-28 21:37:11 +0000241
242 The "subject" and "issuer" fields are themselves dictionaries containing the fields given
243 in the certificate's data structure for each principal::
244
245 {'issuer': {'commonName': u'somemachine.python.org',
246 'countryName': u'US',
247 'localityName': u'Wilmington',
248 'organizationName': u'Python Software Foundation',
249 'organizationalUnitName': u'SSL',
250 'stateOrProvinceName': u'Delaware'},
251 'subject': {'commonName': u'somemachine.python.org',
252 'countryName': u'US',
253 'localityName': u'Wilmington',
254 'organizationName': u'Python Software Foundation',
255 'organizationalUnitName': u'SSL',
256 'stateOrProvinceName': u'Delaware'},
257 'notAfter': 'Sep 4 21:54:26 2007 GMT',
258 'notBefore': 'Aug 25 21:54:26 2007 GMT',
259 'version': 2}
260
261 This certificate is said to be *self-signed*, because the subject
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000262 and issuer are the same entity. The *version* field refers to the X509 version
Thomas Woutersed03b412007-08-28 21:37:11 +0000263 that's used for the certificate.
264
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000265.. method:: sslsocket.ssl_shutdown()
266
267 Closes the SSL context (if any) over the socket, but leaves the socket connection
268 open for further use, if both sides are willing. This is different from :meth:`socket.socket.shutdown`,
269 which will close the connection, but leave the local socket available for further use.
270
271
Thomas Woutersed03b412007-08-28 21:37:11 +0000272Examples
273--------
274
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000275Testing for SSL support
276^^^^^^^^^^^^^^^^^^^^^^^
277
278To test for the presence of SSL support in a Python installation, user code should use the following idiom::
279
280 try:
281 import ssl
282 except ImportError:
283 pass
284 else:
285 [ do something that requires SSL support ]
286
287Client-side operation
288^^^^^^^^^^^^^^^^^^^^^
289
Thomas Woutersed03b412007-08-28 21:37:11 +0000290This example connects to an SSL server, prints the server's address and certificate,
291sends some bytes, and reads part of the response::
292
293 import socket, ssl, pprint
294
295 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
296 ssl_sock = ssl.sslsocket(s, ca_certs="/etc/ca_certs_file", cert_reqs=ssl.CERT_REQUIRED)
297
298 ssl_sock.connect(('www.verisign.com', 443))
299
Georg Brandl6911e3c2007-09-04 07:15:32 +0000300 print(repr(ssl_sock.getpeername()))
301 pprint.pprint(ssl_sock.getpeercert())
Thomas Woutersed03b412007-08-28 21:37:11 +0000302
303 # Set a simple HTTP request -- use httplib in actual code.
304 ssl_sock.write("""GET / HTTP/1.0\r
305 Host: www.verisign.com\r\n\r\n""")
306
307 # Read a chunk of data. Will not necessarily
308 # read all the data returned by the server.
309 data = ssl_sock.read()
310
311 # note that closing the sslsocket will also close the underlying socket
312 ssl_sock.close()
313
314As of August 25, 2007, the certificate printed by this program
315looked like this::
316
317 {'issuer': {'commonName': u'VeriSign Class 3 Extended Validation SSL SGC CA',
318 'countryName': u'US',
319 'organizationName': u'VeriSign, Inc.',
320 'organizationalUnitName': u'Terms of use at https://www.verisign.com/rpa (c)06'},
321 'subject': {'1.3.6.1.4.1.311.60.2.1.2': u'Delaware',
322 '1.3.6.1.4.1.311.60.2.1.3': u'US',
323 'commonName': u'www.verisign.com',
324 'countryName': u'US',
325 'localityName': u'Mountain View',
326 'organizationName': u'VeriSign, Inc.',
327 'organizationalUnitName': u'Terms of use at www.verisign.com/rpa (c)06',
328 'postalCode': u'94043',
329 'serialNumber': u'2497886',
330 'stateOrProvinceName': u'California',
331 'streetAddress': u'487 East Middlefield Road'},
332 'notAfter': 'May 8 23:59:59 2009 GMT',
333 'notBefore': 'May 9 00:00:00 2007 GMT',
334 'version': 2}
335
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000336Server-side operation
337^^^^^^^^^^^^^^^^^^^^^
338
Thomas Woutersed03b412007-08-28 21:37:11 +0000339For server operation, typically you'd need to have a server certificate, and private key, each in a file.
340You'd open a socket, bind it to a port, call :meth:`listen` on it, then start waiting for clients
341to connect::
342
343 import socket, ssl
344
345 bindsocket = socket.socket()
346 bindsocket.bind(('myaddr.mydomain.com', 10023))
347 bindsocket.listen(5)
348
349When one did, you'd call :meth:`accept` on the socket to get the new socket from the other
350end, and use :func:`sslsocket` to create a server-side SSL context for it::
351
352 while True:
353 newsocket, fromaddr = bindsocket.accept()
354 connstream = ssl.sslsocket(newsocket, server_side=True, certfile="mycertfile",
355 keyfile="mykeyfile", ssl_protocol=ssl.PROTOCOL_TLSv1)
356 deal_with_client(connstream)
357
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000358Then you'd read data from the ``connstream`` and do something with it till you are finished with the client (or the client is finished with you)::
Thomas Woutersed03b412007-08-28 21:37:11 +0000359
360 def deal_with_client(connstream):
361
362 data = connstream.read()
363 # null data means the client is finished with us
364 while data:
365 if not do_something(connstream, data):
366 # we'll assume do_something returns False when we're finished with client
367 break
368 data = connstream.read()
369 # finished with client
370 connstream.close()
371
372And go back to listening for new client connections.
373
374
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000375.. _ssl-references:
376
377References
378----------
379
380Class :class:`socket.socket`
381 Documentation of underlying :mod:`socket` class
382
383`Introducing SSL and Certificates using OpenSSL <http://old.pseudonym.org/ssl/wwwj-index.html>`_, by Frederick J. Hirsch
384
385`Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management`, :rfc:`1422`, by Steve Kent