You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

242 lines
7.9 KiB

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