blob: bd67644f77c30e202bf15ef072f7408baceff9b9 [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).
Bill Janssenffe576d2007-09-05 00:46:27 +0000176See also :rfc:`4158` for more discussion of the way in which
177certification chains can be built.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000178
179
180sslsocket Objects
181-----------------
182
183.. class:: sslsocket(sock [, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_SSLv23, ca_certs=None])
184
Bill Janssen426ea0a2007-08-29 22:35:05 +0000185 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance of a subtype
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000186 of :class:`socket.socket` which wraps the underlying socket in an SSL context.
187 For client-side sockets, the context construction is lazy; if the underlying socket isn't
188 connected yet, the context construction will be performed after :meth:`connect` is called
189 on the socket.
190
Bill Janssen426ea0a2007-08-29 22:35:05 +0000191 The ``keyfile`` and ``certfile`` parameters specify optional files which contain a certificate
192 to be used to identify the local side of the connection. See the above discussion of :ref:`ssl-certificates`
193 for more information on how the certificate is stored in the ``certfile``.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000194
Bill Janssen426ea0a2007-08-29 22:35:05 +0000195 Often the private key is stored
196 in the same file as the certificate; in this case, only the ``certfile`` parameter need be
197 passed. If the private key is stored in a separate file, both parameters must be used.
198 If the private key is stored in the ``certfile``, it should come before the first certificate
199 in the certificate chain::
200
201 -----BEGIN RSA PRIVATE KEY-----
202 ... (private key in base64 encoding) ...
203 -----END RSA PRIVATE KEY-----
204 -----BEGIN CERTIFICATE-----
205 ... (certificate in base64 PEM encoding) ...
206 -----END CERTIFICATE-----
207
208 The parameter ``server_side`` is a boolean which identifies whether server-side or client-side
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000209 behavior is desired from this socket.
210
Bill Janssen426ea0a2007-08-29 22:35:05 +0000211 The parameter ``cert_reqs`` specifies whether a certificate is
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000212 required from the other side of the connection, and whether it will
213 be validated if provided. It must be one of the three values
214 :const:`CERT_NONE` (certificates ignored), :const:`CERT_OPTIONAL` (not required,
215 but validated if provided), or :const:`CERT_REQUIRED` (required and
216 validated). If the value of this parameter is not :const:`CERT_NONE`, then
Bill Janssen426ea0a2007-08-29 22:35:05 +0000217 the ``ca_certs`` parameter must point to a file of CA certificates.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000218
Bill Janssen426ea0a2007-08-29 22:35:05 +0000219 The parameter ``ssl_version`` specifies which version of the SSL protocol to use. Typically,
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000220 the server specifies this, and a client connecting to it must use the same protocol. An
221 SSL server using :const:`PROTOCOL_SSLv23` can understand a client connecting via SSL2, SSL3, or TLS1,
222 but a client using :const:`PROTOCOL_SSLv23` can only connect to an SSL2 server.
223
Bill Janssen426ea0a2007-08-29 22:35:05 +0000224 The ``ca_certs`` file contains a set of concatenated "certification authority" certificates,
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000225 which are used to validate certificates passed from the other end of the connection.
Bill Janssen426ea0a2007-08-29 22:35:05 +0000226 See the above discussion of :ref:`ssl-certificates` for more information about how to arrange
227 the certificates in this file.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000228
229.. method:: sslsocket.read([nbytes])
230
Bill Janssen426ea0a2007-08-29 22:35:05 +0000231 Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000232
233.. method:: sslsocket.write(data)
234
Bill Janssen426ea0a2007-08-29 22:35:05 +0000235 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 +0000236 of bytes written.
237
238.. method:: sslsocket.getpeercert()
239
Bill Janssen426ea0a2007-08-29 22:35:05 +0000240 If there is no certificate for the peer on the other end of the connection, returns ``None``.
241 If a certificate was received from the peer, but not validated, returns an empty ``dict`` instance.
242 If a certificate was received and validated, returns a ``dict`` instance with the fields
243 ``subject`` (the principal for which the certificate was issued), ``issuer`` (the signer of
244 the certificate), ``notBefore`` (the time before which the certificate should not be trusted),
245 and ``notAfter`` (the time after which the certificate should not be trusted) filled in.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000246
Bill Janssenffe576d2007-09-05 00:46:27 +0000247 The "subject" and "issuer" fields are tuples containing the name-value fields
248 given in the certificate's data structure for each principal::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000249
Bill Janssenffe576d2007-09-05 00:46:27 +0000250 {'issuer': (('countryName', u'US'),
251 ('stateOrProvinceName', u'Delaware'),
252 ('localityName', u'Wilmington'),
253 ('organizationName', u'Python Software Foundation'),
254 ('organizationalUnitName', u'SSL'),
255 ('commonName', u'somemachine.python.org')),
256 'notAfter': 'Feb 16 16:54:50 2013 GMT',
257 'notBefore': 'Aug 27 16:54:50 2007 GMT',
258 'subject': (('countryName', u'US'),
259 ('stateOrProvinceName', u'Delaware'),
260 ('localityName', u'Wilmington'),
261 ('organizationName', u'Python Software Foundation'),
262 ('organizationalUnitName', u'SSL'),
263 ('commonName', u'somemachine.python.org')),
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000264 'version': 2}
265
266 This certificate is said to be *self-signed*, because the subject
Bill Janssen426ea0a2007-08-29 22:35:05 +0000267 and issuer are the same entity. The *version* field refers to the X509 version
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000268 that's used for the certificate.
269
Bill Janssen426ea0a2007-08-29 22:35:05 +0000270.. method:: sslsocket.ssl_shutdown()
271
272 Closes the SSL context (if any) over the socket, but leaves the socket connection
273 open for further use, if both sides are willing. This is different from :meth:`socket.socket.shutdown`,
274 which will close the connection, but leave the local socket available for further use.
275
276
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000277Examples
278--------
279
Bill Janssen426ea0a2007-08-29 22:35:05 +0000280Testing for SSL support
281^^^^^^^^^^^^^^^^^^^^^^^
282
283To test for the presence of SSL support in a Python installation, user code should use the following idiom::
284
285 try:
286 import ssl
287 except ImportError:
288 pass
289 else:
290 [ do something that requires SSL support ]
291
292Client-side operation
293^^^^^^^^^^^^^^^^^^^^^
294
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000295This example connects to an SSL server, prints the server's address and certificate,
296sends some bytes, and reads part of the response::
297
298 import socket, ssl, pprint
299
300 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
301 ssl_sock = ssl.sslsocket(s, ca_certs="/etc/ca_certs_file", cert_reqs=ssl.CERT_REQUIRED)
302
303 ssl_sock.connect(('www.verisign.com', 443))
304
305 print repr(ssl_sock.getpeername())
306 print pprint.pformat(ssl_sock.getpeercert())
307
308 # Set a simple HTTP request -- use httplib in actual code.
309 ssl_sock.write("""GET / HTTP/1.0\r
310 Host: www.verisign.com\r\n\r\n""")
311
312 # Read a chunk of data. Will not necessarily
313 # read all the data returned by the server.
314 data = ssl_sock.read()
315
316 # note that closing the sslsocket will also close the underlying socket
317 ssl_sock.close()
318
Bill Janssenffe576d2007-09-05 00:46:27 +0000319As of September 4, 2007, the certificate printed by this program
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000320looked like this::
321
Bill Janssenffe576d2007-09-05 00:46:27 +0000322 {'issuer': (('countryName', u'US'),
323 ('organizationName', u'VeriSign, Inc.'),
324 ('organizationalUnitName', u'VeriSign Trust Network'),
325 ('organizationalUnitName',
326 u'Terms of use at https://www.verisign.com/rpa (c)06'),
327 ('commonName',
328 u'VeriSign Class 3 Extended Validation SSL SGC CA')),
329 'notAfter': 'May 8 23:59:59 2009 GMT',
330 'notBefore': 'May 9 00:00:00 2007 GMT',
331 'subject': (('serialNumber', u'2497886'),
332 ('1.3.6.1.4.1.311.60.2.1.3', u'US'),
333 ('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),
334 ('countryName', u'US'),
335 ('postalCode', u'94043'),
336 ('stateOrProvinceName', u'California'),
337 ('localityName', u'Mountain View'),
338 ('streetAddress', u'487 East Middlefield Road'),
339 ('organizationName', u'VeriSign, Inc.'),
340 ('organizationalUnitName', u'Production Security Services'),
341 ('organizationalUnitName',
342 u'Terms of use at www.verisign.com/rpa (c)06'),
343 ('commonName', u'www.verisign.com')),
344 'version': 2}
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000345
Bill Janssen426ea0a2007-08-29 22:35:05 +0000346Server-side operation
347^^^^^^^^^^^^^^^^^^^^^
348
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000349For server operation, typically you'd need to have a server certificate, and private key, each in a file.
350You'd open a socket, bind it to a port, call :meth:`listen` on it, then start waiting for clients
351to connect::
352
353 import socket, ssl
354
355 bindsocket = socket.socket()
356 bindsocket.bind(('myaddr.mydomain.com', 10023))
357 bindsocket.listen(5)
358
359When one did, you'd call :meth:`accept` on the socket to get the new socket from the other
360end, and use :func:`sslsocket` to create a server-side SSL context for it::
361
362 while True:
363 newsocket, fromaddr = bindsocket.accept()
364 connstream = ssl.sslsocket(newsocket, server_side=True, certfile="mycertfile",
365 keyfile="mykeyfile", ssl_protocol=ssl.PROTOCOL_TLSv1)
366 deal_with_client(connstream)
367
Bill Janssen426ea0a2007-08-29 22:35:05 +0000368Then 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 +0000369
370 def deal_with_client(connstream):
371
372 data = connstream.read()
373 # null data means the client is finished with us
374 while data:
375 if not do_something(connstream, data):
376 # we'll assume do_something returns False when we're finished with client
377 break
378 data = connstream.read()
379 # finished with client
380 connstream.close()
381
382And go back to listening for new client connections.
383
384
Bill Janssen426ea0a2007-08-29 22:35:05 +0000385.. _ssl-references:
386
387References
388----------
389
390Class :class:`socket.socket`
391 Documentation of underlying :mod:`socket` class
392
393`Introducing SSL and Certificates using OpenSSL <http://old.pseudonym.org/ssl/wwwj-index.html>`_, by Frederick J. Hirsch
394
395`Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management`, :rfc:`1422`, by Steve Kent
Bill Janssenffe576d2007-09-05 00:46:27 +0000396
397`Internet X.509 Public Key Infrastructure Certificate and CRL Profile`, :rfc:`3280`, Housley et. al.