connection.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. from __future__ import absolute_import
  2. import datetime
  3. import logging
  4. import os
  5. import re
  6. import socket
  7. import warnings
  8. from socket import error as SocketError
  9. from socket import timeout as SocketTimeout
  10. from .packages import six
  11. from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection
  12. from .packages.six.moves.http_client import HTTPException # noqa: F401
  13. from .util.proxy import create_proxy_ssl_context
  14. try: # Compiled with SSL?
  15. import ssl
  16. BaseSSLError = ssl.SSLError
  17. except (ImportError, AttributeError): # Platform-specific: No SSL.
  18. ssl = None
  19. class BaseSSLError(BaseException):
  20. pass
  21. try:
  22. # Python 3: not a no-op, we're adding this to the namespace so it can be imported.
  23. ConnectionError = ConnectionError
  24. except NameError:
  25. # Python 2
  26. class ConnectionError(Exception):
  27. pass
  28. try: # Python 3:
  29. # Not a no-op, we're adding this to the namespace so it can be imported.
  30. BrokenPipeError = BrokenPipeError
  31. except NameError: # Python 2:
  32. class BrokenPipeError(Exception):
  33. pass
  34. from ._collections import HTTPHeaderDict # noqa (historical, removed in v2)
  35. from ._version import __version__
  36. from .exceptions import (
  37. ConnectTimeoutError,
  38. NewConnectionError,
  39. SubjectAltNameWarning,
  40. SystemTimeWarning,
  41. )
  42. from .util import SKIP_HEADER, SKIPPABLE_HEADERS, connection
  43. from .util.ssl_ import (
  44. assert_fingerprint,
  45. create_urllib3_context,
  46. is_ipaddress,
  47. resolve_cert_reqs,
  48. resolve_ssl_version,
  49. ssl_wrap_socket,
  50. )
  51. from .util.ssl_match_hostname import CertificateError, match_hostname
  52. log = logging.getLogger(__name__)
  53. port_by_scheme = {"http": 80, "https": 443}
  54. # When it comes time to update this value as a part of regular maintenance
  55. # (ie test_recent_date is failing) update it to ~6 months before the current date.
  56. RECENT_DATE = datetime.date(2022, 1, 1)
  57. _CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]")
  58. class HTTPConnection(_HTTPConnection, object):
  59. """
  60. Based on :class:`http.client.HTTPConnection` but provides an extra constructor
  61. backwards-compatibility layer between older and newer Pythons.
  62. Additional keyword parameters are used to configure attributes of the connection.
  63. Accepted parameters include:
  64. - ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool`
  65. - ``source_address``: Set the source address for the current connection.
  66. - ``socket_options``: Set specific options on the underlying socket. If not specified, then
  67. defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling
  68. Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.
  69. For example, if you wish to enable TCP Keep Alive in addition to the defaults,
  70. you might pass:
  71. .. code-block:: python
  72. HTTPConnection.default_socket_options + [
  73. (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
  74. ]
  75. Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).
  76. """
  77. default_port = port_by_scheme["http"]
  78. #: Disable Nagle's algorithm by default.
  79. #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``
  80. default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
  81. #: Whether this connection verifies the host's certificate.
  82. is_verified = False
  83. #: Whether this proxy connection (if used) verifies the proxy host's
  84. #: certificate.
  85. proxy_is_verified = None
  86. def __init__(self, *args, **kw):
  87. if not six.PY2:
  88. kw.pop("strict", None)
  89. # Pre-set source_address.
  90. self.source_address = kw.get("source_address")
  91. #: The socket options provided by the user. If no options are
  92. #: provided, we use the default options.
  93. self.socket_options = kw.pop("socket_options", self.default_socket_options)
  94. # Proxy options provided by the user.
  95. self.proxy = kw.pop("proxy", None)
  96. self.proxy_config = kw.pop("proxy_config", None)
  97. _HTTPConnection.__init__(self, *args, **kw)
  98. @property
  99. def host(self):
  100. """
  101. Getter method to remove any trailing dots that indicate the hostname is an FQDN.
  102. In general, SSL certificates don't include the trailing dot indicating a
  103. fully-qualified domain name, and thus, they don't validate properly when
  104. checked against a domain name that includes the dot. In addition, some
  105. servers may not expect to receive the trailing dot when provided.
  106. However, the hostname with trailing dot is critical to DNS resolution; doing a
  107. lookup with the trailing dot will properly only resolve the appropriate FQDN,
  108. whereas a lookup without a trailing dot will search the system's search domain
  109. list. Thus, it's important to keep the original host around for use only in
  110. those cases where it's appropriate (i.e., when doing DNS lookup to establish the
  111. actual TCP connection across which we're going to send HTTP requests).
  112. """
  113. return self._dns_host.rstrip(".")
  114. @host.setter
  115. def host(self, value):
  116. """
  117. Setter for the `host` property.
  118. We assume that only urllib3 uses the _dns_host attribute; httplib itself
  119. only uses `host`, and it seems reasonable that other libraries follow suit.
  120. """
  121. self._dns_host = value
  122. def _new_conn(self):
  123. """Establish a socket connection and set nodelay settings on it.
  124. :return: New socket connection.
  125. """
  126. extra_kw = {}
  127. if self.source_address:
  128. extra_kw["source_address"] = self.source_address
  129. if self.socket_options:
  130. extra_kw["socket_options"] = self.socket_options
  131. try:
  132. conn = connection.create_connection(
  133. (self._dns_host, self.port), self.timeout, **extra_kw
  134. )
  135. except SocketTimeout:
  136. raise ConnectTimeoutError(
  137. self,
  138. "Connection to %s timed out. (connect timeout=%s)"
  139. % (self.host, self.timeout),
  140. )
  141. except SocketError as e:
  142. raise NewConnectionError(
  143. self, "Failed to establish a new connection: %s" % e
  144. )
  145. return conn
  146. def _is_using_tunnel(self):
  147. # Google App Engine's httplib does not define _tunnel_host
  148. return getattr(self, "_tunnel_host", None)
  149. def _prepare_conn(self, conn):
  150. self.sock = conn
  151. if self._is_using_tunnel():
  152. # TODO: Fix tunnel so it doesn't depend on self.sock state.
  153. self._tunnel()
  154. # Mark this connection as not reusable
  155. self.auto_open = 0
  156. def connect(self):
  157. conn = self._new_conn()
  158. self._prepare_conn(conn)
  159. def putrequest(self, method, url, *args, **kwargs):
  160. """ """
  161. # Empty docstring because the indentation of CPython's implementation
  162. # is broken but we don't want this method in our documentation.
  163. match = _CONTAINS_CONTROL_CHAR_RE.search(method)
  164. if match:
  165. raise ValueError(
  166. "Method cannot contain non-token characters %r (found at least %r)"
  167. % (method, match.group())
  168. )
  169. return _HTTPConnection.putrequest(self, method, url, *args, **kwargs)
  170. def putheader(self, header, *values):
  171. """ """
  172. if not any(isinstance(v, str) and v == SKIP_HEADER for v in values):
  173. _HTTPConnection.putheader(self, header, *values)
  174. elif six.ensure_str(header.lower()) not in SKIPPABLE_HEADERS:
  175. raise ValueError(
  176. "urllib3.util.SKIP_HEADER only supports '%s'"
  177. % ("', '".join(map(str.title, sorted(SKIPPABLE_HEADERS))),)
  178. )
  179. def request(self, method, url, body=None, headers=None):
  180. # Update the inner socket's timeout value to send the request.
  181. # This only triggers if the connection is re-used.
  182. if getattr(self, "sock", None) is not None:
  183. self.sock.settimeout(self.timeout)
  184. if headers is None:
  185. headers = {}
  186. else:
  187. # Avoid modifying the headers passed into .request()
  188. headers = headers.copy()
  189. if "user-agent" not in (six.ensure_str(k.lower()) for k in headers):
  190. headers["User-Agent"] = _get_default_user_agent()
  191. super(HTTPConnection, self).request(method, url, body=body, headers=headers)
  192. def request_chunked(self, method, url, body=None, headers=None):
  193. """
  194. Alternative to the common request method, which sends the
  195. body with chunked encoding and not as one block
  196. """
  197. headers = headers or {}
  198. header_keys = set([six.ensure_str(k.lower()) for k in headers])
  199. skip_accept_encoding = "accept-encoding" in header_keys
  200. skip_host = "host" in header_keys
  201. self.putrequest(
  202. method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host
  203. )
  204. if "user-agent" not in header_keys:
  205. self.putheader("User-Agent", _get_default_user_agent())
  206. for header, value in headers.items():
  207. self.putheader(header, value)
  208. if "transfer-encoding" not in header_keys:
  209. self.putheader("Transfer-Encoding", "chunked")
  210. self.endheaders()
  211. if body is not None:
  212. stringish_types = six.string_types + (bytes,)
  213. if isinstance(body, stringish_types):
  214. body = (body,)
  215. for chunk in body:
  216. if not chunk:
  217. continue
  218. if not isinstance(chunk, bytes):
  219. chunk = chunk.encode("utf8")
  220. len_str = hex(len(chunk))[2:]
  221. to_send = bytearray(len_str.encode())
  222. to_send += b"\r\n"
  223. to_send += chunk
  224. to_send += b"\r\n"
  225. self.send(to_send)
  226. # After the if clause, to always have a closed body
  227. self.send(b"0\r\n\r\n")
  228. class HTTPSConnection(HTTPConnection):
  229. """
  230. Many of the parameters to this constructor are passed to the underlying SSL
  231. socket by means of :py:func:`urllib3.util.ssl_wrap_socket`.
  232. """
  233. default_port = port_by_scheme["https"]
  234. cert_reqs = None
  235. ca_certs = None
  236. ca_cert_dir = None
  237. ca_cert_data = None
  238. ssl_version = None
  239. assert_fingerprint = None
  240. tls_in_tls_required = False
  241. def __init__(
  242. self,
  243. host,
  244. port=None,
  245. key_file=None,
  246. cert_file=None,
  247. key_password=None,
  248. strict=None,
  249. timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  250. ssl_context=None,
  251. server_hostname=None,
  252. **kw
  253. ):
  254. HTTPConnection.__init__(self, host, port, strict=strict, timeout=timeout, **kw)
  255. self.key_file = key_file
  256. self.cert_file = cert_file
  257. self.key_password = key_password
  258. self.ssl_context = ssl_context
  259. self.server_hostname = server_hostname
  260. # Required property for Google AppEngine 1.9.0 which otherwise causes
  261. # HTTPS requests to go out as HTTP. (See Issue #356)
  262. self._protocol = "https"
  263. def set_cert(
  264. self,
  265. key_file=None,
  266. cert_file=None,
  267. cert_reqs=None,
  268. key_password=None,
  269. ca_certs=None,
  270. assert_hostname=None,
  271. assert_fingerprint=None,
  272. ca_cert_dir=None,
  273. ca_cert_data=None,
  274. ):
  275. """
  276. This method should only be called once, before the connection is used.
  277. """
  278. # If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also
  279. # have an SSLContext object in which case we'll use its verify_mode.
  280. if cert_reqs is None:
  281. if self.ssl_context is not None:
  282. cert_reqs = self.ssl_context.verify_mode
  283. else:
  284. cert_reqs = resolve_cert_reqs(None)
  285. self.key_file = key_file
  286. self.cert_file = cert_file
  287. self.cert_reqs = cert_reqs
  288. self.key_password = key_password
  289. self.assert_hostname = assert_hostname
  290. self.assert_fingerprint = assert_fingerprint
  291. self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
  292. self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
  293. self.ca_cert_data = ca_cert_data
  294. def connect(self):
  295. # Add certificate verification
  296. self.sock = conn = self._new_conn()
  297. hostname = self.host
  298. tls_in_tls = False
  299. if self._is_using_tunnel():
  300. if self.tls_in_tls_required:
  301. self.sock = conn = self._connect_tls_proxy(hostname, conn)
  302. tls_in_tls = True
  303. # Calls self._set_hostport(), so self.host is
  304. # self._tunnel_host below.
  305. self._tunnel()
  306. # Mark this connection as not reusable
  307. self.auto_open = 0
  308. # Override the host with the one we're requesting data from.
  309. hostname = self._tunnel_host
  310. server_hostname = hostname
  311. if self.server_hostname is not None:
  312. server_hostname = self.server_hostname
  313. is_time_off = datetime.date.today() < RECENT_DATE
  314. if is_time_off:
  315. warnings.warn(
  316. (
  317. "System time is way off (before {0}). This will probably "
  318. "lead to SSL verification errors"
  319. ).format(RECENT_DATE),
  320. SystemTimeWarning,
  321. )
  322. # Wrap socket using verification with the root certs in
  323. # trusted_root_certs
  324. default_ssl_context = False
  325. if self.ssl_context is None:
  326. default_ssl_context = True
  327. self.ssl_context = create_urllib3_context(
  328. ssl_version=resolve_ssl_version(self.ssl_version),
  329. cert_reqs=resolve_cert_reqs(self.cert_reqs),
  330. )
  331. context = self.ssl_context
  332. context.verify_mode = resolve_cert_reqs(self.cert_reqs)
  333. # Try to load OS default certs if none are given.
  334. # Works well on Windows (requires Python3.4+)
  335. if (
  336. not self.ca_certs
  337. and not self.ca_cert_dir
  338. and not self.ca_cert_data
  339. and default_ssl_context
  340. and hasattr(context, "load_default_certs")
  341. ):
  342. context.load_default_certs()
  343. self.sock = ssl_wrap_socket(
  344. sock=conn,
  345. keyfile=self.key_file,
  346. certfile=self.cert_file,
  347. key_password=self.key_password,
  348. ca_certs=self.ca_certs,
  349. ca_cert_dir=self.ca_cert_dir,
  350. ca_cert_data=self.ca_cert_data,
  351. server_hostname=server_hostname,
  352. ssl_context=context,
  353. tls_in_tls=tls_in_tls,
  354. )
  355. # If we're using all defaults and the connection
  356. # is TLSv1 or TLSv1.1 we throw a DeprecationWarning
  357. # for the host.
  358. if (
  359. default_ssl_context
  360. and self.ssl_version is None
  361. and hasattr(self.sock, "version")
  362. and self.sock.version() in {"TLSv1", "TLSv1.1"}
  363. ):
  364. warnings.warn(
  365. "Negotiating TLSv1/TLSv1.1 by default is deprecated "
  366. "and will be disabled in urllib3 v2.0.0. Connecting to "
  367. "'%s' with '%s' can be enabled by explicitly opting-in "
  368. "with 'ssl_version'" % (self.host, self.sock.version()),
  369. DeprecationWarning,
  370. )
  371. if self.assert_fingerprint:
  372. assert_fingerprint(
  373. self.sock.getpeercert(binary_form=True), self.assert_fingerprint
  374. )
  375. elif (
  376. context.verify_mode != ssl.CERT_NONE
  377. and not getattr(context, "check_hostname", False)
  378. and self.assert_hostname is not False
  379. ):
  380. # While urllib3 attempts to always turn off hostname matching from
  381. # the TLS library, this cannot always be done. So we check whether
  382. # the TLS Library still thinks it's matching hostnames.
  383. cert = self.sock.getpeercert()
  384. if not cert.get("subjectAltName", ()):
  385. warnings.warn(
  386. (
  387. "Certificate for {0} has no `subjectAltName`, falling back to check for a "
  388. "`commonName` for now. This feature is being removed by major browsers and "
  389. "deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 "
  390. "for details.)".format(hostname)
  391. ),
  392. SubjectAltNameWarning,
  393. )
  394. _match_hostname(cert, self.assert_hostname or server_hostname)
  395. self.is_verified = (
  396. context.verify_mode == ssl.CERT_REQUIRED
  397. or self.assert_fingerprint is not None
  398. )
  399. def _connect_tls_proxy(self, hostname, conn):
  400. """
  401. Establish a TLS connection to the proxy using the provided SSL context.
  402. """
  403. proxy_config = self.proxy_config
  404. ssl_context = proxy_config.ssl_context
  405. if ssl_context:
  406. # If the user provided a proxy context, we assume CA and client
  407. # certificates have already been set
  408. return ssl_wrap_socket(
  409. sock=conn,
  410. server_hostname=hostname,
  411. ssl_context=ssl_context,
  412. )
  413. ssl_context = create_proxy_ssl_context(
  414. self.ssl_version,
  415. self.cert_reqs,
  416. self.ca_certs,
  417. self.ca_cert_dir,
  418. self.ca_cert_data,
  419. )
  420. # If no cert was provided, use only the default options for server
  421. # certificate validation
  422. socket = ssl_wrap_socket(
  423. sock=conn,
  424. ca_certs=self.ca_certs,
  425. ca_cert_dir=self.ca_cert_dir,
  426. ca_cert_data=self.ca_cert_data,
  427. server_hostname=hostname,
  428. ssl_context=ssl_context,
  429. )
  430. if ssl_context.verify_mode != ssl.CERT_NONE and not getattr(
  431. ssl_context, "check_hostname", False
  432. ):
  433. # While urllib3 attempts to always turn off hostname matching from
  434. # the TLS library, this cannot always be done. So we check whether
  435. # the TLS Library still thinks it's matching hostnames.
  436. cert = socket.getpeercert()
  437. if not cert.get("subjectAltName", ()):
  438. warnings.warn(
  439. (
  440. "Certificate for {0} has no `subjectAltName`, falling back to check for a "
  441. "`commonName` for now. This feature is being removed by major browsers and "
  442. "deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 "
  443. "for details.)".format(hostname)
  444. ),
  445. SubjectAltNameWarning,
  446. )
  447. _match_hostname(cert, hostname)
  448. self.proxy_is_verified = ssl_context.verify_mode == ssl.CERT_REQUIRED
  449. return socket
  450. def _match_hostname(cert, asserted_hostname):
  451. # Our upstream implementation of ssl.match_hostname()
  452. # only applies this normalization to IP addresses so it doesn't
  453. # match DNS SANs so we do the same thing!
  454. stripped_hostname = asserted_hostname.strip("u[]")
  455. if is_ipaddress(stripped_hostname):
  456. asserted_hostname = stripped_hostname
  457. try:
  458. match_hostname(cert, asserted_hostname)
  459. except CertificateError as e:
  460. log.warning(
  461. "Certificate did not match expected hostname: %s. Certificate: %s",
  462. asserted_hostname,
  463. cert,
  464. )
  465. # Add cert to exception and reraise so client code can inspect
  466. # the cert when catching the exception, if they want to
  467. e._peer_cert = cert
  468. raise
  469. def _get_default_user_agent():
  470. return "python-urllib3/%s" % __version__
  471. class DummyConnection(object):
  472. """Used to detect a failed ConnectionCls import."""
  473. pass
  474. if not ssl:
  475. HTTPSConnection = DummyConnection # noqa: F811
  476. VerifiedHTTPSConnection = HTTPSConnection