1
0

ssl_support.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. import os
  2. import socket
  3. import atexit
  4. import re
  5. import functools
  6. from setuptools.extern.six.moves import urllib, http_client, map, filter
  7. from pkg_resources import ResolutionError, ExtractionError
  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. /usr/local/share/certs/ca-root-nss.crt
  24. /etc/ssl/ca-bundle.pem
  25. """.strip().split()
  26. try:
  27. HTTPSHandler = urllib.request.HTTPSHandler
  28. HTTPSConnection = http_client.HTTPSConnection
  29. except AttributeError:
  30. HTTPSHandler = HTTPSConnection = object
  31. is_available = ssl is not None and object not in (
  32. HTTPSHandler, HTTPSConnection)
  33. try:
  34. from ssl import CertificateError, match_hostname
  35. except ImportError:
  36. try:
  37. from backports.ssl_match_hostname import CertificateError
  38. from backports.ssl_match_hostname import match_hostname
  39. except ImportError:
  40. CertificateError = None
  41. match_hostname = None
  42. if not CertificateError:
  43. class CertificateError(ValueError):
  44. pass
  45. if not match_hostname:
  46. def _dnsname_match(dn, hostname, max_wildcards=1):
  47. """Matching according to RFC 6125, section 6.4.3
  48. https://tools.ietf.org/html/rfc6125#section-6.4.3
  49. """
  50. pats = []
  51. if not dn:
  52. return False
  53. # Ported from python3-syntax:
  54. # leftmost, *remainder = dn.split(r'.')
  55. parts = dn.split(r'.')
  56. leftmost = parts[0]
  57. remainder = parts[1:]
  58. wildcards = leftmost.count('*')
  59. if wildcards > max_wildcards:
  60. # Issue #17980: avoid denials of service by refusing more
  61. # than one wildcard per fragment. A survey of established
  62. # policy among SSL implementations showed it to be a
  63. # reasonable choice.
  64. raise CertificateError(
  65. "too many wildcards in certificate DNS name: " + repr(dn))
  66. # speed up common case w/o wildcards
  67. if not wildcards:
  68. return dn.lower() == hostname.lower()
  69. # RFC 6125, section 6.4.3, subitem 1.
  70. # The client SHOULD NOT attempt to match a
  71. # presented identifier in which the wildcard
  72. # character comprises a label other than the
  73. # 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(
  121. "hostname %r doesn't match either of %s"
  122. % (hostname, ', '.join(map(repr, dnsnames))))
  123. elif len(dnsnames) == 1:
  124. raise CertificateError(
  125. "hostname %r doesn't match %r"
  126. % (hostname, dnsnames[0]))
  127. else:
  128. raise CertificateError(
  129. "no appropriate commonName or "
  130. "subjectAltName fields were found")
  131. class VerifyingHTTPSHandler(HTTPSHandler):
  132. """Simple verifying handler: no auth, subclasses, timeouts, etc."""
  133. def __init__(self, ca_bundle):
  134. self.ca_bundle = ca_bundle
  135. HTTPSHandler.__init__(self)
  136. def https_open(self, req):
  137. return self.do_open(
  138. lambda host, **kw: VerifyingHTTPSConn(host, self.ca_bundle, **kw),
  139. req
  140. )
  141. class VerifyingHTTPSConn(HTTPSConnection):
  142. """Simple verifying connection: no auth, subclasses, timeouts, etc."""
  143. def __init__(self, host, ca_bundle, **kw):
  144. HTTPSConnection.__init__(self, host, **kw)
  145. self.ca_bundle = ca_bundle
  146. def connect(self):
  147. sock = socket.create_connection(
  148. (self.host, self.port), getattr(self, 'source_address', None)
  149. )
  150. # Handle the socket if a (proxy) tunnel is present
  151. if hasattr(self, '_tunnel') and getattr(self, '_tunnel_host', None):
  152. self.sock = sock
  153. self._tunnel()
  154. # http://bugs.python.org/issue7776: Python>=3.4.1 and >=2.7.7
  155. # change self.host to mean the proxy server host when tunneling is
  156. # being used. Adapt, since we are interested in the destination
  157. # host for the match_hostname() comparison.
  158. actual_host = self._tunnel_host
  159. else:
  160. actual_host = self.host
  161. if hasattr(ssl, 'create_default_context'):
  162. ctx = ssl.create_default_context(cafile=self.ca_bundle)
  163. self.sock = ctx.wrap_socket(sock, server_hostname=actual_host)
  164. else:
  165. # This is for python < 2.7.9 and < 3.4?
  166. self.sock = ssl.wrap_socket(
  167. sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle
  168. )
  169. try:
  170. match_hostname(self.sock.getpeercert(), actual_host)
  171. except CertificateError:
  172. self.sock.shutdown(socket.SHUT_RDWR)
  173. self.sock.close()
  174. raise
  175. def opener_for(ca_bundle=None):
  176. """Get a urlopen() replacement that uses ca_bundle for verification"""
  177. return urllib.request.build_opener(
  178. VerifyingHTTPSHandler(ca_bundle or find_ca_bundle())
  179. ).open
  180. # from jaraco.functools
  181. def once(func):
  182. @functools.wraps(func)
  183. def wrapper(*args, **kwargs):
  184. if not hasattr(func, 'always_returns'):
  185. func.always_returns = func(*args, **kwargs)
  186. return func.always_returns
  187. return wrapper
  188. @once
  189. def get_win_certfile():
  190. try:
  191. import wincertstore
  192. except ImportError:
  193. return None
  194. class CertFile(wincertstore.CertFile):
  195. def __init__(self):
  196. super(CertFile, self).__init__()
  197. atexit.register(self.close)
  198. def close(self):
  199. try:
  200. super(CertFile, self).close()
  201. except OSError:
  202. pass
  203. _wincerts = CertFile()
  204. _wincerts.addstore('CA')
  205. _wincerts.addstore('ROOT')
  206. return _wincerts.name
  207. def find_ca_bundle():
  208. """Return an existing CA bundle path, or None"""
  209. extant_cert_paths = filter(os.path.isfile, cert_paths)
  210. return (
  211. get_win_certfile()
  212. or next(extant_cert_paths, None)
  213. or _certifi_where()
  214. )
  215. def _certifi_where():
  216. try:
  217. return __import__('certifi').where()
  218. except (ImportError, ResolutionError, ExtractionError):
  219. pass