ssl_support.py 7.9 KB

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