connection.py 18 KB

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