ssl_.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. from __future__ import annotations
  2. import hmac
  3. import os
  4. import socket
  5. import sys
  6. import typing
  7. import warnings
  8. from binascii import unhexlify
  9. from hashlib import md5, sha1, sha256
  10. from ..exceptions import ProxySchemeUnsupported, SSLError
  11. from .url import _BRACELESS_IPV6_ADDRZ_RE, _IPV4_RE
  12. SSLContext = None
  13. SSLTransport = None
  14. HAS_NEVER_CHECK_COMMON_NAME = False
  15. IS_PYOPENSSL = False
  16. ALPN_PROTOCOLS = ["http/1.1"]
  17. _TYPE_VERSION_INFO = typing.Tuple[int, int, int, str, int]
  18. # Maps the length of a digest to a possible hash function producing this digest
  19. HASHFUNC_MAP = {32: md5, 40: sha1, 64: sha256}
  20. def _is_bpo_43522_fixed(
  21. implementation_name: str,
  22. version_info: _TYPE_VERSION_INFO,
  23. pypy_version_info: _TYPE_VERSION_INFO | None,
  24. ) -> bool:
  25. """Return True for CPython 3.8.9+, 3.9.3+ or 3.10+ and PyPy 7.3.8+ where
  26. setting SSLContext.hostname_checks_common_name to False works.
  27. Outside of CPython and PyPy we don't know which implementations work
  28. or not so we conservatively use our hostname matching as we know that works
  29. on all implementations.
  30. https://github.com/urllib3/urllib3/issues/2192#issuecomment-821832963
  31. https://foss.heptapod.net/pypy/pypy/-/issues/3539
  32. """
  33. if implementation_name == "pypy":
  34. # https://foss.heptapod.net/pypy/pypy/-/issues/3129
  35. return pypy_version_info >= (7, 3, 8) # type: ignore[operator]
  36. elif implementation_name == "cpython":
  37. major_minor = version_info[:2]
  38. micro = version_info[2]
  39. return (
  40. (major_minor == (3, 8) and micro >= 9)
  41. or (major_minor == (3, 9) and micro >= 3)
  42. or major_minor >= (3, 10)
  43. )
  44. else: # Defensive:
  45. return False
  46. def _is_has_never_check_common_name_reliable(
  47. openssl_version: str,
  48. openssl_version_number: int,
  49. implementation_name: str,
  50. version_info: _TYPE_VERSION_INFO,
  51. pypy_version_info: _TYPE_VERSION_INFO | None,
  52. ) -> bool:
  53. # As of May 2023, all released versions of LibreSSL fail to reject certificates with
  54. # only common names, see https://github.com/urllib3/urllib3/pull/3024
  55. is_openssl = openssl_version.startswith("OpenSSL ")
  56. # Before fixing OpenSSL issue #14579, the SSL_new() API was not copying hostflags
  57. # like X509_CHECK_FLAG_NEVER_CHECK_SUBJECT, which tripped up CPython.
  58. # https://github.com/openssl/openssl/issues/14579
  59. # This was released in OpenSSL 1.1.1l+ (>=0x101010cf)
  60. is_openssl_issue_14579_fixed = openssl_version_number >= 0x101010CF
  61. return is_openssl and (
  62. is_openssl_issue_14579_fixed
  63. or _is_bpo_43522_fixed(implementation_name, version_info, pypy_version_info)
  64. )
  65. if typing.TYPE_CHECKING:
  66. from ssl import VerifyMode
  67. from typing import Literal, TypedDict
  68. from .ssltransport import SSLTransport as SSLTransportType
  69. class _TYPE_PEER_CERT_RET_DICT(TypedDict, total=False):
  70. subjectAltName: tuple[tuple[str, str], ...]
  71. subject: tuple[tuple[tuple[str, str], ...], ...]
  72. serialNumber: str
  73. # Mapping from 'ssl.PROTOCOL_TLSX' to 'TLSVersion.X'
  74. _SSL_VERSION_TO_TLS_VERSION: dict[int, int] = {}
  75. try: # Do we have ssl at all?
  76. import ssl
  77. from ssl import ( # type: ignore[assignment]
  78. CERT_REQUIRED,
  79. HAS_NEVER_CHECK_COMMON_NAME,
  80. OP_NO_COMPRESSION,
  81. OP_NO_TICKET,
  82. OPENSSL_VERSION,
  83. OPENSSL_VERSION_NUMBER,
  84. PROTOCOL_TLS,
  85. PROTOCOL_TLS_CLIENT,
  86. OP_NO_SSLv2,
  87. OP_NO_SSLv3,
  88. SSLContext,
  89. TLSVersion,
  90. )
  91. PROTOCOL_SSLv23 = PROTOCOL_TLS
  92. # Setting SSLContext.hostname_checks_common_name = False didn't work before CPython
  93. # 3.8.9, 3.9.3, and 3.10 (but OK on PyPy) or OpenSSL 1.1.1l+
  94. if HAS_NEVER_CHECK_COMMON_NAME and not _is_has_never_check_common_name_reliable(
  95. OPENSSL_VERSION,
  96. OPENSSL_VERSION_NUMBER,
  97. sys.implementation.name,
  98. sys.version_info,
  99. sys.pypy_version_info if sys.implementation.name == "pypy" else None, # type: ignore[attr-defined]
  100. ):
  101. HAS_NEVER_CHECK_COMMON_NAME = False
  102. # Need to be careful here in case old TLS versions get
  103. # removed in future 'ssl' module implementations.
  104. for attr in ("TLSv1", "TLSv1_1", "TLSv1_2"):
  105. try:
  106. _SSL_VERSION_TO_TLS_VERSION[getattr(ssl, f"PROTOCOL_{attr}")] = getattr(
  107. TLSVersion, attr
  108. )
  109. except AttributeError: # Defensive:
  110. continue
  111. from .ssltransport import SSLTransport # type: ignore[assignment]
  112. except ImportError:
  113. OP_NO_COMPRESSION = 0x20000 # type: ignore[assignment]
  114. OP_NO_TICKET = 0x4000 # type: ignore[assignment]
  115. OP_NO_SSLv2 = 0x1000000 # type: ignore[assignment]
  116. OP_NO_SSLv3 = 0x2000000 # type: ignore[assignment]
  117. PROTOCOL_SSLv23 = PROTOCOL_TLS = 2 # type: ignore[assignment]
  118. PROTOCOL_TLS_CLIENT = 16 # type: ignore[assignment]
  119. _TYPE_PEER_CERT_RET = typing.Union["_TYPE_PEER_CERT_RET_DICT", bytes, None]
  120. def assert_fingerprint(cert: bytes | None, fingerprint: str) -> None:
  121. """
  122. Checks if given fingerprint matches the supplied certificate.
  123. :param cert:
  124. Certificate as bytes object.
  125. :param fingerprint:
  126. Fingerprint as string of hexdigits, can be interspersed by colons.
  127. """
  128. if cert is None:
  129. raise SSLError("No certificate for the peer.")
  130. fingerprint = fingerprint.replace(":", "").lower()
  131. digest_length = len(fingerprint)
  132. hashfunc = HASHFUNC_MAP.get(digest_length)
  133. if not hashfunc:
  134. raise SSLError(f"Fingerprint of invalid length: {fingerprint}")
  135. # We need encode() here for py32; works on py2 and p33.
  136. fingerprint_bytes = unhexlify(fingerprint.encode())
  137. cert_digest = hashfunc(cert).digest()
  138. if not hmac.compare_digest(cert_digest, fingerprint_bytes):
  139. raise SSLError(
  140. f'Fingerprints did not match. Expected "{fingerprint}", got "{cert_digest.hex()}"'
  141. )
  142. def resolve_cert_reqs(candidate: None | int | str) -> VerifyMode:
  143. """
  144. Resolves the argument to a numeric constant, which can be passed to
  145. the wrap_socket function/method from the ssl module.
  146. Defaults to :data:`ssl.CERT_REQUIRED`.
  147. If given a string it is assumed to be the name of the constant in the
  148. :mod:`ssl` module or its abbreviation.
  149. (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.
  150. If it's neither `None` nor a string we assume it is already the numeric
  151. constant which can directly be passed to wrap_socket.
  152. """
  153. if candidate is None:
  154. return CERT_REQUIRED
  155. if isinstance(candidate, str):
  156. res = getattr(ssl, candidate, None)
  157. if res is None:
  158. res = getattr(ssl, "CERT_" + candidate)
  159. return res # type: ignore[no-any-return]
  160. return candidate # type: ignore[return-value]
  161. def resolve_ssl_version(candidate: None | int | str) -> int:
  162. """
  163. like resolve_cert_reqs
  164. """
  165. if candidate is None:
  166. return PROTOCOL_TLS
  167. if isinstance(candidate, str):
  168. res = getattr(ssl, candidate, None)
  169. if res is None:
  170. res = getattr(ssl, "PROTOCOL_" + candidate)
  171. return typing.cast(int, res)
  172. return candidate
  173. def create_urllib3_context(
  174. ssl_version: int | None = None,
  175. cert_reqs: int | None = None,
  176. options: int | None = None,
  177. ciphers: str | None = None,
  178. ssl_minimum_version: int | None = None,
  179. ssl_maximum_version: int | None = None,
  180. ) -> ssl.SSLContext:
  181. """Creates and configures an :class:`ssl.SSLContext` instance for use with urllib3.
  182. :param ssl_version:
  183. The desired protocol version to use. This will default to
  184. PROTOCOL_SSLv23 which will negotiate the highest protocol that both
  185. the server and your installation of OpenSSL support.
  186. This parameter is deprecated instead use 'ssl_minimum_version'.
  187. :param ssl_minimum_version:
  188. The minimum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value.
  189. :param ssl_maximum_version:
  190. The maximum version of TLS to be used. Use the 'ssl.TLSVersion' enum for specifying the value.
  191. Not recommended to set to anything other than 'ssl.TLSVersion.MAXIMUM_SUPPORTED' which is the
  192. default value.
  193. :param cert_reqs:
  194. Whether to require the certificate verification. This defaults to
  195. ``ssl.CERT_REQUIRED``.
  196. :param options:
  197. Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
  198. ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``.
  199. :param ciphers:
  200. Which cipher suites to allow the server to select. Defaults to either system configured
  201. ciphers if OpenSSL 1.1.1+, otherwise uses a secure default set of ciphers.
  202. :returns:
  203. Constructed SSLContext object with specified options
  204. :rtype: SSLContext
  205. """
  206. if SSLContext is None:
  207. raise TypeError("Can't create an SSLContext object without an ssl module")
  208. # This means 'ssl_version' was specified as an exact value.
  209. if ssl_version not in (None, PROTOCOL_TLS, PROTOCOL_TLS_CLIENT):
  210. # Disallow setting 'ssl_version' and 'ssl_minimum|maximum_version'
  211. # to avoid conflicts.
  212. if ssl_minimum_version is not None or ssl_maximum_version is not None:
  213. raise ValueError(
  214. "Can't specify both 'ssl_version' and either "
  215. "'ssl_minimum_version' or 'ssl_maximum_version'"
  216. )
  217. # 'ssl_version' is deprecated and will be removed in the future.
  218. else:
  219. # Use 'ssl_minimum_version' and 'ssl_maximum_version' instead.
  220. ssl_minimum_version = _SSL_VERSION_TO_TLS_VERSION.get(
  221. ssl_version, TLSVersion.MINIMUM_SUPPORTED
  222. )
  223. ssl_maximum_version = _SSL_VERSION_TO_TLS_VERSION.get(
  224. ssl_version, TLSVersion.MAXIMUM_SUPPORTED
  225. )
  226. # This warning message is pushing users to use 'ssl_minimum_version'
  227. # instead of both min/max. Best practice is to only set the minimum version and
  228. # keep the maximum version to be it's default value: 'TLSVersion.MAXIMUM_SUPPORTED'
  229. warnings.warn(
  230. "'ssl_version' option is deprecated and will be "
  231. "removed in urllib3 v2.1.0. Instead use 'ssl_minimum_version'",
  232. category=DeprecationWarning,
  233. stacklevel=2,
  234. )
  235. # PROTOCOL_TLS is deprecated in Python 3.10 so we always use PROTOCOL_TLS_CLIENT
  236. context = SSLContext(PROTOCOL_TLS_CLIENT)
  237. if ssl_minimum_version is not None:
  238. context.minimum_version = ssl_minimum_version
  239. else: # Python <3.10 defaults to 'MINIMUM_SUPPORTED' so explicitly set TLSv1.2 here
  240. context.minimum_version = TLSVersion.TLSv1_2
  241. if ssl_maximum_version is not None:
  242. context.maximum_version = ssl_maximum_version
  243. # Unless we're given ciphers defer to either system ciphers in
  244. # the case of OpenSSL 1.1.1+ or use our own secure default ciphers.
  245. if ciphers:
  246. context.set_ciphers(ciphers)
  247. # Setting the default here, as we may have no ssl module on import
  248. cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
  249. if options is None:
  250. options = 0
  251. # SSLv2 is easily broken and is considered harmful and dangerous
  252. options |= OP_NO_SSLv2
  253. # SSLv3 has several problems and is now dangerous
  254. options |= OP_NO_SSLv3
  255. # Disable compression to prevent CRIME attacks for OpenSSL 1.0+
  256. # (issue #309)
  257. options |= OP_NO_COMPRESSION
  258. # TLSv1.2 only. Unless set explicitly, do not request tickets.
  259. # This may save some bandwidth on wire, and although the ticket is encrypted,
  260. # there is a risk associated with it being on wire,
  261. # if the server is not rotating its ticketing keys properly.
  262. options |= OP_NO_TICKET
  263. context.options |= options
  264. # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is
  265. # necessary for conditional client cert authentication with TLS 1.3.
  266. # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older
  267. # versions of Python. We only enable if certificate verification is enabled to work
  268. # around Python issue #37428
  269. # See: https://bugs.python.org/issue37428
  270. if (
  271. cert_reqs == ssl.CERT_REQUIRED
  272. and getattr(context, "post_handshake_auth", None) is not None
  273. ):
  274. context.post_handshake_auth = True
  275. # The order of the below lines setting verify_mode and check_hostname
  276. # matter due to safe-guards SSLContext has to prevent an SSLContext with
  277. # check_hostname=True, verify_mode=NONE/OPTIONAL.
  278. # We always set 'check_hostname=False' for pyOpenSSL so we rely on our own
  279. # 'ssl.match_hostname()' implementation.
  280. if cert_reqs == ssl.CERT_REQUIRED and not IS_PYOPENSSL:
  281. context.verify_mode = cert_reqs
  282. context.check_hostname = True
  283. else:
  284. context.check_hostname = False
  285. context.verify_mode = cert_reqs
  286. try:
  287. context.hostname_checks_common_name = False
  288. except AttributeError: # Defensive: for CPython < 3.8.9 and 3.9.3; for PyPy < 7.3.8
  289. pass
  290. # Enable logging of TLS session keys via defacto standard environment variable
  291. # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values.
  292. if hasattr(context, "keylog_filename"):
  293. sslkeylogfile = os.environ.get("SSLKEYLOGFILE")
  294. if sslkeylogfile:
  295. context.keylog_filename = sslkeylogfile
  296. return context
  297. @typing.overload
  298. def ssl_wrap_socket(
  299. sock: socket.socket,
  300. keyfile: str | None = ...,
  301. certfile: str | None = ...,
  302. cert_reqs: int | None = ...,
  303. ca_certs: str | None = ...,
  304. server_hostname: str | None = ...,
  305. ssl_version: int | None = ...,
  306. ciphers: str | None = ...,
  307. ssl_context: ssl.SSLContext | None = ...,
  308. ca_cert_dir: str | None = ...,
  309. key_password: str | None = ...,
  310. ca_cert_data: None | str | bytes = ...,
  311. tls_in_tls: Literal[False] = ...,
  312. ) -> ssl.SSLSocket:
  313. ...
  314. @typing.overload
  315. def ssl_wrap_socket(
  316. sock: socket.socket,
  317. keyfile: str | None = ...,
  318. certfile: str | None = ...,
  319. cert_reqs: int | None = ...,
  320. ca_certs: str | None = ...,
  321. server_hostname: str | None = ...,
  322. ssl_version: int | None = ...,
  323. ciphers: str | None = ...,
  324. ssl_context: ssl.SSLContext | None = ...,
  325. ca_cert_dir: str | None = ...,
  326. key_password: str | None = ...,
  327. ca_cert_data: None | str | bytes = ...,
  328. tls_in_tls: bool = ...,
  329. ) -> ssl.SSLSocket | SSLTransportType:
  330. ...
  331. def ssl_wrap_socket(
  332. sock: socket.socket,
  333. keyfile: str | None = None,
  334. certfile: str | None = None,
  335. cert_reqs: int | None = None,
  336. ca_certs: str | None = None,
  337. server_hostname: str | None = None,
  338. ssl_version: int | None = None,
  339. ciphers: str | None = None,
  340. ssl_context: ssl.SSLContext | None = None,
  341. ca_cert_dir: str | None = None,
  342. key_password: str | None = None,
  343. ca_cert_data: None | str | bytes = None,
  344. tls_in_tls: bool = False,
  345. ) -> ssl.SSLSocket | SSLTransportType:
  346. """
  347. All arguments except for server_hostname, ssl_context, tls_in_tls, ca_cert_data and
  348. ca_cert_dir have the same meaning as they do when using
  349. :func:`ssl.create_default_context`, :meth:`ssl.SSLContext.load_cert_chain`,
  350. :meth:`ssl.SSLContext.set_ciphers` and :meth:`ssl.SSLContext.wrap_socket`.
  351. :param server_hostname:
  352. When SNI is supported, the expected hostname of the certificate
  353. :param ssl_context:
  354. A pre-made :class:`SSLContext` object. If none is provided, one will
  355. be created using :func:`create_urllib3_context`.
  356. :param ciphers:
  357. A string of ciphers we wish the client to support.
  358. :param ca_cert_dir:
  359. A directory containing CA certificates in multiple separate files, as
  360. supported by OpenSSL's -CApath flag or the capath argument to
  361. SSLContext.load_verify_locations().
  362. :param key_password:
  363. Optional password if the keyfile is encrypted.
  364. :param ca_cert_data:
  365. Optional string containing CA certificates in PEM format suitable for
  366. passing as the cadata parameter to SSLContext.load_verify_locations()
  367. :param tls_in_tls:
  368. Use SSLTransport to wrap the existing socket.
  369. """
  370. context = ssl_context
  371. if context is None:
  372. # Note: This branch of code and all the variables in it are only used in tests.
  373. # We should consider deprecating and removing this code.
  374. context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers)
  375. if ca_certs or ca_cert_dir or ca_cert_data:
  376. try:
  377. context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data)
  378. except OSError as e:
  379. raise SSLError(e) from e
  380. elif ssl_context is None and hasattr(context, "load_default_certs"):
  381. # try to load OS default certs; works well on Windows.
  382. context.load_default_certs()
  383. # Attempt to detect if we get the goofy behavior of the
  384. # keyfile being encrypted and OpenSSL asking for the
  385. # passphrase via the terminal and instead error out.
  386. if keyfile and key_password is None and _is_key_file_encrypted(keyfile):
  387. raise SSLError("Client private key is encrypted, password is required")
  388. if certfile:
  389. if key_password is None:
  390. context.load_cert_chain(certfile, keyfile)
  391. else:
  392. context.load_cert_chain(certfile, keyfile, key_password)
  393. try:
  394. context.set_alpn_protocols(ALPN_PROTOCOLS)
  395. except NotImplementedError: # Defensive: in CI, we always have set_alpn_protocols
  396. pass
  397. ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls, server_hostname)
  398. return ssl_sock
  399. def is_ipaddress(hostname: str | bytes) -> bool:
  400. """Detects whether the hostname given is an IPv4 or IPv6 address.
  401. Also detects IPv6 addresses with Zone IDs.
  402. :param str hostname: Hostname to examine.
  403. :return: True if the hostname is an IP address, False otherwise.
  404. """
  405. if isinstance(hostname, bytes):
  406. # IDN A-label bytes are ASCII compatible.
  407. hostname = hostname.decode("ascii")
  408. return bool(_IPV4_RE.match(hostname) or _BRACELESS_IPV6_ADDRZ_RE.match(hostname))
  409. def _is_key_file_encrypted(key_file: str) -> bool:
  410. """Detects if a key file is encrypted or not."""
  411. with open(key_file) as f:
  412. for line in f:
  413. # Look for Proc-Type: 4,ENCRYPTED
  414. if "ENCRYPTED" in line:
  415. return True
  416. return False
  417. def _ssl_wrap_socket_impl(
  418. sock: socket.socket,
  419. ssl_context: ssl.SSLContext,
  420. tls_in_tls: bool,
  421. server_hostname: str | None = None,
  422. ) -> ssl.SSLSocket | SSLTransportType:
  423. if tls_in_tls:
  424. if not SSLTransport:
  425. # Import error, ssl is not available.
  426. raise ProxySchemeUnsupported(
  427. "TLS in TLS requires support for the 'ssl' module"
  428. )
  429. SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context)
  430. return SSLTransport(sock, ssl_context, server_hostname)
  431. return ssl_context.wrap_socket(sock, server_hostname=server_hostname)