Guido van Rossum | 8ee23bb | 2007-08-27 19:11:11 +0000 | [diff] [blame^] | 1 | |
| 2 | :mod:`ssl` --- SSL wrapper for socket objects, and utility functions |
| 3 | ==================================================================== |
| 4 | |
| 5 | .. module:: ssl |
| 6 | :synopsis: SSL wrapper for socket objects, and utility functions |
| 7 | |
| 8 | .. versionadded:: 2.6 |
| 9 | |
| 10 | |
| 11 | This module provides access to Transport Layer Security (often known |
| 12 | as "Secure Sockets Layer") encryption and peer authentication |
| 13 | facilities for network sockets, both client-side and server-side. |
| 14 | This module uses the OpenSSL library. It is available on all modern |
| 15 | Unix systems, Windows, Mac OS X, and probably additional |
| 16 | platforms, as long as OpenSSL is installed on that platform. |
| 17 | |
| 18 | .. note:: |
| 19 | |
| 20 | Some behavior may be platform dependent, since calls are made to the operating |
| 21 | system socket APIs. |
| 22 | |
| 23 | This section documents the objects and functions in the `ssl` module; |
| 24 | for more general information about TLS, SSL, and certificates, the |
| 25 | reader is referred to the paper, *Introducing SSL and Certificates using OpenSSL*, by Frederick J. Hirsch, at |
| 26 | http://old.pseudonym.org/ssl/wwwj-index.html. |
| 27 | |
| 28 | This module defines a class, :class:`ssl.sslsocket`, which is |
| 29 | derived from the :class:`socket.socket` type, and supports additional |
| 30 | :meth:`read` and :meth:`write` methods, along with a method, :meth:`getpeercert`, |
| 31 | to retrieve the certificate of the other side of the connection. |
| 32 | |
| 33 | This module defines the following functions, exceptions, and constants: |
| 34 | |
| 35 | .. function:: cert_time_to_seconds(timestring) |
| 36 | |
| 37 | Returns a floating-point value containing a normal seconds-after-the-epoch time |
| 38 | value, given the time-string representing the "notBefore" or "notAfter" date |
| 39 | from a certificate. |
| 40 | |
| 41 | Here's an example:: |
| 42 | |
| 43 | >>> import ssl |
| 44 | >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT") |
| 45 | 1178694000.0 |
| 46 | >>> import time |
| 47 | >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")) |
| 48 | 'Wed May 9 00:00:00 2007' |
| 49 | >>> |
| 50 | |
| 51 | .. exception:: sslerror |
| 52 | |
| 53 | Raised to signal an error from the underlying SSL implementation. This |
| 54 | signifies some problem in the higher-level |
| 55 | encryption and authentication layer that's superimposed on the underlying |
| 56 | network connection. |
| 57 | |
| 58 | .. data:: CERT_NONE |
| 59 | |
| 60 | Value to pass to the `cert_reqs` parameter to :func:`sslobject` |
| 61 | when no certificates will be required or validated from the other |
| 62 | side of the socket connection. |
| 63 | |
| 64 | .. data:: CERT_OPTIONAL |
| 65 | |
| 66 | Value to pass to the `cert_reqs` parameter to :func:`sslobject` |
| 67 | when no certificates will be required from the other side of the |
| 68 | socket connection, but if they are provided, will be validated. |
| 69 | Note that use of this setting requires a valid certificate |
| 70 | validation file also be passed as a value of the `ca_certs` |
| 71 | parameter. |
| 72 | |
| 73 | .. data:: CERT_REQUIRED |
| 74 | |
| 75 | Value to pass to the `cert_reqs` parameter to :func:`sslobject` |
| 76 | when certificates will be required from the other side of the |
| 77 | socket connection. Note that use of this setting requires a valid certificate |
| 78 | validation file also be passed as a value of the `ca_certs` |
| 79 | parameter. |
| 80 | |
| 81 | .. data:: PROTOCOL_SSLv2 |
| 82 | |
| 83 | Selects SSL version 2 as the channel encryption protocol. |
| 84 | |
| 85 | .. data:: PROTOCOL_SSLv23 |
| 86 | |
| 87 | Selects SSL version 2 or 3 as the channel encryption protocol. This is a setting to use for maximum compatibility |
| 88 | with the other end of an SSL connection, but it may cause the specific ciphers chosen for the encryption to be |
| 89 | of fairly low quality. |
| 90 | |
| 91 | .. data:: PROTOCOL_SSLv3 |
| 92 | |
| 93 | Selects SSL version 3 as the channel encryption protocol. |
| 94 | |
| 95 | .. data:: PROTOCOL_TLSv1 |
| 96 | |
| 97 | Selects SSL version 2 as the channel encryption protocol. This is |
| 98 | the most modern version, and probably the best choice for maximum |
| 99 | protection, if both sides can speak it. |
| 100 | |
| 101 | |
| 102 | Certificates |
| 103 | ------------ |
| 104 | |
| 105 | Certificates in general are part of a public-key / private-key system. In this system, each `principal`, |
| 106 | (which may be a machine, or a person, or an organization) is assigned a unique two-part encryption key. |
| 107 | One part of the key is public, and is called the *public key*; the other part is kept secret, and is called |
| 108 | the *private key*. The two parts are related, in that if you encrypt a message with one of the parts, you can |
| 109 | decrypt it with the other part, and **only** with the other part. |
| 110 | |
| 111 | A certificate contains information about two principals. It contains |
| 112 | the name of a *subject*, and the subject's public key. It also |
| 113 | contains a statement by a second principal, the *issuer*, that the |
| 114 | subject is who he claims to be, and that this is indeed the subject's |
| 115 | public key. The issuer's statement is signed with the issuer's |
| 116 | private key, which only the issuer knows. However, anyone can verify |
| 117 | the issuer's statement by finding the issuer's public key, decrypting |
| 118 | the statement with it, and comparing it to the other information in |
| 119 | the certificate. The certificate also contains information about the |
| 120 | time period over which it is valid. This is expressed as two fields, |
| 121 | called "notBefore" and "notAfter". |
| 122 | |
| 123 | The underlying system which is used in the Python SSL support is |
| 124 | called "OpenSSL". It contains facilities for constructing and |
| 125 | validating certificates. In the Python use of certificates, the other |
| 126 | side of a network connection can be required to produce a certificate, |
| 127 | and that certificate can be validated against a file filled with |
| 128 | self-signed *root* certificates (so-called because the issuer is the |
| 129 | same as the subject), and and "CA" (certification authority) |
| 130 | certificates assured by those root certificates (and by other CA |
| 131 | certificates). Either side of a connection, client or server, can |
| 132 | request certificates and validation, and the connection can be optionally |
| 133 | set up to fail if a valid certificate is not presented by the other side. |
| 134 | |
| 135 | |
| 136 | sslsocket Objects |
| 137 | ----------------- |
| 138 | |
| 139 | .. class:: sslsocket(sock [, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_SSLv23, ca_certs=None]) |
| 140 | |
| 141 | Takes an instance *sock* of :class:`socket.socket`, and returns an instance of a subtype |
| 142 | of :class:`socket.socket` which wraps the underlying socket in an SSL context. |
| 143 | For client-side sockets, the context construction is lazy; if the underlying socket isn't |
| 144 | connected yet, the context construction will be performed after :meth:`connect` is called |
| 145 | on the socket. |
| 146 | |
| 147 | The `keyfile` and `certfile` parameters specify optional files which contain a certificate |
| 148 | to be used to identify the local side of the connection. Often the private key is stored |
| 149 | in the same file as the certificate; in this case, only the `certfile` parameter need be |
| 150 | passed. If the private key is stored in a separate file, both parameters must be used. |
| 151 | |
| 152 | The parameter `server_side` is a boolean which identifies whether server-side or client-side |
| 153 | behavior is desired from this socket. |
| 154 | |
| 155 | The parameter `cert_reqs` specifies whether a certificate is |
| 156 | required from the other side of the connection, and whether it will |
| 157 | be validated if provided. It must be one of the three values |
| 158 | :const:`CERT_NONE` (certificates ignored), :const:`CERT_OPTIONAL` (not required, |
| 159 | but validated if provided), or :const:`CERT_REQUIRED` (required and |
| 160 | validated). If the value of this parameter is not :const:`CERT_NONE`, then |
| 161 | the `ca_certs` parameter must point to a file of CA certificates. |
| 162 | |
| 163 | The parameter `ssl_version` specifies which version of the SSL protocol to use. Typically, |
| 164 | the server specifies this, and a client connecting to it must use the same protocol. An |
| 165 | SSL server using :const:`PROTOCOL_SSLv23` can understand a client connecting via SSL2, SSL3, or TLS1, |
| 166 | but a client using :const:`PROTOCOL_SSLv23` can only connect to an SSL2 server. |
| 167 | |
| 168 | The `ca_certs` file contains a set of concatenated "certification authority" certificates, |
| 169 | which are used to validate certificates passed from the other end of the connection. |
| 170 | This file |
| 171 | contains the certificates in PEM format (IETF RFC 1422) where each certificate is |
| 172 | encoded in base64 encoding and surrounded with a header and footer:: |
| 173 | |
| 174 | -----BEGIN CERTIFICATE----- |
| 175 | ... (CA certificate in base64 encoding) ... |
| 176 | -----END CERTIFICATE----- |
| 177 | |
| 178 | The various certificates in the file are just concatenated together:: |
| 179 | |
| 180 | -----BEGIN CERTIFICATE----- |
| 181 | ... (CA certificate in base64 encoding) ... |
| 182 | -----END CERTIFICATE----- |
| 183 | -----BEGIN CERTIFICATE----- |
| 184 | ... (a second CA certificate in base64 encoding) ... |
| 185 | -----END CERTIFICATE----- |
| 186 | -----BEGIN CERTIFICATE----- |
| 187 | ... (a root certificate in base64 encoding) ... |
| 188 | -----END CERTIFICATE----- |
| 189 | |
| 190 | Some "standard" root certificates are available at |
| 191 | http://www.thawte.com/roots/ (for Thawte roots) and |
| 192 | http://www.verisign.com/support/roots.html (for Verisign roots). |
| 193 | |
| 194 | .. method:: sslsocket.read([nbytes]) |
| 195 | |
| 196 | Reads up to `nbytes` bytes from the SSL-encrypted channel and returns them. |
| 197 | |
| 198 | .. method:: sslsocket.write(data) |
| 199 | |
| 200 | Writes the `data` to the other side of the connection, using the SSL channel to encrypt. Returns the number |
| 201 | of bytes written. |
| 202 | |
| 203 | .. method:: sslsocket.getpeercert() |
| 204 | |
| 205 | If there is no certificate for the peer on the other end of the connection, returns `None`. |
| 206 | If a certificate was received from the peer, but not validated, returns an empty `dict` instance. |
| 207 | If a certificate was received and validated, returns a `dict` instance with the fields |
| 208 | `subject` (the principal for which the certificate was issued), `issuer` (the signer of |
| 209 | the certificate), `notBefore` (the time before which the certificate should not be trusted), |
| 210 | and `notAfter` (the time after which the certificate should not be trusted) filled in. |
| 211 | |
| 212 | The "subject" and "issuer" fields are themselves dictionaries containing the fields given |
| 213 | in the certificate's data structure for each principal:: |
| 214 | |
| 215 | {'issuer': {'commonName': u'somemachine.python.org', |
| 216 | 'countryName': u'US', |
| 217 | 'localityName': u'Wilmington', |
| 218 | 'organizationName': u'Python Software Foundation', |
| 219 | 'organizationalUnitName': u'SSL', |
| 220 | 'stateOrProvinceName': u'Delaware'}, |
| 221 | 'subject': {'commonName': u'somemachine.python.org', |
| 222 | 'countryName': u'US', |
| 223 | 'localityName': u'Wilmington', |
| 224 | 'organizationName': u'Python Software Foundation', |
| 225 | 'organizationalUnitName': u'SSL', |
| 226 | 'stateOrProvinceName': u'Delaware'}, |
| 227 | 'notAfter': 'Sep 4 21:54:26 2007 GMT', |
| 228 | 'notBefore': 'Aug 25 21:54:26 2007 GMT', |
| 229 | 'version': 2} |
| 230 | |
| 231 | This certificate is said to be *self-signed*, because the subject |
| 232 | and issuer are the same entity. The *version* field refers the the X509 version |
| 233 | that's used for the certificate. |
| 234 | |
| 235 | Examples |
| 236 | -------- |
| 237 | |
| 238 | This example connects to an SSL server, prints the server's address and certificate, |
| 239 | sends some bytes, and reads part of the response:: |
| 240 | |
| 241 | import socket, ssl, pprint |
| 242 | |
| 243 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 244 | ssl_sock = ssl.sslsocket(s, ca_certs="/etc/ca_certs_file", cert_reqs=ssl.CERT_REQUIRED) |
| 245 | |
| 246 | ssl_sock.connect(('www.verisign.com', 443)) |
| 247 | |
| 248 | print repr(ssl_sock.getpeername()) |
| 249 | print pprint.pformat(ssl_sock.getpeercert()) |
| 250 | |
| 251 | # Set a simple HTTP request -- use httplib in actual code. |
| 252 | ssl_sock.write("""GET / HTTP/1.0\r |
| 253 | Host: www.verisign.com\r\n\r\n""") |
| 254 | |
| 255 | # Read a chunk of data. Will not necessarily |
| 256 | # read all the data returned by the server. |
| 257 | data = ssl_sock.read() |
| 258 | |
| 259 | # note that closing the sslsocket will also close the underlying socket |
| 260 | ssl_sock.close() |
| 261 | |
| 262 | As of August 25, 2007, the certificate printed by this program |
| 263 | looked like this:: |
| 264 | |
| 265 | {'issuer': {'commonName': u'VeriSign Class 3 Extended Validation SSL SGC CA', |
| 266 | 'countryName': u'US', |
| 267 | 'organizationName': u'VeriSign, Inc.', |
| 268 | 'organizationalUnitName': u'Terms of use at https://www.verisign.com/rpa (c)06'}, |
| 269 | 'subject': {'1.3.6.1.4.1.311.60.2.1.2': u'Delaware', |
| 270 | '1.3.6.1.4.1.311.60.2.1.3': u'US', |
| 271 | 'commonName': u'www.verisign.com', |
| 272 | 'countryName': u'US', |
| 273 | 'localityName': u'Mountain View', |
| 274 | 'organizationName': u'VeriSign, Inc.', |
| 275 | 'organizationalUnitName': u'Terms of use at www.verisign.com/rpa (c)06', |
| 276 | 'postalCode': u'94043', |
| 277 | 'serialNumber': u'2497886', |
| 278 | 'stateOrProvinceName': u'California', |
| 279 | 'streetAddress': u'487 East Middlefield Road'}, |
| 280 | 'notAfter': 'May 8 23:59:59 2009 GMT', |
| 281 | 'notBefore': 'May 9 00:00:00 2007 GMT', |
| 282 | 'version': 2} |
| 283 | |
| 284 | For server operation, typically you'd need to have a server certificate, and private key, each in a file. |
| 285 | You'd open a socket, bind it to a port, call :meth:`listen` on it, then start waiting for clients |
| 286 | to connect:: |
| 287 | |
| 288 | import socket, ssl |
| 289 | |
| 290 | bindsocket = socket.socket() |
| 291 | bindsocket.bind(('myaddr.mydomain.com', 10023)) |
| 292 | bindsocket.listen(5) |
| 293 | |
| 294 | When one did, you'd call :meth:`accept` on the socket to get the new socket from the other |
| 295 | end, and use :func:`sslsocket` to create a server-side SSL context for it:: |
| 296 | |
| 297 | while True: |
| 298 | newsocket, fromaddr = bindsocket.accept() |
| 299 | connstream = ssl.sslsocket(newsocket, server_side=True, certfile="mycertfile", |
| 300 | keyfile="mykeyfile", ssl_protocol=ssl.PROTOCOL_TLSv1) |
| 301 | deal_with_client(connstream) |
| 302 | |
| 303 | Then 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):: |
| 304 | |
| 305 | def deal_with_client(connstream): |
| 306 | |
| 307 | data = connstream.read() |
| 308 | # null data means the client is finished with us |
| 309 | while data: |
| 310 | if not do_something(connstream, data): |
| 311 | # we'll assume do_something returns False when we're finished with client |
| 312 | break |
| 313 | data = connstream.read() |
| 314 | # finished with client |
| 315 | connstream.close() |
| 316 | |
| 317 | And go back to listening for new client connections. |
| 318 | |
| 319 | |