blob: fb41091cae65e7f6f77eadee2e84077bf719637a [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
Bill Janssen98d19da2007-09-10 21:51:02 +000015.. index:: single: OpenSSL; (use in module ssl)
16
17.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
18
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000019This module provides access to Transport Layer Security (often known
20as "Secure Sockets Layer") encryption and peer authentication
21facilities for network sockets, both client-side and server-side.
22This module uses the OpenSSL library. It is available on all modern
23Unix systems, Windows, Mac OS X, and probably additional
24platforms, as long as OpenSSL is installed on that platform.
25
26.. note::
27
28 Some behavior may be platform dependent, since calls are made to the operating
Bill Janssen98d19da2007-09-10 21:51:02 +000029 system socket APIs. The installed version of OpenSSL may also cause
30 variations in behavior.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000031
Bill Janssen426ea0a2007-08-29 22:35:05 +000032This section documents the objects and functions in the ``ssl`` module;
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000033for more general information about TLS, SSL, and certificates, the
Bill Janssen98d19da2007-09-10 21:51:02 +000034reader is referred to the documents in the "See Also" section at
35the bottom.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000036
Bill Janssen93bf9ce2007-09-11 02:42:07 +000037This module provides a class, :class:`ssl.SSLSocket`, which is
38derived from the :class:`socket.socket` type, and provides
39a socket-like wrapper that also encrypts and decrypts the data
40going over the socket with SSL. It supports additional
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000041:meth:`read` and :meth:`write` methods, along with a method, :meth:`getpeercert`,
Bill Janssen93bf9ce2007-09-11 02:42:07 +000042to retrieve the certificate of the other side of the connection, and
43a method, :meth:`cipher`, to retrieve the cipher being used for the
44secure connection.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000045
Bill Janssen93bf9ce2007-09-11 02:42:07 +000046Functions, Constants, and Exceptions
47------------------------------------
Guido van Rossum8ee23bb2007-08-27 19:11:11 +000048
Bill Janssen93bf9ce2007-09-11 02:42:07 +000049.. exception:: SSLError
50
51 Raised to signal an error from the underlying SSL implementation. This
52 signifies some problem in the higher-level
53 encryption and authentication layer that's superimposed on the underlying
54 network connection. This error is a subtype of :exc:`socket.error`, which
55 in turn is a subtype of :exc:`IOError`.
56
Bill Janssen296a59d2007-09-16 22:06:00 +000057.. function:: wrap_socket (sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None)
Bill Janssen98d19da2007-09-10 21:51:02 +000058
59 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance of :class:`ssl.SSLSocket`, a subtype
60 of :class:`socket.socket`, which wraps the underlying socket in an SSL context.
61 For client-side sockets, the context construction is lazy; if the underlying socket isn't
62 connected yet, the context construction will be performed after :meth:`connect` is called
63 on the socket. For server-side sockets, if the socket has no remote peer, it is assumed
64 to be a listening socket, and the server-side SSL wrapping is automatically performed
Bill Janssen93bf9ce2007-09-11 02:42:07 +000065 on client connections accepted via the :meth:`accept` method. :func:`wrap_socket` may
66 raise :exc:`SSLError`.
Bill Janssen98d19da2007-09-10 21:51:02 +000067
68 The ``keyfile`` and ``certfile`` parameters specify optional files which contain a certificate
69 to be used to identify the local side of the connection. See the discussion of :ref:`ssl-certificates`
70 for more information on how the certificate is stored in the ``certfile``.
71
72 Often the private key is stored
73 in the same file as the certificate; in this case, only the ``certfile`` parameter need be
74 passed. If the private key is stored in a separate file, both parameters must be used.
75 If the private key is stored in the ``certfile``, it should come before the first certificate
76 in the certificate chain::
77
78 -----BEGIN RSA PRIVATE KEY-----
79 ... (private key in base64 encoding) ...
80 -----END RSA PRIVATE KEY-----
81 -----BEGIN CERTIFICATE-----
82 ... (certificate in base64 PEM encoding) ...
83 -----END CERTIFICATE-----
84
85 The parameter ``server_side`` is a boolean which identifies whether server-side or client-side
86 behavior is desired from this socket.
87
88 The parameter ``cert_reqs`` specifies whether a certificate is
89 required from the other side of the connection, and whether it will
90 be validated if provided. It must be one of the three values
91 :const:`CERT_NONE` (certificates ignored), :const:`CERT_OPTIONAL` (not required,
92 but validated if provided), or :const:`CERT_REQUIRED` (required and
93 validated). If the value of this parameter is not :const:`CERT_NONE`, then
94 the ``ca_certs`` parameter must point to a file of CA certificates.
95
96 The ``ca_certs`` file contains a set of concatenated "certification authority" certificates,
97 which are used to validate certificates passed from the other end of the connection.
98 See the discussion of :ref:`ssl-certificates` for more information about how to arrange
99 the certificates in this file.
100
101 The parameter ``ssl_version`` specifies which version of the SSL protocol to use.
102 Typically, the server chooses a particular protocol version, and the client
103 must adapt to the server's choice. Most of the versions are not interoperable
104 with the other versions. If not specified, for client-side operation, the
105 default SSL version is SSLv3; for server-side operation, SSLv23. These
106 version selections provide the most compatibility with other versions.
107
108 Here's a table showing which versions in a client (down the side)
109 can connect to which versions in a server (along the top):
110
111 .. table::
112
113 ======================== ========= ========= ========== =========
114 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1**
Georg Brandl2b92f6b2007-12-06 01:52:24 +0000115 ------------------------ --------- --------- ---------- ---------
Bill Janssen98d19da2007-09-10 21:51:02 +0000116 *SSLv2* yes no yes* no
117 *SSLv3* yes yes yes no
118 *SSLv23* yes no yes no
119 *TLSv1* no no yes yes
120 ======================== ========= ========= ========== =========
121
Georg Brandl2b92f6b2007-12-06 01:52:24 +0000122 In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4),
Bill Janssen98d19da2007-09-10 21:51:02 +0000123 an SSLv2 client could not connect to an SSLv23 server.
124
125.. function:: RAND_status()
126
127 Returns True if the SSL pseudo-random number generator has been
128 seeded with 'enough' randomness, and False otherwise. You can use
129 :func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness
130 of the pseudo-random number generator.
131
132.. function:: RAND_egd(path)
133
134 If you are running an entropy-gathering daemon (EGD) somewhere, and ``path``
135 is the pathname of a socket connection open to it, this will read
136 256 bytes of randomness from the socket, and add it to the SSL pseudo-random number generator
137 to increase the security of generated secret keys. This is typically only
138 necessary on systems without better sources of randomness.
139
140 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000141 sources of entropy-gathering daemons.
Bill Janssen98d19da2007-09-10 21:51:02 +0000142
143.. function:: RAND_add(bytes, entropy)
144
145 Mixes the given ``bytes`` into the SSL pseudo-random number generator.
146 The parameter ``entropy`` (a float) is a lower bound on the entropy
147 contained in string (so you can always use :const:`0.0`).
148 See :rfc:`1750` for more information on sources of entropy.
149
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000150.. function:: cert_time_to_seconds(timestring)
151
152 Returns a floating-point value containing a normal seconds-after-the-epoch time
153 value, given the time-string representing the "notBefore" or "notAfter" date
154 from a certificate.
155
156 Here's an example::
157
158 >>> import ssl
159 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
160 1178694000.0
161 >>> import time
162 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
163 'Wed May 9 00:00:00 2007'
164 >>>
165
Bill Janssen296a59d2007-09-16 22:06:00 +0000166.. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
167
168 Given the address ``addr`` of an SSL-protected server, as a
169 (*hostname*, *port-number*) pair, fetches the server's certificate,
170 and returns it as a PEM-encoded string. If ``ssl_version`` is
171 specified, uses that version of the SSL protocol to attempt to
172 connect to the server. If ``ca_certs`` is specified, it should be
173 a file containing a list of root certificates, the same format as
174 used for the same parameter in :func:`wrap_socket`. The call will
175 attempt to validate the server certificate against that set of root
176 certificates, and will fail if the validation attempt fails.
177
178.. function:: DER_cert_to_PEM_cert (DER_cert_bytes)
179
180 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
181 string version of the same certificate.
182
183.. function:: PEM_cert_to_DER_cert (PEM_cert_string)
184
185 Given a certificate as an ASCII PEM string, returns a DER-encoded
186 sequence of bytes for that same certificate.
187
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000188.. data:: CERT_NONE
189
Bill Janssen426ea0a2007-08-29 22:35:05 +0000190 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000191 when no certificates will be required or validated from the other
192 side of the socket connection.
193
194.. data:: CERT_OPTIONAL
195
Bill Janssen426ea0a2007-08-29 22:35:05 +0000196 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000197 when no certificates will be required from the other side of the
198 socket connection, but if they are provided, will be validated.
199 Note that use of this setting requires a valid certificate
Bill Janssen426ea0a2007-08-29 22:35:05 +0000200 validation file also be passed as a value of the ``ca_certs``
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000201 parameter.
202
203.. data:: CERT_REQUIRED
204
Bill Janssen426ea0a2007-08-29 22:35:05 +0000205 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000206 when certificates will be required from the other side of the
207 socket connection. Note that use of this setting requires a valid certificate
Bill Janssen426ea0a2007-08-29 22:35:05 +0000208 validation file also be passed as a value of the ``ca_certs``
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000209 parameter.
210
211.. data:: PROTOCOL_SSLv2
212
213 Selects SSL version 2 as the channel encryption protocol.
214
215.. data:: PROTOCOL_SSLv23
216
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000217 Selects SSL version 2 or 3 as the channel encryption protocol.
218 This is a setting to use with servers for maximum compatibility
219 with the other end of an SSL connection, but it may cause the
220 specific ciphers chosen for the encryption to be of fairly low
221 quality.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000222
223.. data:: PROTOCOL_SSLv3
224
225 Selects SSL version 3 as the channel encryption protocol.
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000226 For clients, this is the maximally compatible SSL variant.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000227
228.. data:: PROTOCOL_TLSv1
229
Andrew M. Kuchling529b1a92007-10-20 19:25:37 +0000230 Selects TLS version 1 as the channel encryption protocol. This is
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000231 the most modern version, and probably the best choice for maximum
232 protection, if both sides can speak it.
233
234
Bill Janssen98d19da2007-09-10 21:51:02 +0000235SSLSocket Objects
236-----------------
237
238.. method:: SSLSocket.read([nbytes=1024])
239
240 Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them.
241
242.. method:: SSLSocket.write(data)
243
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000244 Writes the ``data`` to the other side of the connection, using the
245 SSL channel to encrypt. Returns the number of bytes written.
Bill Janssen98d19da2007-09-10 21:51:02 +0000246
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000247.. method:: SSLSocket.getpeercert(binary_form=False)
Bill Janssen98d19da2007-09-10 21:51:02 +0000248
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000249 If there is no certificate for the peer on the other end of the
250 connection, returns ``None``.
Bill Janssen98d19da2007-09-10 21:51:02 +0000251
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000252 If the the parameter ``binary_form`` is :const:`False`, and a
253 certificate was received from the peer, this method returns a
254 :class:`dict` instance. If the certificate was not validated, the
255 dict is empty. If the certificate was validated, it returns a dict
256 with the keys ``subject`` (the principal for which the certificate
257 was issued), and ``notAfter`` (the time after which the certificate
258 should not be trusted). The certificate was already validated, so
259 the ``notBefore`` and ``issuer`` fields are not returned. If a
260 certificate contains an instance of the *Subject Alternative Name*
261 extension (see :rfc:`3280`), there will also be a
262 ``subjectAltName`` key in the dictionary.
263
264 The "subject" field is a tuple containing the sequence of relative
265 distinguished names (RDNs) given in the certificate's data
266 structure for the principal, and each RDN is a sequence of
267 name-value pairs::
Bill Janssen98d19da2007-09-10 21:51:02 +0000268
269 {'notAfter': 'Feb 16 16:54:50 2013 GMT',
270 'subject': ((('countryName', u'US'),),
271 (('stateOrProvinceName', u'Delaware'),),
272 (('localityName', u'Wilmington'),),
273 (('organizationName', u'Python Software Foundation'),),
274 (('organizationalUnitName', u'SSL'),),
275 (('commonName', u'somemachine.python.org'),))}
276
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000277 If the ``binary_form`` parameter is :const:`True`, and a
278 certificate was provided, this method returns the DER-encoded form
Bill Janssen296a59d2007-09-16 22:06:00 +0000279 of the entire certificate as a sequence of bytes, or :const:`None` if the
280 peer did not provide a certificate. This return
281 value is independent of validation; if validation was required
282 (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
283 been validated, but if :const:`CERT_NONE` was used to establish the
284 connection, the certificate, if present, will not have been validated.
Bill Janssen98d19da2007-09-10 21:51:02 +0000285
286.. method:: SSLSocket.cipher()
287
288 Returns a three-value tuple containing the name of the cipher being
289 used, the version of the SSL protocol that defines its use, and the
290 number of secret bits being used. If no connection has been
291 established, returns ``None``.
292
Bill Janssen98d19da2007-09-10 21:51:02 +0000293
294.. index:: single: certificates
295
296.. index:: single: X509 certificate
297
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000298.. _ssl-certificates:
299
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000300Certificates
301------------
302
Bill Janssen426ea0a2007-08-29 22:35:05 +0000303Certificates in general are part of a public-key / private-key system. In this system, each *principal*,
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000304(which may be a machine, or a person, or an organization) is assigned a unique two-part encryption key.
305One part of the key is public, and is called the *public key*; the other part is kept secret, and is called
306the *private key*. The two parts are related, in that if you encrypt a message with one of the parts, you can
307decrypt it with the other part, and **only** with the other part.
308
309A certificate contains information about two principals. It contains
310the name of a *subject*, and the subject's public key. It also
311contains a statement by a second principal, the *issuer*, that the
312subject is who he claims to be, and that this is indeed the subject's
313public key. The issuer's statement is signed with the issuer's
314private key, which only the issuer knows. However, anyone can verify
315the issuer's statement by finding the issuer's public key, decrypting
316the statement with it, and comparing it to the other information in
317the certificate. The certificate also contains information about the
318time period over which it is valid. This is expressed as two fields,
319called "notBefore" and "notAfter".
320
Bill Janssen426ea0a2007-08-29 22:35:05 +0000321In the Python use of certificates, a client or server
322can use a certificate to prove who they are. The other
323side of a network connection can also be required to produce a certificate,
324and that certificate can be validated to the satisfaction
325of the client or server that requires such validation.
Bill Janssen98d19da2007-09-10 21:51:02 +0000326The connection attempt can be set to raise an exception if
327the validation fails. Validation is done
328automatically, by the underlying OpenSSL framework; the
329application need not concern itself with its mechanics.
330But the application does usually need to provide
331sets of certificates to allow this process to take place.
Bill Janssen426ea0a2007-08-29 22:35:05 +0000332
333Python uses files to contain certificates. They should be formatted
334as "PEM" (see :rfc:`1422`), which is a base-64 encoded form wrapped
335with a header line and a footer line::
336
337 -----BEGIN CERTIFICATE-----
338 ... (certificate in base64 PEM encoding) ...
339 -----END CERTIFICATE-----
340
341The Python files which contain certificates can contain a sequence
342of certificates, sometimes called a *certificate chain*. This chain
343should start with the specific certificate for the principal who "is"
344the client or server, and then the certificate for the issuer of that
345certificate, and then the certificate for the issuer of *that* certificate,
346and so on up the chain till you get to a certificate which is *self-signed*,
347that is, a certificate which has the same subject and issuer,
348sometimes called a *root certificate*. The certificates should just
349be concatenated together in the certificate file. For example, suppose
350we had a three certificate chain, from our server certificate to the
351certificate of the certification authority that signed our server certificate,
352to the root certificate of the agency which issued the certification authority's
353certificate::
354
355 -----BEGIN CERTIFICATE-----
356 ... (certificate for your server)...
357 -----END CERTIFICATE-----
358 -----BEGIN CERTIFICATE-----
359 ... (the certificate for the CA)...
360 -----END CERTIFICATE-----
361 -----BEGIN CERTIFICATE-----
362 ... (the root certificate for the CA's issuer)...
363 -----END CERTIFICATE-----
364
365If you are going to require validation of the other side of the connection's
366certificate, you need to provide a "CA certs" file, filled with the certificate
367chains for each issuer you are willing to trust. Again, this file just
368contains these chains concatenated together. For validation, Python will
369use the first chain it finds in the file which matches.
Bill Janssen98d19da2007-09-10 21:51:02 +0000370Some "standard" root certificates are available from various certification
371authorities:
372`CACert.org <http://www.cacert.org/index.php?id=3>`_,
373`Thawte <http://www.thawte.com/roots/>`_,
374`Verisign <http://www.verisign.com/support/roots.html>`_,
Bill Janssen296a59d2007-09-16 22:06:00 +0000375`Positive SSL <http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_ (used by python.org),
Bill Janssen98d19da2007-09-10 21:51:02 +0000376`Equifax and GeoTrust <http://www.geotrust.com/resources/root_certificates/index.asp>`_.
377
378In general, if you are using
379SSL3 or TLS1, you don't need to put the full chain in your "CA certs" file;
380you only need the root certificates, and the remote peer is supposed to
381furnish the other certificates necessary to chain from its certificate to
382a root certificate.
383See :rfc:`4158` for more discussion of the way in which
Bill Janssenffe576d2007-09-05 00:46:27 +0000384certification chains can be built.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000385
Bill Janssen98d19da2007-09-10 21:51:02 +0000386If you are going to create a server that provides SSL-encrypted
387connection services, you will need to acquire a certificate for that
388service. There are many ways of acquiring appropriate certificates,
389such as buying one from a certification authority. Another common
390practice is to generate a self-signed certificate. The simplest
391way to do this is with the OpenSSL package, using something like
392the following::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000393
Bill Janssen98d19da2007-09-10 21:51:02 +0000394 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
395 Generating a 1024 bit RSA private key
396 .......++++++
397 .............................++++++
398 writing new private key to 'cert.pem'
399 -----
400 You are about to be asked to enter information that will be incorporated
401 into your certificate request.
402 What you are about to enter is what is called a Distinguished Name or a DN.
403 There are quite a few fields but you can leave some blank
404 For some fields there will be a default value,
405 If you enter '.', the field will be left blank.
406 -----
407 Country Name (2 letter code) [AU]:US
408 State or Province Name (full name) [Some-State]:MyState
409 Locality Name (eg, city) []:Some City
410 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
411 Organizational Unit Name (eg, section) []:My Group
412 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
413 Email Address []:ops@myserver.mygroup.myorganization.com
414 %
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000415
Bill Janssen98d19da2007-09-10 21:51:02 +0000416The disadvantage of a self-signed certificate is that it is its
417own root certificate, and no one else will have it in their cache
418of known (and trusted) root certificates.
Bill Janssen426ea0a2007-08-29 22:35:05 +0000419
420
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000421Examples
422--------
423
Bill Janssen426ea0a2007-08-29 22:35:05 +0000424Testing for SSL support
425^^^^^^^^^^^^^^^^^^^^^^^
426
427To test for the presence of SSL support in a Python installation, user code should use the following idiom::
428
429 try:
430 import ssl
431 except ImportError:
432 pass
433 else:
434 [ do something that requires SSL support ]
435
436Client-side operation
437^^^^^^^^^^^^^^^^^^^^^
438
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000439This example connects to an SSL server, prints the server's address and certificate,
440sends some bytes, and reads part of the response::
441
442 import socket, ssl, pprint
443
444 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Bill Janssen98d19da2007-09-10 21:51:02 +0000445
446 # require a certificate from the server
447 ssl_sock = ssl.wrap_socket(s,
448 ca_certs="/etc/ca_certs_file",
449 cert_reqs=ssl.CERT_REQUIRED)
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000450
451 ssl_sock.connect(('www.verisign.com', 443))
452
453 print repr(ssl_sock.getpeername())
Bill Janssen98d19da2007-09-10 21:51:02 +0000454 print ssl_sock.cipher()
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000455 print pprint.pformat(ssl_sock.getpeercert())
456
457 # Set a simple HTTP request -- use httplib in actual code.
458 ssl_sock.write("""GET / HTTP/1.0\r
459 Host: www.verisign.com\r\n\r\n""")
460
461 # Read a chunk of data. Will not necessarily
462 # read all the data returned by the server.
463 data = ssl_sock.read()
464
Bill Janssen98d19da2007-09-10 21:51:02 +0000465 # note that closing the SSLSocket will also close the underlying socket
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000466 ssl_sock.close()
467
Bill Janssen98d19da2007-09-10 21:51:02 +0000468As of September 6, 2007, the certificate printed by this program
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000469looked like this::
470
Bill Janssen98d19da2007-09-10 21:51:02 +0000471 {'notAfter': 'May 8 23:59:59 2009 GMT',
472 'subject': ((('serialNumber', u'2497886'),),
473 (('1.3.6.1.4.1.311.60.2.1.3', u'US'),),
474 (('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),),
475 (('countryName', u'US'),),
476 (('postalCode', u'94043'),),
477 (('stateOrProvinceName', u'California'),),
478 (('localityName', u'Mountain View'),),
479 (('streetAddress', u'487 East Middlefield Road'),),
480 (('organizationName', u'VeriSign, Inc.'),),
481 (('organizationalUnitName',
482 u'Production Security Services'),),
483 (('organizationalUnitName',
484 u'Terms of use at www.verisign.com/rpa (c)06'),),
485 (('commonName', u'www.verisign.com'),))}
486
487which is a fairly poorly-formed ``subject`` field.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000488
Bill Janssen426ea0a2007-08-29 22:35:05 +0000489Server-side operation
490^^^^^^^^^^^^^^^^^^^^^
491
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000492For server operation, typically you'd need to have a server certificate, and private key, each in a file.
493You'd open a socket, bind it to a port, call :meth:`listen` on it, then start waiting for clients
494to connect::
495
496 import socket, ssl
497
498 bindsocket = socket.socket()
499 bindsocket.bind(('myaddr.mydomain.com', 10023))
500 bindsocket.listen(5)
501
502When one did, you'd call :meth:`accept` on the socket to get the new socket from the other
Bill Janssen98d19da2007-09-10 21:51:02 +0000503end, and use :func:`wrap_socket` to create a server-side SSL context for it::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000504
505 while True:
506 newsocket, fromaddr = bindsocket.accept()
Bill Janssen98d19da2007-09-10 21:51:02 +0000507 connstream = ssl.wrap_socket(newsocket,
508 server_side=True,
509 certfile="mycertfile",
510 keyfile="mykeyfile",
Andrew M. Kuchlingaea8d2e2008-04-18 02:40:47 +0000511 ssl_version=ssl.PROTOCOL_TLSv1)
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000512 deal_with_client(connstream)
513
Bill Janssen426ea0a2007-08-29 22:35:05 +0000514Then 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 +0000515
516 def deal_with_client(connstream):
517
518 data = connstream.read()
519 # null data means the client is finished with us
520 while data:
521 if not do_something(connstream, data):
Bill Janssen98d19da2007-09-10 21:51:02 +0000522 # we'll assume do_something returns False
523 # when we're finished with client
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000524 break
525 data = connstream.read()
526 # finished with client
527 connstream.close()
528
529And go back to listening for new client connections.
530
531
Bill Janssen98d19da2007-09-10 21:51:02 +0000532.. seealso::
Bill Janssen426ea0a2007-08-29 22:35:05 +0000533
Bill Janssen98d19da2007-09-10 21:51:02 +0000534 Class :class:`socket.socket`
535 Documentation of underlying :mod:`socket` class
Bill Janssen426ea0a2007-08-29 22:35:05 +0000536
Bill Janssen98d19da2007-09-10 21:51:02 +0000537 `Introducing SSL and Certificates using OpenSSL <http://old.pseudonym.org/ssl/wwwj-index.html>`_
538 Frederick J. Hirsch
Bill Janssen426ea0a2007-08-29 22:35:05 +0000539
Bill Janssen98d19da2007-09-10 21:51:02 +0000540 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
541 Steve Kent
Bill Janssen426ea0a2007-08-29 22:35:05 +0000542
Bill Janssen98d19da2007-09-10 21:51:02 +0000543 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
544 D. Eastlake et. al.
Bill Janssenffe576d2007-09-05 00:46:27 +0000545
Bill Janssen98d19da2007-09-10 21:51:02 +0000546 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
547 Housley et. al.