ssl_.py 18 KB

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