ssl_.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. from __future__ import absolute_import
  2. import hashlib
  3. import hmac
  4. import os
  5. import sys
  6. import warnings
  7. from binascii import hexlify, unhexlify
  8. from ..exceptions import (
  9. InsecurePlatformWarning,
  10. ProxySchemeUnsupported,
  11. SNIMissingWarning,
  12. SSLError,
  13. )
  14. from ..packages import six
  15. from .url import BRACELESS_IPV6_ADDRZ_RE, IPV4_RE
  16. SSLContext = None
  17. SSLTransport = None
  18. HAS_SNI = False
  19. IS_PYOPENSSL = False
  20. IS_SECURETRANSPORT = False
  21. ALPN_PROTOCOLS = ["http/1.1"]
  22. # Maps the length of a digest to a possible hash function producing this digest
  23. HASHFUNC_MAP = {
  24. length: getattr(hashlib, algorithm, None)
  25. for length, algorithm in ((32, "md5"), (40, "sha1"), (64, "sha256"))
  26. }
  27. def _const_compare_digest_backport(a, b):
  28. """
  29. Compare two digests of equal length in constant time.
  30. The digests must be of type str/bytes.
  31. Returns True if the digests match, and False otherwise.
  32. """
  33. result = abs(len(a) - len(b))
  34. for left, right in zip(bytearray(a), bytearray(b)):
  35. result |= left ^ right
  36. return result == 0
  37. _const_compare_digest = getattr(hmac, "compare_digest", _const_compare_digest_backport)
  38. try: # Test for SSL features
  39. import ssl
  40. from ssl import CERT_REQUIRED, wrap_socket
  41. except ImportError:
  42. pass
  43. try:
  44. from ssl import HAS_SNI # Has SNI?
  45. except ImportError:
  46. pass
  47. try:
  48. from .ssltransport import SSLTransport
  49. except ImportError:
  50. pass
  51. try: # Platform-specific: Python 3.6
  52. from ssl import PROTOCOL_TLS
  53. PROTOCOL_SSLv23 = PROTOCOL_TLS
  54. except ImportError:
  55. try:
  56. from ssl import PROTOCOL_SSLv23 as PROTOCOL_TLS
  57. PROTOCOL_SSLv23 = PROTOCOL_TLS
  58. except ImportError:
  59. PROTOCOL_SSLv23 = PROTOCOL_TLS = 2
  60. try:
  61. from ssl import PROTOCOL_TLS_CLIENT
  62. except ImportError:
  63. PROTOCOL_TLS_CLIENT = PROTOCOL_TLS
  64. try:
  65. from ssl import OP_NO_COMPRESSION, OP_NO_SSLv2, OP_NO_SSLv3
  66. except ImportError:
  67. OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000
  68. OP_NO_COMPRESSION = 0x20000
  69. try: # OP_NO_TICKET was added in Python 3.6
  70. from ssl import OP_NO_TICKET
  71. except ImportError:
  72. OP_NO_TICKET = 0x4000
  73. # A secure default.
  74. # Sources for more information on TLS ciphers:
  75. #
  76. # - https://wiki.mozilla.org/Security/Server_Side_TLS
  77. # - https://www.ssllabs.com/projects/best-practices/index.html
  78. # - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
  79. #
  80. # The general intent is:
  81. # - prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),
  82. # - prefer ECDHE over DHE for better performance,
  83. # - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and
  84. # security,
  85. # - prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common,
  86. # - disable NULL authentication, MD5 MACs, DSS, and other
  87. # insecure ciphers for security reasons.
  88. # - NOTE: TLS 1.3 cipher suites are managed through a different interface
  89. # not exposed by CPython (yet!) and are enabled by default if they're available.
  90. DEFAULT_CIPHERS = ":".join(
  91. [
  92. "ECDHE+AESGCM",
  93. "ECDHE+CHACHA20",
  94. "DHE+AESGCM",
  95. "DHE+CHACHA20",
  96. "ECDH+AESGCM",
  97. "DH+AESGCM",
  98. "ECDH+AES",
  99. "DH+AES",
  100. "RSA+AESGCM",
  101. "RSA+AES",
  102. "!aNULL",
  103. "!eNULL",
  104. "!MD5",
  105. "!DSS",
  106. ]
  107. )
  108. try:
  109. from ssl import SSLContext # Modern SSL?
  110. except ImportError:
  111. class SSLContext(object): # Platform-specific: Python 2
  112. def __init__(self, protocol_version):
  113. self.protocol = protocol_version
  114. # Use default values from a real SSLContext
  115. self.check_hostname = False
  116. self.verify_mode = ssl.CERT_NONE
  117. self.ca_certs = None
  118. self.options = 0
  119. self.certfile = None
  120. self.keyfile = None
  121. self.ciphers = None
  122. def load_cert_chain(self, certfile, keyfile):
  123. self.certfile = certfile
  124. self.keyfile = keyfile
  125. def load_verify_locations(self, cafile=None, capath=None, cadata=None):
  126. self.ca_certs = cafile
  127. if capath is not None:
  128. raise SSLError("CA directories not supported in older Pythons")
  129. if cadata is not None:
  130. raise SSLError("CA data not supported in older Pythons")
  131. def set_ciphers(self, cipher_suite):
  132. self.ciphers = cipher_suite
  133. def wrap_socket(self, socket, server_hostname=None, server_side=False):
  134. warnings.warn(
  135. "A true SSLContext object is not available. This prevents "
  136. "urllib3 from configuring SSL appropriately and may cause "
  137. "certain SSL connections to fail. You can upgrade to a newer "
  138. "version of Python to solve this. For more information, see "
  139. "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"
  140. "#ssl-warnings",
  141. InsecurePlatformWarning,
  142. )
  143. kwargs = {
  144. "keyfile": self.keyfile,
  145. "certfile": self.certfile,
  146. "ca_certs": self.ca_certs,
  147. "cert_reqs": self.verify_mode,
  148. "ssl_version": self.protocol,
  149. "server_side": server_side,
  150. }
  151. return wrap_socket(socket, ciphers=self.ciphers, **kwargs)
  152. def assert_fingerprint(cert, fingerprint):
  153. """
  154. Checks if given fingerprint matches the supplied certificate.
  155. :param cert:
  156. Certificate as bytes object.
  157. :param fingerprint:
  158. Fingerprint as string of hexdigits, can be interspersed by colons.
  159. """
  160. fingerprint = fingerprint.replace(":", "").lower()
  161. digest_length = len(fingerprint)
  162. if digest_length not in HASHFUNC_MAP:
  163. raise SSLError("Fingerprint of invalid length: {0}".format(fingerprint))
  164. hashfunc = HASHFUNC_MAP.get(digest_length)
  165. if hashfunc is None:
  166. raise SSLError(
  167. "Hash function implementation unavailable for fingerprint length: {0}".format(
  168. digest_length
  169. )
  170. )
  171. # We need encode() here for py32; works on py2 and p33.
  172. fingerprint_bytes = unhexlify(fingerprint.encode())
  173. cert_digest = hashfunc(cert).digest()
  174. if not _const_compare_digest(cert_digest, fingerprint_bytes):
  175. raise SSLError(
  176. 'Fingerprints did not match. Expected "{0}", got "{1}".'.format(
  177. fingerprint, hexlify(cert_digest)
  178. )
  179. )
  180. def resolve_cert_reqs(candidate):
  181. """
  182. Resolves the argument to a numeric constant, which can be passed to
  183. the wrap_socket function/method from the ssl module.
  184. Defaults to :data:`ssl.CERT_REQUIRED`.
  185. If given a string it is assumed to be the name of the constant in the
  186. :mod:`ssl` module or its abbreviation.
  187. (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.
  188. If it's neither `None` nor a string we assume it is already the numeric
  189. constant which can directly be passed to wrap_socket.
  190. """
  191. if candidate is None:
  192. return CERT_REQUIRED
  193. if isinstance(candidate, str):
  194. res = getattr(ssl, candidate, None)
  195. if res is None:
  196. res = getattr(ssl, "CERT_" + candidate)
  197. return res
  198. return candidate
  199. def resolve_ssl_version(candidate):
  200. """
  201. like resolve_cert_reqs
  202. """
  203. if candidate is None:
  204. return PROTOCOL_TLS
  205. if isinstance(candidate, str):
  206. res = getattr(ssl, candidate, None)
  207. if res is None:
  208. res = getattr(ssl, "PROTOCOL_" + candidate)
  209. return res
  210. return candidate
  211. def create_urllib3_context(
  212. ssl_version=None, cert_reqs=None, options=None, ciphers=None
  213. ):
  214. """All arguments have the same meaning as ``ssl_wrap_socket``.
  215. By default, this function does a lot of the same work that
  216. ``ssl.create_default_context`` does on Python 3.4+. It:
  217. - Disables SSLv2, SSLv3, and compression
  218. - Sets a restricted set of server ciphers
  219. If you wish to enable SSLv3, you can do::
  220. from urllib3.util import ssl_
  221. context = ssl_.create_urllib3_context()
  222. context.options &= ~ssl_.OP_NO_SSLv3
  223. You can do the same to enable compression (substituting ``COMPRESSION``
  224. for ``SSLv3`` in the last line above).
  225. :param ssl_version:
  226. The desired protocol version to use. This will default to
  227. PROTOCOL_SSLv23 which will negotiate the highest protocol that both
  228. the server and your installation of OpenSSL support.
  229. :param cert_reqs:
  230. Whether to require the certificate verification. This defaults to
  231. ``ssl.CERT_REQUIRED``.
  232. :param options:
  233. Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
  234. ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``.
  235. :param ciphers:
  236. Which cipher suites to allow the server to select.
  237. :returns:
  238. Constructed SSLContext object with specified options
  239. :rtype: SSLContext
  240. """
  241. # PROTOCOL_TLS is deprecated in Python 3.10
  242. if not ssl_version or ssl_version == PROTOCOL_TLS:
  243. ssl_version = PROTOCOL_TLS_CLIENT
  244. context = SSLContext(ssl_version)
  245. context.set_ciphers(ciphers or DEFAULT_CIPHERS)
  246. # Setting the default here, as we may have no ssl module on import
  247. cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
  248. if options is None:
  249. options = 0
  250. # SSLv2 is easily broken and is considered harmful and dangerous
  251. options |= OP_NO_SSLv2
  252. # SSLv3 has several problems and is now dangerous
  253. options |= OP_NO_SSLv3
  254. # Disable compression to prevent CRIME attacks for OpenSSL 1.0+
  255. # (issue #309)
  256. options |= OP_NO_COMPRESSION
  257. # TLSv1.2 only. Unless set explicitly, do not request tickets.
  258. # This may save some bandwidth on wire, and although the ticket is encrypted,
  259. # there is a risk associated with it being on wire,
  260. # if the server is not rotating its ticketing keys properly.
  261. options |= OP_NO_TICKET
  262. context.options |= options
  263. # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is
  264. # necessary for conditional client cert authentication with TLS 1.3.
  265. # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older
  266. # versions of Python. We only enable on Python 3.7.4+ or if certificate
  267. # verification is enabled to work around Python issue #37428
  268. # See: https://bugs.python.org/issue37428
  269. if (cert_reqs == ssl.CERT_REQUIRED or sys.version_info >= (3, 7, 4)) and getattr(
  270. context, "post_handshake_auth", None
  271. ) is not None:
  272. context.post_handshake_auth = True
  273. def disable_check_hostname():
  274. if (
  275. getattr(context, "check_hostname", None) is not None
  276. ): # Platform-specific: Python 3.2
  277. # We do our own verification, including fingerprints and alternative
  278. # hostnames. So disable it here
  279. context.check_hostname = False
  280. # The order of the below lines setting verify_mode and check_hostname
  281. # matter due to safe-guards SSLContext has to prevent an SSLContext with
  282. # check_hostname=True, verify_mode=NONE/OPTIONAL. This is made even more
  283. # complex because we don't know whether PROTOCOL_TLS_CLIENT will be used
  284. # or not so we don't know the initial state of the freshly created SSLContext.
  285. if cert_reqs == ssl.CERT_REQUIRED:
  286. context.verify_mode = cert_reqs
  287. disable_check_hostname()
  288. else:
  289. disable_check_hostname()
  290. context.verify_mode = cert_reqs
  291. # Enable logging of TLS session keys via defacto standard environment variable
  292. # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values.
  293. if hasattr(context, "keylog_filename"):
  294. sslkeylogfile = os.environ.get("SSLKEYLOGFILE")
  295. if sslkeylogfile:
  296. context.keylog_filename = sslkeylogfile
  297. return context
  298. def ssl_wrap_socket(
  299. sock,
  300. keyfile=None,
  301. certfile=None,
  302. cert_reqs=None,
  303. ca_certs=None,
  304. server_hostname=None,
  305. ssl_version=None,
  306. ciphers=None,
  307. ssl_context=None,
  308. ca_cert_dir=None,
  309. key_password=None,
  310. ca_cert_data=None,
  311. tls_in_tls=False,
  312. ):
  313. """
  314. All arguments except for server_hostname, ssl_context, and ca_cert_dir have
  315. the same meaning as they do when using :func:`ssl.wrap_socket`.
  316. :param server_hostname:
  317. When SNI is supported, the expected hostname of the certificate
  318. :param ssl_context:
  319. A pre-made :class:`SSLContext` object. If none is provided, one will
  320. be created using :func:`create_urllib3_context`.
  321. :param ciphers:
  322. A string of ciphers we wish the client to support.
  323. :param ca_cert_dir:
  324. A directory containing CA certificates in multiple separate files, as
  325. supported by OpenSSL's -CApath flag or the capath argument to
  326. SSLContext.load_verify_locations().
  327. :param key_password:
  328. Optional password if the keyfile is encrypted.
  329. :param ca_cert_data:
  330. Optional string containing CA certificates in PEM format suitable for
  331. passing as the cadata parameter to SSLContext.load_verify_locations()
  332. :param tls_in_tls:
  333. Use SSLTransport to wrap the existing socket.
  334. """
  335. context = ssl_context
  336. if context is None:
  337. # Note: This branch of code and all the variables in it are no longer
  338. # used by urllib3 itself. We should consider deprecating and removing
  339. # this code.
  340. context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers)
  341. if ca_certs or ca_cert_dir or ca_cert_data:
  342. try:
  343. context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data)
  344. except (IOError, OSError) as e:
  345. raise SSLError(e)
  346. elif ssl_context is None and hasattr(context, "load_default_certs"):
  347. # try to load OS default certs; works well on Windows (require Python3.4+)
  348. context.load_default_certs()
  349. # Attempt to detect if we get the goofy behavior of the
  350. # keyfile being encrypted and OpenSSL asking for the
  351. # passphrase via the terminal and instead error out.
  352. if keyfile and key_password is None and _is_key_file_encrypted(keyfile):
  353. raise SSLError("Client private key is encrypted, password is required")
  354. if certfile:
  355. if key_password is None:
  356. context.load_cert_chain(certfile, keyfile)
  357. else:
  358. context.load_cert_chain(certfile, keyfile, key_password)
  359. try:
  360. if hasattr(context, "set_alpn_protocols"):
  361. context.set_alpn_protocols(ALPN_PROTOCOLS)
  362. except NotImplementedError: # Defensive: in CI, we always have set_alpn_protocols
  363. pass
  364. # If we detect server_hostname is an IP address then the SNI
  365. # extension should not be used according to RFC3546 Section 3.1
  366. use_sni_hostname = server_hostname and not is_ipaddress(server_hostname)
  367. # SecureTransport uses server_hostname in certificate verification.
  368. send_sni = (use_sni_hostname and HAS_SNI) or (
  369. IS_SECURETRANSPORT and server_hostname
  370. )
  371. # Do not warn the user if server_hostname is an invalid SNI hostname.
  372. if not HAS_SNI and use_sni_hostname:
  373. warnings.warn(
  374. "An HTTPS request has been made, but the SNI (Server Name "
  375. "Indication) extension to TLS is not available on this platform. "
  376. "This may cause the server to present an incorrect TLS "
  377. "certificate, which can cause validation failures. You can upgrade to "
  378. "a newer version of Python to solve this. For more information, see "
  379. "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"
  380. "#ssl-warnings",
  381. SNIMissingWarning,
  382. )
  383. if send_sni:
  384. ssl_sock = _ssl_wrap_socket_impl(
  385. sock, context, tls_in_tls, server_hostname=server_hostname
  386. )
  387. else:
  388. ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)
  389. return ssl_sock
  390. def is_ipaddress(hostname):
  391. """Detects whether the hostname given is an IPv4 or IPv6 address.
  392. Also detects IPv6 addresses with Zone IDs.
  393. :param str hostname: Hostname to examine.
  394. :return: True if the hostname is an IP address, False otherwise.
  395. """
  396. if not six.PY2 and isinstance(hostname, bytes):
  397. # IDN A-label bytes are ASCII compatible.
  398. hostname = hostname.decode("ascii")
  399. return bool(IPV4_RE.match(hostname) or BRACELESS_IPV6_ADDRZ_RE.match(hostname))
  400. def _is_key_file_encrypted(key_file):
  401. """Detects if a key file is encrypted or not."""
  402. with open(key_file, "r") as f:
  403. for line in f:
  404. # Look for Proc-Type: 4,ENCRYPTED
  405. if "ENCRYPTED" in line:
  406. return True
  407. return False
  408. def _ssl_wrap_socket_impl(sock, ssl_context, tls_in_tls, server_hostname=None):
  409. if tls_in_tls:
  410. if not SSLTransport:
  411. # Import error, ssl is not available.
  412. raise ProxySchemeUnsupported(
  413. "TLS in TLS requires support for the 'ssl' module"
  414. )
  415. SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context)
  416. return SSLTransport(sock, ssl_context, server_hostname)
  417. if server_hostname:
  418. return ssl_context.wrap_socket(sock, server_hostname=server_hostname)
  419. else:
  420. return ssl_context.wrap_socket(sock)