OLD | NEW |
(Empty) | |
| 1 import os |
| 2 import socket |
| 3 import atexit |
| 4 import re |
| 5 import functools |
| 6 |
| 7 from six.moves import urllib, http_client, map, filter |
| 8 |
| 9 from pkg_resources import ResolutionError, ExtractionError |
| 10 |
| 11 try: |
| 12 import ssl |
| 13 except ImportError: |
| 14 ssl = None |
| 15 |
| 16 __all__ = [ |
| 17 'VerifyingHTTPSHandler', 'find_ca_bundle', 'is_available', 'cert_paths', |
| 18 'opener_for' |
| 19 ] |
| 20 |
| 21 cert_paths = """ |
| 22 /etc/pki/tls/certs/ca-bundle.crt |
| 23 /etc/ssl/certs/ca-certificates.crt |
| 24 /usr/share/ssl/certs/ca-bundle.crt |
| 25 /usr/local/share/certs/ca-root.crt |
| 26 /etc/ssl/cert.pem |
| 27 /System/Library/OpenSSL/certs/cert.pem |
| 28 /usr/local/share/certs/ca-root-nss.crt |
| 29 /etc/ssl/ca-bundle.pem |
| 30 """.strip().split() |
| 31 |
| 32 try: |
| 33 HTTPSHandler = urllib.request.HTTPSHandler |
| 34 HTTPSConnection = http_client.HTTPSConnection |
| 35 except AttributeError: |
| 36 HTTPSHandler = HTTPSConnection = object |
| 37 |
| 38 is_available = ssl is not None and object not in (HTTPSHandler, HTTPSConnection) |
| 39 |
| 40 |
| 41 try: |
| 42 from ssl import CertificateError, match_hostname |
| 43 except ImportError: |
| 44 try: |
| 45 from backports.ssl_match_hostname import CertificateError |
| 46 from backports.ssl_match_hostname import match_hostname |
| 47 except ImportError: |
| 48 CertificateError = None |
| 49 match_hostname = None |
| 50 |
| 51 if not CertificateError: |
| 52 |
| 53 class CertificateError(ValueError): |
| 54 pass |
| 55 |
| 56 |
| 57 if not match_hostname: |
| 58 |
| 59 def _dnsname_match(dn, hostname, max_wildcards=1): |
| 60 """Matching according to RFC 6125, section 6.4.3 |
| 61 |
| 62 http://tools.ietf.org/html/rfc6125#section-6.4.3 |
| 63 """ |
| 64 pats = [] |
| 65 if not dn: |
| 66 return False |
| 67 |
| 68 # Ported from python3-syntax: |
| 69 # leftmost, *remainder = dn.split(r'.') |
| 70 parts = dn.split(r'.') |
| 71 leftmost = parts[0] |
| 72 remainder = parts[1:] |
| 73 |
| 74 wildcards = leftmost.count('*') |
| 75 if wildcards > max_wildcards: |
| 76 # Issue #17980: avoid denials of service by refusing more |
| 77 # than one wildcard per fragment. A survey of established |
| 78 # policy among SSL implementations showed it to be a |
| 79 # reasonable choice. |
| 80 raise CertificateError( |
| 81 "too many wildcards in certificate DNS name: " + repr(dn)) |
| 82 |
| 83 # speed up common case w/o wildcards |
| 84 if not wildcards: |
| 85 return dn.lower() == hostname.lower() |
| 86 |
| 87 # RFC 6125, section 6.4.3, subitem 1. |
| 88 # The client SHOULD NOT attempt to match a presented identifier in which |
| 89 # the wildcard character comprises a label other than the left-most labe
l. |
| 90 if leftmost == '*': |
| 91 # When '*' is a fragment by itself, it matches a non-empty dotless |
| 92 # fragment. |
| 93 pats.append('[^.]+') |
| 94 elif leftmost.startswith('xn--') or hostname.startswith('xn--'): |
| 95 # RFC 6125, section 6.4.3, subitem 3. |
| 96 # The client SHOULD NOT attempt to match a presented identifier |
| 97 # where the wildcard character is embedded within an A-label or |
| 98 # U-label of an internationalized domain name. |
| 99 pats.append(re.escape(leftmost)) |
| 100 else: |
| 101 # Otherwise, '*' matches any dotless string, e.g. www* |
| 102 pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) |
| 103 |
| 104 # add the remaining fragments, ignore any wildcards |
| 105 for frag in remainder: |
| 106 pats.append(re.escape(frag)) |
| 107 |
| 108 pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) |
| 109 return pat.match(hostname) |
| 110 |
| 111 def match_hostname(cert, hostname): |
| 112 """Verify that *cert* (in decoded format as returned by |
| 113 SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 |
| 114 rules are followed, but IP addresses are not accepted for *hostname*. |
| 115 |
| 116 CertificateError is raised on failure. On success, the function |
| 117 returns nothing. |
| 118 """ |
| 119 if not cert: |
| 120 raise ValueError("empty or no certificate") |
| 121 dnsnames = [] |
| 122 san = cert.get('subjectAltName', ()) |
| 123 for key, value in san: |
| 124 if key == 'DNS': |
| 125 if _dnsname_match(value, hostname): |
| 126 return |
| 127 dnsnames.append(value) |
| 128 if not dnsnames: |
| 129 # The subject is only checked when there is no dNSName entry |
| 130 # in subjectAltName |
| 131 for sub in cert.get('subject', ()): |
| 132 for key, value in sub: |
| 133 # XXX according to RFC 2818, the most specific Common Name |
| 134 # must be used. |
| 135 if key == 'commonName': |
| 136 if _dnsname_match(value, hostname): |
| 137 return |
| 138 dnsnames.append(value) |
| 139 if len(dnsnames) > 1: |
| 140 raise CertificateError("hostname %r " |
| 141 "doesn't match either of %s" |
| 142 % (hostname, ', '.join(map(repr, dnsnames)))) |
| 143 elif len(dnsnames) == 1: |
| 144 raise CertificateError("hostname %r " |
| 145 "doesn't match %r" |
| 146 % (hostname, dnsnames[0])) |
| 147 else: |
| 148 raise CertificateError("no appropriate commonName or " |
| 149 "subjectAltName fields were found") |
| 150 |
| 151 |
| 152 class VerifyingHTTPSHandler(HTTPSHandler): |
| 153 """Simple verifying handler: no auth, subclasses, timeouts, etc.""" |
| 154 |
| 155 def __init__(self, ca_bundle): |
| 156 self.ca_bundle = ca_bundle |
| 157 HTTPSHandler.__init__(self) |
| 158 |
| 159 def https_open(self, req): |
| 160 return self.do_open( |
| 161 lambda host, **kw: VerifyingHTTPSConn(host, self.ca_bundle, **kw), r
eq |
| 162 ) |
| 163 |
| 164 |
| 165 class VerifyingHTTPSConn(HTTPSConnection): |
| 166 """Simple verifying connection: no auth, subclasses, timeouts, etc.""" |
| 167 |
| 168 def __init__(self, host, ca_bundle, **kw): |
| 169 HTTPSConnection.__init__(self, host, **kw) |
| 170 self.ca_bundle = ca_bundle |
| 171 |
| 172 def connect(self): |
| 173 sock = socket.create_connection( |
| 174 (self.host, self.port), getattr(self, 'source_address', None) |
| 175 ) |
| 176 |
| 177 # Handle the socket if a (proxy) tunnel is present |
| 178 if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None): |
| 179 self.sock = sock |
| 180 self._tunnel() |
| 181 # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7 |
| 182 # change self.host to mean the proxy server host when tunneling is |
| 183 # being used. Adapt, since we are interested in the destination |
| 184 # host for the match_hostname() comparison. |
| 185 actual_host = self._tunnel_host |
| 186 else: |
| 187 actual_host = self.host |
| 188 |
| 189 self.sock = ssl.wrap_socket( |
| 190 sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle |
| 191 ) |
| 192 try: |
| 193 match_hostname(self.sock.getpeercert(), actual_host) |
| 194 except CertificateError: |
| 195 self.sock.shutdown(socket.SHUT_RDWR) |
| 196 self.sock.close() |
| 197 raise |
| 198 |
| 199 |
| 200 def opener_for(ca_bundle=None): |
| 201 """Get a urlopen() replacement that uses ca_bundle for verification""" |
| 202 return urllib.request.build_opener( |
| 203 VerifyingHTTPSHandler(ca_bundle or find_ca_bundle()) |
| 204 ).open |
| 205 |
| 206 |
| 207 # from jaraco.functools |
| 208 def once(func): |
| 209 @functools.wraps(func) |
| 210 def wrapper(*args, **kwargs): |
| 211 if not hasattr(func, 'always_returns'): |
| 212 func.always_returns = func(*args, **kwargs) |
| 213 return func.always_returns |
| 214 return wrapper |
| 215 |
| 216 |
| 217 @once |
| 218 def get_win_certfile(): |
| 219 try: |
| 220 import wincertstore |
| 221 except ImportError: |
| 222 return None |
| 223 |
| 224 class CertFile(wincertstore.CertFile): |
| 225 def __init__(self): |
| 226 super(CertFile, self).__init__() |
| 227 atexit.register(self.close) |
| 228 |
| 229 def close(self): |
| 230 try: |
| 231 super(CertFile, self).close() |
| 232 except OSError: |
| 233 pass |
| 234 |
| 235 _wincerts = CertFile() |
| 236 _wincerts.addstore('CA') |
| 237 _wincerts.addstore('ROOT') |
| 238 return _wincerts.name |
| 239 |
| 240 |
| 241 def find_ca_bundle(): |
| 242 """Return an existing CA bundle path, or None""" |
| 243 extant_cert_paths = filter(os.path.isfile, cert_paths) |
| 244 return ( |
| 245 get_win_certfile() |
| 246 or next(extant_cert_paths, None) |
| 247 or _certifi_where() |
| 248 ) |
| 249 |
| 250 |
| 251 def _certifi_where(): |
| 252 try: |
| 253 return __import__('certifi').where() |
| 254 except (ImportError, ResolutionError, ExtractionError): |
| 255 pass |
OLD | NEW |