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