PageRenderTime 53ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/env/lib/python3.3/site-packages/setuptools/ssl_support.py

https://github.com/wantsomechocolate/MosaicMaker
Python | 255 lines | 252 code | 3 blank | 0 comment | 5 complexity | ad88284615847bb36e7310a89d671d01 MD5 | raw file
  1. import sys, os, socket, atexit, re
  2. import pkg_resources
  3. from pkg_resources import ResolutionError, ExtractionError
  4. from setuptools.compat import urllib2
  5. try:
  6. import ssl
  7. except ImportError:
  8. ssl = None
  9. __all__ = [
  10. 'VerifyingHTTPSHandler', 'find_ca_bundle', 'is_available', 'cert_paths',
  11. 'opener_for'
  12. ]
  13. cert_paths = """
  14. /etc/pki/tls/certs/ca-bundle.crt
  15. /etc/ssl/certs/ca-certificates.crt
  16. /usr/share/ssl/certs/ca-bundle.crt
  17. /usr/local/share/certs/ca-root.crt
  18. /etc/ssl/cert.pem
  19. /System/Library/OpenSSL/certs/cert.pem
  20. """.strip().split()
  21. HTTPSHandler = HTTPSConnection = object
  22. for what, where in (
  23. ('HTTPSHandler', ['urllib2','urllib.request']),
  24. ('HTTPSConnection', ['httplib', 'http.client']),
  25. ):
  26. for module in where:
  27. try:
  28. exec("from %s import %s" % (module, what))
  29. except ImportError:
  30. pass
  31. is_available = ssl is not None and object not in (HTTPSHandler, HTTPSConnection)
  32. try:
  33. from socket import create_connection
  34. except ImportError:
  35. _GLOBAL_DEFAULT_TIMEOUT = getattr(socket, '_GLOBAL_DEFAULT_TIMEOUT', object())
  36. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
  37. source_address=None):
  38. """Connect to *address* and return the socket object.
  39. Convenience function. Connect to *address* (a 2-tuple ``(host,
  40. port)``) and return the socket object. Passing the optional
  41. *timeout* parameter will set the timeout on the socket instance
  42. before attempting to connect. If no *timeout* is supplied, the
  43. global default timeout setting returned by :func:`getdefaulttimeout`
  44. is used. If *source_address* is set it must be a tuple of (host, port)
  45. for the socket to bind as a source address before making the connection.
  46. An host of '' or port 0 tells the OS to use the default.
  47. """
  48. host, port = address
  49. err = None
  50. for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
  51. af, socktype, proto, canonname, sa = res
  52. sock = None
  53. try:
  54. sock = socket.socket(af, socktype, proto)
  55. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  56. sock.settimeout(timeout)
  57. if source_address:
  58. sock.bind(source_address)
  59. sock.connect(sa)
  60. return sock
  61. except error:
  62. err = True
  63. if sock is not None:
  64. sock.close()
  65. if err:
  66. raise
  67. else:
  68. raise error("getaddrinfo returns an empty list")
  69. try:
  70. from ssl import CertificateError, match_hostname
  71. except ImportError:
  72. class CertificateError(ValueError):
  73. pass
  74. def _dnsname_to_pat(dn, max_wildcards=1):
  75. pats = []
  76. for frag in dn.split(r'.'):
  77. if frag.count('*') > max_wildcards:
  78. # Issue #17980: avoid denials of service by refusing more
  79. # than one wildcard per fragment. A survery of established
  80. # policy among SSL implementations showed it to be a
  81. # reasonable choice.
  82. raise CertificateError(
  83. "too many wildcards in certificate DNS name: " + repr(dn))
  84. if frag == '*':
  85. # When '*' is a fragment by itself, it matches a non-empty dotless
  86. # fragment.
  87. pats.append('[^.]+')
  88. else:
  89. # Otherwise, '*' matches any dotless fragment.
  90. frag = re.escape(frag)
  91. pats.append(frag.replace(r'\*', '[^.]*'))
  92. return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
  93. def match_hostname(cert, hostname):
  94. """Verify that *cert* (in decoded format as returned by
  95. SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
  96. are mostly followed, but IP addresses are not accepted for *hostname*.
  97. CertificateError is raised on failure. On success, the function
  98. returns nothing.
  99. """
  100. if not cert:
  101. raise ValueError("empty or no certificate")
  102. dnsnames = []
  103. san = cert.get('subjectAltName', ())
  104. for key, value in san:
  105. if key == 'DNS':
  106. if _dnsname_to_pat(value).match(hostname):
  107. return
  108. dnsnames.append(value)
  109. if not dnsnames:
  110. # The subject is only checked when there is no dNSName entry
  111. # in subjectAltName
  112. for sub in cert.get('subject', ()):
  113. for key, value in sub:
  114. # XXX according to RFC 2818, the most specific Common Name
  115. # must be used.
  116. if key == 'commonName':
  117. if _dnsname_to_pat(value).match(hostname):
  118. return
  119. dnsnames.append(value)
  120. if len(dnsnames) > 1:
  121. raise CertificateError("hostname %r "
  122. "doesn't match either of %s"
  123. % (hostname, ', '.join(map(repr, dnsnames))))
  124. elif len(dnsnames) == 1:
  125. raise CertificateError("hostname %r "
  126. "doesn't match %r"
  127. % (hostname, dnsnames[0]))
  128. else:
  129. raise CertificateError("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), req
  139. )
  140. class VerifyingHTTPSConn(HTTPSConnection):
  141. """Simple verifying connection: no auth, subclasses, timeouts, etc."""
  142. def __init__(self, host, ca_bundle, **kw):
  143. HTTPSConnection.__init__(self, host, **kw)
  144. self.ca_bundle = ca_bundle
  145. def connect(self):
  146. sock = create_connection(
  147. (self.host, self.port), getattr(self,'source_address',None)
  148. )
  149. self.sock = ssl.wrap_socket(
  150. sock, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_bundle
  151. )
  152. try:
  153. match_hostname(self.sock.getpeercert(), self.host)
  154. except CertificateError:
  155. self.sock.shutdown(socket.SHUT_RDWR)
  156. self.sock.close()
  157. raise
  158. def opener_for(ca_bundle=None):
  159. """Get a urlopen() replacement that uses ca_bundle for verification"""
  160. return urllib2.build_opener(
  161. VerifyingHTTPSHandler(ca_bundle or find_ca_bundle())
  162. ).open
  163. _wincerts = None
  164. def get_win_certfile():
  165. global _wincerts
  166. if _wincerts is not None:
  167. return _wincerts.name
  168. try:
  169. from wincertstore import CertFile
  170. except ImportError:
  171. return None
  172. class MyCertFile(CertFile):
  173. def __init__(self, stores=(), certs=()):
  174. CertFile.__init__(self)
  175. for store in stores:
  176. self.addstore(store)
  177. self.addcerts(certs)
  178. atexit.register(self.close)
  179. _wincerts = MyCertFile(stores=['CA', 'ROOT'])
  180. return _wincerts.name
  181. def find_ca_bundle():
  182. """Return an existing CA bundle path, or None"""
  183. if os.name=='nt':
  184. return get_win_certfile()
  185. else:
  186. for cert_path in cert_paths:
  187. if os.path.isfile(cert_path):
  188. return cert_path
  189. try:
  190. return pkg_resources.resource_filename('certifi', 'cacert.pem')
  191. except (ImportError, ResolutionError, ExtractionError):
  192. return None