connection.py 33 KB

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