You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

connection.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. def connect(self):
  199. conn = self._new_conn()
  200. self._prepare_conn(conn)
  201. # Wrap socket using verification with the root certs in
  202. # trusted_root_certs
  203. default_ssl_context = False
  204. if self.ssl_context is None:
  205. default_ssl_context = True
  206. self.ssl_context = create_urllib3_context(
  207. ssl_version=resolve_ssl_version(self.ssl_version),
  208. cert_reqs=resolve_cert_reqs(self.cert_reqs),
  209. )
  210. # Try to load OS default certs if none are given.
  211. # Works well on Windows (requires Python3.4+)
  212. context = self.ssl_context
  213. if (
  214. not self.ca_certs
  215. and not self.ca_cert_dir
  216. and default_ssl_context
  217. and hasattr(context, "load_default_certs")
  218. ):
  219. context.load_default_certs()
  220. self.sock = ssl_wrap_socket(
  221. sock=conn,
  222. keyfile=self.key_file,
  223. certfile=self.cert_file,
  224. key_password=self.key_password,
  225. ssl_context=self.ssl_context,
  226. server_hostname=self.server_hostname,
  227. )
  228. class VerifiedHTTPSConnection(HTTPSConnection):
  229. """
  230. Based on httplib.HTTPSConnection but wraps the socket with
  231. SSL certification.
  232. """
  233. cert_reqs = None
  234. ca_certs = None
  235. ca_cert_dir = None
  236. ssl_version = None
  237. assert_fingerprint = None
  238. def set_cert(
  239. self,
  240. key_file=None,
  241. cert_file=None,
  242. cert_reqs=None,
  243. key_password=None,
  244. ca_certs=None,
  245. assert_hostname=None,
  246. assert_fingerprint=None,
  247. ca_cert_dir=None,
  248. ):
  249. """
  250. This method should only be called once, before the connection is used.
  251. """
  252. # If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also
  253. # have an SSLContext object in which case we'll use its verify_mode.
  254. if cert_reqs is None:
  255. if self.ssl_context is not None:
  256. cert_reqs = self.ssl_context.verify_mode
  257. else:
  258. cert_reqs = resolve_cert_reqs(None)
  259. self.key_file = key_file
  260. self.cert_file = cert_file
  261. self.cert_reqs = cert_reqs
  262. self.key_password = key_password
  263. self.assert_hostname = assert_hostname
  264. self.assert_fingerprint = assert_fingerprint
  265. self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
  266. self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
  267. def connect(self):
  268. # Add certificate verification
  269. conn = self._new_conn()
  270. hostname = self.host
  271. # Google App Engine's httplib does not define _tunnel_host
  272. if getattr(self, "_tunnel_host", None):
  273. self.sock = conn
  274. # Calls self._set_hostport(), so self.host is
  275. # self._tunnel_host below.
  276. self._tunnel()
  277. # Mark this connection as not reusable
  278. self.auto_open = 0
  279. # Override the host with the one we're requesting data from.
  280. hostname = self._tunnel_host
  281. server_hostname = hostname
  282. if self.server_hostname is not None:
  283. server_hostname = self.server_hostname
  284. is_time_off = datetime.date.today() < RECENT_DATE
  285. if is_time_off:
  286. warnings.warn(
  287. (
  288. "System time is way off (before {0}). This will probably "
  289. "lead to SSL verification errors"
  290. ).format(RECENT_DATE),
  291. SystemTimeWarning,
  292. )
  293. # Wrap socket using verification with the root certs in
  294. # trusted_root_certs
  295. default_ssl_context = False
  296. if self.ssl_context is None:
  297. default_ssl_context = True
  298. self.ssl_context = create_urllib3_context(
  299. ssl_version=resolve_ssl_version(self.ssl_version),
  300. cert_reqs=resolve_cert_reqs(self.cert_reqs),
  301. )
  302. context = self.ssl_context
  303. context.verify_mode = resolve_cert_reqs(self.cert_reqs)
  304. # Try to load OS default certs if none are given.
  305. # Works well on Windows (requires Python3.4+)
  306. if (
  307. not self.ca_certs
  308. and not self.ca_cert_dir
  309. and default_ssl_context
  310. and hasattr(context, "load_default_certs")
  311. ):
  312. context.load_default_certs()
  313. self.sock = ssl_wrap_socket(
  314. sock=conn,
  315. keyfile=self.key_file,
  316. certfile=self.cert_file,
  317. key_password=self.key_password,
  318. ca_certs=self.ca_certs,
  319. ca_cert_dir=self.ca_cert_dir,
  320. server_hostname=server_hostname,
  321. ssl_context=context,
  322. )
  323. if self.assert_fingerprint:
  324. assert_fingerprint(
  325. self.sock.getpeercert(binary_form=True), self.assert_fingerprint
  326. )
  327. elif (
  328. context.verify_mode != ssl.CERT_NONE
  329. and not getattr(context, "check_hostname", False)
  330. and self.assert_hostname is not False
  331. ):
  332. # While urllib3 attempts to always turn off hostname matching from
  333. # the TLS library, this cannot always be done. So we check whether
  334. # the TLS Library still thinks it's matching hostnames.
  335. cert = self.sock.getpeercert()
  336. if not cert.get("subjectAltName", ()):
  337. warnings.warn(
  338. (
  339. "Certificate for {0} has no `subjectAltName`, falling back to check for a "
  340. "`commonName` for now. This feature is being removed by major browsers and "
  341. "deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 "
  342. "for details.)".format(hostname)
  343. ),
  344. SubjectAltNameWarning,
  345. )
  346. _match_hostname(cert, self.assert_hostname or server_hostname)
  347. self.is_verified = (
  348. context.verify_mode == ssl.CERT_REQUIRED
  349. or self.assert_fingerprint is not None
  350. )
  351. def _match_hostname(cert, asserted_hostname):
  352. try:
  353. match_hostname(cert, asserted_hostname)
  354. except CertificateError as e:
  355. log.warning(
  356. "Certificate did not match expected hostname: %s. Certificate: %s",
  357. asserted_hostname,
  358. cert,
  359. )
  360. # Add cert to exception and reraise so client code can inspect
  361. # the cert when catching the exception, if they want to
  362. e._peer_cert = cert
  363. raise
  364. if ssl:
  365. # Make a copy for testing.
  366. UnverifiedHTTPSConnection = HTTPSConnection
  367. HTTPSConnection = VerifiedHTTPSConnection
  368. else:
  369. HTTPSConnection = DummyConnection