connection.py 15 KB

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