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 |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 58 | import re |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 59 | |
| 60 | import _ssl # if we can't import it, let the error propagate |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 61 | |
Antoine Pitrou | 04f6a32 | 2010-04-05 21:40:07 +0000 | [diff] [blame] | 62 | from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 63 | from _ssl import _SSLContext, SSLError |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 64 | from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 65 | from _ssl import (PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, |
| 66 | PROTOCOL_TLSv1) |
Antoine Pitrou | b521877 | 2010-05-21 09:56:06 +0000 | [diff] [blame] | 67 | from _ssl import OP_ALL, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1 |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 68 | from _ssl import RAND_status, RAND_egd, RAND_add |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 69 | from _ssl import ( |
| 70 | SSL_ERROR_ZERO_RETURN, |
| 71 | SSL_ERROR_WANT_READ, |
| 72 | SSL_ERROR_WANT_WRITE, |
| 73 | SSL_ERROR_WANT_X509_LOOKUP, |
| 74 | SSL_ERROR_SYSCALL, |
| 75 | SSL_ERROR_SSL, |
| 76 | SSL_ERROR_WANT_CONNECT, |
| 77 | SSL_ERROR_EOF, |
| 78 | SSL_ERROR_INVALID_ERROR_CODE, |
| 79 | ) |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 80 | from _ssl import HAS_SNI |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 81 | |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 82 | from socket import getnameinfo as _getnameinfo |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 83 | from socket import error as socket_error |
Antoine Pitrou | 15399c3 | 2011-04-28 19:23:55 +0200 | [diff] [blame^] | 84 | from socket import socket, AF_INET, SOCK_STREAM, create_connection |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 85 | import base64 # for DER-to-PEM translation |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 86 | import traceback |
Antoine Pitrou | de8cf32 | 2010-04-26 17:29:05 +0000 | [diff] [blame] | 87 | import errno |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 88 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 89 | |
Antoine Pitrou | 59fdd67 | 2010-10-08 10:37:08 +0000 | [diff] [blame] | 90 | class CertificateError(ValueError): |
| 91 | pass |
| 92 | |
| 93 | |
| 94 | def _dnsname_to_pat(dn): |
| 95 | pats = [] |
| 96 | for frag in dn.split(r'.'): |
| 97 | if frag == '*': |
| 98 | # When '*' is a fragment by itself, it matches a non-empty dotless |
| 99 | # fragment. |
| 100 | pats.append('[^.]+') |
| 101 | else: |
| 102 | # Otherwise, '*' matches any dotless fragment. |
| 103 | frag = re.escape(frag) |
| 104 | pats.append(frag.replace(r'\*', '[^.]*')) |
| 105 | return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) |
| 106 | |
| 107 | |
| 108 | def match_hostname(cert, hostname): |
| 109 | """Verify that *cert* (in decoded format as returned by |
| 110 | SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules |
| 111 | are mostly followed, but IP addresses are not accepted for *hostname*. |
| 112 | |
| 113 | CertificateError is raised on failure. On success, the function |
| 114 | returns nothing. |
| 115 | """ |
| 116 | if not cert: |
| 117 | raise ValueError("empty or no certificate") |
| 118 | dnsnames = [] |
| 119 | san = cert.get('subjectAltName', ()) |
| 120 | for key, value in san: |
| 121 | if key == 'DNS': |
| 122 | if _dnsname_to_pat(value).match(hostname): |
| 123 | return |
| 124 | dnsnames.append(value) |
| 125 | if not san: |
| 126 | # The subject is only checked when subjectAltName is empty |
| 127 | for sub in cert.get('subject', ()): |
| 128 | for key, value in sub: |
| 129 | # XXX according to RFC 2818, the most specific Common Name |
| 130 | # must be used. |
| 131 | if key == 'commonName': |
| 132 | if _dnsname_to_pat(value).match(hostname): |
| 133 | return |
| 134 | dnsnames.append(value) |
| 135 | if len(dnsnames) > 1: |
| 136 | raise CertificateError("hostname %r " |
| 137 | "doesn't match either of %s" |
| 138 | % (hostname, ', '.join(map(repr, dnsnames)))) |
| 139 | elif len(dnsnames) == 1: |
| 140 | raise CertificateError("hostname %r " |
| 141 | "doesn't match %r" |
| 142 | % (hostname, dnsnames[0])) |
| 143 | else: |
| 144 | raise CertificateError("no appropriate commonName or " |
| 145 | "subjectAltName fields were found") |
| 146 | |
| 147 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 148 | class SSLContext(_SSLContext): |
| 149 | """An SSLContext holds various SSL-related configuration options and |
| 150 | data, such as certificates and possibly a private key.""" |
| 151 | |
| 152 | __slots__ = ('protocol',) |
| 153 | |
| 154 | def __new__(cls, protocol, *args, **kwargs): |
| 155 | return _SSLContext.__new__(cls, protocol) |
| 156 | |
| 157 | def __init__(self, protocol): |
| 158 | self.protocol = protocol |
| 159 | |
| 160 | def wrap_socket(self, sock, server_side=False, |
| 161 | do_handshake_on_connect=True, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 162 | suppress_ragged_eofs=True, |
| 163 | server_hostname=None): |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 164 | return SSLSocket(sock=sock, server_side=server_side, |
| 165 | do_handshake_on_connect=do_handshake_on_connect, |
| 166 | suppress_ragged_eofs=suppress_ragged_eofs, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 167 | server_hostname=server_hostname, |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 168 | _context=self) |
| 169 | |
| 170 | |
| 171 | class SSLSocket(socket): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 172 | """This class implements a subtype of socket.socket that wraps |
| 173 | the underlying OS socket in an SSL context when necessary, and |
| 174 | provides read and write methods over that channel.""" |
| 175 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 176 | def __init__(self, sock=None, keyfile=None, certfile=None, |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 177 | server_side=False, cert_reqs=CERT_NONE, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 178 | ssl_version=PROTOCOL_SSLv23, ca_certs=None, |
| 179 | do_handshake_on_connect=True, |
| 180 | family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 181 | suppress_ragged_eofs=True, ciphers=None, |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 182 | server_hostname=None, |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 183 | _context=None): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 184 | |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 185 | if _context: |
| 186 | self.context = _context |
| 187 | else: |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 188 | if server_side and not certfile: |
| 189 | raise ValueError("certfile must be specified for server-side " |
| 190 | "operations") |
Giampaolo Rodolà | 8b7da62 | 2010-08-30 18:28:05 +0000 | [diff] [blame] | 191 | if keyfile and not certfile: |
| 192 | raise ValueError("certfile must be specified") |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 193 | if certfile and not keyfile: |
| 194 | keyfile = certfile |
| 195 | self.context = SSLContext(ssl_version) |
| 196 | self.context.verify_mode = cert_reqs |
| 197 | if ca_certs: |
| 198 | self.context.load_verify_locations(ca_certs) |
| 199 | if certfile: |
| 200 | self.context.load_cert_chain(certfile, keyfile) |
| 201 | if ciphers: |
| 202 | self.context.set_ciphers(ciphers) |
| 203 | self.keyfile = keyfile |
| 204 | self.certfile = certfile |
| 205 | self.cert_reqs = cert_reqs |
| 206 | self.ssl_version = ssl_version |
| 207 | self.ca_certs = ca_certs |
| 208 | self.ciphers = ciphers |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 209 | if server_side and server_hostname: |
| 210 | raise ValueError("server_hostname can only be specified " |
| 211 | "in client mode") |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 212 | self.server_side = server_side |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 213 | self.server_hostname = server_hostname |
Antoine Pitrou | 152efa2 | 2010-05-16 18:19:27 +0000 | [diff] [blame] | 214 | self.do_handshake_on_connect = do_handshake_on_connect |
| 215 | self.suppress_ragged_eofs = suppress_ragged_eofs |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 216 | connected = False |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 217 | if sock is not None: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 218 | socket.__init__(self, |
| 219 | family=sock.family, |
| 220 | type=sock.type, |
| 221 | proto=sock.proto, |
Antoine Pitrou | e43f9d0 | 2010-08-08 23:24:50 +0000 | [diff] [blame] | 222 | fileno=sock.fileno()) |
Antoine Pitrou | 40f0874 | 2010-04-24 22:04:40 +0000 | [diff] [blame] | 223 | self.settimeout(sock.gettimeout()) |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 224 | # see if it's connected |
| 225 | try: |
| 226 | sock.getpeername() |
| 227 | except socket_error as e: |
| 228 | if e.errno != errno.ENOTCONN: |
| 229 | raise |
| 230 | else: |
| 231 | connected = True |
Antoine Pitrou | 6e451df | 2010-08-09 20:39:54 +0000 | [diff] [blame] | 232 | sock.detach() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 233 | elif fileno is not None: |
| 234 | socket.__init__(self, fileno=fileno) |
| 235 | else: |
| 236 | socket.__init__(self, family=family, type=type, proto=proto) |
| 237 | |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 238 | self._closed = False |
| 239 | self._sslobj = None |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 240 | self._connected = connected |
Antoine Pitrou | fa2b938 | 2010-04-26 22:17:47 +0000 | [diff] [blame] | 241 | if connected: |
| 242 | # create the SSL object |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 243 | try: |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 244 | self._sslobj = self.context._wrap_socket(self, server_side, |
| 245 | server_hostname) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 246 | if do_handshake_on_connect: |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 247 | timeout = self.gettimeout() |
| 248 | if timeout == 0.0: |
| 249 | # non-blocking |
| 250 | 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] | 251 | self.do_handshake() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 252 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 253 | except socket_error as x: |
| 254 | self.close() |
| 255 | raise x |
| 256 | |
Guido van Rossum | b7b030e | 2007-11-16 01:28:45 +0000 | [diff] [blame] | 257 | def dup(self): |
| 258 | raise NotImplemented("Can't dup() %s instances" % |
| 259 | self.__class__.__name__) |
| 260 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 261 | def _checkClosed(self, msg=None): |
| 262 | # raise an exception here if you wish to check for spurious closes |
| 263 | pass |
| 264 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 265 | def read(self, len=0, buffer=None): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 266 | """Read up to LEN bytes and return them. |
| 267 | Return zero-length string on EOF.""" |
| 268 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 269 | self._checkClosed() |
| 270 | try: |
Antoine Pitrou | 24e561a | 2010-09-03 18:38:17 +0000 | [diff] [blame] | 271 | if buffer is not None: |
| 272 | v = self._sslobj.read(len, buffer) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 273 | else: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 274 | v = self._sslobj.read(len or 1024) |
| 275 | return v |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 276 | except SSLError as x: |
| 277 | if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: |
Antoine Pitrou | 24e561a | 2010-09-03 18:38:17 +0000 | [diff] [blame] | 278 | if buffer is not None: |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 279 | return 0 |
| 280 | else: |
| 281 | return b'' |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 282 | else: |
| 283 | raise |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 284 | |
| 285 | def write(self, data): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 286 | """Write DATA to the underlying SSL channel. Returns |
| 287 | number of bytes of DATA actually transmitted.""" |
| 288 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 289 | self._checkClosed() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 290 | return self._sslobj.write(data) |
| 291 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 292 | def getpeercert(self, binary_form=False): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 293 | """Returns a formatted version of the data in the |
| 294 | certificate provided by the other end of the SSL channel. |
| 295 | Return None if no certificate was provided, {} if a |
| 296 | certificate was provided, but not validated.""" |
| 297 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 298 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 299 | return self._sslobj.peer_certificate(binary_form) |
| 300 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 301 | def cipher(self): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 302 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 303 | if not self._sslobj: |
| 304 | return None |
| 305 | else: |
| 306 | return self._sslobj.cipher() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 307 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 308 | def send(self, data, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 309 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 310 | if self._sslobj: |
| 311 | if flags != 0: |
| 312 | raise ValueError( |
| 313 | "non-zero flags not allowed in calls to send() on %s" % |
| 314 | self.__class__) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 315 | while True: |
| 316 | try: |
| 317 | v = self._sslobj.write(data) |
| 318 | except SSLError as x: |
| 319 | if x.args[0] == SSL_ERROR_WANT_READ: |
| 320 | return 0 |
| 321 | elif x.args[0] == SSL_ERROR_WANT_WRITE: |
| 322 | return 0 |
| 323 | else: |
| 324 | raise |
| 325 | else: |
| 326 | return v |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 327 | else: |
| 328 | return socket.send(self, data, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 329 | |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 330 | def sendto(self, data, flags_or_addr, addr=None): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 331 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 332 | if self._sslobj: |
Bill Janssen | 980f314 | 2008-06-29 00:05:51 +0000 | [diff] [blame] | 333 | raise ValueError("sendto not allowed on instances of %s" % |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 334 | self.__class__) |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 335 | elif addr is None: |
| 336 | return socket.sendto(self, data, flags_or_addr) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 337 | else: |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 338 | return socket.sendto(self, data, flags_or_addr, addr) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 339 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 340 | def sendall(self, data, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 341 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 342 | if self._sslobj: |
Giampaolo Rodolà | 374f835 | 2010-08-29 12:08:09 +0000 | [diff] [blame] | 343 | if flags != 0: |
| 344 | raise ValueError( |
| 345 | "non-zero flags not allowed in calls to sendall() on %s" % |
| 346 | self.__class__) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 347 | amount = len(data) |
| 348 | count = 0 |
| 349 | while (count < amount): |
| 350 | v = self.send(data[count:]) |
| 351 | count += v |
| 352 | return amount |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 353 | else: |
| 354 | return socket.sendall(self, data, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 355 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 356 | def recv(self, buflen=1024, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 357 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 358 | if self._sslobj: |
| 359 | if flags != 0: |
| 360 | raise ValueError( |
Antoine Pitrou | 5733c08 | 2010-03-22 14:49:10 +0000 | [diff] [blame] | 361 | "non-zero flags not allowed in calls to recv() on %s" % |
| 362 | self.__class__) |
| 363 | return self.read(buflen) |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 364 | else: |
| 365 | return socket.recv(self, buflen, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 366 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 367 | def recv_into(self, buffer, nbytes=None, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 368 | self._checkClosed() |
| 369 | if buffer and (nbytes is None): |
| 370 | nbytes = len(buffer) |
| 371 | elif nbytes is None: |
| 372 | nbytes = 1024 |
| 373 | if self._sslobj: |
| 374 | if flags != 0: |
| 375 | raise ValueError( |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 376 | "non-zero flags not allowed in calls to recv_into() on %s" % |
| 377 | self.__class__) |
Antoine Pitrou | 5733c08 | 2010-03-22 14:49:10 +0000 | [diff] [blame] | 378 | return self.read(nbytes, buffer) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 379 | else: |
| 380 | return socket.recv_into(self, buffer, nbytes, flags) |
| 381 | |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 382 | def recvfrom(self, buflen=1024, flags=0): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 383 | self._checkClosed() |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 384 | if self._sslobj: |
Bill Janssen | 980f314 | 2008-06-29 00:05:51 +0000 | [diff] [blame] | 385 | raise ValueError("recvfrom not allowed on instances of %s" % |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 386 | self.__class__) |
| 387 | else: |
Antoine Pitrou | a468adc | 2010-09-14 14:43:44 +0000 | [diff] [blame] | 388 | return socket.recvfrom(self, buflen, flags) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 389 | |
Bill Janssen | 58afe4c | 2008-09-08 16:45:19 +0000 | [diff] [blame] | 390 | def recvfrom_into(self, buffer, nbytes=None, flags=0): |
| 391 | self._checkClosed() |
| 392 | if self._sslobj: |
| 393 | raise ValueError("recvfrom_into not allowed on instances of %s" % |
| 394 | self.__class__) |
| 395 | else: |
| 396 | return socket.recvfrom_into(self, buffer, nbytes, flags) |
| 397 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 398 | def pending(self): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 399 | self._checkClosed() |
| 400 | if self._sslobj: |
| 401 | return self._sslobj.pending() |
| 402 | else: |
| 403 | return 0 |
| 404 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 405 | def shutdown(self, how): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 406 | self._checkClosed() |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 407 | self._sslobj = None |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 408 | socket.shutdown(self, how) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 409 | |
Ezio Melotti | dc55e67 | 2010-01-18 09:15:14 +0000 | [diff] [blame] | 410 | def unwrap(self): |
Bill Janssen | 40a0f66 | 2008-08-12 16:56:25 +0000 | [diff] [blame] | 411 | if self._sslobj: |
| 412 | s = self._sslobj.shutdown() |
| 413 | self._sslobj = None |
| 414 | return s |
| 415 | else: |
| 416 | raise ValueError("No SSL wrapper around " + str(self)) |
| 417 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 418 | def _real_close(self): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 419 | self._sslobj = None |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 420 | # self._closed = True |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 421 | socket._real_close(self) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 422 | |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 423 | def do_handshake(self, block=False): |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 424 | """Perform a TLS/SSL handshake.""" |
| 425 | |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 426 | timeout = self.gettimeout() |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 427 | try: |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 428 | if timeout == 0.0 and block: |
| 429 | self.settimeout(None) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 430 | self._sslobj.do_handshake() |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 431 | finally: |
| 432 | self.settimeout(timeout) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 433 | |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 434 | def _real_connect(self, addr, return_errno): |
Giampaolo Rodolà | 745ab38 | 2010-08-29 19:25:49 +0000 | [diff] [blame] | 435 | if self.server_side: |
| 436 | raise ValueError("can't connect in server-side mode") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 437 | # Here we assume that the socket is client-side, and not |
| 438 | # connected at the time of the call. We connect it, then wrap it. |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 439 | if self._connected: |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 440 | raise ValueError("attempt to connect already-connected SSLSocket!") |
Antoine Pitrou | d532321 | 2010-10-22 18:19:07 +0000 | [diff] [blame] | 441 | self._sslobj = self.context._wrap_socket(self, False, self.server_hostname) |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 442 | try: |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 443 | socket.connect(self, addr) |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 444 | if self.do_handshake_on_connect: |
| 445 | self.do_handshake() |
Antoine Pitrou | e93bf7a | 2011-02-26 23:24:06 +0000 | [diff] [blame] | 446 | except socket_error as e: |
| 447 | if return_errno: |
| 448 | return e.errno |
| 449 | else: |
| 450 | self._sslobj = None |
| 451 | raise e |
| 452 | self._connected = True |
| 453 | return 0 |
| 454 | |
| 455 | def connect(self, addr): |
| 456 | """Connects to remote ADDR, and then wraps the connection in |
| 457 | an SSL channel.""" |
| 458 | self._real_connect(addr, False) |
| 459 | |
| 460 | def connect_ex(self, addr): |
| 461 | """Connects to remote ADDR, and then wraps the connection in |
| 462 | an SSL channel.""" |
| 463 | return self._real_connect(addr, True) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 464 | |
| 465 | def accept(self): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 466 | """Accepts a new connection from a remote client, and returns |
| 467 | a tuple containing that new connection wrapped with a server-side |
| 468 | SSL channel, and the address of the remote client.""" |
| 469 | |
| 470 | newsock, addr = socket.accept(self) |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 471 | return (SSLSocket(sock=newsock, |
| 472 | keyfile=self.keyfile, certfile=self.certfile, |
| 473 | server_side=True, |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 474 | cert_reqs=self.cert_reqs, |
| 475 | ssl_version=self.ssl_version, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 476 | ca_certs=self.ca_certs, |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 477 | ciphers=self.ciphers, |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 478 | do_handshake_on_connect= |
| 479 | self.do_handshake_on_connect), |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 480 | addr) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 481 | |
Guido van Rossum | e6650f9 | 2007-12-06 19:05:55 +0000 | [diff] [blame] | 482 | def __del__(self): |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 483 | # sys.stderr.write("__del__ on %s\n" % repr(self)) |
Guido van Rossum | e6650f9 | 2007-12-06 19:05:55 +0000 | [diff] [blame] | 484 | self._real_close() |
| 485 | |
Bill Janssen | 54cc54c | 2007-12-14 22:08:56 +0000 | [diff] [blame] | 486 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 487 | def wrap_socket(sock, keyfile=None, certfile=None, |
| 488 | server_side=False, cert_reqs=CERT_NONE, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 489 | ssl_version=PROTOCOL_SSLv23, ca_certs=None, |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 490 | do_handshake_on_connect=True, |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 491 | suppress_ragged_eofs=True, ciphers=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 492 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 493 | return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 494 | server_side=server_side, cert_reqs=cert_reqs, |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 495 | ssl_version=ssl_version, ca_certs=ca_certs, |
Bill Janssen | 48dc27c | 2007-12-05 03:38:10 +0000 | [diff] [blame] | 496 | do_handshake_on_connect=do_handshake_on_connect, |
Antoine Pitrou | 2d9cb9c | 2010-04-17 17:40:45 +0000 | [diff] [blame] | 497 | suppress_ragged_eofs=suppress_ragged_eofs, |
| 498 | ciphers=ciphers) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 499 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 500 | # some utility functions |
| 501 | |
| 502 | def cert_time_to_seconds(cert_time): |
Thomas Wouters | 47b49bf | 2007-08-30 22:15:33 +0000 | [diff] [blame] | 503 | """Takes a date-time string in standard ASN1_print form |
| 504 | ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return |
| 505 | a Python time value in seconds past the epoch.""" |
| 506 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 507 | import time |
| 508 | return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT")) |
| 509 | |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 510 | PEM_HEADER = "-----BEGIN CERTIFICATE-----" |
| 511 | PEM_FOOTER = "-----END CERTIFICATE-----" |
| 512 | |
| 513 | def DER_cert_to_PEM_cert(der_cert_bytes): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 514 | """Takes a certificate in binary DER format and returns the |
| 515 | PEM version of it as a string.""" |
| 516 | |
Bill Janssen | 6e027db | 2007-11-15 22:23:56 +0000 | [diff] [blame] | 517 | f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict') |
| 518 | return (PEM_HEADER + '\n' + |
| 519 | textwrap.fill(f, 64) + '\n' + |
| 520 | PEM_FOOTER + '\n') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 521 | |
| 522 | def PEM_cert_to_DER_cert(pem_cert_string): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 523 | """Takes a certificate in ASCII PEM format and returns the |
| 524 | DER-encoded version of it as a byte sequence""" |
| 525 | |
| 526 | if not pem_cert_string.startswith(PEM_HEADER): |
| 527 | raise ValueError("Invalid PEM encoding; must start with %s" |
| 528 | % PEM_HEADER) |
| 529 | if not pem_cert_string.strip().endswith(PEM_FOOTER): |
| 530 | raise ValueError("Invalid PEM encoding; must end with %s" |
| 531 | % PEM_FOOTER) |
| 532 | d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] |
Georg Brandl | 706824f | 2009-06-04 09:42:55 +0000 | [diff] [blame] | 533 | return base64.decodebytes(d.encode('ASCII', 'strict')) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 534 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 535 | def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 536 | """Retrieve the certificate from the server at the specified address, |
| 537 | and return it as a PEM-encoded string. |
| 538 | If 'ca_certs' is specified, validate the server cert against it. |
| 539 | If 'ssl_version' is specified, use it in the connection attempt.""" |
| 540 | |
| 541 | host, port = addr |
| 542 | if (ca_certs is not None): |
| 543 | cert_reqs = CERT_REQUIRED |
| 544 | else: |
| 545 | cert_reqs = CERT_NONE |
Antoine Pitrou | 15399c3 | 2011-04-28 19:23:55 +0200 | [diff] [blame^] | 546 | s = create_connection(addr) |
| 547 | s = wrap_socket(s, ssl_version=ssl_version, |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 548 | cert_reqs=cert_reqs, ca_certs=ca_certs) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 549 | dercert = s.getpeercert(True) |
| 550 | s.close() |
| 551 | return DER_cert_to_PEM_cert(dercert) |
| 552 | |
Guido van Rossum | 5b8b155 | 2007-11-16 00:06:11 +0000 | [diff] [blame] | 553 | def get_protocol_name(protocol_code): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 554 | if protocol_code == PROTOCOL_TLSv1: |
| 555 | return "TLSv1" |
| 556 | elif protocol_code == PROTOCOL_SSLv23: |
| 557 | return "SSLv23" |
| 558 | elif protocol_code == PROTOCOL_SSLv2: |
| 559 | return "SSLv2" |
| 560 | elif protocol_code == PROTOCOL_SSLv3: |
| 561 | return "SSLv3" |
| 562 | else: |
| 563 | return "<unknown>" |