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