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