blob: 5c783453d3bd29e9d95c908944ad388e92b5d458 [file] [log] [blame]
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001:mod:`ssl` --- SSL wrapper for socket objects
Georg Brandlb044b2a2009-09-16 16:05:59 +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 Brandlb044b2a2009-09-16 16:05:59 +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 Brandlb044b2a2009-09-16 16:05:59 +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 Brandlb044b2a2009-09-16 16:05:59 +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 Brandlb044b2a2009-09-16 16:05:59 +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
34additional :meth:`read` and :meth:`write` methods, along with a method,
35:meth:`getpeercert`, to retrieve the certificate of the other side of the
36connection, and a method, :meth:`cipher`, to retrieve the cipher being used for
37the secure connection.
Thomas Woutersed03b412007-08-28 21:37:11 +000038
Thomas Wouters1b7f8912007-09-19 03:06:30 +000039Functions, Constants, and Exceptions
40------------------------------------
41
42.. exception:: SSLError
43
Georg Brandl48310cd2009-01-03 21:18:54 +000044 Raised to signal an error from the underlying SSL implementation. This
Georg Brandlb044b2a2009-09-16 16:05:59 +000045 signifies some problem in the higher-level encryption and authentication
46 layer that's superimposed on the underlying network connection. This error
47 is a subtype of :exc:`socket.error`, which in turn is a subtype of
48 :exc:`IOError`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000049
Georg Brandlb044b2a2009-09-16 16:05:59 +000050.. 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)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000051
Georg Brandlb044b2a2009-09-16 16:05:59 +000052 Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
53 of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
54 the underlying socket in an SSL context. For client-side sockets, the
55 context construction is lazy; if the underlying socket isn't connected yet,
56 the context construction will be performed after :meth:`connect` is called on
57 the socket. For server-side sockets, if the socket has no remote peer, it is
58 assumed to be a listening socket, and the server-side SSL wrapping is
59 automatically performed on client connections accepted via the :meth:`accept`
60 method. :func:`wrap_socket` may raise :exc:`SSLError`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000061
Georg Brandlb044b2a2009-09-16 16:05:59 +000062 The ``keyfile`` and ``certfile`` parameters specify optional files which
63 contain a certificate to be used to identify the local side of the
64 connection. See the discussion of :ref:`ssl-certificates` for more
65 information on how the certificate is stored in the ``certfile``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000066
Georg Brandlb044b2a2009-09-16 16:05:59 +000067 Often the private key is stored in the same file as the certificate; in this
68 case, only the ``certfile`` parameter need be passed. If the private key is
69 stored in a separate file, both parameters must be used. If the private key
70 is stored in the ``certfile``, it should come before the first certificate in
71 the certificate chain::
Thomas Wouters1b7f8912007-09-19 03:06:30 +000072
73 -----BEGIN RSA PRIVATE KEY-----
74 ... (private key in base64 encoding) ...
75 -----END RSA PRIVATE KEY-----
76 -----BEGIN CERTIFICATE-----
77 ... (certificate in base64 PEM encoding) ...
78 -----END CERTIFICATE-----
79
Georg Brandlb044b2a2009-09-16 16:05:59 +000080 The parameter ``server_side`` is a boolean which identifies whether
81 server-side or client-side behavior is desired from this socket.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000082
Georg Brandlb044b2a2009-09-16 16:05:59 +000083 The parameter ``cert_reqs`` specifies whether a certificate is required from
84 the other side of the connection, and whether it will be validated if
85 provided. It must be one of the three values :const:`CERT_NONE`
86 (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
87 if provided), or :const:`CERT_REQUIRED` (required and validated). If the
88 value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
89 parameter must point to a file of CA certificates.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000090
Georg Brandlb044b2a2009-09-16 16:05:59 +000091 The ``ca_certs`` file contains a set of concatenated "certification
92 authority" certificates, which are used to validate certificates passed from
93 the other end of the connection. See the discussion of
94 :ref:`ssl-certificates` for more information about how to arrange the
95 certificates in this file.
Thomas Wouters1b7f8912007-09-19 03:06:30 +000096
Georg Brandlb044b2a2009-09-16 16:05:59 +000097 The parameter ``ssl_version`` specifies which version of the SSL protocol to
98 use. Typically, the server chooses a particular protocol version, and the
99 client must adapt to the server's choice. Most of the versions are not
100 interoperable with the other versions. If not specified, for client-side
101 operation, the default SSL version is SSLv3; for server-side operation,
102 SSLv23. These version selections provide the most compatibility with other
103 versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000104
Georg Brandlb044b2a2009-09-16 16:05:59 +0000105 Here's a table showing which versions in a client (down the side) can connect
106 to which versions in a server (along the top):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000107
108 .. table::
109
110 ======================== ========= ========= ========== =========
111 *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1**
Christian Heimes255f53b2007-12-08 15:33:56 +0000112 ------------------------ --------- --------- ---------- ---------
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000113 *SSLv2* yes no yes* no
114 *SSLv3* yes yes yes no
115 *SSLv23* yes no yes no
116 *TLSv1* no no yes yes
117 ======================== ========= ========= ========== =========
118
Georg Brandlb044b2a2009-09-16 16:05:59 +0000119 In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4), an
120 SSLv2 client could not connect to an SSLv23 server.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000121
Bill Janssen48dc27c2007-12-05 03:38:10 +0000122 The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
123 handshake automatically after doing a :meth:`socket.connect`, or whether the
Georg Brandlb044b2a2009-09-16 16:05:59 +0000124 application program will call it explicitly, by invoking the
125 :meth:`SSLSocket.do_handshake` method. Calling
126 :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
127 blocking behavior of the socket I/O involved in the handshake.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000128
Georg Brandlb044b2a2009-09-16 16:05:59 +0000129 The parameter ``suppress_ragged_eofs`` specifies how the
130 :meth:`SSLSocket.read` method should signal unexpected EOF from the other end
131 of the connection. If specified as :const:`True` (the default), it returns a
132 normal EOF in response to unexpected EOF errors raised from the underlying
133 socket; if :const:`False`, it will raise the exceptions back to the caller.
Bill Janssen48dc27c2007-12-05 03:38:10 +0000134
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000135.. function:: RAND_status()
136
Georg Brandlb044b2a2009-09-16 16:05:59 +0000137 Returns True if the SSL pseudo-random number generator has been seeded with
138 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
139 and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
140 number generator.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000141
142.. function:: RAND_egd(path)
143
144 If you are running an entropy-gathering daemon (EGD) somewhere, and ``path``
Georg Brandlb044b2a2009-09-16 16:05:59 +0000145 is the pathname of a socket connection open to it, this will read 256 bytes
146 of randomness from the socket, and add it to the SSL pseudo-random number
147 generator to increase the security of generated secret keys. This is
148 typically only necessary on systems without better sources of randomness.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000149
Georg Brandlb044b2a2009-09-16 16:05:59 +0000150 See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
151 of entropy-gathering daemons.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000152
153.. function:: RAND_add(bytes, entropy)
154
Georg Brandlb044b2a2009-09-16 16:05:59 +0000155 Mixes the given ``bytes`` into the SSL pseudo-random number generator. The
156 parameter ``entropy`` (a float) is a lower bound on the entropy contained in
157 string (so you can always use :const:`0.0`). See :rfc:`1750` for more
158 information on sources of entropy.
Thomas Woutersed03b412007-08-28 21:37:11 +0000159
160.. function:: cert_time_to_seconds(timestring)
161
Georg Brandlb044b2a2009-09-16 16:05:59 +0000162 Returns a floating-point value containing a normal seconds-after-the-epoch
163 time value, given the time-string representing the "notBefore" or "notAfter"
164 date from a certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000165
166 Here's an example::
167
168 >>> import ssl
169 >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
170 1178694000.0
171 >>> import time
172 >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
173 'Wed May 9 00:00:00 2007'
Georg Brandl48310cd2009-01-03 21:18:54 +0000174 >>>
Thomas Woutersed03b412007-08-28 21:37:11 +0000175
Georg Brandlb044b2a2009-09-16 16:05:59 +0000176.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Thomas Woutersed03b412007-08-28 21:37:11 +0000177
Georg Brandlb044b2a2009-09-16 16:05:59 +0000178 Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
179 *port-number*) pair, fetches the server's certificate, and returns it as a
180 PEM-encoded string. If ``ssl_version`` is specified, uses that version of
181 the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
182 specified, it should be a file containing a list of root certificates, the
183 same format as used for the same parameter in :func:`wrap_socket`. The call
184 will attempt to validate the server certificate against that set of root
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000185 certificates, and will fail if the validation attempt fails.
186
Georg Brandlb044b2a2009-09-16 16:05:59 +0000187.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000188
189 Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
190 string version of the same certificate.
191
Georg Brandlb044b2a2009-09-16 16:05:59 +0000192.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000193
Georg Brandlb044b2a2009-09-16 16:05:59 +0000194 Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
195 bytes for that same certificate.
Thomas Woutersed03b412007-08-28 21:37:11 +0000196
197.. data:: CERT_NONE
198
Georg Brandlb044b2a2009-09-16 16:05:59 +0000199 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
200 certificates will be required or validated from the other side of the socket
201 connection.
Thomas Woutersed03b412007-08-28 21:37:11 +0000202
203.. data:: CERT_OPTIONAL
204
Georg Brandlb044b2a2009-09-16 16:05:59 +0000205 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
206 certificates will be required from the other side of the socket connection,
207 but if they are provided, will be validated. Note that use of this setting
208 requires a valid certificate validation file also be passed as a value of the
209 ``ca_certs`` parameter.
Thomas Woutersed03b412007-08-28 21:37:11 +0000210
211.. data:: CERT_REQUIRED
212
Georg Brandlb044b2a2009-09-16 16:05:59 +0000213 Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when
214 certificates will be required from the other side of the socket connection.
215 Note that use of this setting requires a valid certificate validation file
216 also be passed as a value of the ``ca_certs`` parameter.
Thomas Woutersed03b412007-08-28 21:37:11 +0000217
218.. data:: PROTOCOL_SSLv2
219
220 Selects SSL version 2 as the channel encryption protocol.
221
Antoine Pitrou21b7e532010-05-16 14:20:17 +0000222 .. warning::
223
224 SSL version 2 is insecure. Its use is highly discouraged.
225
Thomas Woutersed03b412007-08-28 21:37:11 +0000226.. data:: PROTOCOL_SSLv23
227
Georg Brandlb044b2a2009-09-16 16:05:59 +0000228 Selects SSL version 2 or 3 as the channel encryption protocol. This is a
229 setting to use with servers for maximum compatibility with the other end of
230 an SSL connection, but it may cause the specific ciphers chosen for the
231 encryption to be of fairly low quality.
Thomas Woutersed03b412007-08-28 21:37:11 +0000232
233.. data:: PROTOCOL_SSLv3
234
Georg Brandlb044b2a2009-09-16 16:05:59 +0000235 Selects SSL version 3 as the channel encryption protocol. For clients, this
236 is the maximally compatible SSL variant.
Thomas Woutersed03b412007-08-28 21:37:11 +0000237
238.. data:: PROTOCOL_TLSv1
239
Georg Brandlb044b2a2009-09-16 16:05:59 +0000240 Selects TLS version 1 as the channel encryption protocol. This is the most
241 modern version, and probably the best choice for maximum protection, if both
242 sides can speak it.
Thomas Woutersed03b412007-08-28 21:37:11 +0000243
244
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000245SSLSocket Objects
246-----------------
247
Bill Janssen48dc27c2007-12-05 03:38:10 +0000248.. method:: SSLSocket.read(nbytes=1024, buffer=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000249
250 Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them.
Georg Brandlb044b2a2009-09-16 16:05:59 +0000251 If the ``buffer`` is specified, it will attempt to read into the buffer the
252 minimum of the size of the buffer and ``nbytes``, if that is specified. If
253 no buffer is specified, an immutable buffer is allocated and returned with
254 the data read from the socket.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000255
256.. method:: SSLSocket.write(data)
257
Georg Brandlb044b2a2009-09-16 16:05:59 +0000258 Writes the ``data`` to the other side of the connection, using the SSL
259 channel to encrypt. Returns the number of bytes written.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000260
Bill Janssen48dc27c2007-12-05 03:38:10 +0000261.. method:: SSLSocket.do_handshake()
262
Georg Brandlb044b2a2009-09-16 16:05:59 +0000263 Performs the SSL setup handshake. If the socket is non-blocking, this method
264 may raise :exc:`SSLError` with the value of the exception instance's
265 ``args[0]`` being either :const:`SSL_ERROR_WANT_READ` or
266 :const:`SSL_ERROR_WANT_WRITE`, and should be called again until it stops
267 raising those exceptions. Here's an example of how to do that::
Bill Janssen48dc27c2007-12-05 03:38:10 +0000268
269 while True:
270 try:
271 sock.do_handshake()
272 break
273 except ssl.SSLError as err:
274 if err.args[0] == ssl.SSL_ERROR_WANT_READ:
275 select.select([sock], [], [])
276 elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
277 select.select([], [sock], [])
278 else:
279 raise
280
Bill Janssen688356f2008-08-12 17:09:27 +0000281.. method:: SSLSocket.unwrap()
282
Georg Brandlb044b2a2009-09-16 16:05:59 +0000283 Performs the SSL shutdown handshake, which removes the TLS layer from the
284 underlying socket, and returns the underlying socket object. This can be
285 used to go from encrypted operation over a connection to unencrypted. The
286 returned socket should always be used for further communication with the
287 other side of the connection, rather than the original socket
Bill Janssen688356f2008-08-12 17:09:27 +0000288
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000289.. method:: SSLSocket.getpeercert(binary_form=False)
290
Georg Brandlb044b2a2009-09-16 16:05:59 +0000291 If there is no certificate for the peer on the other end of the connection,
292 returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000293
Georg Brandlb044b2a2009-09-16 16:05:59 +0000294 If the parameter ``binary_form`` is :const:`False`, and a certificate was
295 received from the peer, this method returns a :class:`dict` instance. If the
296 certificate was not validated, the dict is empty. If the certificate was
297 validated, it returns a dict with the keys ``subject`` (the principal for
298 which the certificate was issued), and ``notAfter`` (the time after which the
299 certificate should not be trusted). The certificate was already validated,
300 so the ``notBefore`` and ``issuer`` fields are not returned. If a
301 certificate contains an instance of the *Subject Alternative Name* extension
302 (see :rfc:`3280`), there will also be a ``subjectAltName`` key in the
303 dictionary.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000304
305 The "subject" field is a tuple containing the sequence of relative
Georg Brandlb044b2a2009-09-16 16:05:59 +0000306 distinguished names (RDNs) given in the certificate's data structure for the
307 principal, and each RDN is a sequence of name-value pairs::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000308
309 {'notAfter': 'Feb 16 16:54:50 2013 GMT',
Ezio Melotti713e0422009-09-13 08:13:21 +0000310 'subject': ((('countryName', 'US'),),
311 (('stateOrProvinceName', 'Delaware'),),
312 (('localityName', 'Wilmington'),),
313 (('organizationName', 'Python Software Foundation'),),
314 (('organizationalUnitName', 'SSL'),),
315 (('commonName', 'somemachine.python.org'),))}
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000316
Georg Brandlb044b2a2009-09-16 16:05:59 +0000317 If the ``binary_form`` parameter is :const:`True`, and a certificate was
318 provided, this method returns the DER-encoded form of the entire certificate
319 as a sequence of bytes, or :const:`None` if the peer did not provide a
320 certificate. This return value is independent of validation; if validation
321 was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000322 been validated, but if :const:`CERT_NONE` was used to establish the
323 connection, the certificate, if present, will not have been validated.
324
325.. method:: SSLSocket.cipher()
326
Georg Brandlb044b2a2009-09-16 16:05:59 +0000327 Returns a three-value tuple containing the name of the cipher being used, the
328 version of the SSL protocol that defines its use, and the number of secret
329 bits being used. If no connection has been established, returns ``None``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000330
331
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000332.. method:: SSLSocket.unwrap()
333
Georg Brandlb044b2a2009-09-16 16:05:59 +0000334 Performs the SSL shutdown handshake, which removes the TLS layer from the
335 underlying socket, and returns the underlying socket object. This can be
336 used to go from encrypted operation over a connection to unencrypted. The
337 returned socket should always be used for further communication with the
338 other side of the connection, rather than the original socket.
Benjamin Peterson4aeec042008-08-19 21:42:13 +0000339
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000340.. index:: single: certificates
341
342.. index:: single: X509 certificate
343
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000344.. _ssl-certificates:
345
Thomas Woutersed03b412007-08-28 21:37:11 +0000346Certificates
347------------
348
Georg Brandlb044b2a2009-09-16 16:05:59 +0000349Certificates in general are part of a public-key / private-key system. In this
350system, each *principal*, (which may be a machine, or a person, or an
351organization) is assigned a unique two-part encryption key. One part of the key
352is public, and is called the *public key*; the other part is kept secret, and is
353called the *private key*. The two parts are related, in that if you encrypt a
354message with one of the parts, you can decrypt it with the other part, and
355**only** with the other part.
Thomas Woutersed03b412007-08-28 21:37:11 +0000356
Georg Brandlb044b2a2009-09-16 16:05:59 +0000357A certificate contains information about two principals. It contains the name
358of a *subject*, and the subject's public key. It also contains a statement by a
359second principal, the *issuer*, that the subject is who he claims to be, and
360that this is indeed the subject's public key. The issuer's statement is signed
361with the issuer's private key, which only the issuer knows. However, anyone can
362verify the issuer's statement by finding the issuer's public key, decrypting the
363statement with it, and comparing it to the other information in the certificate.
364The certificate also contains information about the time period over which it is
365valid. This is expressed as two fields, called "notBefore" and "notAfter".
Thomas Woutersed03b412007-08-28 21:37:11 +0000366
Georg Brandlb044b2a2009-09-16 16:05:59 +0000367In the Python use of certificates, a client or server can use a certificate to
368prove who they are. The other side of a network connection can also be required
369to produce a certificate, and that certificate can be validated to the
370satisfaction of the client or server that requires such validation. The
371connection attempt can be set to raise an exception if the validation fails.
372Validation is done automatically, by the underlying OpenSSL framework; the
373application need not concern itself with its mechanics. But the application
374does usually need to provide sets of certificates to allow this process to take
375place.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000376
Georg Brandlb044b2a2009-09-16 16:05:59 +0000377Python uses files to contain certificates. They should be formatted as "PEM"
378(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
379and a footer line::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000380
381 -----BEGIN CERTIFICATE-----
382 ... (certificate in base64 PEM encoding) ...
383 -----END CERTIFICATE-----
384
Georg Brandlb044b2a2009-09-16 16:05:59 +0000385The Python files which contain certificates can contain a sequence of
386certificates, sometimes called a *certificate chain*. This chain should start
387with the specific certificate for the principal who "is" the client or server,
388and then the certificate for the issuer of that certificate, and then the
389certificate for the issuer of *that* certificate, and so on up the chain till
390you get to a certificate which is *self-signed*, that is, a certificate which
391has the same subject and issuer, sometimes called a *root certificate*. The
392certificates should just be concatenated together in the certificate file. For
393example, suppose we had a three certificate chain, from our server certificate
394to the certificate of the certification authority that signed our server
395certificate, to the root certificate of the agency which issued the
396certification authority's certificate::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000397
398 -----BEGIN CERTIFICATE-----
399 ... (certificate for your server)...
400 -----END CERTIFICATE-----
401 -----BEGIN CERTIFICATE-----
402 ... (the certificate for the CA)...
403 -----END CERTIFICATE-----
404 -----BEGIN CERTIFICATE-----
405 ... (the root certificate for the CA's issuer)...
406 -----END CERTIFICATE-----
407
408If you are going to require validation of the other side of the connection's
409certificate, you need to provide a "CA certs" file, filled with the certificate
Georg Brandlb044b2a2009-09-16 16:05:59 +0000410chains for each issuer you are willing to trust. Again, this file just contains
411these chains concatenated together. For validation, Python will use the first
412chain it finds in the file which matches. Some "standard" root certificates are
413available from various certification authorities: `CACert.org
414<http://www.cacert.org/index.php?id=3>`_, `Thawte
415<http://www.thawte.com/roots/>`_, `Verisign
416<http://www.verisign.com/support/roots.html>`_, `Positive SSL
417<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
418(used by python.org), `Equifax and GeoTrust
419<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000420
Georg Brandlb044b2a2009-09-16 16:05:59 +0000421In general, if you are using SSL3 or TLS1, you don't need to put the full chain
422in your "CA certs" file; you only need the root certificates, and the remote
423peer is supposed to furnish the other certificates necessary to chain from its
424certificate to a root certificate. See :rfc:`4158` for more discussion of the
425way in which certification chains can be built.
Thomas Woutersed03b412007-08-28 21:37:11 +0000426
Georg Brandlb044b2a2009-09-16 16:05:59 +0000427If you are going to create a server that provides SSL-encrypted connection
428services, you will need to acquire a certificate for that service. There are
429many ways of acquiring appropriate certificates, such as buying one from a
430certification authority. Another common practice is to generate a self-signed
431certificate. The simplest way to do this is with the OpenSSL package, using
432something like the following::
Thomas Woutersed03b412007-08-28 21:37:11 +0000433
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000434 % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
435 Generating a 1024 bit RSA private key
436 .......++++++
437 .............................++++++
438 writing new private key to 'cert.pem'
439 -----
440 You are about to be asked to enter information that will be incorporated
441 into your certificate request.
442 What you are about to enter is what is called a Distinguished Name or a DN.
443 There are quite a few fields but you can leave some blank
444 For some fields there will be a default value,
445 If you enter '.', the field will be left blank.
446 -----
447 Country Name (2 letter code) [AU]:US
448 State or Province Name (full name) [Some-State]:MyState
449 Locality Name (eg, city) []:Some City
450 Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
451 Organizational Unit Name (eg, section) []:My Group
452 Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
453 Email Address []:ops@myserver.mygroup.myorganization.com
454 %
Thomas Woutersed03b412007-08-28 21:37:11 +0000455
Georg Brandlb044b2a2009-09-16 16:05:59 +0000456The disadvantage of a self-signed certificate is that it is its own root
457certificate, and no one else will have it in their cache of known (and trusted)
458root certificates.
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000459
460
Thomas Woutersed03b412007-08-28 21:37:11 +0000461Examples
462--------
463
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000464Testing for SSL support
465^^^^^^^^^^^^^^^^^^^^^^^
466
Georg Brandlb044b2a2009-09-16 16:05:59 +0000467To test for the presence of SSL support in a Python installation, user code
468should use the following idiom::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000469
470 try:
471 import ssl
472 except ImportError:
473 pass
474 else:
475 [ do something that requires SSL support ]
476
477Client-side operation
478^^^^^^^^^^^^^^^^^^^^^
479
Georg Brandlb044b2a2009-09-16 16:05:59 +0000480This example connects to an SSL server, prints the server's address and
481certificate, sends some bytes, and reads part of the response::
Thomas Woutersed03b412007-08-28 21:37:11 +0000482
483 import socket, ssl, pprint
484
485 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000486
487 # require a certificate from the server
488 ssl_sock = ssl.wrap_socket(s,
489 ca_certs="/etc/ca_certs_file",
490 cert_reqs=ssl.CERT_REQUIRED)
Thomas Woutersed03b412007-08-28 21:37:11 +0000491
492 ssl_sock.connect(('www.verisign.com', 443))
493
Georg Brandl6911e3c2007-09-04 07:15:32 +0000494 print(repr(ssl_sock.getpeername()))
495 pprint.pprint(ssl_sock.getpeercert())
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000496 print(pprint.pformat(ssl_sock.getpeercert()))
Thomas Woutersed03b412007-08-28 21:37:11 +0000497
Georg Brandl24420152008-05-26 16:32:26 +0000498 # Set a simple HTTP request -- use http.client in actual code.
Thomas Woutersed03b412007-08-28 21:37:11 +0000499 ssl_sock.write("""GET / HTTP/1.0\r
500 Host: www.verisign.com\r\n\r\n""")
501
502 # Read a chunk of data. Will not necessarily
503 # read all the data returned by the server.
504 data = ssl_sock.read()
505
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000506 # note that closing the SSLSocket will also close the underlying socket
Thomas Woutersed03b412007-08-28 21:37:11 +0000507 ssl_sock.close()
508
Georg Brandlb044b2a2009-09-16 16:05:59 +0000509As of September 6, 2007, the certificate printed by this program looked like
510this::
Thomas Woutersed03b412007-08-28 21:37:11 +0000511
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000512 {'notAfter': 'May 8 23:59:59 2009 GMT',
Ezio Melotti713e0422009-09-13 08:13:21 +0000513 'subject': ((('serialNumber', '2497886'),),
514 (('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
515 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
516 (('countryName', 'US'),),
517 (('postalCode', '94043'),),
518 (('stateOrProvinceName', 'California'),),
519 (('localityName', 'Mountain View'),),
520 (('streetAddress', '487 East Middlefield Road'),),
521 (('organizationName', 'VeriSign, Inc.'),),
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522 (('organizationalUnitName',
Ezio Melotti713e0422009-09-13 08:13:21 +0000523 'Production Security Services'),),
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000524 (('organizationalUnitName',
Ezio Melotti713e0422009-09-13 08:13:21 +0000525 'Terms of use at www.verisign.com/rpa (c)06'),),
526 (('commonName', 'www.verisign.com'),))}
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000527
528which is a fairly poorly-formed ``subject`` field.
Thomas Woutersed03b412007-08-28 21:37:11 +0000529
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000530Server-side operation
531^^^^^^^^^^^^^^^^^^^^^
532
Georg Brandlb044b2a2009-09-16 16:05:59 +0000533For server operation, typically you'd need to have a server certificate, and
534private key, each in a file. You'd open a socket, bind it to a port, call
535:meth:`listen` on it, then start waiting for clients to connect::
Thomas Woutersed03b412007-08-28 21:37:11 +0000536
537 import socket, ssl
538
539 bindsocket = socket.socket()
540 bindsocket.bind(('myaddr.mydomain.com', 10023))
541 bindsocket.listen(5)
542
Georg Brandlb044b2a2009-09-16 16:05:59 +0000543When one did, you'd call :meth:`accept` on the socket to get the new socket from
544the other end, and use :func:`wrap_socket` to create a server-side SSL context
545for it::
Thomas Woutersed03b412007-08-28 21:37:11 +0000546
547 while True:
548 newsocket, fromaddr = bindsocket.accept()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000549 connstream = ssl.wrap_socket(newsocket,
550 server_side=True,
551 certfile="mycertfile",
552 keyfile="mykeyfile",
Christian Heimesdae2a892008-04-19 00:55:37 +0000553 ssl_version=ssl.PROTOCOL_TLSv1)
Thomas Woutersed03b412007-08-28 21:37:11 +0000554 deal_with_client(connstream)
555
Georg Brandlb044b2a2009-09-16 16:05:59 +0000556Then you'd read data from the ``connstream`` and do something with it till you
557are finished with the client (or the client is finished with you)::
Thomas Woutersed03b412007-08-28 21:37:11 +0000558
559 def deal_with_client(connstream):
560
561 data = connstream.read()
562 # null data means the client is finished with us
563 while data:
564 if not do_something(connstream, data):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000565 # we'll assume do_something returns False
566 # when we're finished with client
Thomas Woutersed03b412007-08-28 21:37:11 +0000567 break
568 data = connstream.read()
569 # finished with client
570 connstream.close()
571
572And go back to listening for new client connections.
573
Georg Brandl48310cd2009-01-03 21:18:54 +0000574
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000575.. seealso::
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000576
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000577 Class :class:`socket.socket`
578 Documentation of underlying :mod:`socket` class
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000579
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000580 `Introducing SSL and Certificates using OpenSSL <http://old.pseudonym.org/ssl/wwwj-index.html>`_
581 Frederick J. Hirsch
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000582
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000583 `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
584 Steve Kent
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000585
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000586 `RFC 1750: Randomness Recommendations for Security <http://www.ietf.org/rfc/rfc1750>`_
587 D. Eastlake et. al.
Thomas Wouters89d996e2007-09-08 17:39:28 +0000588
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000589 `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <http://www.ietf.org/rfc/rfc3280>`_
590 Housley et. al.