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