blob: 2ab62071e232ae72141a072d7ef020d7829ef003 [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
57.. 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**
115 *SSLv2* yes no yes* no
116 *SSLv3* yes yes yes no
117 *SSLv23* yes no yes no
118 *TLSv1* no no yes yes
119 ======================== ========= ========= ========== =========
120
121 `*` In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4),
122 an SSLv2 client could not connect to an SSLv23 server.
123
124.. function:: RAND_status()
125
126 Returns True if the SSL pseudo-random number generator has been
127 seeded with 'enough' randomness, and False otherwise. You can use
128 :func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness
129 of the pseudo-random number generator.
130
131.. function:: RAND_egd(path)
132
133 If you are running an entropy-gathering daemon (EGD) somewhere, and ``path``
134 is the pathname of a socket connection open to it, this will read
135 256 bytes of randomness from the socket, and add it to the SSL pseudo-random number generator
136 to increase the security of generated secret keys. This is typically only
137 necessary on systems without better sources of randomness.
138
139 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000140 sources of entropy-gathering daemons.
Bill Janssen98d19da2007-09-10 21:51:02 +0000141
142.. function:: RAND_add(bytes, entropy)
143
144 Mixes the given ``bytes`` into the SSL pseudo-random number generator.
145 The parameter ``entropy`` (a float) is a lower bound on the entropy
146 contained in string (so you can always use :const:`0.0`).
147 See :rfc:`1750` for more information on sources of entropy.
148
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000149.. function:: cert_time_to_seconds(timestring)
150
151 Returns a floating-point value containing a normal seconds-after-the-epoch time
152 value, given the time-string representing the "notBefore" or "notAfter" date
153 from a certificate.
154
155 Here's an example::
156
157 >>> import ssl
158 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
159 1178694000.0
160 >>> import time
161 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
162 'Wed May 9 00:00:00 2007'
163 >>>
164
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000165.. data:: CERT_NONE
166
Bill Janssen426ea0a2007-08-29 22:35:05 +0000167 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000168 when no certificates will be required or validated from the other
169 side of the socket connection.
170
171.. data:: CERT_OPTIONAL
172
Bill Janssen426ea0a2007-08-29 22:35:05 +0000173 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000174 when no certificates will be required from the other side of the
175 socket connection, but if they are provided, will be validated.
176 Note that use of this setting requires a valid certificate
Bill Janssen426ea0a2007-08-29 22:35:05 +0000177 validation file also be passed as a value of the ``ca_certs``
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000178 parameter.
179
180.. data:: CERT_REQUIRED
181
Bill Janssen426ea0a2007-08-29 22:35:05 +0000182 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000183 when certificates will be required from the other side of the
184 socket connection. Note that use of this setting requires a valid certificate
Bill Janssen426ea0a2007-08-29 22:35:05 +0000185 validation file also be passed as a value of the ``ca_certs``
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000186 parameter.
187
188.. data:: PROTOCOL_SSLv2
189
190 Selects SSL version 2 as the channel encryption protocol.
191
192.. data:: PROTOCOL_SSLv23
193
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000194 Selects SSL version 2 or 3 as the channel encryption protocol.
195 This is a setting to use with servers for maximum compatibility
196 with the other end of an SSL connection, but it may cause the
197 specific ciphers chosen for the encryption to be of fairly low
198 quality.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000199
200.. data:: PROTOCOL_SSLv3
201
202 Selects SSL version 3 as the channel encryption protocol.
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000203 For clients, this is the maximally compatible SSL variant.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000204
205.. data:: PROTOCOL_TLSv1
206
207 Selects SSL version 2 as the channel encryption protocol. This is
208 the most modern version, and probably the best choice for maximum
209 protection, if both sides can speak it.
210
211
Bill Janssen98d19da2007-09-10 21:51:02 +0000212SSLSocket Objects
213-----------------
214
215.. method:: SSLSocket.read([nbytes=1024])
216
217 Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them.
218
219.. method:: SSLSocket.write(data)
220
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000221 Writes the ``data`` to the other side of the connection, using the
222 SSL channel to encrypt. Returns the number of bytes written.
Bill Janssen98d19da2007-09-10 21:51:02 +0000223
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000224.. method:: SSLSocket.getpeercert(binary_form=False)
Bill Janssen98d19da2007-09-10 21:51:02 +0000225
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000226 If there is no certificate for the peer on the other end of the
227 connection, returns ``None``.
Bill Janssen98d19da2007-09-10 21:51:02 +0000228
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000229 If the the parameter ``binary_form`` is :const:`False`, and a
230 certificate was received from the peer, this method returns a
231 :class:`dict` instance. If the certificate was not validated, the
232 dict is empty. If the certificate was validated, it returns a dict
233 with the keys ``subject`` (the principal for which the certificate
234 was issued), and ``notAfter`` (the time after which the certificate
235 should not be trusted). The certificate was already validated, so
236 the ``notBefore`` and ``issuer`` fields are not returned. If a
237 certificate contains an instance of the *Subject Alternative Name*
238 extension (see :rfc:`3280`), there will also be a
239 ``subjectAltName`` key in the dictionary.
240
241 The "subject" field is a tuple containing the sequence of relative
242 distinguished names (RDNs) given in the certificate's data
243 structure for the principal, and each RDN is a sequence of
244 name-value pairs::
Bill Janssen98d19da2007-09-10 21:51:02 +0000245
246 {'notAfter': 'Feb 16 16:54:50 2013 GMT',
247 'subject': ((('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
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000254 If the ``binary_form`` parameter is :const:`True`, and a
255 certificate was provided, this method returns the DER-encoded form
256 of the entire certificate as a sequence of bytes. Note that this
257 binary certificate may not be valid.
Bill Janssen98d19da2007-09-10 21:51:02 +0000258
259.. method:: SSLSocket.cipher()
260
261 Returns a three-value tuple containing the name of the cipher being
262 used, the version of the SSL protocol that defines its use, and the
263 number of secret bits being used. If no connection has been
264 established, returns ``None``.
265
266.. method:: SSLSocket.ssl_shutdown()
267
268 Closes the SSL context (if any) over the socket, but leaves the socket connection
269 open for further use, if both sides are willing. This is different from :meth:`socket.socket.shutdown`,
270 which will close the connection, but leave the local socket available for further use.
271
272
273.. index:: single: certificates
274
275.. index:: single: X509 certificate
276
Bill Janssen93bf9ce2007-09-11 02:42:07 +0000277.. _ssl-certificates:
278
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000279Certificates
280------------
281
Bill Janssen426ea0a2007-08-29 22:35:05 +0000282Certificates in general are part of a public-key / private-key system. In this system, each *principal*,
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000283(which may be a machine, or a person, or an organization) is assigned a unique two-part encryption key.
284One part of the key is public, and is called the *public key*; the other part is kept secret, and is called
285the *private key*. The two parts are related, in that if you encrypt a message with one of the parts, you can
286decrypt it with the other part, and **only** with the other part.
287
288A certificate contains information about two principals. It contains
289the name of a *subject*, and the subject's public key. It also
290contains a statement by a second principal, the *issuer*, that the
291subject is who he claims to be, and that this is indeed the subject's
292public key. The issuer's statement is signed with the issuer's
293private key, which only the issuer knows. However, anyone can verify
294the issuer's statement by finding the issuer's public key, decrypting
295the statement with it, and comparing it to the other information in
296the certificate. The certificate also contains information about the
297time period over which it is valid. This is expressed as two fields,
298called "notBefore" and "notAfter".
299
Bill Janssen426ea0a2007-08-29 22:35:05 +0000300In the Python use of certificates, a client or server
301can use a certificate to prove who they are. The other
302side of a network connection can also be required to produce a certificate,
303and that certificate can be validated to the satisfaction
304of the client or server that requires such validation.
Bill Janssen98d19da2007-09-10 21:51:02 +0000305The connection attempt can be set to raise an exception if
306the validation fails. Validation is done
307automatically, by the underlying OpenSSL framework; the
308application need not concern itself with its mechanics.
309But the application does usually need to provide
310sets of certificates to allow this process to take place.
Bill Janssen426ea0a2007-08-29 22:35:05 +0000311
312Python uses files to contain certificates. They should be formatted
313as "PEM" (see :rfc:`1422`), which is a base-64 encoded form wrapped
314with a header line and a footer line::
315
316 -----BEGIN CERTIFICATE-----
317 ... (certificate in base64 PEM encoding) ...
318 -----END CERTIFICATE-----
319
320The Python files which contain certificates can contain a sequence
321of certificates, sometimes called a *certificate chain*. This chain
322should start with the specific certificate for the principal who "is"
323the client or server, and then the certificate for the issuer of that
324certificate, and then the certificate for the issuer of *that* certificate,
325and so on up the chain till you get to a certificate which is *self-signed*,
326that is, a certificate which has the same subject and issuer,
327sometimes called a *root certificate*. The certificates should just
328be concatenated together in the certificate file. For example, suppose
329we had a three certificate chain, from our server certificate to the
330certificate of the certification authority that signed our server certificate,
331to the root certificate of the agency which issued the certification authority's
332certificate::
333
334 -----BEGIN CERTIFICATE-----
335 ... (certificate for your server)...
336 -----END CERTIFICATE-----
337 -----BEGIN CERTIFICATE-----
338 ... (the certificate for the CA)...
339 -----END CERTIFICATE-----
340 -----BEGIN CERTIFICATE-----
341 ... (the root certificate for the CA's issuer)...
342 -----END CERTIFICATE-----
343
344If you are going to require validation of the other side of the connection's
345certificate, you need to provide a "CA certs" file, filled with the certificate
346chains for each issuer you are willing to trust. Again, this file just
347contains these chains concatenated together. For validation, Python will
348use the first chain it finds in the file which matches.
Bill Janssen98d19da2007-09-10 21:51:02 +0000349Some "standard" root certificates are available from various certification
350authorities:
351`CACert.org <http://www.cacert.org/index.php?id=3>`_,
352`Thawte <http://www.thawte.com/roots/>`_,
353`Verisign <http://www.verisign.com/support/roots.html>`_,
354`Equifax and GeoTrust <http://www.geotrust.com/resources/root_certificates/index.asp>`_.
355
356In general, if you are using
357SSL3 or TLS1, you don't need to put the full chain in your "CA certs" file;
358you only need the root certificates, and the remote peer is supposed to
359furnish the other certificates necessary to chain from its certificate to
360a root certificate.
361See :rfc:`4158` for more discussion of the way in which
Bill Janssenffe576d2007-09-05 00:46:27 +0000362certification chains can be built.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000363
Bill Janssen98d19da2007-09-10 21:51:02 +0000364If you are going to create a server that provides SSL-encrypted
365connection services, you will need to acquire a certificate for that
366service. There are many ways of acquiring appropriate certificates,
367such as buying one from a certification authority. Another common
368practice is to generate a self-signed certificate. The simplest
369way to do this is with the OpenSSL package, using something like
370the following::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000371
Bill Janssen98d19da2007-09-10 21:51:02 +0000372 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
373 Generating a 1024 bit RSA private key
374 .......++++++
375 .............................++++++
376 writing new private key to 'cert.pem'
377 -----
378 You are about to be asked to enter information that will be incorporated
379 into your certificate request.
380 What you are about to enter is what is called a Distinguished Name or a DN.
381 There are quite a few fields but you can leave some blank
382 For some fields there will be a default value,
383 If you enter '.', the field will be left blank.
384 -----
385 Country Name (2 letter code) [AU]:US
386 State or Province Name (full name) [Some-State]:MyState
387 Locality Name (eg, city) []:Some City
388 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
389 Organizational Unit Name (eg, section) []:My Group
390 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
391 Email Address []:ops@myserver.mygroup.myorganization.com
392 %
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000393
Bill Janssen98d19da2007-09-10 21:51:02 +0000394The disadvantage of a self-signed certificate is that it is its
395own root certificate, and no one else will have it in their cache
396of known (and trusted) root certificates.
Bill Janssen426ea0a2007-08-29 22:35:05 +0000397
398
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000399Examples
400--------
401
Bill Janssen426ea0a2007-08-29 22:35:05 +0000402Testing for SSL support
403^^^^^^^^^^^^^^^^^^^^^^^
404
405To test for the presence of SSL support in a Python installation, user code should use the following idiom::
406
407 try:
408 import ssl
409 except ImportError:
410 pass
411 else:
412 [ do something that requires SSL support ]
413
414Client-side operation
415^^^^^^^^^^^^^^^^^^^^^
416
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000417This example connects to an SSL server, prints the server's address and certificate,
418sends some bytes, and reads part of the response::
419
420 import socket, ssl, pprint
421
422 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Bill Janssen98d19da2007-09-10 21:51:02 +0000423
424 # require a certificate from the server
425 ssl_sock = ssl.wrap_socket(s,
426 ca_certs="/etc/ca_certs_file",
427 cert_reqs=ssl.CERT_REQUIRED)
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000428
429 ssl_sock.connect(('www.verisign.com', 443))
430
431 print repr(ssl_sock.getpeername())
Bill Janssen98d19da2007-09-10 21:51:02 +0000432 print ssl_sock.cipher()
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000433 print pprint.pformat(ssl_sock.getpeercert())
434
435 # Set a simple HTTP request -- use httplib in actual code.
436 ssl_sock.write("""GET / HTTP/1.0\r
437 Host: www.verisign.com\r\n\r\n""")
438
439 # Read a chunk of data. Will not necessarily
440 # read all the data returned by the server.
441 data = ssl_sock.read()
442
Bill Janssen98d19da2007-09-10 21:51:02 +0000443 # note that closing the SSLSocket will also close the underlying socket
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000444 ssl_sock.close()
445
Bill Janssen98d19da2007-09-10 21:51:02 +0000446As of September 6, 2007, the certificate printed by this program
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000447looked like this::
448
Bill Janssen98d19da2007-09-10 21:51:02 +0000449 {'notAfter': 'May 8 23:59:59 2009 GMT',
450 'subject': ((('serialNumber', u'2497886'),),
451 (('1.3.6.1.4.1.311.60.2.1.3', u'US'),),
452 (('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),),
453 (('countryName', u'US'),),
454 (('postalCode', u'94043'),),
455 (('stateOrProvinceName', u'California'),),
456 (('localityName', u'Mountain View'),),
457 (('streetAddress', u'487 East Middlefield Road'),),
458 (('organizationName', u'VeriSign, Inc.'),),
459 (('organizationalUnitName',
460 u'Production Security Services'),),
461 (('organizationalUnitName',
462 u'Terms of use at www.verisign.com/rpa (c)06'),),
463 (('commonName', u'www.verisign.com'),))}
464
465which is a fairly poorly-formed ``subject`` field.
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000466
Bill Janssen426ea0a2007-08-29 22:35:05 +0000467Server-side operation
468^^^^^^^^^^^^^^^^^^^^^
469
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000470For server operation, typically you'd need to have a server certificate, and private key, each in a file.
471You'd open a socket, bind it to a port, call :meth:`listen` on it, then start waiting for clients
472to connect::
473
474 import socket, ssl
475
476 bindsocket = socket.socket()
477 bindsocket.bind(('myaddr.mydomain.com', 10023))
478 bindsocket.listen(5)
479
480When 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 +0000481end, and use :func:`wrap_socket` to create a server-side SSL context for it::
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000482
483 while True:
484 newsocket, fromaddr = bindsocket.accept()
Bill Janssen98d19da2007-09-10 21:51:02 +0000485 connstream = ssl.wrap_socket(newsocket,
486 server_side=True,
487 certfile="mycertfile",
488 keyfile="mykeyfile",
489 ssl_protocol=ssl.PROTOCOL_TLSv1)
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000490 deal_with_client(connstream)
491
Bill Janssen426ea0a2007-08-29 22:35:05 +0000492Then 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 +0000493
494 def deal_with_client(connstream):
495
496 data = connstream.read()
497 # null data means the client is finished with us
498 while data:
499 if not do_something(connstream, data):
Bill Janssen98d19da2007-09-10 21:51:02 +0000500 # we'll assume do_something returns False
501 # when we're finished with client
Guido van Rossum8ee23bb2007-08-27 19:11:11 +0000502 break
503 data = connstream.read()
504 # finished with client
505 connstream.close()
506
507And go back to listening for new client connections.
508
509
Bill Janssen98d19da2007-09-10 21:51:02 +0000510.. seealso::
Bill Janssen426ea0a2007-08-29 22:35:05 +0000511
Bill Janssen98d19da2007-09-10 21:51:02 +0000512 Class :class:`socket.socket`
513 Documentation of underlying :mod:`socket` class
Bill Janssen426ea0a2007-08-29 22:35:05 +0000514
Bill Janssen98d19da2007-09-10 21:51:02 +0000515 `Introducing SSL and Certificates using OpenSSL <http://old.pseudonym.org/ssl/wwwj-index.html>`_
516 Frederick J. Hirsch
Bill Janssen426ea0a2007-08-29 22:35:05 +0000517
Bill Janssen98d19da2007-09-10 21:51:02 +0000518 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
519 Steve Kent
Bill Janssen426ea0a2007-08-29 22:35:05 +0000520
Bill Janssen98d19da2007-09-10 21:51:02 +0000521 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
522 D. Eastlake et. al.
Bill Janssenffe576d2007-09-05 00:46:27 +0000523
Bill Janssen98d19da2007-09-10 21:51:02 +0000524 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
525 Housley et. al.