connection.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. from __future__ import annotations
  2. import datetime
  3. import http.client
  4. import logging
  5. import os
  6. import re
  7. import socket
  8. import sys
  9. import threading
  10. import typing
  11. import warnings
  12. from http.client import HTTPConnection as _HTTPConnection
  13. from http.client import HTTPException as HTTPException # noqa: F401
  14. from http.client import ResponseNotReady
  15. from socket import timeout as SocketTimeout
  16. if typing.TYPE_CHECKING:
  17. from .response import HTTPResponse
  18. from .util.ssl_ import _TYPE_PEER_CERT_RET_DICT
  19. from .util.ssltransport import SSLTransport
  20. from ._collections import HTTPHeaderDict
  21. from .http2 import probe as http2_probe
  22. from .util.response import assert_header_parsing
  23. from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT, Timeout
  24. from .util.util import to_str
  25. from .util.wait import wait_for_read
  26. try: # Compiled with SSL?
  27. import ssl
  28. BaseSSLError = ssl.SSLError
  29. except (ImportError, AttributeError):
  30. ssl = None # type: ignore[assignment]
  31. class BaseSSLError(BaseException): # type: ignore[no-redef]
  32. pass
  33. from ._base_connection import _TYPE_BODY
  34. from ._base_connection import ProxyConfig as ProxyConfig
  35. from ._base_connection import _ResponseOptions as _ResponseOptions
  36. from ._version import __version__
  37. from .exceptions import (
  38. ConnectTimeoutError,
  39. HeaderParsingError,
  40. NameResolutionError,
  41. NewConnectionError,
  42. ProxyError,
  43. SystemTimeWarning,
  44. )
  45. from .util import SKIP_HEADER, SKIPPABLE_HEADERS, connection, ssl_
  46. from .util.request import body_to_chunks
  47. from .util.ssl_ import assert_fingerprint as _assert_fingerprint
  48. from .util.ssl_ import (
  49. create_urllib3_context,
  50. is_ipaddress,
  51. resolve_cert_reqs,
  52. resolve_ssl_version,
  53. ssl_wrap_socket,
  54. )
  55. from .util.ssl_match_hostname import CertificateError, match_hostname
  56. from .util.url import Url
  57. # Not a no-op, we're adding this to the namespace so it can be imported.
  58. ConnectionError = ConnectionError
  59. BrokenPipeError = BrokenPipeError
  60. log = logging.getLogger(__name__)
  61. port_by_scheme = {"http": 80, "https": 443}
  62. # When it comes time to update this value as a part of regular maintenance
  63. # (ie test_recent_date is failing) update it to ~6 months before the current date.
  64. RECENT_DATE = datetime.date(2023, 6, 1)
  65. _CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]")
  66. _HAS_SYS_AUDIT = hasattr(sys, "audit")
  67. class HTTPConnection(_HTTPConnection):
  68. """
  69. Based on :class:`http.client.HTTPConnection` but provides an extra constructor
  70. backwards-compatibility layer between older and newer Pythons.
  71. Additional keyword parameters are used to configure attributes of the connection.
  72. Accepted parameters include:
  73. - ``source_address``: Set the source address for the current connection.
  74. - ``socket_options``: Set specific options on the underlying socket. If not specified, then
  75. defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling
  76. Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.
  77. For example, if you wish to enable TCP Keep Alive in addition to the defaults,
  78. you might pass:
  79. .. code-block:: python
  80. HTTPConnection.default_socket_options + [
  81. (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
  82. ]
  83. Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).
  84. """
  85. default_port: typing.ClassVar[int] = port_by_scheme["http"] # type: ignore[misc]
  86. #: Disable Nagle's algorithm by default.
  87. #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``
  88. default_socket_options: typing.ClassVar[connection._TYPE_SOCKET_OPTIONS] = [
  89. (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  90. ]
  91. #: Whether this connection verifies the host's certificate.
  92. is_verified: bool = False
  93. #: Whether this proxy connection verified the proxy host's certificate.
  94. # If no proxy is currently connected to the value will be ``None``.
  95. proxy_is_verified: bool | None = None
  96. blocksize: int
  97. source_address: tuple[str, int] | None
  98. socket_options: connection._TYPE_SOCKET_OPTIONS | None
  99. _has_connected_to_proxy: bool
  100. _response_options: _ResponseOptions | None
  101. _tunnel_host: str | None
  102. _tunnel_port: int | None
  103. _tunnel_scheme: str | None
  104. def __init__(
  105. self,
  106. host: str,
  107. port: int | None = None,
  108. *,
  109. timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
  110. source_address: tuple[str, int] | None = None,
  111. blocksize: int = 16384,
  112. socket_options: None
  113. | (connection._TYPE_SOCKET_OPTIONS) = default_socket_options,
  114. proxy: Url | None = None,
  115. proxy_config: ProxyConfig | None = None,
  116. ) -> None:
  117. super().__init__(
  118. host=host,
  119. port=port,
  120. timeout=Timeout.resolve_default_timeout(timeout),
  121. source_address=source_address,
  122. blocksize=blocksize,
  123. )
  124. self.socket_options = socket_options
  125. self.proxy = proxy
  126. self.proxy_config = proxy_config
  127. self._has_connected_to_proxy = False
  128. self._response_options = None
  129. self._tunnel_host: str | None = None
  130. self._tunnel_port: int | None = None
  131. self._tunnel_scheme: str | None = None
  132. @property
  133. def host(self) -> str:
  134. """
  135. Getter method to remove any trailing dots that indicate the hostname is an FQDN.
  136. In general, SSL certificates don't include the trailing dot indicating a
  137. fully-qualified domain name, and thus, they don't validate properly when
  138. checked against a domain name that includes the dot. In addition, some
  139. servers may not expect to receive the trailing dot when provided.
  140. However, the hostname with trailing dot is critical to DNS resolution; doing a
  141. lookup with the trailing dot will properly only resolve the appropriate FQDN,
  142. whereas a lookup without a trailing dot will search the system's search domain
  143. list. Thus, it's important to keep the original host around for use only in
  144. those cases where it's appropriate (i.e., when doing DNS lookup to establish the
  145. actual TCP connection across which we're going to send HTTP requests).
  146. """
  147. return self._dns_host.rstrip(".")
  148. @host.setter
  149. def host(self, value: str) -> None:
  150. """
  151. Setter for the `host` property.
  152. We assume that only urllib3 uses the _dns_host attribute; httplib itself
  153. only uses `host`, and it seems reasonable that other libraries follow suit.
  154. """
  155. self._dns_host = value
  156. def _new_conn(self) -> socket.socket:
  157. """Establish a socket connection and set nodelay settings on it.
  158. :return: New socket connection.
  159. """
  160. try:
  161. sock = connection.create_connection(
  162. (self._dns_host, self.port),
  163. self.timeout,
  164. source_address=self.source_address,
  165. socket_options=self.socket_options,
  166. )
  167. except socket.gaierror as e:
  168. raise NameResolutionError(self.host, self, e) from e
  169. except SocketTimeout as e:
  170. raise ConnectTimeoutError(
  171. self,
  172. f"Connection to {self.host} timed out. (connect timeout={self.timeout})",
  173. ) from e
  174. except OSError as e:
  175. raise NewConnectionError(
  176. self, f"Failed to establish a new connection: {e}"
  177. ) from e
  178. # Audit hooks are only available in Python 3.8+
  179. if _HAS_SYS_AUDIT:
  180. sys.audit("http.client.connect", self, self.host, self.port)
  181. return sock
  182. def set_tunnel(
  183. self,
  184. host: str,
  185. port: int | None = None,
  186. headers: typing.Mapping[str, str] | None = None,
  187. scheme: str = "http",
  188. ) -> None:
  189. if scheme not in ("http", "https"):
  190. raise ValueError(
  191. f"Invalid proxy scheme for tunneling: {scheme!r}, must be either 'http' or 'https'"
  192. )
  193. super().set_tunnel(host, port=port, headers=headers)
  194. self._tunnel_scheme = scheme
  195. if sys.version_info < (3, 11, 4):
  196. def _tunnel(self) -> None:
  197. _MAXLINE = http.client._MAXLINE # type: ignore[attr-defined]
  198. connect = b"CONNECT %s:%d HTTP/1.0\r\n" % ( # type: ignore[str-format]
  199. self._tunnel_host.encode("ascii"), # type: ignore[union-attr]
  200. self._tunnel_port,
  201. )
  202. headers = [connect]
  203. for header, value in self._tunnel_headers.items(): # type: ignore[attr-defined]
  204. headers.append(f"{header}: {value}\r\n".encode("latin-1"))
  205. headers.append(b"\r\n")
  206. # Making a single send() call instead of one per line encourages
  207. # the host OS to use a more optimal packet size instead of
  208. # potentially emitting a series of small packets.
  209. self.send(b"".join(headers))
  210. del headers
  211. response = self.response_class(self.sock, method=self._method) # type: ignore[attr-defined]
  212. try:
  213. (version, code, message) = response._read_status() # type: ignore[attr-defined]
  214. if code != http.HTTPStatus.OK:
  215. self.close()
  216. raise OSError(f"Tunnel connection failed: {code} {message.strip()}")
  217. while True:
  218. line = response.fp.readline(_MAXLINE + 1)
  219. if len(line) > _MAXLINE:
  220. raise http.client.LineTooLong("header line")
  221. if not line:
  222. # for sites which EOF without sending a trailer
  223. break
  224. if line in (b"\r\n", b"\n", b""):
  225. break
  226. if self.debuglevel > 0:
  227. print("header:", line.decode())
  228. finally:
  229. response.close()
  230. def connect(self) -> None:
  231. self.sock = self._new_conn()
  232. if self._tunnel_host:
  233. # If we're tunneling it means we're connected to our proxy.
  234. self._has_connected_to_proxy = True
  235. # TODO: Fix tunnel so it doesn't depend on self.sock state.
  236. self._tunnel()
  237. # If there's a proxy to be connected to we are fully connected.
  238. # This is set twice (once above and here) due to forwarding proxies
  239. # not using tunnelling.
  240. self._has_connected_to_proxy = bool(self.proxy)
  241. if self._has_connected_to_proxy:
  242. self.proxy_is_verified = False
  243. @property
  244. def is_closed(self) -> bool:
  245. return self.sock is None
  246. @property
  247. def is_connected(self) -> bool:
  248. if self.sock is None:
  249. return False
  250. return not wait_for_read(self.sock, timeout=0.0)
  251. @property
  252. def has_connected_to_proxy(self) -> bool:
  253. return self._has_connected_to_proxy
  254. @property
  255. def proxy_is_forwarding(self) -> bool:
  256. """
  257. Return True if a forwarding proxy is configured, else return False
  258. """
  259. return bool(self.proxy) and self._tunnel_host is None
  260. def close(self) -> None:
  261. try:
  262. super().close()
  263. finally:
  264. # Reset all stateful properties so connection
  265. # can be re-used without leaking prior configs.
  266. self.sock = None
  267. self.is_verified = False
  268. self.proxy_is_verified = None
  269. self._has_connected_to_proxy = False
  270. self._response_options = None
  271. self._tunnel_host = None
  272. self._tunnel_port = None
  273. self._tunnel_scheme = None
  274. def putrequest(
  275. self,
  276. method: str,
  277. url: str,
  278. skip_host: bool = False,
  279. skip_accept_encoding: bool = False,
  280. ) -> None:
  281. """"""
  282. # Empty docstring because the indentation of CPython's implementation
  283. # is broken but we don't want this method in our documentation.
  284. match = _CONTAINS_CONTROL_CHAR_RE.search(method)
  285. if match:
  286. raise ValueError(
  287. f"Method cannot contain non-token characters {method!r} (found at least {match.group()!r})"
  288. )
  289. return super().putrequest(
  290. method, url, skip_host=skip_host, skip_accept_encoding=skip_accept_encoding
  291. )
  292. def putheader(self, header: str, *values: str) -> None: # type: ignore[override]
  293. """"""
  294. if not any(isinstance(v, str) and v == SKIP_HEADER for v in values):
  295. super().putheader(header, *values)
  296. elif to_str(header.lower()) not in SKIPPABLE_HEADERS:
  297. skippable_headers = "', '".join(
  298. [str.title(header) for header in sorted(SKIPPABLE_HEADERS)]
  299. )
  300. raise ValueError(
  301. f"urllib3.util.SKIP_HEADER only supports '{skippable_headers}'"
  302. )
  303. # `request` method's signature intentionally violates LSP.
  304. # urllib3's API is different from `http.client.HTTPConnection` and the subclassing is only incidental.
  305. def request( # type: ignore[override]
  306. self,
  307. method: str,
  308. url: str,
  309. body: _TYPE_BODY | None = None,
  310. headers: typing.Mapping[str, str] | None = None,
  311. *,
  312. chunked: bool = False,
  313. preload_content: bool = True,
  314. decode_content: bool = True,
  315. enforce_content_length: bool = True,
  316. ) -> None:
  317. # Update the inner socket's timeout value to send the request.
  318. # This only triggers if the connection is re-used.
  319. if self.sock is not None:
  320. self.sock.settimeout(self.timeout)
  321. # Store these values to be fed into the HTTPResponse
  322. # object later. TODO: Remove this in favor of a real
  323. # HTTP lifecycle mechanism.
  324. # We have to store these before we call .request()
  325. # because sometimes we can still salvage a response
  326. # off the wire even if we aren't able to completely
  327. # send the request body.
  328. self._response_options = _ResponseOptions(
  329. request_method=method,
  330. request_url=url,
  331. preload_content=preload_content,
  332. decode_content=decode_content,
  333. enforce_content_length=enforce_content_length,
  334. )
  335. if headers is None:
  336. headers = {}
  337. header_keys = frozenset(to_str(k.lower()) for k in headers)
  338. skip_accept_encoding = "accept-encoding" in header_keys
  339. skip_host = "host" in header_keys
  340. self.putrequest(
  341. method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host
  342. )
  343. # Transform the body into an iterable of sendall()-able chunks
  344. # and detect if an explicit Content-Length is doable.
  345. chunks_and_cl = body_to_chunks(body, method=method, blocksize=self.blocksize)
  346. chunks = chunks_and_cl.chunks
  347. content_length = chunks_and_cl.content_length
  348. # When chunked is explicit set to 'True' we respect that.
  349. if chunked:
  350. if "transfer-encoding" not in header_keys:
  351. self.putheader("Transfer-Encoding", "chunked")
  352. else:
  353. # Detect whether a framing mechanism is already in use. If so
  354. # we respect that value, otherwise we pick chunked vs content-length
  355. # depending on the type of 'body'.
  356. if "content-length" in header_keys:
  357. chunked = False
  358. elif "transfer-encoding" in header_keys:
  359. chunked = True
  360. # Otherwise we go off the recommendation of 'body_to_chunks()'.
  361. else:
  362. chunked = False
  363. if content_length is None:
  364. if chunks is not None:
  365. chunked = True
  366. self.putheader("Transfer-Encoding", "chunked")
  367. else:
  368. self.putheader("Content-Length", str(content_length))
  369. # Now that framing headers are out of the way we send all the other headers.
  370. if "user-agent" not in header_keys:
  371. self.putheader("User-Agent", _get_default_user_agent())
  372. for header, value in headers.items():
  373. self.putheader(header, value)
  374. self.endheaders()
  375. # If we're given a body we start sending that in chunks.
  376. if chunks is not None:
  377. for chunk in chunks:
  378. # Sending empty chunks isn't allowed for TE: chunked
  379. # as it indicates the end of the body.
  380. if not chunk:
  381. continue
  382. if isinstance(chunk, str):
  383. chunk = chunk.encode("utf-8")
  384. if chunked:
  385. self.send(b"%x\r\n%b\r\n" % (len(chunk), chunk))
  386. else:
  387. self.send(chunk)
  388. # Regardless of whether we have a body or not, if we're in
  389. # chunked mode we want to send an explicit empty chunk.
  390. if chunked:
  391. self.send(b"0\r\n\r\n")
  392. def request_chunked(
  393. self,
  394. method: str,
  395. url: str,
  396. body: _TYPE_BODY | None = None,
  397. headers: typing.Mapping[str, str] | None = None,
  398. ) -> None:
  399. """
  400. Alternative to the common request method, which sends the
  401. body with chunked encoding and not as one block
  402. """
  403. warnings.warn(
  404. "HTTPConnection.request_chunked() is deprecated and will be removed "
  405. "in urllib3 v2.1.0. Instead use HTTPConnection.request(..., chunked=True).",
  406. category=DeprecationWarning,
  407. stacklevel=2,
  408. )
  409. self.request(method, url, body=body, headers=headers, chunked=True)
  410. def getresponse( # type: ignore[override]
  411. self,
  412. ) -> HTTPResponse:
  413. """
  414. Get the response from the server.
  415. If the HTTPConnection is in the correct state, returns an instance of HTTPResponse or of whatever object is returned by the response_class variable.
  416. If a request has not been sent or if a previous response has not be handled, ResponseNotReady is raised. If the HTTP response indicates that the connection should be closed, then it will be closed before the response is returned. When the connection is closed, the underlying socket is closed.
  417. """
  418. # Raise the same error as http.client.HTTPConnection
  419. if self._response_options is None:
  420. raise ResponseNotReady()
  421. # Reset this attribute for being used again.
  422. resp_options = self._response_options
  423. self._response_options = None
  424. # Since the connection's timeout value may have been updated
  425. # we need to set the timeout on the socket.
  426. self.sock.settimeout(self.timeout)
  427. # This is needed here to avoid circular import errors
  428. from .response import HTTPResponse
  429. # Get the response from http.client.HTTPConnection
  430. httplib_response = super().getresponse()
  431. try:
  432. assert_header_parsing(httplib_response.msg)
  433. except (HeaderParsingError, TypeError) as hpe:
  434. log.warning(
  435. "Failed to parse headers (url=%s): %s",
  436. _url_from_connection(self, resp_options.request_url),
  437. hpe,
  438. exc_info=True,
  439. )
  440. headers = HTTPHeaderDict(httplib_response.msg.items())
  441. response = HTTPResponse(
  442. body=httplib_response,
  443. headers=headers,
  444. status=httplib_response.status,
  445. version=httplib_response.version,
  446. version_string=getattr(self, "_http_vsn_str", "HTTP/?"),
  447. reason=httplib_response.reason,
  448. preload_content=resp_options.preload_content,
  449. decode_content=resp_options.decode_content,
  450. original_response=httplib_response,
  451. enforce_content_length=resp_options.enforce_content_length,
  452. request_method=resp_options.request_method,
  453. request_url=resp_options.request_url,
  454. )
  455. return response
  456. class HTTPSConnection(HTTPConnection):
  457. """
  458. Many of the parameters to this constructor are passed to the underlying SSL
  459. socket by means of :py:func:`urllib3.util.ssl_wrap_socket`.
  460. """
  461. default_port = port_by_scheme["https"] # type: ignore[misc]
  462. cert_reqs: int | str | None = None
  463. ca_certs: str | None = None
  464. ca_cert_dir: str | None = None
  465. ca_cert_data: None | str | bytes = None
  466. ssl_version: int | str | None = None
  467. ssl_minimum_version: int | None = None
  468. ssl_maximum_version: int | None = None
  469. assert_fingerprint: str | None = None
  470. _connect_callback: typing.Callable[..., None] | None = None
  471. def __init__(
  472. self,
  473. host: str,
  474. port: int | None = None,
  475. *,
  476. timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
  477. source_address: tuple[str, int] | None = None,
  478. blocksize: int = 16384,
  479. socket_options: None
  480. | (connection._TYPE_SOCKET_OPTIONS) = HTTPConnection.default_socket_options,
  481. proxy: Url | None = None,
  482. proxy_config: ProxyConfig | None = None,
  483. cert_reqs: int | str | None = None,
  484. assert_hostname: None | str | typing.Literal[False] = None,
  485. assert_fingerprint: str | None = None,
  486. server_hostname: str | None = None,
  487. ssl_context: ssl.SSLContext | None = None,
  488. ca_certs: str | None = None,
  489. ca_cert_dir: str | None = None,
  490. ca_cert_data: None | str | bytes = None,
  491. ssl_minimum_version: int | None = None,
  492. ssl_maximum_version: int | None = None,
  493. ssl_version: int | str | None = None, # Deprecated
  494. cert_file: str | None = None,
  495. key_file: str | None = None,
  496. key_password: str | None = None,
  497. ) -> None:
  498. super().__init__(
  499. host,
  500. port=port,
  501. timeout=timeout,
  502. source_address=source_address,
  503. blocksize=blocksize,
  504. socket_options=socket_options,
  505. proxy=proxy,
  506. proxy_config=proxy_config,
  507. )
  508. self.key_file = key_file
  509. self.cert_file = cert_file
  510. self.key_password = key_password
  511. self.ssl_context = ssl_context
  512. self.server_hostname = server_hostname
  513. self.assert_hostname = assert_hostname
  514. self.assert_fingerprint = assert_fingerprint
  515. self.ssl_version = ssl_version
  516. self.ssl_minimum_version = ssl_minimum_version
  517. self.ssl_maximum_version = ssl_maximum_version
  518. self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
  519. self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
  520. self.ca_cert_data = ca_cert_data
  521. # cert_reqs depends on ssl_context so calculate last.
  522. if cert_reqs is None:
  523. if self.ssl_context is not None:
  524. cert_reqs = self.ssl_context.verify_mode
  525. else:
  526. cert_reqs = resolve_cert_reqs(None)
  527. self.cert_reqs = cert_reqs
  528. self._connect_callback = None
  529. def set_cert(
  530. self,
  531. key_file: str | None = None,
  532. cert_file: str | None = None,
  533. cert_reqs: int | str | None = None,
  534. key_password: str | None = None,
  535. ca_certs: str | None = None,
  536. assert_hostname: None | str | typing.Literal[False] = None,
  537. assert_fingerprint: str | None = None,
  538. ca_cert_dir: str | None = None,
  539. ca_cert_data: None | str | bytes = None,
  540. ) -> None:
  541. """
  542. This method should only be called once, before the connection is used.
  543. """
  544. warnings.warn(
  545. "HTTPSConnection.set_cert() is deprecated and will be removed "
  546. "in urllib3 v2.1.0. Instead provide the parameters to the "
  547. "HTTPSConnection constructor.",
  548. category=DeprecationWarning,
  549. stacklevel=2,
  550. )
  551. # If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also
  552. # have an SSLContext object in which case we'll use its verify_mode.
  553. if cert_reqs is None:
  554. if self.ssl_context is not None:
  555. cert_reqs = self.ssl_context.verify_mode
  556. else:
  557. cert_reqs = resolve_cert_reqs(None)
  558. self.key_file = key_file
  559. self.cert_file = cert_file
  560. self.cert_reqs = cert_reqs
  561. self.key_password = key_password
  562. self.assert_hostname = assert_hostname
  563. self.assert_fingerprint = assert_fingerprint
  564. self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
  565. self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
  566. self.ca_cert_data = ca_cert_data
  567. def connect(self) -> None:
  568. # Today we don't need to be doing this step before the /actual/ socket
  569. # connection, however in the future we'll need to decide whether to
  570. # create a new socket or re-use an existing "shared" socket as a part
  571. # of the HTTP/2 handshake dance.
  572. if self._tunnel_host is not None and self._tunnel_port is not None:
  573. probe_http2_host = self._tunnel_host
  574. probe_http2_port = self._tunnel_port
  575. else:
  576. probe_http2_host = self.host
  577. probe_http2_port = self.port
  578. # Check if the target origin supports HTTP/2.
  579. # If the value comes back as 'None' it means that the current thread
  580. # is probing for HTTP/2 support. Otherwise, we're waiting for another
  581. # probe to complete, or we get a value right away.
  582. target_supports_http2: bool | None
  583. if "h2" in ssl_.ALPN_PROTOCOLS:
  584. target_supports_http2 = http2_probe.acquire_and_get(
  585. host=probe_http2_host, port=probe_http2_port
  586. )
  587. else:
  588. # If HTTP/2 isn't going to be offered it doesn't matter if
  589. # the target supports HTTP/2. Don't want to make a probe.
  590. target_supports_http2 = False
  591. if self._connect_callback is not None:
  592. self._connect_callback(
  593. "before connect",
  594. thread_id=threading.get_ident(),
  595. target_supports_http2=target_supports_http2,
  596. )
  597. try:
  598. sock: socket.socket | ssl.SSLSocket
  599. self.sock = sock = self._new_conn()
  600. server_hostname: str = self.host
  601. tls_in_tls = False
  602. # Do we need to establish a tunnel?
  603. if self._tunnel_host is not None:
  604. # We're tunneling to an HTTPS origin so need to do TLS-in-TLS.
  605. if self._tunnel_scheme == "https":
  606. # _connect_tls_proxy will verify and assign proxy_is_verified
  607. self.sock = sock = self._connect_tls_proxy(self.host, sock)
  608. tls_in_tls = True
  609. elif self._tunnel_scheme == "http":
  610. self.proxy_is_verified = False
  611. # If we're tunneling it means we're connected to our proxy.
  612. self._has_connected_to_proxy = True
  613. self._tunnel()
  614. # Override the host with the one we're requesting data from.
  615. server_hostname = self._tunnel_host
  616. if self.server_hostname is not None:
  617. server_hostname = self.server_hostname
  618. is_time_off = datetime.date.today() < RECENT_DATE
  619. if is_time_off:
  620. warnings.warn(
  621. (
  622. f"System time is way off (before {RECENT_DATE}). This will probably "
  623. "lead to SSL verification errors"
  624. ),
  625. SystemTimeWarning,
  626. )
  627. # Remove trailing '.' from fqdn hostnames to allow certificate validation
  628. server_hostname_rm_dot = server_hostname.rstrip(".")
  629. sock_and_verified = _ssl_wrap_socket_and_match_hostname(
  630. sock=sock,
  631. cert_reqs=self.cert_reqs,
  632. ssl_version=self.ssl_version,
  633. ssl_minimum_version=self.ssl_minimum_version,
  634. ssl_maximum_version=self.ssl_maximum_version,
  635. ca_certs=self.ca_certs,
  636. ca_cert_dir=self.ca_cert_dir,
  637. ca_cert_data=self.ca_cert_data,
  638. cert_file=self.cert_file,
  639. key_file=self.key_file,
  640. key_password=self.key_password,
  641. server_hostname=server_hostname_rm_dot,
  642. ssl_context=self.ssl_context,
  643. tls_in_tls=tls_in_tls,
  644. assert_hostname=self.assert_hostname,
  645. assert_fingerprint=self.assert_fingerprint,
  646. )
  647. self.sock = sock_and_verified.socket
  648. # If an error occurs during connection/handshake we may need to release
  649. # our lock so another connection can probe the origin.
  650. except BaseException:
  651. if self._connect_callback is not None:
  652. self._connect_callback(
  653. "after connect failure",
  654. thread_id=threading.get_ident(),
  655. target_supports_http2=target_supports_http2,
  656. )
  657. if target_supports_http2 is None:
  658. http2_probe.set_and_release(
  659. host=probe_http2_host, port=probe_http2_port, supports_http2=None
  660. )
  661. raise
  662. # If this connection doesn't know if the origin supports HTTP/2
  663. # we report back to the HTTP/2 probe our result.
  664. if target_supports_http2 is None:
  665. supports_http2 = sock_and_verified.socket.selected_alpn_protocol() == "h2"
  666. http2_probe.set_and_release(
  667. host=probe_http2_host,
  668. port=probe_http2_port,
  669. supports_http2=supports_http2,
  670. )
  671. # Forwarding proxies can never have a verified target since
  672. # the proxy is the one doing the verification. Should instead
  673. # use a CONNECT tunnel in order to verify the target.
  674. # See: https://github.com/urllib3/urllib3/issues/3267.
  675. if self.proxy_is_forwarding:
  676. self.is_verified = False
  677. else:
  678. self.is_verified = sock_and_verified.is_verified
  679. # If there's a proxy to be connected to we are fully connected.
  680. # This is set twice (once above and here) due to forwarding proxies
  681. # not using tunnelling.
  682. self._has_connected_to_proxy = bool(self.proxy)
  683. # Set `self.proxy_is_verified` unless it's already set while
  684. # establishing a tunnel.
  685. if self._has_connected_to_proxy and self.proxy_is_verified is None:
  686. self.proxy_is_verified = sock_and_verified.is_verified
  687. def _connect_tls_proxy(self, hostname: str, sock: socket.socket) -> ssl.SSLSocket:
  688. """
  689. Establish a TLS connection to the proxy using the provided SSL context.
  690. """
  691. # `_connect_tls_proxy` is called when self._tunnel_host is truthy.
  692. proxy_config = typing.cast(ProxyConfig, self.proxy_config)
  693. ssl_context = proxy_config.ssl_context
  694. sock_and_verified = _ssl_wrap_socket_and_match_hostname(
  695. sock,
  696. cert_reqs=self.cert_reqs,
  697. ssl_version=self.ssl_version,
  698. ssl_minimum_version=self.ssl_minimum_version,
  699. ssl_maximum_version=self.ssl_maximum_version,
  700. ca_certs=self.ca_certs,
  701. ca_cert_dir=self.ca_cert_dir,
  702. ca_cert_data=self.ca_cert_data,
  703. server_hostname=hostname,
  704. ssl_context=ssl_context,
  705. assert_hostname=proxy_config.assert_hostname,
  706. assert_fingerprint=proxy_config.assert_fingerprint,
  707. # Features that aren't implemented for proxies yet:
  708. cert_file=None,
  709. key_file=None,
  710. key_password=None,
  711. tls_in_tls=False,
  712. )
  713. self.proxy_is_verified = sock_and_verified.is_verified
  714. return sock_and_verified.socket # type: ignore[return-value]
  715. class _WrappedAndVerifiedSocket(typing.NamedTuple):
  716. """
  717. Wrapped socket and whether the connection is
  718. verified after the TLS handshake
  719. """
  720. socket: ssl.SSLSocket | SSLTransport
  721. is_verified: bool
  722. def _ssl_wrap_socket_and_match_hostname(
  723. sock: socket.socket,
  724. *,
  725. cert_reqs: None | str | int,
  726. ssl_version: None | str | int,
  727. ssl_minimum_version: int | None,
  728. ssl_maximum_version: int | None,
  729. cert_file: str | None,
  730. key_file: str | None,
  731. key_password: str | None,
  732. ca_certs: str | None,
  733. ca_cert_dir: str | None,
  734. ca_cert_data: None | str | bytes,
  735. assert_hostname: None | str | typing.Literal[False],
  736. assert_fingerprint: str | None,
  737. server_hostname: str | None,
  738. ssl_context: ssl.SSLContext | None,
  739. tls_in_tls: bool = False,
  740. ) -> _WrappedAndVerifiedSocket:
  741. """Logic for constructing an SSLContext from all TLS parameters, passing
  742. that down into ssl_wrap_socket, and then doing certificate verification
  743. either via hostname or fingerprint. This function exists to guarantee
  744. that both proxies and targets have the same behavior when connecting via TLS.
  745. """
  746. default_ssl_context = False
  747. if ssl_context is None:
  748. default_ssl_context = True
  749. context = create_urllib3_context(
  750. ssl_version=resolve_ssl_version(ssl_version),
  751. ssl_minimum_version=ssl_minimum_version,
  752. ssl_maximum_version=ssl_maximum_version,
  753. cert_reqs=resolve_cert_reqs(cert_reqs),
  754. )
  755. else:
  756. context = ssl_context
  757. context.verify_mode = resolve_cert_reqs(cert_reqs)
  758. # In some cases, we want to verify hostnames ourselves
  759. if (
  760. # `ssl` can't verify fingerprints or alternate hostnames
  761. assert_fingerprint
  762. or assert_hostname
  763. # assert_hostname can be set to False to disable hostname checking
  764. or assert_hostname is False
  765. # We still support OpenSSL 1.0.2, which prevents us from verifying
  766. # hostnames easily: https://github.com/pyca/pyopenssl/pull/933
  767. or ssl_.IS_PYOPENSSL
  768. or not ssl_.HAS_NEVER_CHECK_COMMON_NAME
  769. ):
  770. context.check_hostname = False
  771. # Try to load OS default certs if none are given. We need to do the hasattr() check
  772. # for custom pyOpenSSL SSLContext objects because they don't support
  773. # load_default_certs().
  774. if (
  775. not ca_certs
  776. and not ca_cert_dir
  777. and not ca_cert_data
  778. and default_ssl_context
  779. and hasattr(context, "load_default_certs")
  780. ):
  781. context.load_default_certs()
  782. # Ensure that IPv6 addresses are in the proper format and don't have a
  783. # scope ID. Python's SSL module fails to recognize scoped IPv6 addresses
  784. # and interprets them as DNS hostnames.
  785. if server_hostname is not None:
  786. normalized = server_hostname.strip("[]")
  787. if "%" in normalized:
  788. normalized = normalized[: normalized.rfind("%")]
  789. if is_ipaddress(normalized):
  790. server_hostname = normalized
  791. ssl_sock = ssl_wrap_socket(
  792. sock=sock,
  793. keyfile=key_file,
  794. certfile=cert_file,
  795. key_password=key_password,
  796. ca_certs=ca_certs,
  797. ca_cert_dir=ca_cert_dir,
  798. ca_cert_data=ca_cert_data,
  799. server_hostname=server_hostname,
  800. ssl_context=context,
  801. tls_in_tls=tls_in_tls,
  802. )
  803. try:
  804. if assert_fingerprint:
  805. _assert_fingerprint(
  806. ssl_sock.getpeercert(binary_form=True), assert_fingerprint
  807. )
  808. elif (
  809. context.verify_mode != ssl.CERT_NONE
  810. and not context.check_hostname
  811. and assert_hostname is not False
  812. ):
  813. cert: _TYPE_PEER_CERT_RET_DICT = ssl_sock.getpeercert() # type: ignore[assignment]
  814. # Need to signal to our match_hostname whether to use 'commonName' or not.
  815. # If we're using our own constructed SSLContext we explicitly set 'False'
  816. # because PyPy hard-codes 'True' from SSLContext.hostname_checks_common_name.
  817. if default_ssl_context:
  818. hostname_checks_common_name = False
  819. else:
  820. hostname_checks_common_name = (
  821. getattr(context, "hostname_checks_common_name", False) or False
  822. )
  823. _match_hostname(
  824. cert,
  825. assert_hostname or server_hostname, # type: ignore[arg-type]
  826. hostname_checks_common_name,
  827. )
  828. return _WrappedAndVerifiedSocket(
  829. socket=ssl_sock,
  830. is_verified=context.verify_mode == ssl.CERT_REQUIRED
  831. or bool(assert_fingerprint),
  832. )
  833. except BaseException:
  834. ssl_sock.close()
  835. raise
  836. def _match_hostname(
  837. cert: _TYPE_PEER_CERT_RET_DICT | None,
  838. asserted_hostname: str,
  839. hostname_checks_common_name: bool = False,
  840. ) -> None:
  841. # Our upstream implementation of ssl.match_hostname()
  842. # only applies this normalization to IP addresses so it doesn't
  843. # match DNS SANs so we do the same thing!
  844. stripped_hostname = asserted_hostname.strip("[]")
  845. if is_ipaddress(stripped_hostname):
  846. asserted_hostname = stripped_hostname
  847. try:
  848. match_hostname(cert, asserted_hostname, hostname_checks_common_name)
  849. except CertificateError as e:
  850. log.warning(
  851. "Certificate did not match expected hostname: %s. Certificate: %s",
  852. asserted_hostname,
  853. cert,
  854. )
  855. # Add cert to exception and reraise so client code can inspect
  856. # the cert when catching the exception, if they want to
  857. e._peer_cert = cert # type: ignore[attr-defined]
  858. raise
  859. def _wrap_proxy_error(err: Exception, proxy_scheme: str | None) -> ProxyError:
  860. # Look for the phrase 'wrong version number', if found
  861. # then we should warn the user that we're very sure that
  862. # this proxy is HTTP-only and they have a configuration issue.
  863. error_normalized = " ".join(re.split("[^a-z]", str(err).lower()))
  864. is_likely_http_proxy = (
  865. "wrong version number" in error_normalized
  866. or "unknown protocol" in error_normalized
  867. or "record layer failure" in error_normalized
  868. )
  869. http_proxy_warning = (
  870. ". Your proxy appears to only use HTTP and not HTTPS, "
  871. "try changing your proxy URL to be HTTP. See: "
  872. "https://urllib3.readthedocs.io/en/latest/advanced-usage.html"
  873. "#https-proxy-error-http-proxy"
  874. )
  875. new_err = ProxyError(
  876. f"Unable to connect to proxy"
  877. f"{http_proxy_warning if is_likely_http_proxy and proxy_scheme == 'https' else ''}",
  878. err,
  879. )
  880. new_err.__cause__ = err
  881. return new_err
  882. def _get_default_user_agent() -> str:
  883. return f"python-urllib3/{__version__}"
  884. class DummyConnection:
  885. """Used to detect a failed ConnectionCls import."""
  886. if not ssl:
  887. HTTPSConnection = DummyConnection # type: ignore[misc, assignment] # noqa: F811
  888. VerifiedHTTPSConnection = HTTPSConnection
  889. def _url_from_connection(
  890. conn: HTTPConnection | HTTPSConnection, path: str | None = None
  891. ) -> str:
  892. """Returns the URL from a given connection. This is mainly used for testing and logging."""
  893. scheme = "https" if isinstance(conn, HTTPSConnection) else "http"
  894. return Url(scheme=scheme, host=conn.host, port=conn.port, path=path).url