connection.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. from __future__ import absolute_import
  2. import datetime
  3. import logging
  4. import os
  5. import socket
  6. from socket import error as SocketError, timeout as SocketTimeout
  7. import warnings
  8. from .packages import six
  9. from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection
  10. from .packages.six.moves.http_client import HTTPException # noqa: F401
  11. try: # Compiled with SSL?
  12. import ssl
  13. BaseSSLError = ssl.SSLError
  14. except (ImportError, AttributeError): # Platform-specific: No SSL.
  15. ssl = None
  16. class BaseSSLError(BaseException):
  17. pass
  18. try:
  19. # Python 3: not a no-op, we're adding this to the namespace so it can be imported.
  20. ConnectionError = ConnectionError
  21. except NameError:
  22. # Python 2
  23. class ConnectionError(Exception):
  24. pass
  25. from .exceptions import (
  26. NewConnectionError,
  27. ConnectTimeoutError,
  28. SubjectAltNameWarning,
  29. SystemTimeWarning,
  30. )
  31. from .packages.ssl_match_hostname import match_hostname, CertificateError
  32. from .util.ssl_ import (
  33. resolve_cert_reqs,
  34. resolve_ssl_version,
  35. assert_fingerprint,
  36. create_urllib3_context,
  37. ssl_wrap_socket,
  38. )
  39. from .util import connection
  40. from ._collections import HTTPHeaderDict
  41. log = logging.getLogger(__name__)
  42. port_by_scheme = {"http": 80, "https": 443}
  43. # When it comes time to update this value as a part of regular maintenance
  44. # (ie test_recent_date is failing) update it to ~6 months before the current date.
  45. RECENT_DATE = datetime.date(2019, 1, 1)
  46. class DummyConnection(object):
  47. """Used to detect a failed ConnectionCls import."""
  48. pass
  49. class HTTPConnection(_HTTPConnection, object):
  50. """
  51. Based on httplib.HTTPConnection but provides an extra constructor
  52. backwards-compatibility layer between older and newer Pythons.
  53. Additional keyword parameters are used to configure attributes of the connection.
  54. Accepted parameters include:
  55. - ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool`
  56. - ``source_address``: Set the source address for the current connection.
  57. - ``socket_options``: Set specific options on the underlying socket. If not specified, then
  58. defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling
  59. Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.
  60. For example, if you wish to enable TCP Keep Alive in addition to the defaults,
  61. you might pass::
  62. HTTPConnection.default_socket_options + [
  63. (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
  64. ]
  65. Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).
  66. """
  67. default_port = port_by_scheme["http"]
  68. #: Disable Nagle's algorithm by default.
  69. #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``
  70. default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
  71. #: Whether this connection verifies the host's certificate.
  72. is_verified = False
  73. def __init__(self, *args, **kw):
  74. if not six.PY2:
  75. kw.pop("strict", None)
  76. # Pre-set source_address.
  77. self.source_address = kw.get("source_address")
  78. #: The socket options provided by the user. If no options are
  79. #: provided, we use the default options.
  80. self.socket_options = kw.pop("socket_options", self.default_socket_options)
  81. _HTTPConnection.__init__(self, *args, **kw)
  82. @property
  83. def host(self):
  84. """
  85. Getter method to remove any trailing dots that indicate the hostname is an FQDN.
  86. In general, SSL certificates don't include the trailing dot indicating a
  87. fully-qualified domain name, and thus, they don't validate properly when
  88. checked against a domain name that includes the dot. In addition, some
  89. servers may not expect to receive the trailing dot when provided.
  90. However, the hostname with trailing dot is critical to DNS resolution; doing a
  91. lookup with the trailing dot will properly only resolve the appropriate FQDN,
  92. whereas a lookup without a trailing dot will search the system's search domain
  93. list. Thus, it's important to keep the original host around for use only in
  94. those cases where it's appropriate (i.e., when doing DNS lookup to establish the
  95. actual TCP connection across which we're going to send HTTP requests).
  96. """
  97. return self._dns_host.rstrip(".")
  98. @host.setter
  99. def host(self, value):
  100. """
  101. Setter for the `host` property.
  102. We assume that only urllib3 uses the _dns_host attribute; httplib itself
  103. only uses `host`, and it seems reasonable that other libraries follow suit.
  104. """
  105. self._dns_host = value
  106. def _new_conn(self):
  107. """ Establish a socket connection and set nodelay settings on it.
  108. :return: New socket connection.
  109. """
  110. extra_kw = {}
  111. if self.source_address:
  112. extra_kw["source_address"] = self.source_address
  113. if self.socket_options:
  114. extra_kw["socket_options"] = self.socket_options
  115. try:
  116. conn = connection.create_connection(
  117. (self._dns_host, self.port), self.timeout, **extra_kw
  118. )
  119. except SocketTimeout:
  120. raise ConnectTimeoutError(
  121. self,
  122. "Connection to %s timed out. (connect timeout=%s)"
  123. % (self.host, self.timeout),
  124. )
  125. except SocketError as e:
  126. raise NewConnectionError(
  127. self, "Failed to establish a new connection: %s" % e
  128. )
  129. return conn
  130. def _prepare_conn(self, conn):
  131. self.sock = conn
  132. # Google App Engine's httplib does not define _tunnel_host
  133. if getattr(self, "_tunnel_host", None):
  134. # TODO: Fix tunnel so it doesn't depend on self.sock state.
  135. self._tunnel()
  136. # Mark this connection as not reusable
  137. self.auto_open = 0
  138. def connect(self):
  139. conn = self._new_conn()
  140. self._prepare_conn(conn)
  141. def request_chunked(self, method, url, body=None, headers=None):
  142. """
  143. Alternative to the common request method, which sends the
  144. body with chunked encoding and not as one block
  145. """
  146. headers = HTTPHeaderDict(headers if headers is not None else {})
  147. skip_accept_encoding = "accept-encoding" in headers
  148. skip_host = "host" in headers
  149. self.putrequest(
  150. method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host
  151. )
  152. for header, value in headers.items():
  153. self.putheader(header, value)
  154. if "transfer-encoding" not in headers:
  155. self.putheader("Transfer-Encoding", "chunked")
  156. self.endheaders()
  157. if body is not None:
  158. stringish_types = six.string_types + (bytes,)
  159. if isinstance(body, stringish_types):
  160. body = (body,)
  161. for chunk in body:
  162. if not chunk:
  163. continue
  164. if not isinstance(chunk, bytes):
  165. chunk = chunk.encode("utf8")
  166. len_str = hex(len(chunk))[2:]
  167. self.send(len_str.encode("utf-8"))
  168. self.send(b"\r\n")
  169. self.send(chunk)
  170. self.send(b"\r\n")
  171. # After the if clause, to always have a closed body
  172. self.send(b"0\r\n\r\n")
  173. class HTTPSConnection(HTTPConnection):
  174. default_port = port_by_scheme["https"]
  175. ssl_version = None
  176. def __init__(
  177. self,
  178. host,
  179. port=None,
  180. key_file=None,
  181. cert_file=None,
  182. key_password=None,
  183. strict=None,
  184. timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  185. ssl_context=None,
  186. server_hostname=None,
  187. **kw
  188. ):
  189. HTTPConnection.__init__(self, host, port, strict=strict, timeout=timeout, **kw)
  190. self.key_file = key_file
  191. self.cert_file = cert_file
  192. self.key_password = key_password
  193. self.ssl_context = ssl_context
  194. self.server_hostname = server_hostname
  195. # Required property for Google AppEngine 1.9.0 which otherwise causes
  196. # HTTPS requests to go out as HTTP. (See Issue #356)
  197. self._protocol = "https"
  198. class VerifiedHTTPSConnection(HTTPSConnection):
  199. """
  200. Based on httplib.HTTPSConnection but wraps the socket with
  201. SSL certification.
  202. """
  203. cert_reqs = None
  204. ca_certs = None
  205. ca_cert_dir = None
  206. ssl_version = None
  207. assert_fingerprint = None
  208. def set_cert(
  209. self,
  210. key_file=None,
  211. cert_file=None,
  212. cert_reqs=None,
  213. key_password=None,
  214. ca_certs=None,
  215. assert_hostname=None,
  216. assert_fingerprint=None,
  217. ca_cert_dir=None,
  218. ):
  219. """
  220. This method should only be called once, before the connection is used.
  221. """
  222. # If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also
  223. # have an SSLContext object in which case we'll use its verify_mode.
  224. if cert_reqs is None:
  225. if self.ssl_context is not None:
  226. cert_reqs = self.ssl_context.verify_mode
  227. else:
  228. cert_reqs = resolve_cert_reqs(None)
  229. self.key_file = key_file
  230. self.cert_file = cert_file
  231. self.cert_reqs = cert_reqs
  232. self.key_password = key_password
  233. self.assert_hostname = assert_hostname
  234. self.assert_fingerprint = assert_fingerprint
  235. self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
  236. self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
  237. def connect(self):
  238. # Add certificate verification
  239. conn = self._new_conn()
  240. hostname = self.host
  241. # Google App Engine's httplib does not define _tunnel_host
  242. if getattr(self, "_tunnel_host", None):
  243. self.sock = conn
  244. # Calls self._set_hostport(), so self.host is
  245. # self._tunnel_host below.
  246. self._tunnel()
  247. # Mark this connection as not reusable
  248. self.auto_open = 0
  249. # Override the host with the one we're requesting data from.
  250. hostname = self._tunnel_host
  251. server_hostname = hostname
  252. if self.server_hostname is not None:
  253. server_hostname = self.server_hostname
  254. is_time_off = datetime.date.today() < RECENT_DATE
  255. if is_time_off:
  256. warnings.warn(
  257. (
  258. "System time is way off (before {0}). This will probably "
  259. "lead to SSL verification errors"
  260. ).format(RECENT_DATE),
  261. SystemTimeWarning,
  262. )
  263. # Wrap socket using verification with the root certs in
  264. # trusted_root_certs
  265. default_ssl_context = False
  266. if self.ssl_context is None:
  267. default_ssl_context = True
  268. self.ssl_context = create_urllib3_context(
  269. ssl_version=resolve_ssl_version(self.ssl_version),
  270. cert_reqs=resolve_cert_reqs(self.cert_reqs),
  271. )
  272. context = self.ssl_context
  273. context.verify_mode = resolve_cert_reqs(self.cert_reqs)
  274. # Try to load OS default certs if none are given.
  275. # Works well on Windows (requires Python3.4+)
  276. if (
  277. not self.ca_certs
  278. and not self.ca_cert_dir
  279. and default_ssl_context
  280. and hasattr(context, "load_default_certs")
  281. ):
  282. context.load_default_certs()
  283. self.sock = ssl_wrap_socket(
  284. sock=conn,
  285. keyfile=self.key_file,
  286. certfile=self.cert_file,
  287. key_password=self.key_password,
  288. ca_certs=self.ca_certs,
  289. ca_cert_dir=self.ca_cert_dir,
  290. server_hostname=server_hostname,
  291. ssl_context=context,
  292. )
  293. if self.assert_fingerprint:
  294. assert_fingerprint(
  295. self.sock.getpeercert(binary_form=True), self.assert_fingerprint
  296. )
  297. elif (
  298. context.verify_mode != ssl.CERT_NONE
  299. and not getattr(context, "check_hostname", False)
  300. and self.assert_hostname is not False
  301. ):
  302. # While urllib3 attempts to always turn off hostname matching from
  303. # the TLS library, this cannot always be done. So we check whether
  304. # the TLS Library still thinks it's matching hostnames.
  305. cert = self.sock.getpeercert()
  306. if not cert.get("subjectAltName", ()):
  307. warnings.warn(
  308. (
  309. "Certificate for {0} has no `subjectAltName`, falling back to check for a "
  310. "`commonName` for now. This feature is being removed by major browsers and "
  311. "deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 "
  312. "for details.)".format(hostname)
  313. ),
  314. SubjectAltNameWarning,
  315. )
  316. _match_hostname(cert, self.assert_hostname or server_hostname)
  317. self.is_verified = (
  318. context.verify_mode == ssl.CERT_REQUIRED
  319. or self.assert_fingerprint is not None
  320. )
  321. def _match_hostname(cert, asserted_hostname):
  322. try:
  323. match_hostname(cert, asserted_hostname)
  324. except CertificateError as e:
  325. log.warning(
  326. "Certificate did not match expected hostname: %s. Certificate: %s",
  327. asserted_hostname,
  328. cert,
  329. )
  330. # Add cert to exception and reraise so client code can inspect
  331. # the cert when catching the exception, if they want to
  332. e._peer_cert = cert
  333. raise
  334. if ssl:
  335. # Make a copy for testing.
  336. UnverifiedHTTPSConnection = HTTPSConnection
  337. HTTPSConnection = VerifiedHTTPSConnection
  338. else:
  339. HTTPSConnection = DummyConnection