Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1 | # Wrapper module for _ssl, providing some additional facilities |
| 2 | # implemented in Python. Written by Bill Janssen. |
| 3 | |
Guido van Rossum | 245b42e | 2007-08-29 03:59:57 +0000 | [diff] [blame^] | 4 | raise ImportError("ssl.py is temporarily out of order") |
| 5 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 6 | """\ |
| 7 | This module provides some more Pythonic support for SSL. |
| 8 | |
| 9 | Object types: |
| 10 | |
| 11 | sslsocket -- subtype of socket.socket which does SSL over the socket |
| 12 | |
| 13 | Exceptions: |
| 14 | |
| 15 | sslerror -- exception raised for I/O errors |
| 16 | |
| 17 | Functions: |
| 18 | |
| 19 | cert_time_to_seconds -- convert time string used for certificate |
| 20 | notBefore and notAfter functions to integer |
| 21 | seconds past the Epoch (the time values |
| 22 | returned from time.time()) |
| 23 | |
| 24 | fetch_server_certificate (HOST, PORT) -- fetch the certificate provided |
| 25 | by the server running on HOST at port PORT. No |
| 26 | validation of the certificate is performed. |
| 27 | |
| 28 | Integer constants: |
| 29 | |
| 30 | SSL_ERROR_ZERO_RETURN |
| 31 | SSL_ERROR_WANT_READ |
| 32 | SSL_ERROR_WANT_WRITE |
| 33 | SSL_ERROR_WANT_X509_LOOKUP |
| 34 | SSL_ERROR_SYSCALL |
| 35 | SSL_ERROR_SSL |
| 36 | SSL_ERROR_WANT_CONNECT |
| 37 | |
| 38 | SSL_ERROR_EOF |
| 39 | SSL_ERROR_INVALID_ERROR_CODE |
| 40 | |
| 41 | The following group define certificate requirements that one side is |
| 42 | allowing/requiring from the other side: |
| 43 | |
| 44 | CERT_NONE - no certificates from the other side are required (or will |
| 45 | be looked at if provided) |
| 46 | CERT_OPTIONAL - certificates are not required, but if provided will be |
| 47 | validated, and if validation fails, the connection will |
| 48 | also fail |
| 49 | CERT_REQUIRED - certificates are required, and will be validated, and |
| 50 | if validation fails, the connection will also fail |
| 51 | |
| 52 | The following constants identify various SSL protocol variants: |
| 53 | |
| 54 | PROTOCOL_SSLv2 |
| 55 | PROTOCOL_SSLv3 |
| 56 | PROTOCOL_SSLv23 |
| 57 | PROTOCOL_TLSv1 |
| 58 | """ |
| 59 | |
| 60 | import os, sys |
| 61 | |
| 62 | import _ssl # if we can't import it, let the error propagate |
| 63 | from socket import socket |
| 64 | from _ssl import sslerror |
| 65 | from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED |
| 66 | from _ssl import PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1 |
| 67 | |
| 68 | # Root certs: |
| 69 | # |
| 70 | # The "ca_certs" argument to sslsocket() expects a file containing one or more |
| 71 | # certificates that are roots of various certificate signing chains. This file |
| 72 | # contains the certificates in PEM format (RFC ) where each certificate is |
| 73 | # encoded in base64 encoding and surrounded with a header and footer: |
| 74 | # -----BEGIN CERTIFICATE----- |
| 75 | # ... (CA certificate in base64 encoding) ... |
| 76 | # -----END CERTIFICATE----- |
| 77 | # The various certificates in the file are just concatenated together: |
| 78 | # -----BEGIN CERTIFICATE----- |
| 79 | # ... (CA certificate in base64 encoding) ... |
| 80 | # -----END CERTIFICATE----- |
| 81 | # -----BEGIN CERTIFICATE----- |
| 82 | # ... (a second CA certificate in base64 encoding) ... |
| 83 | # -----END CERTIFICATE----- |
| 84 | # |
| 85 | # Some "standard" root certificates are available at |
| 86 | # |
| 87 | # http://www.thawte.com/roots/ (for Thawte roots) |
| 88 | # http://www.verisign.com/support/roots.html (for Verisign) |
| 89 | |
| 90 | class sslsocket (socket): |
| 91 | |
| 92 | def __init__(self, sock, keyfile=None, certfile=None, |
| 93 | server_side=False, cert_reqs=CERT_NONE, |
| 94 | ssl_version=PROTOCOL_SSLv23, ca_certs=None): |
| 95 | socket.__init__(self, _sock=sock._sock) |
| 96 | if certfile and not keyfile: |
| 97 | keyfile = certfile |
| 98 | if server_side: |
| 99 | self._sslobj = _ssl.sslwrap(self._sock, 1, keyfile, certfile, |
| 100 | cert_reqs, ssl_version, ca_certs) |
| 101 | else: |
| 102 | # see if it's connected |
| 103 | try: |
| 104 | socket.getpeername(self) |
| 105 | except: |
| 106 | # no, no connection yet |
| 107 | self._sslobj = None |
| 108 | else: |
| 109 | # yes, create the SSL object |
| 110 | self._sslobj = _ssl.sslwrap(self._sock, 0, keyfile, certfile, |
| 111 | cert_reqs, ssl_version, ca_certs) |
| 112 | self.keyfile = keyfile |
| 113 | self.certfile = certfile |
| 114 | self.cert_reqs = cert_reqs |
| 115 | self.ssl_version = ssl_version |
| 116 | self.ca_certs = ca_certs |
| 117 | |
| 118 | def read(self, len=1024): |
| 119 | return self._sslobj.read(len) |
| 120 | |
| 121 | def write(self, data): |
| 122 | return self._sslobj.write(data) |
| 123 | |
| 124 | def getpeercert(self): |
| 125 | return self._sslobj.peer_certificate() |
| 126 | |
| 127 | def send (self, data, flags=0): |
| 128 | if flags != 0: |
| 129 | raise ValueError( |
| 130 | "non-zero flags not allowed in calls to send() on %s" % |
| 131 | self.__class__) |
| 132 | return self._sslobj.write(data) |
| 133 | |
| 134 | def send_to (self, data, addr, flags=0): |
| 135 | raise ValueError("send_to not allowed on instances of %s" % |
| 136 | self.__class__) |
| 137 | |
| 138 | def sendall (self, data, flags=0): |
| 139 | if flags != 0: |
| 140 | raise ValueError( |
| 141 | "non-zero flags not allowed in calls to sendall() on %s" % |
| 142 | self.__class__) |
| 143 | return self._sslobj.write(data) |
| 144 | |
| 145 | def recv (self, buflen=1024, flags=0): |
| 146 | if flags != 0: |
| 147 | raise ValueError( |
| 148 | "non-zero flags not allowed in calls to sendall() on %s" % |
| 149 | self.__class__) |
| 150 | return self._sslobj.read(data, buflen) |
| 151 | |
| 152 | def recv_from (self, addr, buflen=1024, flags=0): |
| 153 | raise ValueError("recv_from not allowed on instances of %s" % |
| 154 | self.__class__) |
| 155 | |
| 156 | def shutdown(self): |
| 157 | if self._sslobj: |
| 158 | self._sslobj.shutdown() |
| 159 | self._sslobj = None |
| 160 | else: |
| 161 | socket.shutdown(self) |
| 162 | |
| 163 | def close(self): |
| 164 | if self._sslobj: |
| 165 | self.shutdown() |
| 166 | else: |
| 167 | socket.close(self) |
| 168 | |
| 169 | def connect(self, addr): |
| 170 | # Here we assume that the socket is client-side, and not |
| 171 | # connected at the time of the call. We connect it, then wrap it. |
| 172 | if self._sslobj or (self.getsockname()[1] != 0): |
| 173 | raise ValueError("attempt to connect already-connected sslsocket!") |
| 174 | socket.connect(self, addr) |
| 175 | self._sslobj = _ssl.sslwrap(self._sock, 0, self.keyfile, self.certfile, |
| 176 | self.cert_reqs, self.ssl_version, |
| 177 | self.ca_certs) |
| 178 | |
| 179 | def accept(self): |
| 180 | raise ValueError("accept() not supported on an sslsocket") |
| 181 | |
| 182 | |
| 183 | # some utility functions |
| 184 | |
| 185 | def cert_time_to_seconds(cert_time): |
| 186 | import time |
| 187 | return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT")) |
| 188 | |
| 189 | # a replacement for the old socket.ssl function |
| 190 | |
| 191 | def sslwrap_simple (sock, keyfile=None, certfile=None): |
| 192 | |
| 193 | return _ssl.sslwrap(sock._sock, 0, keyfile, certfile, CERT_NONE, |
| 194 | PROTOCOL_SSLv23, None) |
| 195 | |
| 196 | # fetch the certificate that the server is providing in PEM form |
| 197 | |
| 198 | def fetch_server_certificate (host, port): |
| 199 | |
| 200 | import re, tempfile, os |
| 201 | |
| 202 | def subproc(cmd): |
| 203 | from subprocess import Popen, PIPE, STDOUT |
| 204 | proc = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True) |
| 205 | status = proc.wait() |
| 206 | output = proc.stdout.read() |
| 207 | return status, output |
| 208 | |
| 209 | def strip_to_x509_cert(certfile_contents, outfile=None): |
| 210 | m = re.search(r"^([-]+BEGIN CERTIFICATE[-]+[\r]*\n" |
| 211 | r".*[\r]*^[-]+END CERTIFICATE[-]+)$", |
| 212 | certfile_contents, re.MULTILINE | re.DOTALL) |
| 213 | if not m: |
| 214 | return None |
| 215 | else: |
| 216 | tn = tempfile.mktemp() |
| 217 | fp = open(tn, "w") |
| 218 | fp.write(m.group(1) + "\n") |
| 219 | fp.close() |
| 220 | try: |
| 221 | tn2 = (outfile or tempfile.mktemp()) |
| 222 | status, output = subproc(r'openssl x509 -in "%s" -out "%s"' % |
| 223 | (tn, tn2)) |
| 224 | if status != 0: |
| 225 | raise OperationError(status, tsig, output) |
| 226 | fp = open(tn2, 'rb') |
| 227 | data = fp.read() |
| 228 | fp.close() |
| 229 | os.unlink(tn2) |
| 230 | return data |
| 231 | finally: |
| 232 | os.unlink(tn) |
| 233 | |
| 234 | if sys.platform.startswith("win"): |
| 235 | tfile = tempfile.mktemp() |
| 236 | fp = open(tfile, "w") |
| 237 | fp.write("quit\n") |
| 238 | fp.close() |
| 239 | try: |
| 240 | status, output = subproc( |
| 241 | 'openssl s_client -connect "%s:%s" -showcerts < "%s"' % |
| 242 | (host, port, tfile)) |
| 243 | finally: |
| 244 | os.unlink(tfile) |
| 245 | else: |
| 246 | status, output = subproc( |
| 247 | 'openssl s_client -connect "%s:%s" -showcerts < /dev/null' % |
| 248 | (host, port)) |
| 249 | if status != 0: |
| 250 | raise OSError(status) |
| 251 | certtext = strip_to_x509_cert(output) |
| 252 | if not certtext: |
| 253 | raise ValueError("Invalid response received from server at %s:%s" % |
| 254 | (host, port)) |
| 255 | return certtext |