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 | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 4 | """This module provides some more Pythonic support for SSL. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 5 | |
| 6 | Object types: |
| 7 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 8 | SSLSocket -- subtype of socket.socket which does SSL over the socket |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 9 | |
| 10 | Exceptions: |
| 11 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 12 | SSLError -- exception raised for I/O errors |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 13 | |
| 14 | Functions: |
| 15 | |
| 16 | cert_time_to_seconds -- convert time string used for certificate |
| 17 | notBefore and notAfter functions to integer |
| 18 | seconds past the Epoch (the time values |
| 19 | returned from time.time()) |
| 20 | |
| 21 | fetch_server_certificate (HOST, PORT) -- fetch the certificate provided |
| 22 | by the server running on HOST at port PORT. No |
| 23 | validation of the certificate is performed. |
| 24 | |
| 25 | Integer constants: |
| 26 | |
| 27 | SSL_ERROR_ZERO_RETURN |
| 28 | SSL_ERROR_WANT_READ |
| 29 | SSL_ERROR_WANT_WRITE |
| 30 | SSL_ERROR_WANT_X509_LOOKUP |
| 31 | SSL_ERROR_SYSCALL |
| 32 | SSL_ERROR_SSL |
| 33 | SSL_ERROR_WANT_CONNECT |
| 34 | |
| 35 | SSL_ERROR_EOF |
| 36 | SSL_ERROR_INVALID_ERROR_CODE |
| 37 | |
| 38 | The following group define certificate requirements that one side is |
| 39 | allowing/requiring from the other side: |
| 40 | |
| 41 | CERT_NONE - no certificates from the other side are required (or will |
| 42 | be looked at if provided) |
| 43 | CERT_OPTIONAL - certificates are not required, but if provided will be |
| 44 | validated, and if validation fails, the connection will |
| 45 | also fail |
| 46 | CERT_REQUIRED - certificates are required, and will be validated, and |
| 47 | if validation fails, the connection will also fail |
| 48 | |
| 49 | The following constants identify various SSL protocol variants: |
| 50 | |
| 51 | PROTOCOL_SSLv2 |
| 52 | PROTOCOL_SSLv3 |
| 53 | PROTOCOL_SSLv23 |
| 54 | PROTOCOL_TLSv1 |
| 55 | """ |
| 56 | |
Christian Heimes | 05e8be1 | 2008-02-23 18:30:17 +0000 | [diff] [blame] | 57 | import textwrap |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 58 | |
| 59 | import _ssl # if we can't import it, let the error propagate |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 60 | |
| 61 | from _ssl import SSLError |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 62 | from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 63 | from _ssl import (PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, |
| 64 | PROTOCOL_TLSv1) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 65 | from _ssl import RAND_status, RAND_egd, RAND_add |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 66 | from _ssl import ( |
| 67 | SSL_ERROR_ZERO_RETURN, |
| 68 | SSL_ERROR_WANT_READ, |
| 69 | SSL_ERROR_WANT_WRITE, |
| 70 | SSL_ERROR_WANT_X509_LOOKUP, |
| 71 | SSL_ERROR_SYSCALL, |
| 72 | SSL_ERROR_SSL, |
| 73 | SSL_ERROR_WANT_CONNECT, |
| 74 | SSL_ERROR_EOF, |
| 75 | SSL_ERROR_INVALID_ERROR_CODE, |
| 76 | ) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 77 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 78 | from socket import socket, AF_INET, SOCK_STREAM, error |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 79 | from socket import getnameinfo as _getnameinfo |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 80 | from socket import error as socket_error |
Guido van Rossum | 39eb8fa | 2007-11-16 01:24:05 +0000 | [diff] [blame] | 81 | from socket import dup as _dup |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 82 | import base64 # for DER-to-PEM translation |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 83 | import traceback |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 84 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 85 | class SSLSocket(socket): |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 86 | |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 87 | """This class implements a subtype of socket.socket that wraps |
| 88 | the underlying OS socket in an SSL context when necessary, and |
| 89 | provides read and write methods over that channel.""" |
| 90 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 91 | def __init__(self, sock=None, keyfile=None, certfile=None, |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 92 | server_side=False, cert_reqs=CERT_NONE, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 93 | ssl_version=PROTOCOL_SSLv23, ca_certs=None, |
| 94 | do_handshake_on_connect=True, |
| 95 | family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, |
| 96 | suppress_ragged_eofs=True): |
| 97 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 98 | if sock is not None: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 99 | socket.__init__(self, |
| 100 | family=sock.family, |
| 101 | type=sock.type, |
| 102 | proto=sock.proto, |
| 103 | fileno=_dup(sock.fileno())) |
Guido van Rossum | 39eb8fa | 2007-11-16 01:24:05 +0000 | [diff] [blame] | 104 | sock.close() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 105 | elif fileno is not None: |
| 106 | socket.__init__(self, fileno=fileno) |
| 107 | else: |
| 108 | socket.__init__(self, family=family, type=type, proto=proto) |
| 109 | |
| 110 | self._closed = False |
| 111 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 112 | if certfile and not keyfile: |
| 113 | keyfile = certfile |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 114 | # see if it's connected |
| 115 | try: |
| 116 | socket.getpeername(self) |
| 117 | except: |
| 118 | # no, no connection yet |
| 119 | self._sslobj = None |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 120 | else: |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 121 | # yes, create the SSL object |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 122 | try: |
| 123 | self._sslobj = _ssl.sslwrap(self, server_side, |
| 124 | keyfile, certfile, |
| 125 | cert_reqs, ssl_version, ca_certs) |
| 126 | if do_handshake_on_connect: |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 127 | timeout = self.gettimeout() |
| 128 | if timeout == 0.0: |
| 129 | # non-blocking |
| 130 | raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets") |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 131 | self.do_handshake() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 132 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 133 | except socket_error as x: |
| 134 | self.close() |
| 135 | raise x |
| 136 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 137 | self.keyfile = keyfile |
| 138 | self.certfile = certfile |
| 139 | self.cert_reqs = cert_reqs |
| 140 | self.ssl_version = ssl_version |
| 141 | self.ca_certs = ca_certs |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 142 | self.do_handshake_on_connect = do_handshake_on_connect |
| 143 | self.suppress_ragged_eofs = suppress_ragged_eofs |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 144 | |
Guido van Rossum | b7b030e | 2007-11-16 01:28:45 +0000 | [diff] [blame] | 145 | def dup(self): |
| 146 | raise NotImplemented("Can't dup() %s instances" % |
| 147 | self.__class__.__name__) |
| 148 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 149 | def _checkClosed(self, msg=None): |
| 150 | # raise an exception here if you wish to check for spurious closes |
| 151 | pass |
| 152 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 153 | def read(self, len=0, buffer=None): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 154 | """Read up to LEN bytes and return them. |
| 155 | Return zero-length string on EOF.""" |
| 156 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 157 | self._checkClosed() |
| 158 | try: |
| 159 | if buffer: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 160 | v = self._sslobj.read(buffer, len) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 161 | else: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 162 | v = self._sslobj.read(len or 1024) |
| 163 | return v |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 164 | except SSLError as x: |
| 165 | if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 166 | if buffer: |
| 167 | return 0 |
| 168 | else: |
| 169 | return b'' |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 170 | else: |
| 171 | raise |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 172 | |
| 173 | def write(self, data): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 174 | """Write DATA to the underlying SSL channel. Returns |
| 175 | number of bytes of DATA actually transmitted.""" |
| 176 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 177 | self._checkClosed() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 178 | return self._sslobj.write(data) |
| 179 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 180 | def getpeercert(self, binary_form=False): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 181 | """Returns a formatted version of the data in the |
| 182 | certificate provided by the other end of the SSL channel. |
| 183 | Return None if no certificate was provided, {} if a |
| 184 | certificate was provided, but not validated.""" |
| 185 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 186 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 187 | return self._sslobj.peer_certificate(binary_form) |
| 188 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 189 | def cipher(self): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 190 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 191 | if not self._sslobj: |
| 192 | return None |
| 193 | else: |
| 194 | return self._sslobj.cipher() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 195 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 196 | def send(self, data, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 197 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 198 | if self._sslobj: |
| 199 | if flags != 0: |
| 200 | raise ValueError( |
| 201 | "non-zero flags not allowed in calls to send() on %s" % |
| 202 | self.__class__) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 203 | while True: |
| 204 | try: |
| 205 | v = self._sslobj.write(data) |
| 206 | except SSLError as x: |
| 207 | if x.args[0] == SSL_ERROR_WANT_READ: |
| 208 | return 0 |
| 209 | elif x.args[0] == SSL_ERROR_WANT_WRITE: |
| 210 | return 0 |
| 211 | else: |
| 212 | raise |
| 213 | else: |
| 214 | return v |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 215 | else: |
| 216 | return socket.send(self, data, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 217 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 218 | def send_to(self, data, addr, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 219 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 220 | if self._sslobj: |
| 221 | raise ValueError("send_to not allowed on instances of %s" % |
| 222 | self.__class__) |
| 223 | else: |
| 224 | return socket.send_to(self, data, addr, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 225 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 226 | def sendall(self, data, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 227 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 228 | if self._sslobj: |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 229 | amount = len(data) |
| 230 | count = 0 |
| 231 | while (count < amount): |
| 232 | v = self.send(data[count:]) |
| 233 | count += v |
| 234 | return amount |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 235 | else: |
| 236 | return socket.sendall(self, data, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 237 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 238 | def recv(self, buflen=1024, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 239 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 240 | if self._sslobj: |
| 241 | if flags != 0: |
| 242 | raise ValueError( |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 243 | "non-zero flags not allowed in calls to recv_into() on %s" % |
| 244 | self.__class__) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 245 | while True: |
| 246 | try: |
| 247 | return self.read(buflen) |
| 248 | except SSLError as x: |
| 249 | if x.args[0] == SSL_ERROR_WANT_READ: |
| 250 | continue |
| 251 | else: |
| 252 | raise x |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 253 | else: |
| 254 | return socket.recv(self, buflen, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 255 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 256 | def recv_into(self, buffer, nbytes=None, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 257 | self._checkClosed() |
| 258 | if buffer and (nbytes is None): |
| 259 | nbytes = len(buffer) |
| 260 | elif nbytes is None: |
| 261 | nbytes = 1024 |
| 262 | if self._sslobj: |
| 263 | if flags != 0: |
| 264 | raise ValueError( |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 265 | "non-zero flags not allowed in calls to recv_into() on %s" % |
| 266 | self.__class__) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 267 | while True: |
| 268 | try: |
| 269 | v = self.read(nbytes, buffer) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 270 | return v |
| 271 | except SSLError as x: |
| 272 | if x.args[0] == SSL_ERROR_WANT_READ: |
| 273 | continue |
| 274 | else: |
| 275 | raise x |
| 276 | else: |
| 277 | return socket.recv_into(self, buffer, nbytes, flags) |
| 278 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 279 | def recv_from(self, addr, buflen=1024, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 280 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 281 | if self._sslobj: |
| 282 | raise ValueError("recv_from not allowed on instances of %s" % |
| 283 | self.__class__) |
| 284 | else: |
| 285 | return socket.recv_from(self, addr, buflen, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 286 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 287 | def pending(self): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 288 | self._checkClosed() |
| 289 | if self._sslobj: |
| 290 | return self._sslobj.pending() |
| 291 | else: |
| 292 | return 0 |
| 293 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 294 | def shutdown(self, how): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 295 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 296 | self._sslobj = None |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 297 | socket.shutdown(self, how) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 298 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 299 | def _real_close(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 300 | self._sslobj = None |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 301 | # self._closed = True |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 302 | socket._real_close(self) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 303 | |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 304 | def do_handshake(self, block=False): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 305 | """Perform a TLS/SSL handshake.""" |
| 306 | |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 307 | timeout = self.gettimeout() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 308 | try: |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 309 | if timeout == 0.0 and block: |
| 310 | self.settimeout(None) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 311 | self._sslobj.do_handshake() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 312 | finally: |
| 313 | self.settimeout(timeout) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 314 | |
| 315 | def connect(self, addr): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 316 | """Connects to remote ADDR, and then wraps the connection in |
| 317 | an SSL channel.""" |
| 318 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 319 | # Here we assume that the socket is client-side, and not |
| 320 | # connected at the time of the call. We connect it, then wrap it. |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 321 | if self._sslobj: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 322 | raise ValueError("attempt to connect already-connected SSLSocket!") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 323 | socket.connect(self, addr) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 324 | self._sslobj = _ssl.sslwrap(self, False, self.keyfile, self.certfile, |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 325 | self.cert_reqs, self.ssl_version, |
| 326 | self.ca_certs) |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 327 | try: |
| 328 | if self.do_handshake_on_connect: |
| 329 | self.do_handshake() |
| 330 | except: |
| 331 | self._sslobj = None |
| 332 | raise |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 333 | |
| 334 | def accept(self): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 335 | """Accepts a new connection from a remote client, and returns |
| 336 | a tuple containing that new connection wrapped with a server-side |
| 337 | SSL channel, and the address of the remote client.""" |
| 338 | |
| 339 | newsock, addr = socket.accept(self) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 340 | return (SSLSocket(sock=newsock, |
| 341 | keyfile=self.keyfile, certfile=self.certfile, |
| 342 | server_side=True, |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 343 | cert_reqs=self.cert_reqs, |
| 344 | ssl_version=self.ssl_version, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 345 | ca_certs=self.ca_certs, |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 346 | do_handshake_on_connect= |
| 347 | self.do_handshake_on_connect), |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 348 | addr) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 349 | |
Guido van Rossum | e6650f9 | 2007-12-06 19:05:55 +0000 | [diff] [blame] | 350 | def __del__(self): |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 351 | # sys.stderr.write("__del__ on %s\n" % repr(self)) |
Guido van Rossum | e6650f9 | 2007-12-06 19:05:55 +0000 | [diff] [blame] | 352 | self._real_close() |
| 353 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 354 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 355 | def wrap_socket(sock, keyfile=None, certfile=None, |
| 356 | server_side=False, cert_reqs=CERT_NONE, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 357 | ssl_version=PROTOCOL_SSLv23, ca_certs=None, |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 358 | do_handshake_on_connect=True, |
| 359 | suppress_ragged_eofs=True): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 360 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 361 | return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 362 | server_side=server_side, cert_reqs=cert_reqs, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 363 | ssl_version=ssl_version, ca_certs=ca_certs, |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 364 | do_handshake_on_connect=do_handshake_on_connect, |
| 365 | suppress_ragged_eofs=suppress_ragged_eofs) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 366 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 367 | # some utility functions |
| 368 | |
| 369 | def cert_time_to_seconds(cert_time): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 370 | """Takes a date-time string in standard ASN1_print form |
| 371 | ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return |
| 372 | a Python time value in seconds past the epoch.""" |
| 373 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 374 | import time |
| 375 | return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT")) |
| 376 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 377 | PEM_HEADER = "-----BEGIN CERTIFICATE-----" |
| 378 | PEM_FOOTER = "-----END CERTIFICATE-----" |
| 379 | |
| 380 | def DER_cert_to_PEM_cert(der_cert_bytes): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 381 | """Takes a certificate in binary DER format and returns the |
| 382 | PEM version of it as a string.""" |
| 383 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 384 | f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict') |
| 385 | return (PEM_HEADER + '\n' + |
| 386 | textwrap.fill(f, 64) + '\n' + |
| 387 | PEM_FOOTER + '\n') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 388 | |
| 389 | def PEM_cert_to_DER_cert(pem_cert_string): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 390 | """Takes a certificate in ASCII PEM format and returns the |
| 391 | DER-encoded version of it as a byte sequence""" |
| 392 | |
| 393 | if not pem_cert_string.startswith(PEM_HEADER): |
| 394 | raise ValueError("Invalid PEM encoding; must start with %s" |
| 395 | % PEM_HEADER) |
| 396 | if not pem_cert_string.strip().endswith(PEM_FOOTER): |
| 397 | raise ValueError("Invalid PEM encoding; must end with %s" |
| 398 | % PEM_FOOTER) |
| 399 | d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 400 | return base64.decodestring(d.encode('ASCII', 'strict')) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 401 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 402 | def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 403 | """Retrieve the certificate from the server at the specified address, |
| 404 | and return it as a PEM-encoded string. |
| 405 | If 'ca_certs' is specified, validate the server cert against it. |
| 406 | If 'ssl_version' is specified, use it in the connection attempt.""" |
| 407 | |
| 408 | host, port = addr |
| 409 | if (ca_certs is not None): |
| 410 | cert_reqs = CERT_REQUIRED |
| 411 | else: |
| 412 | cert_reqs = CERT_NONE |
| 413 | s = wrap_socket(socket(), ssl_version=ssl_version, |
| 414 | cert_reqs=cert_reqs, ca_certs=ca_certs) |
| 415 | s.connect(addr) |
| 416 | dercert = s.getpeercert(True) |
| 417 | s.close() |
| 418 | return DER_cert_to_PEM_cert(dercert) |
| 419 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 420 | def get_protocol_name(protocol_code): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 421 | if protocol_code == PROTOCOL_TLSv1: |
| 422 | return "TLSv1" |
| 423 | elif protocol_code == PROTOCOL_SSLv23: |
| 424 | return "SSLv23" |
| 425 | elif protocol_code == PROTOCOL_SSLv2: |
| 426 | return "SSLv2" |
| 427 | elif protocol_code == PROTOCOL_SSLv3: |
| 428 | return "SSLv3" |
| 429 | else: |
| 430 | return "<unknown>" |