PageRenderTime 29ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/aws/apg-activitystream/apg-activitystream-csv-convert-lambda/urllib3/util/ssl_.py

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