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