blob: b6a7f46fb75aa78b8665f389ac57d65b5d1188d7 [file] [log] [blame]
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001:mod:`ssl` --- SSL wrapper for socket objects
Georg Brandl7f01a132009-09-16 15:58:14 +00002=============================================
Thomas Woutersed03b412007-08-28 21:37:11 +00003
4.. module:: ssl
Thomas Wouters47b49bf2007-08-30 22:15:33 +00005 :synopsis: SSL wrapper for socket objects
6
7.. moduleauthor:: Bill Janssen <bill.janssen@gmail.com>
Thomas Wouters47b49bf2007-08-30 22:15:33 +00008.. sectionauthor:: Bill Janssen <bill.janssen@gmail.com>
9
Thomas Woutersed03b412007-08-28 21:37:11 +000010
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011.. index:: single: OpenSSL; (use in module ssl)
12
13.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
14
Georg Brandl7f01a132009-09-16 15:58:14 +000015This module provides access to Transport Layer Security (often known as "Secure
16Sockets Layer") encryption and peer authentication facilities for network
17sockets, both client-side and server-side. This module uses the OpenSSL
18library. It is available on all modern Unix systems, Windows, Mac OS X, and
19probably additional platforms, as long as OpenSSL is installed on that platform.
Thomas Woutersed03b412007-08-28 21:37:11 +000020
21.. note::
22
Georg Brandl7f01a132009-09-16 15:58:14 +000023 Some behavior may be platform dependent, since calls are made to the
24 operating system socket APIs. The installed version of OpenSSL may also
25 cause variations in behavior.
Thomas Woutersed03b412007-08-28 21:37:11 +000026
Georg Brandl7f01a132009-09-16 15:58:14 +000027This section documents the objects and functions in the ``ssl`` module; for more
28general information about TLS, SSL, and certificates, the reader is referred to
29the documents in the "See Also" section at the bottom.
Thomas Woutersed03b412007-08-28 21:37:11 +000030
Georg Brandl7f01a132009-09-16 15:58:14 +000031This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
32:class:`socket.socket` type, and provides a socket-like wrapper that also
33encrypts and decrypts the data going over the socket with SSL. It supports
Antoine Pitroudab64262010-09-19 13:31:06 +000034additional methods such as :meth:`getpeercert`, which retrieves the
35certificate of the other side of the connection, and :meth:`cipher`,which
36retrieves the cipher being used for the secure connection.
Thomas Woutersed03b412007-08-28 21:37:11 +000037
Antoine Pitrou152efa22010-05-16 18:19:27 +000038For more sophisticated applications, the :class:`ssl.SSLContext` class
39helps manage settings and certificates, which can then be inherited
40by SSL sockets created through the :meth:`SSLContext.wrap_socket` method.
41
42
Thomas Wouters1b7f8912007-09-19 03:06:30 +000043Functions, Constants, and Exceptions
44------------------------------------
45
46.. exception:: SSLError
47
Georg Brandl48310cd2009-01-03 21:18:54 +000048 Raised to signal an error from the underlying SSL implementation. This
Georg Brandl7f01a132009-09-16 15:58:14 +000049 signifies some problem in the higher-level encryption and authentication
50 layer that's superimposed on the underlying network connection. This error
51 is a subtype of :exc:`socket.error`, which in turn is a subtype of
52 :exc:`IOError`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000053
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +000054.. function:: wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000055
Georg Brandl7f01a132009-09-16 15:58:14 +000056 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
57 of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
58 the underlying socket in an SSL context. For client-side sockets, the
59 context construction is lazy; if the underlying socket isn't connected yet,
60 the context construction will be performed after :meth:`connect` is called on
61 the socket. For server-side sockets, if the socket has no remote peer, it is
62 assumed to be a listening socket, and the server-side SSL wrapping is
63 automatically performed on client connections accepted via the :meth:`accept`
64 method. :func:`wrap_socket` may raise :exc:`SSLError`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000065
Georg Brandl7f01a132009-09-16 15:58:14 +000066 The ``keyfile`` and ``certfile`` parameters specify optional files which
67 contain a certificate to be used to identify the local side of the
68 connection. See the discussion of :ref:`ssl-certificates` for more
69 information on how the certificate is stored in the ``certfile``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000070
Georg Brandl7f01a132009-09-16 15:58:14 +000071 The parameter ``server_side`` is a boolean which identifies whether
72 server-side or client-side behavior is desired from this socket.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000073
Georg Brandl7f01a132009-09-16 15:58:14 +000074 The parameter ``cert_reqs`` specifies whether a certificate is required from
75 the other side of the connection, and whether it will be validated if
76 provided. It must be one of the three values :const:`CERT_NONE`
77 (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
78 if provided), or :const:`CERT_REQUIRED` (required and validated). If the
79 value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
80 parameter must point to a file of CA certificates.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000081
Georg Brandl7f01a132009-09-16 15:58:14 +000082 The ``ca_certs`` file contains a set of concatenated "certification
83 authority" certificates, which are used to validate certificates passed from
84 the other end of the connection. See the discussion of
85 :ref:`ssl-certificates` for more information about how to arrange the
86 certificates in this file.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000087
Georg Brandl7f01a132009-09-16 15:58:14 +000088 The parameter ``ssl_version`` specifies which version of the SSL protocol to
89 use. Typically, the server chooses a particular protocol version, and the
90 client must adapt to the server's choice. Most of the versions are not
91 interoperable with the other versions. If not specified, for client-side
92 operation, the default SSL version is SSLv3; for server-side operation,
93 SSLv23. These version selections provide the most compatibility with other
94 versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000095
Georg Brandl7f01a132009-09-16 15:58:14 +000096 Here's a table showing which versions in a client (down the side) can connect
97 to which versions in a server (along the top):
Thomas Wouters1b7f8912007-09-19 03:06:30 +000098
99 .. table::
100
101 ======================== ========= ========= ========== =========
102 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1**
Christian Heimes255f53b2007-12-08 15:33:56 +0000103 ------------------------ --------- --------- ---------- ---------
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000104 *SSLv2* yes no yes no
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000105 *SSLv3* yes yes yes no
106 *SSLv23* yes no yes no
107 *TLSv1* no no yes yes
108 ======================== ========= ========= ========== =========
109
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000110 .. note::
111
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000112 Which connections succeed will vary depending on the version of
113 OpenSSL. For instance, in some older versions of OpenSSL (such
114 as 0.9.7l on OS X 10.4), an SSLv2 client could not connect to an
115 SSLv23 server. Another example: beginning with OpenSSL 1.0.0,
116 an SSLv23 client will not actually attempt SSLv2 connections
117 unless you explicitly enable SSLv2 ciphers; for example, you
118 might specify ``"ALL"`` or ``"SSLv2"`` as the *ciphers* parameter
119 to enable them.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000120
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000121 The *ciphers* parameter sets the available ciphers for this SSL object.
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000122 It should be a string in the `OpenSSL cipher list format
123 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000124
Bill Janssen48dc27c2007-12-05 03:38:10 +0000125 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
126 handshake automatically after doing a :meth:`socket.connect`, or whether the
Georg Brandl7f01a132009-09-16 15:58:14 +0000127 application program will call it explicitly, by invoking the
128 :meth:`SSLSocket.do_handshake` method. Calling
129 :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
130 blocking behavior of the socket I/O involved in the handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000131
Georg Brandl7f01a132009-09-16 15:58:14 +0000132 The parameter ``suppress_ragged_eofs`` specifies how the
Antoine Pitroudab64262010-09-19 13:31:06 +0000133 :meth:`SSLSocket.recv` method should signal unexpected EOF from the other end
Georg Brandl7f01a132009-09-16 15:58:14 +0000134 of the connection. If specified as :const:`True` (the default), it returns a
Antoine Pitroudab64262010-09-19 13:31:06 +0000135 normal EOF (an empty bytes object) in response to unexpected EOF errors
136 raised from the underlying socket; if :const:`False`, it will raise the
137 exceptions back to the caller.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000138
Ezio Melotti4d5195b2010-04-20 10:57:44 +0000139 .. versionchanged:: 3.2
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000140 New optional argument *ciphers*.
141
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000142.. function:: RAND_status()
143
Georg Brandl7f01a132009-09-16 15:58:14 +0000144 Returns True if the SSL pseudo-random number generator has been seeded with
145 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
146 and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
147 number generator.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000148
149.. function:: RAND_egd(path)
150
151 If you are running an entropy-gathering daemon (EGD) somewhere, and ``path``
Georg Brandl7f01a132009-09-16 15:58:14 +0000152 is the pathname of a socket connection open to it, this will read 256 bytes
153 of randomness from the socket, and add it to the SSL pseudo-random number
154 generator to increase the security of generated secret keys. This is
155 typically only necessary on systems without better sources of randomness.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000156
Georg Brandl7f01a132009-09-16 15:58:14 +0000157 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
158 of entropy-gathering daemons.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000159
160.. function:: RAND_add(bytes, entropy)
161
Georg Brandl7f01a132009-09-16 15:58:14 +0000162 Mixes the given ``bytes`` into the SSL pseudo-random number generator. The
163 parameter ``entropy`` (a float) is a lower bound on the entropy contained in
164 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
165 information on sources of entropy.
Thomas Woutersed03b412007-08-28 21:37:11 +0000166
167.. function:: cert_time_to_seconds(timestring)
168
Georg Brandl7f01a132009-09-16 15:58:14 +0000169 Returns a floating-point value containing a normal seconds-after-the-epoch
170 time value, given the time-string representing the "notBefore" or "notAfter"
171 date from a certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000172
173 Here's an example::
174
175 >>> import ssl
176 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
177 1178694000.0
178 >>> import time
179 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
180 'Wed May 9 00:00:00 2007'
Georg Brandl48310cd2009-01-03 21:18:54 +0000181 >>>
Thomas Woutersed03b412007-08-28 21:37:11 +0000182
Georg Brandl7f01a132009-09-16 15:58:14 +0000183.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000184
Georg Brandl7f01a132009-09-16 15:58:14 +0000185 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
186 *port-number*) pair, fetches the server's certificate, and returns it as a
187 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
188 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
189 specified, it should be a file containing a list of root certificates, the
190 same format as used for the same parameter in :func:`wrap_socket`. The call
191 will attempt to validate the server certificate against that set of root
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000192 certificates, and will fail if the validation attempt fails.
193
Georg Brandl7f01a132009-09-16 15:58:14 +0000194.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000195
196 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
197 string version of the same certificate.
198
Georg Brandl7f01a132009-09-16 15:58:14 +0000199.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000200
Georg Brandl7f01a132009-09-16 15:58:14 +0000201 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
202 bytes for that same certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000203
204.. data:: CERT_NONE
205
Antoine Pitrou152efa22010-05-16 18:19:27 +0000206 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
207 parameter to :func:`wrap_socket`. In this mode (the default), no
208 certificates will be required from the other side of the socket connection.
209 If a certificate is received from the other end, no attempt to validate it
210 is made.
211
212 See the discussion of :ref:`ssl-security` below.
Thomas Woutersed03b412007-08-28 21:37:11 +0000213
214.. data:: CERT_OPTIONAL
215
Antoine Pitrou152efa22010-05-16 18:19:27 +0000216 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
217 parameter to :func:`wrap_socket`. In this mode no certificates will be
218 required from the other side of the socket connection; but if they
219 are provided, validation will be attempted and an :class:`SSLError`
220 will be raised on failure.
221
222 Use of this setting requires a valid set of CA certificates to
223 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
224 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000225
226.. data:: CERT_REQUIRED
227
Antoine Pitrou152efa22010-05-16 18:19:27 +0000228 Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
229 parameter to :func:`wrap_socket`. In this mode, certificates are
230 required from the other side of the socket connection; an :class:`SSLError`
231 will be raised if no certificate is provided, or if its validation fails.
232
233 Use of this setting requires a valid set of CA certificates to
234 be passed, either to :meth:`SSLContext.load_verify_locations` or as a
235 value of the ``ca_certs`` parameter to :func:`wrap_socket`.
Thomas Woutersed03b412007-08-28 21:37:11 +0000236
237.. data:: PROTOCOL_SSLv2
238
239 Selects SSL version 2 as the channel encryption protocol.
240
Antoine Pitrou8eac60d2010-05-16 14:19:41 +0000241 .. warning::
242
243 SSL version 2 is insecure. Its use is highly discouraged.
244
Thomas Woutersed03b412007-08-28 21:37:11 +0000245.. data:: PROTOCOL_SSLv23
246
Georg Brandl7f01a132009-09-16 15:58:14 +0000247 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
248 setting to use with servers for maximum compatibility with the other end of
249 an SSL connection, but it may cause the specific ciphers chosen for the
250 encryption to be of fairly low quality.
Thomas Woutersed03b412007-08-28 21:37:11 +0000251
252.. data:: PROTOCOL_SSLv3
253
Georg Brandl7f01a132009-09-16 15:58:14 +0000254 Selects SSL version 3 as the channel encryption protocol. For clients, this
255 is the maximally compatible SSL variant.
Thomas Woutersed03b412007-08-28 21:37:11 +0000256
257.. data:: PROTOCOL_TLSv1
258
Georg Brandl7f01a132009-09-16 15:58:14 +0000259 Selects TLS version 1 as the channel encryption protocol. This is the most
260 modern version, and probably the best choice for maximum protection, if both
261 sides can speak it.
Thomas Woutersed03b412007-08-28 21:37:11 +0000262
Antoine Pitroub5218772010-05-21 09:56:06 +0000263.. data:: OP_ALL
264
265 Enables workarounds for various bugs present in other SSL implementations.
266 This option is set by default.
267
268 .. versionadded:: 3.2
269
270.. data:: OP_NO_SSLv2
271
272 Prevents an SSLv2 connection. This option is only applicable in
273 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
274 choosing SSLv2 as the protocol version.
275
276 .. versionadded:: 3.2
277
278.. data:: OP_NO_SSLv3
279
280 Prevents an SSLv3 connection. This option is only applicable in
281 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
282 choosing SSLv3 as the protocol version.
283
284 .. versionadded:: 3.2
285
286.. data:: OP_NO_TLSv1
287
288 Prevents a TLSv1 connection. This option is only applicable in
289 conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
290 choosing TLSv1 as the protocol version.
291
292 .. versionadded:: 3.2
293
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000294.. data:: OPENSSL_VERSION
295
296 The version string of the OpenSSL library loaded by the interpreter::
297
298 >>> ssl.OPENSSL_VERSION
299 'OpenSSL 0.9.8k 25 Mar 2009'
300
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000301 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000302
303.. data:: OPENSSL_VERSION_INFO
304
305 A tuple of five integers representing version information about the
306 OpenSSL library::
307
308 >>> ssl.OPENSSL_VERSION_INFO
309 (0, 9, 8, 11, 15)
310
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000311 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000312
313.. data:: OPENSSL_VERSION_NUMBER
314
315 The raw version number of the OpenSSL library, as a single integer::
316
317 >>> ssl.OPENSSL_VERSION_NUMBER
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000318 9470143
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000319 >>> hex(ssl.OPENSSL_VERSION_NUMBER)
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000320 '0x9080bf'
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000321
Antoine Pitrou43a94c312010-04-05 21:44:48 +0000322 .. versionadded:: 3.2
Antoine Pitrou04f6a322010-04-05 21:40:07 +0000323
Thomas Woutersed03b412007-08-28 21:37:11 +0000324
Antoine Pitrou152efa22010-05-16 18:19:27 +0000325SSL Sockets
326-----------
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000327
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000328SSL sockets provide the basic interface of :ref:`socket-objects`. However,
329not all functionality is supported (for example, passing a non-zero ``flags``
Antoine Pitroudab64262010-09-19 13:31:06 +0000330argument to :meth:`~socket.socket.recv()` is not allowed).
Antoine Pitrou792ff3e2010-09-19 13:19:21 +0000331
332SSL sockets also have the following additional methods and attributes:
333
Bill Janssen48dc27c2007-12-05 03:38:10 +0000334.. method:: SSLSocket.do_handshake()
335
Georg Brandl7f01a132009-09-16 15:58:14 +0000336 Performs the SSL setup handshake. If the socket is non-blocking, this method
337 may raise :exc:`SSLError` with the value of the exception instance's
338 ``args[0]`` being either :const:`SSL_ERROR_WANT_READ` or
339 :const:`SSL_ERROR_WANT_WRITE`, and should be called again until it stops
340 raising those exceptions. Here's an example of how to do that::
Bill Janssen48dc27c2007-12-05 03:38:10 +0000341
342 while True:
343 try:
344 sock.do_handshake()
345 break
346 except ssl.SSLError as err:
347 if err.args[0] == ssl.SSL_ERROR_WANT_READ:
348 select.select([sock], [], [])
349 elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
350 select.select([], [sock], [])
351 else:
352 raise
353
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000354.. method:: SSLSocket.getpeercert(binary_form=False)
355
Georg Brandl7f01a132009-09-16 15:58:14 +0000356 If there is no certificate for the peer on the other end of the connection,
357 returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000358
Georg Brandl7f01a132009-09-16 15:58:14 +0000359 If the parameter ``binary_form`` is :const:`False`, and a certificate was
360 received from the peer, this method returns a :class:`dict` instance. If the
361 certificate was not validated, the dict is empty. If the certificate was
362 validated, it returns a dict with the keys ``subject`` (the principal for
363 which the certificate was issued), and ``notAfter`` (the time after which the
364 certificate should not be trusted). The certificate was already validated,
365 so the ``notBefore`` and ``issuer`` fields are not returned. If a
366 certificate contains an instance of the *Subject Alternative Name* extension
367 (see :rfc:`3280`), there will also be a ``subjectAltName`` key in the
368 dictionary.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000369
370 The "subject" field is a tuple containing the sequence of relative
Georg Brandl7f01a132009-09-16 15:58:14 +0000371 distinguished names (RDNs) given in the certificate's data structure for the
372 principal, and each RDN is a sequence of name-value pairs::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000373
374 {'notAfter': 'Feb 16 16:54:50 2013 GMT',
Ezio Melotti985e24d2009-09-13 07:54:02 +0000375 'subject': ((('countryName', 'US'),),
376 (('stateOrProvinceName', 'Delaware'),),
377 (('localityName', 'Wilmington'),),
378 (('organizationName', 'Python Software Foundation'),),
379 (('organizationalUnitName', 'SSL'),),
380 (('commonName', 'somemachine.python.org'),))}
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000381
Georg Brandl7f01a132009-09-16 15:58:14 +0000382 If the ``binary_form`` parameter is :const:`True`, and a certificate was
383 provided, this method returns the DER-encoded form of the entire certificate
384 as a sequence of bytes, or :const:`None` if the peer did not provide a
385 certificate. This return value is independent of validation; if validation
386 was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000387 been validated, but if :const:`CERT_NONE` was used to establish the
388 connection, the certificate, if present, will not have been validated.
389
390.. method:: SSLSocket.cipher()
391
Georg Brandl7f01a132009-09-16 15:58:14 +0000392 Returns a three-value tuple containing the name of the cipher being used, the
393 version of the SSL protocol that defines its use, and the number of secret
394 bits being used. If no connection has been established, returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000395
396
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000397.. method:: SSLSocket.unwrap()
398
Georg Brandl7f01a132009-09-16 15:58:14 +0000399 Performs the SSL shutdown handshake, which removes the TLS layer from the
400 underlying socket, and returns the underlying socket object. This can be
401 used to go from encrypted operation over a connection to unencrypted. The
402 returned socket should always be used for further communication with the
403 other side of the connection, rather than the original socket.
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000404
Antoine Pitrou152efa22010-05-16 18:19:27 +0000405
Antoine Pitrouec883db2010-05-24 21:20:20 +0000406.. attribute:: SSLSocket.context
407
408 The :class:`SSLContext` object this SSL socket is tied to. If the SSL
409 socket was created using the top-level :func:`wrap_socket` function
410 (rather than :meth:`SSLContext.wrap_socket`), this is a custom context
411 object created for this SSL socket.
412
413 .. versionadded:: 3.2
414
415
Antoine Pitrou152efa22010-05-16 18:19:27 +0000416SSL Contexts
417------------
418
Antoine Pitroucafaad42010-05-24 15:58:43 +0000419.. versionadded:: 3.2
420
Antoine Pitrou152efa22010-05-16 18:19:27 +0000421.. class:: SSLContext(protocol)
422
423 An object holding various data longer-lived than single SSL connections,
424 such as SSL configuration options, certificate(s) and private key(s).
425 You must pass *protocol* which must be one of the ``PROTOCOL_*`` constants
426 defined in this module. :data:`PROTOCOL_SSLv23` is recommended for
427 maximum interoperability.
428
429:class:`SSLContext` objects have the following methods and attributes:
430
431.. method:: SSLContext.load_cert_chain(certfile, keyfile=None)
432
433 Load a private key and the corresponding certificate. The *certfile*
434 string must be the path to a single file in PEM format containing the
435 certificate as well as any number of CA certificates needed to establish
436 the certificate's authenticity. The *keyfile* string, if present, must
437 point to a file containing the private key in. Otherwise the private
438 key will be taken from *certfile* as well. See the discussion of
439 :ref:`ssl-certificates` for more information on how the certificate
440 is stored in the *certfile*.
441
442 An :class:`SSLError` is raised if the private key doesn't
443 match with the certificate.
444
445.. method:: SSLContext.load_verify_locations(cafile=None, capath=None)
446
447 Load a set of "certification authority" (CA) certificates used to validate
448 other peers' certificates when :data:`verify_mode` is other than
449 :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified.
450
451 The *cafile* string, if present, is the path to a file of concatenated
452 CA certificates in PEM format. See the discussion of
453 :ref:`ssl-certificates` for more information about how to arrange the
454 certificates in this file.
455
456 The *capath* string, if present, is
457 the path to a directory containing several CA certificates in PEM format,
458 following an `OpenSSL specific layout
459 <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
460
461.. method:: SSLContext.set_ciphers(ciphers)
462
463 Set the available ciphers for sockets created with this context.
464 It should be a string in the `OpenSSL cipher list format
465 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
466 If no cipher can be selected (because compile-time options or other
467 configuration forbids use of all the specified ciphers), an
468 :class:`SSLError` will be raised.
469
470 .. note::
471 when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
472 give the currently selected cipher.
473
474.. method:: SSLContext.wrap_socket(sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True)
475
476 Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
477 object. The SSL socket is tied to the context, its settings and
478 certificates. The parameters *server_side*, *do_handshake_on_connect*
479 and *suppress_ragged_eofs* have the same meaning as in the top-level
480 :func:`wrap_socket` function.
481
Antoine Pitroub5218772010-05-21 09:56:06 +0000482.. attribute:: SSLContext.options
483
484 An integer representing the set of SSL options enabled on this context.
485 The default value is :data:`OP_ALL`, but you can specify other options
486 such as :data:`OP_NO_SSLv2` by ORing them together.
487
488 .. note::
489 With versions of OpenSSL older than 0.9.8m, it is only possible
490 to set options, not to clear them. Attempting to clear an option
491 (by resetting the corresponding bits) will raise a ``ValueError``.
492
Antoine Pitrou152efa22010-05-16 18:19:27 +0000493.. attribute:: SSLContext.protocol
494
495 The protocol version chosen when constructing the context. This attribute
496 is read-only.
497
498.. attribute:: SSLContext.verify_mode
499
500 Whether to try to verify other peers' certificates and how to behave
501 if verification fails. This attribute must be one of
502 :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.
503
504
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000505.. index:: single: certificates
506
507.. index:: single: X509 certificate
508
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000509.. _ssl-certificates:
510
Thomas Woutersed03b412007-08-28 21:37:11 +0000511Certificates
512------------
513
Georg Brandl7f01a132009-09-16 15:58:14 +0000514Certificates in general are part of a public-key / private-key system. In this
515system, each *principal*, (which may be a machine, or a person, or an
516organization) is assigned a unique two-part encryption key. One part of the key
517is public, and is called the *public key*; the other part is kept secret, and is
518called the *private key*. The two parts are related, in that if you encrypt a
519message with one of the parts, you can decrypt it with the other part, and
520**only** with the other part.
Thomas Woutersed03b412007-08-28 21:37:11 +0000521
Georg Brandl7f01a132009-09-16 15:58:14 +0000522A certificate contains information about two principals. It contains the name
523of a *subject*, and the subject's public key. It also contains a statement by a
524second principal, the *issuer*, that the subject is who he claims to be, and
525that this is indeed the subject's public key. The issuer's statement is signed
526with the issuer's private key, which only the issuer knows. However, anyone can
527verify the issuer's statement by finding the issuer's public key, decrypting the
528statement with it, and comparing it to the other information in the certificate.
529The certificate also contains information about the time period over which it is
530valid. This is expressed as two fields, called "notBefore" and "notAfter".
Thomas Woutersed03b412007-08-28 21:37:11 +0000531
Georg Brandl7f01a132009-09-16 15:58:14 +0000532In the Python use of certificates, a client or server can use a certificate to
533prove who they are. The other side of a network connection can also be required
534to produce a certificate, and that certificate can be validated to the
535satisfaction of the client or server that requires such validation. The
536connection attempt can be set to raise an exception if the validation fails.
537Validation is done automatically, by the underlying OpenSSL framework; the
538application need not concern itself with its mechanics. But the application
539does usually need to provide sets of certificates to allow this process to take
540place.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000541
Georg Brandl7f01a132009-09-16 15:58:14 +0000542Python uses files to contain certificates. They should be formatted as "PEM"
543(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
544and a footer line::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000545
546 -----BEGIN CERTIFICATE-----
547 ... (certificate in base64 PEM encoding) ...
548 -----END CERTIFICATE-----
549
Antoine Pitrou152efa22010-05-16 18:19:27 +0000550Certificate chains
551^^^^^^^^^^^^^^^^^^
552
Georg Brandl7f01a132009-09-16 15:58:14 +0000553The Python files which contain certificates can contain a sequence of
554certificates, sometimes called a *certificate chain*. This chain should start
555with the specific certificate for the principal who "is" the client or server,
556and then the certificate for the issuer of that certificate, and then the
557certificate for the issuer of *that* certificate, and so on up the chain till
558you get to a certificate which is *self-signed*, that is, a certificate which
559has the same subject and issuer, sometimes called a *root certificate*. The
560certificates should just be concatenated together in the certificate file. For
561example, suppose we had a three certificate chain, from our server certificate
562to the certificate of the certification authority that signed our server
563certificate, to the root certificate of the agency which issued the
564certification authority's certificate::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000565
566 -----BEGIN CERTIFICATE-----
567 ... (certificate for your server)...
568 -----END CERTIFICATE-----
569 -----BEGIN CERTIFICATE-----
570 ... (the certificate for the CA)...
571 -----END CERTIFICATE-----
572 -----BEGIN CERTIFICATE-----
573 ... (the root certificate for the CA's issuer)...
574 -----END CERTIFICATE-----
575
Antoine Pitrou152efa22010-05-16 18:19:27 +0000576CA certificates
577^^^^^^^^^^^^^^^
578
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000579If you are going to require validation of the other side of the connection's
580certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandl7f01a132009-09-16 15:58:14 +0000581chains for each issuer you are willing to trust. Again, this file just contains
582these chains concatenated together. For validation, Python will use the first
583chain it finds in the file which matches. Some "standard" root certificates are
584available from various certification authorities: `CACert.org
585<http://www.cacert.org/index.php?id=3>`_, `Thawte
586<http://www.thawte.com/roots/>`_, `Verisign
587<http://www.verisign.com/support/roots.html>`_, `Positive SSL
588<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
589(used by python.org), `Equifax and GeoTrust
590<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000591
Georg Brandl7f01a132009-09-16 15:58:14 +0000592In general, if you are using SSL3 or TLS1, you don't need to put the full chain
593in your "CA certs" file; you only need the root certificates, and the remote
594peer is supposed to furnish the other certificates necessary to chain from its
595certificate to a root certificate. See :rfc:`4158` for more discussion of the
596way in which certification chains can be built.
Thomas Woutersed03b412007-08-28 21:37:11 +0000597
Antoine Pitrou152efa22010-05-16 18:19:27 +0000598Combined key and certificate
599^^^^^^^^^^^^^^^^^^^^^^^^^^^^
600
601Often the private key is stored in the same file as the certificate; in this
602case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain`
603and :func:`wrap_socket` needs to be passed. If the private key is stored
604with the certificate, it should come before the first certificate in
605the certificate chain::
606
607 -----BEGIN RSA PRIVATE KEY-----
608 ... (private key in base64 encoding) ...
609 -----END RSA PRIVATE KEY-----
610 -----BEGIN CERTIFICATE-----
611 ... (certificate in base64 PEM encoding) ...
612 -----END CERTIFICATE-----
613
614Self-signed certificates
615^^^^^^^^^^^^^^^^^^^^^^^^
616
Georg Brandl7f01a132009-09-16 15:58:14 +0000617If you are going to create a server that provides SSL-encrypted connection
618services, you will need to acquire a certificate for that service. There are
619many ways of acquiring appropriate certificates, such as buying one from a
620certification authority. Another common practice is to generate a self-signed
621certificate. The simplest way to do this is with the OpenSSL package, using
622something like the following::
Thomas Woutersed03b412007-08-28 21:37:11 +0000623
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000624 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
625 Generating a 1024 bit RSA private key
626 .......++++++
627 .............................++++++
628 writing new private key to 'cert.pem'
629 -----
630 You are about to be asked to enter information that will be incorporated
631 into your certificate request.
632 What you are about to enter is what is called a Distinguished Name or a DN.
633 There are quite a few fields but you can leave some blank
634 For some fields there will be a default value,
635 If you enter '.', the field will be left blank.
636 -----
637 Country Name (2 letter code) [AU]:US
638 State or Province Name (full name) [Some-State]:MyState
639 Locality Name (eg, city) []:Some City
640 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
641 Organizational Unit Name (eg, section) []:My Group
642 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
643 Email Address []:ops@myserver.mygroup.myorganization.com
644 %
Thomas Woutersed03b412007-08-28 21:37:11 +0000645
Georg Brandl7f01a132009-09-16 15:58:14 +0000646The disadvantage of a self-signed certificate is that it is its own root
647certificate, and no one else will have it in their cache of known (and trusted)
648root certificates.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000649
650
Thomas Woutersed03b412007-08-28 21:37:11 +0000651Examples
652--------
653
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000654Testing for SSL support
655^^^^^^^^^^^^^^^^^^^^^^^
656
Georg Brandl7f01a132009-09-16 15:58:14 +0000657To test for the presence of SSL support in a Python installation, user code
658should use the following idiom::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000659
660 try:
661 import ssl
662 except ImportError:
663 pass
664 else:
665 [ do something that requires SSL support ]
666
667Client-side operation
668^^^^^^^^^^^^^^^^^^^^^
669
Georg Brandl7f01a132009-09-16 15:58:14 +0000670This example connects to an SSL server, prints the server's address and
671certificate, sends some bytes, and reads part of the response::
Thomas Woutersed03b412007-08-28 21:37:11 +0000672
673 import socket, ssl, pprint
674
675 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000676
677 # require a certificate from the server
678 ssl_sock = ssl.wrap_socket(s,
679 ca_certs="/etc/ca_certs_file",
680 cert_reqs=ssl.CERT_REQUIRED)
Thomas Woutersed03b412007-08-28 21:37:11 +0000681
682 ssl_sock.connect(('www.verisign.com', 443))
683
Georg Brandl6911e3c2007-09-04 07:15:32 +0000684 print(repr(ssl_sock.getpeername()))
685 pprint.pprint(ssl_sock.getpeercert())
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000686 print(pprint.pformat(ssl_sock.getpeercert()))
Thomas Woutersed03b412007-08-28 21:37:11 +0000687
Georg Brandl24420152008-05-26 16:32:26 +0000688 # Set a simple HTTP request -- use http.client in actual code.
Antoine Pitroudab64262010-09-19 13:31:06 +0000689 ssl_sock.sendall(b"GET / HTTP/1.0\r\nHost: www.verisign.com\r\n\r\n")
Thomas Woutersed03b412007-08-28 21:37:11 +0000690
691 # Read a chunk of data. Will not necessarily
692 # read all the data returned by the server.
Antoine Pitroudab64262010-09-19 13:31:06 +0000693 data = ssl_sock.recv()
Thomas Woutersed03b412007-08-28 21:37:11 +0000694
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000695 # note that closing the SSLSocket will also close the underlying socket
Thomas Woutersed03b412007-08-28 21:37:11 +0000696 ssl_sock.close()
697
Georg Brandl7f01a132009-09-16 15:58:14 +0000698As of September 6, 2007, the certificate printed by this program looked like
699this::
Thomas Woutersed03b412007-08-28 21:37:11 +0000700
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000701 {'notAfter': 'May 8 23:59:59 2009 GMT',
Ezio Melotti985e24d2009-09-13 07:54:02 +0000702 'subject': ((('serialNumber', '2497886'),),
703 (('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
704 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
705 (('countryName', 'US'),),
706 (('postalCode', '94043'),),
707 (('stateOrProvinceName', 'California'),),
708 (('localityName', 'Mountain View'),),
709 (('streetAddress', '487 East Middlefield Road'),),
710 (('organizationName', 'VeriSign, Inc.'),),
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000711 (('organizationalUnitName',
Ezio Melotti985e24d2009-09-13 07:54:02 +0000712 'Production Security Services'),),
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000713 (('organizationalUnitName',
Ezio Melotti985e24d2009-09-13 07:54:02 +0000714 'Terms of use at www.verisign.com/rpa (c)06'),),
715 (('commonName', 'www.verisign.com'),))}
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000716
717which is a fairly poorly-formed ``subject`` field.
Thomas Woutersed03b412007-08-28 21:37:11 +0000718
Antoine Pitrou152efa22010-05-16 18:19:27 +0000719This other example first creates an SSL context, instructs it to verify
720certificates sent by peers, and feeds it a set of recognized certificate
721authorities (CA)::
722
723 >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
724 >>> context.verify_mode = ssl.CERT_OPTIONAL
725 >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
726
727(it is assumed your operating system places a bundle of all CA certificates
728in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an error and have
729to adjust the location)
730
731When you use the context to connect to a server, :const:`CERT_OPTIONAL`
732validates the server certificate: it ensures that the server certificate
733was signed with one of the CA certificates, and checks the signature for
734correctness::
735
736 >>> conn = context.wrap_socket(socket.socket(socket.AF_INET))
737 >>> conn.connect(("linuxfr.org", 443))
738
739You should then fetch the certificate and check its fields for conformity.
740Here, the ``commonName`` field in the ``subject`` matches the desired HTTPS
741host ``linuxfr.org``::
742
743 >>> pprint.pprint(conn.getpeercert())
744 {'notAfter': 'Jun 26 21:41:46 2011 GMT',
745 'subject': ((('commonName', 'linuxfr.org'),),),
746 'subjectAltName': (('DNS', 'linuxfr.org'), ('othername', '<unsupported>'))}
747
748Now that you are assured of its authenticity, you can proceed to talk with
749the server::
750
Antoine Pitroudab64262010-09-19 13:31:06 +0000751 >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
752 >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
Antoine Pitrou152efa22010-05-16 18:19:27 +0000753 [b'HTTP/1.1 302 Found',
754 b'Date: Sun, 16 May 2010 13:43:28 GMT',
755 b'Server: Apache/2.2',
756 b'Location: https://linuxfr.org/pub/',
757 b'Vary: Accept-Encoding',
758 b'Connection: close',
759 b'Content-Type: text/html; charset=iso-8859-1',
760 b'',
761 b'']
762
763
764See the discussion of :ref:`ssl-security` below.
765
766
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000767Server-side operation
768^^^^^^^^^^^^^^^^^^^^^
769
Antoine Pitrou152efa22010-05-16 18:19:27 +0000770For server operation, typically you'll need to have a server certificate, and
771private key, each in a file. You'll first create a context holding the key
772and the certificate, so that clients can check your authenticity. Then
773you'll open a socket, bind it to a port, call :meth:`listen` on it, and start
774waiting for clients to connect::
Thomas Woutersed03b412007-08-28 21:37:11 +0000775
776 import socket, ssl
777
Antoine Pitrou152efa22010-05-16 18:19:27 +0000778 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
779 context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")
780
Thomas Woutersed03b412007-08-28 21:37:11 +0000781 bindsocket = socket.socket()
782 bindsocket.bind(('myaddr.mydomain.com', 10023))
783 bindsocket.listen(5)
784
Antoine Pitrou152efa22010-05-16 18:19:27 +0000785When a client connects, you'll call :meth:`accept` on the socket to get the
786new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket`
787method to create a server-side SSL socket for the connection::
Thomas Woutersed03b412007-08-28 21:37:11 +0000788
789 while True:
790 newsocket, fromaddr = bindsocket.accept()
Antoine Pitrou152efa22010-05-16 18:19:27 +0000791 connstream = context.wrap_socket(newsocket, server_side=True)
792 try:
793 deal_with_client(connstream)
794 finally:
795 connstream.close()
Thomas Woutersed03b412007-08-28 21:37:11 +0000796
Antoine Pitrou152efa22010-05-16 18:19:27 +0000797Then you'll read data from the ``connstream`` and do something with it till you
Georg Brandl7f01a132009-09-16 15:58:14 +0000798are finished with the client (or the client is finished with you)::
Thomas Woutersed03b412007-08-28 21:37:11 +0000799
800 def deal_with_client(connstream):
Antoine Pitroudab64262010-09-19 13:31:06 +0000801 data = connstream.recv(1024)
Antoine Pitrou152efa22010-05-16 18:19:27 +0000802 # empty data means the client is finished with us
Thomas Woutersed03b412007-08-28 21:37:11 +0000803 while data:
804 if not do_something(connstream, data):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805 # we'll assume do_something returns False
806 # when we're finished with client
Thomas Woutersed03b412007-08-28 21:37:11 +0000807 break
Antoine Pitroudab64262010-09-19 13:31:06 +0000808 data = connstream.recv(1024)
Thomas Woutersed03b412007-08-28 21:37:11 +0000809 # finished with client
Thomas Woutersed03b412007-08-28 21:37:11 +0000810
Antoine Pitrou152efa22010-05-16 18:19:27 +0000811And go back to listening for new client connections (of course, a real server
812would probably handle each client connection in a separate thread, or put
813the sockets in non-blocking mode and use an event loop).
814
815
816.. _ssl-security:
817
818Security considerations
819-----------------------
820
821Verifying certificates
822^^^^^^^^^^^^^^^^^^^^^^
823
824:const:`CERT_NONE` is the default. Since it does not authenticate the other
825peer, it can be insecure, especially in client mode where most of time you
826would like to ensure the authenticity of the server you're talking to.
827Therefore, when in client mode, it is highly recommended to use
828:const:`CERT_REQUIRED`. However, it is in itself not sufficient; you also
829have to check that the server certificate (obtained with
830:meth:`SSLSocket.getpeercert`) matches the desired service. The exact way
831of doing so depends on the higher-level protocol used; for example, with
832HTTPS, you'll check that the host name in the URL matches either the
833``commonName`` field in the ``subjectName``, or one of the ``DNS`` fields
834in the ``subjectAltName``.
835
836In server mode, if you want to authenticate your clients using the SSL layer
837(rather than using a higher-level authentication mechanism), you'll also have
838to specify :const:`CERT_REQUIRED` and similarly check the client certificate.
839
840 .. note::
841
842 In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are
843 equivalent unless anonymous ciphers are enabled (they are disabled
844 by default).
Thomas Woutersed03b412007-08-28 21:37:11 +0000845
Antoine Pitroub5218772010-05-21 09:56:06 +0000846Protocol versions
847^^^^^^^^^^^^^^^^^
848
849SSL version 2 is considered insecure and is therefore dangerous to use. If
850you want maximum compatibility between clients and servers, it is recommended
851to use :const:`PROTOCOL_SSLv23` as the protocol version and then disable
852SSLv2 explicitly using the :data:`SSLContext.options` attribute::
853
854 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
855 context.options |= ssl.OP_NO_SSLv2
856
857The SSL context created above will allow SSLv3 and TLSv1 connections, but
858not SSLv2.
859
Georg Brandl48310cd2009-01-03 21:18:54 +0000860
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861.. seealso::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000862
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000863 Class :class:`socket.socket`
864 Documentation of underlying :mod:`socket` class
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000865
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000866 `Introducing SSL and Certificates using OpenSSL <http://old.pseudonym.org/ssl/wwwj-index.html>`_
867 Frederick J. Hirsch
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000868
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000869 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
870 Steve Kent
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000871
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000872 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
873 D. Eastlake et. al.
Thomas Wouters89d996e2007-09-08 17:39:28 +0000874
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000875 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
876 Housley et. al.