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.

ssl_.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. from __future__ import absolute_import
  2. import errno
  3. import warnings
  4. import hmac
  5. from binascii import hexlify, unhexlify
  6. from hashlib import md5, sha1, sha256
  7. from ..exceptions import SSLError, InsecurePlatformWarning, SNIMissingWarning
  8. SSLContext = None
  9. HAS_SNI = False
  10. IS_PYOPENSSL = False
  11. IS_SECURETRANSPORT = False
  12. # Maps the length of a digest to a possible hash function producing this digest
  13. HASHFUNC_MAP = {
  14. 32: md5,
  15. 40: sha1,
  16. 64: sha256,
  17. }
  18. def _const_compare_digest_backport(a, b):
  19. """
  20. Compare two digests of equal length in constant time.
  21. The digests must be of type str/bytes.
  22. Returns True if the digests match, and False otherwise.
  23. """
  24. result = abs(len(a) - len(b))
  25. for l, r in zip(bytearray(a), bytearray(b)):
  26. result |= l ^ r
  27. return result == 0
  28. _const_compare_digest = getattr(hmac, 'compare_digest',
  29. _const_compare_digest_backport)
  30. try: # Test for SSL features
  31. import ssl
  32. from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23
  33. from ssl import HAS_SNI # Has SNI?
  34. except ImportError:
  35. pass
  36. try:
  37. from ssl import OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION
  38. except ImportError:
  39. OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000
  40. OP_NO_COMPRESSION = 0x20000
  41. # A secure default.
  42. # Sources for more information on TLS ciphers:
  43. #
  44. # - https://wiki.mozilla.org/Security/Server_Side_TLS
  45. # - https://www.ssllabs.com/projects/best-practices/index.html
  46. # - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
  47. #
  48. # The general intent is:
  49. # - Prefer TLS 1.3 cipher suites
  50. # - prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),
  51. # - prefer ECDHE over DHE for better performance,
  52. # - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and
  53. # security,
  54. # - prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common,
  55. # - disable NULL authentication, MD5 MACs and DSS for security reasons.
  56. DEFAULT_CIPHERS = ':'.join([
  57. 'TLS13-AES-256-GCM-SHA384',
  58. 'TLS13-CHACHA20-POLY1305-SHA256',
  59. 'TLS13-AES-128-GCM-SHA256',
  60. 'ECDH+AESGCM',
  61. 'ECDH+CHACHA20',
  62. 'DH+AESGCM',
  63. 'DH+CHACHA20',
  64. 'ECDH+AES256',
  65. 'DH+AES256',
  66. 'ECDH+AES128',
  67. 'DH+AES',
  68. 'RSA+AESGCM',
  69. 'RSA+AES',
  70. '!aNULL',
  71. '!eNULL',
  72. '!MD5',
  73. ])
  74. try:
  75. from ssl import SSLContext # Modern SSL?
  76. except ImportError:
  77. import sys
  78. class SSLContext(object): # Platform-specific: Python 2 & 3.1
  79. supports_set_ciphers = ((2, 7) <= sys.version_info < (3,) or
  80. (3, 2) <= sys.version_info)
  81. def __init__(self, protocol_version):
  82. self.protocol = protocol_version
  83. # Use default values from a real SSLContext
  84. self.check_hostname = False
  85. self.verify_mode = ssl.CERT_NONE
  86. self.ca_certs = None
  87. self.options = 0
  88. self.certfile = None
  89. self.keyfile = None
  90. self.ciphers = None
  91. def load_cert_chain(self, certfile, keyfile):
  92. self.certfile = certfile
  93. self.keyfile = keyfile
  94. def load_verify_locations(self, cafile=None, capath=None):
  95. self.ca_certs = cafile
  96. if capath is not None:
  97. raise SSLError("CA directories not supported in older Pythons")
  98. def set_ciphers(self, cipher_suite):
  99. if not self.supports_set_ciphers:
  100. raise TypeError(
  101. 'Your version of Python does not support setting '
  102. 'a custom cipher suite. Please upgrade to Python '
  103. '2.7, 3.2, or later if you need this functionality.'
  104. )
  105. self.ciphers = cipher_suite
  106. def wrap_socket(self, socket, server_hostname=None, server_side=False):
  107. warnings.warn(
  108. 'A true SSLContext object is not available. This prevents '
  109. 'urllib3 from configuring SSL appropriately and may cause '
  110. 'certain SSL connections to fail. You can upgrade to a newer '
  111. 'version of Python to solve this. For more information, see '
  112. 'https://urllib3.readthedocs.io/en/latest/advanced-usage.html'
  113. '#ssl-warnings',
  114. InsecurePlatformWarning
  115. )
  116. kwargs = {
  117. 'keyfile': self.keyfile,
  118. 'certfile': self.certfile,
  119. 'ca_certs': self.ca_certs,
  120. 'cert_reqs': self.verify_mode,
  121. 'ssl_version': self.protocol,
  122. 'server_side': server_side,
  123. }
  124. if self.supports_set_ciphers: # Platform-specific: Python 2.7+
  125. return wrap_socket(socket, ciphers=self.ciphers, **kwargs)
  126. else: # Platform-specific: Python 2.6
  127. return wrap_socket(socket, **kwargs)
  128. def assert_fingerprint(cert, fingerprint):
  129. """
  130. Checks if given fingerprint matches the supplied certificate.
  131. :param cert:
  132. Certificate as bytes object.
  133. :param fingerprint:
  134. Fingerprint as string of hexdigits, can be interspersed by colons.
  135. """
  136. fingerprint = fingerprint.replace(':', '').lower()
  137. digest_length = len(fingerprint)
  138. hashfunc = HASHFUNC_MAP.get(digest_length)
  139. if not hashfunc:
  140. raise SSLError(
  141. 'Fingerprint of invalid length: {0}'.format(fingerprint))
  142. # We need encode() here for py32; works on py2 and p33.
  143. fingerprint_bytes = unhexlify(fingerprint.encode())
  144. cert_digest = hashfunc(cert).digest()
  145. if not _const_compare_digest(cert_digest, fingerprint_bytes):
  146. raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'
  147. .format(fingerprint, hexlify(cert_digest)))
  148. def resolve_cert_reqs(candidate):
  149. """
  150. Resolves the argument to a numeric constant, which can be passed to
  151. the wrap_socket function/method from the ssl module.
  152. Defaults to :data:`ssl.CERT_NONE`.
  153. If given a string it is assumed to be the name of the constant in the
  154. :mod:`ssl` module or its abbrevation.
  155. (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.
  156. If it's neither `None` nor a string we assume it is already the numeric
  157. constant which can directly be passed to wrap_socket.
  158. """
  159. if candidate is None:
  160. return CERT_NONE
  161. if isinstance(candidate, str):
  162. res = getattr(ssl, candidate, None)
  163. if res is None:
  164. res = getattr(ssl, 'CERT_' + candidate)
  165. return res
  166. return candidate
  167. def resolve_ssl_version(candidate):
  168. """
  169. like resolve_cert_reqs
  170. """
  171. if candidate is None:
  172. return PROTOCOL_SSLv23
  173. if isinstance(candidate, str):
  174. res = getattr(ssl, candidate, None)
  175. if res is None:
  176. res = getattr(ssl, 'PROTOCOL_' + candidate)
  177. return res
  178. return candidate
  179. def create_urllib3_context(ssl_version=None, cert_reqs=None,
  180. options=None, ciphers=None):
  181. """All arguments have the same meaning as ``ssl_wrap_socket``.
  182. By default, this function does a lot of the same work that
  183. ``ssl.create_default_context`` does on Python 3.4+. It:
  184. - Disables SSLv2, SSLv3, and compression
  185. - Sets a restricted set of server ciphers
  186. If you wish to enable SSLv3, you can do::
  187. from pip._vendor.urllib3.util import ssl_
  188. context = ssl_.create_urllib3_context()
  189. context.options &= ~ssl_.OP_NO_SSLv3
  190. You can do the same to enable compression (substituting ``COMPRESSION``
  191. for ``SSLv3`` in the last line above).
  192. :param ssl_version:
  193. The desired protocol version to use. This will default to
  194. PROTOCOL_SSLv23 which will negotiate the highest protocol that both
  195. the server and your installation of OpenSSL support.
  196. :param cert_reqs:
  197. Whether to require the certificate verification. This defaults to
  198. ``ssl.CERT_REQUIRED``.
  199. :param options:
  200. Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
  201. ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``.
  202. :param ciphers:
  203. Which cipher suites to allow the server to select.
  204. :returns:
  205. Constructed SSLContext object with specified options
  206. :rtype: SSLContext
  207. """
  208. context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23)
  209. # Setting the default here, as we may have no ssl module on import
  210. cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
  211. if options is None:
  212. options = 0
  213. # SSLv2 is easily broken and is considered harmful and dangerous
  214. options |= OP_NO_SSLv2
  215. # SSLv3 has several problems and is now dangerous
  216. options |= OP_NO_SSLv3
  217. # Disable compression to prevent CRIME attacks for OpenSSL 1.0+
  218. # (issue #309)
  219. options |= OP_NO_COMPRESSION
  220. context.options |= options
  221. if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6
  222. context.set_ciphers(ciphers or DEFAULT_CIPHERS)
  223. context.verify_mode = cert_reqs
  224. if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2
  225. # We do our own verification, including fingerprints and alternative
  226. # hostnames. So disable it here
  227. context.check_hostname = False
  228. return context
  229. def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
  230. ca_certs=None, server_hostname=None,
  231. ssl_version=None, ciphers=None, ssl_context=None,
  232. ca_cert_dir=None):
  233. """
  234. All arguments except for server_hostname, ssl_context, and ca_cert_dir have
  235. the same meaning as they do when using :func:`ssl.wrap_socket`.
  236. :param server_hostname:
  237. When SNI is supported, the expected hostname of the certificate
  238. :param ssl_context:
  239. A pre-made :class:`SSLContext` object. If none is provided, one will
  240. be created using :func:`create_urllib3_context`.
  241. :param ciphers:
  242. A string of ciphers we wish the client to support. This is not
  243. supported on Python 2.6 as the ssl module does not support it.
  244. :param ca_cert_dir:
  245. A directory containing CA certificates in multiple separate files, as
  246. supported by OpenSSL's -CApath flag or the capath argument to
  247. SSLContext.load_verify_locations().
  248. """
  249. context = ssl_context
  250. if context is None:
  251. # Note: This branch of code and all the variables in it are no longer
  252. # used by urllib3 itself. We should consider deprecating and removing
  253. # this code.
  254. context = create_urllib3_context(ssl_version, cert_reqs,
  255. ciphers=ciphers)
  256. if ca_certs or ca_cert_dir:
  257. try:
  258. context.load_verify_locations(ca_certs, ca_cert_dir)
  259. except IOError as e: # Platform-specific: Python 2.6, 2.7, 3.2
  260. raise SSLError(e)
  261. # Py33 raises FileNotFoundError which subclasses OSError
  262. # These are not equivalent unless we check the errno attribute
  263. except OSError as e: # Platform-specific: Python 3.3 and beyond
  264. if e.errno == errno.ENOENT:
  265. raise SSLError(e)
  266. raise
  267. elif getattr(context, 'load_default_certs', None) is not None:
  268. # try to load OS default certs; works well on Windows (require Python3.4+)
  269. context.load_default_certs()
  270. if certfile:
  271. context.load_cert_chain(certfile, keyfile)
  272. if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
  273. return context.wrap_socket(sock, server_hostname=server_hostname)
  274. warnings.warn(
  275. 'An HTTPS request has been made, but the SNI (Subject Name '
  276. 'Indication) extension to TLS is not available on this platform. '
  277. 'This may cause the server to present an incorrect TLS '
  278. 'certificate, which can cause validation failures. You can upgrade to '
  279. 'a newer version of Python to solve this. For more information, see '
  280. 'https://urllib3.readthedocs.io/en/latest/advanced-usage.html'
  281. '#ssl-warnings',
  282. SNIMissingWarning
  283. )
  284. return context.wrap_socket(sock)