connection.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. # SPDX-License-Identifier: MIT
  2. from __future__ import absolute_import
  3. import datetime
  4. import logging
  5. import os
  6. import sys
  7. import socket
  8. from socket import error as SocketError, timeout as SocketTimeout
  9. import warnings
  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. try: # Compiled with SSL?
  14. import ssl
  15. BaseSSLError = ssl.SSLError
  16. except (ImportError, AttributeError): # Platform-specific: No SSL.
  17. ssl = None
  18. class BaseSSLError(BaseException):
  19. pass
  20. try: # Python 3:
  21. # Not a no-op, we're adding this to the namespace so it can be imported.
  22. ConnectionError = ConnectionError
  23. except NameError: # Python 2:
  24. class ConnectionError(Exception):
  25. pass
  26. from .exceptions import (
  27. NewConnectionError,
  28. ConnectTimeoutError,
  29. SubjectAltNameWarning,
  30. SystemTimeWarning,
  31. )
  32. from .packages.ssl_match_hostname import match_hostname, CertificateError
  33. from .util.ssl_ import (
  34. resolve_cert_reqs,
  35. resolve_ssl_version,
  36. assert_fingerprint,
  37. create_urllib3_context,
  38. ssl_wrap_socket
  39. )
  40. from .util import connection
  41. from ._collections import HTTPHeaderDict
  42. log = logging.getLogger(__name__)
  43. port_by_scheme = {
  44. 'http': 80,
  45. 'https': 443,
  46. }
  47. # When updating RECENT_DATE, move it to
  48. # within two years of the current date, and no
  49. # earlier than 6 months ago.
  50. RECENT_DATE = datetime.date(2016, 1, 1)
  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. .. note:: This is ignored for Python 2.6. It is only applied for 2.7 and 3.x
  63. - ``socket_options``: Set specific options on the underlying socket. If not specified, then
  64. defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling
  65. Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.
  66. For example, if you wish to enable TCP Keep Alive in addition to the defaults,
  67. you might pass::
  68. HTTPConnection.default_socket_options + [
  69. (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
  70. ]
  71. Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).
  72. """
  73. default_port = port_by_scheme['http']
  74. #: Disable Nagle's algorithm by default.
  75. #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``
  76. default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
  77. #: Whether this connection verifies the host's certificate.
  78. is_verified = False
  79. def __init__(self, *args, **kw):
  80. if six.PY3: # Python 3
  81. kw.pop('strict', None)
  82. # Pre-set source_address in case we have an older Python like 2.6.
  83. self.source_address = kw.get('source_address')
  84. if sys.version_info < (2, 7): # Python 2.6
  85. # _HTTPConnection on Python 2.6 will balk at this keyword arg, but
  86. # not newer versions. We can still use it when creating a
  87. # connection though, so we pop it *after* we have saved it as
  88. # self.source_address.
  89. kw.pop('source_address', None)
  90. #: The socket options provided by the user. If no options are
  91. #: provided, we use the default options.
  92. self.socket_options = kw.pop('socket_options', self.default_socket_options)
  93. # Superclass also sets self.source_address in Python 2.7+.
  94. _HTTPConnection.__init__(self, *args, **kw)
  95. def _new_conn(self):
  96. """ Establish a socket connection and set nodelay settings on it.
  97. :return: New socket connection.
  98. """
  99. extra_kw = {}
  100. if self.source_address:
  101. extra_kw['source_address'] = self.source_address
  102. if self.socket_options:
  103. extra_kw['socket_options'] = self.socket_options
  104. try:
  105. conn = connection.create_connection(
  106. (self.host, self.port), self.timeout, **extra_kw)
  107. except SocketTimeout as e:
  108. raise ConnectTimeoutError(
  109. self, "Connection to %s timed out. (connect timeout=%s)" %
  110. (self.host, self.timeout))
  111. except SocketError as e:
  112. raise NewConnectionError(
  113. self, "Failed to establish a new connection: %s" % e)
  114. return conn
  115. def _prepare_conn(self, conn):
  116. self.sock = conn
  117. # the _tunnel_host attribute was added in python 2.6.3 (via
  118. # http://hg.python.org/cpython/rev/0f57b30a152f) so pythons 2.6(0-2) do
  119. # not have them.
  120. if getattr(self, '_tunnel_host', None):
  121. # TODO: Fix tunnel so it doesn't depend on self.sock state.
  122. self._tunnel()
  123. # Mark this connection as not reusable
  124. self.auto_open = 0
  125. def connect(self):
  126. conn = self._new_conn()
  127. self._prepare_conn(conn)
  128. def request_chunked(self, method, url, body=None, headers=None):
  129. """
  130. Alternative to the common request method, which sends the
  131. body with chunked encoding and not as one block
  132. """
  133. headers = HTTPHeaderDict(headers if headers is not None else {})
  134. skip_accept_encoding = 'accept-encoding' in headers
  135. skip_host = 'host' in headers
  136. self.putrequest(
  137. method,
  138. url,
  139. skip_accept_encoding=skip_accept_encoding,
  140. skip_host=skip_host
  141. )
  142. for header, value in headers.items():
  143. self.putheader(header, value)
  144. if 'transfer-encoding' not in headers:
  145. self.putheader('Transfer-Encoding', 'chunked')
  146. self.endheaders()
  147. if body is not None:
  148. stringish_types = six.string_types + (six.binary_type,)
  149. if isinstance(body, stringish_types):
  150. body = (body,)
  151. for chunk in body:
  152. if not chunk:
  153. continue
  154. if not isinstance(chunk, six.binary_type):
  155. chunk = chunk.encode('utf8')
  156. len_str = hex(len(chunk))[2:]
  157. self.send(len_str.encode('utf-8'))
  158. self.send(b'\r\n')
  159. self.send(chunk)
  160. self.send(b'\r\n')
  161. # After the if clause, to always have a closed body
  162. self.send(b'0\r\n\r\n')
  163. class HTTPSConnection(HTTPConnection):
  164. default_port = port_by_scheme['https']
  165. ssl_version = None
  166. def __init__(self, host, port=None, key_file=None, cert_file=None,
  167. strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  168. ssl_context=None, **kw):
  169. HTTPConnection.__init__(self, host, port, strict=strict,
  170. timeout=timeout, **kw)
  171. self.key_file = key_file
  172. self.cert_file = cert_file
  173. self.ssl_context = ssl_context
  174. # Required property for Google AppEngine 1.9.0 which otherwise causes
  175. # HTTPS requests to go out as HTTP. (See Issue #356)
  176. self._protocol = 'https'
  177. def connect(self):
  178. conn = self._new_conn()
  179. self._prepare_conn(conn)
  180. if self.ssl_context is None:
  181. self.ssl_context = create_urllib3_context(
  182. ssl_version=resolve_ssl_version(None),
  183. cert_reqs=resolve_cert_reqs(None),
  184. )
  185. self.sock = ssl_wrap_socket(
  186. sock=conn,
  187. keyfile=self.key_file,
  188. certfile=self.cert_file,
  189. ssl_context=self.ssl_context,
  190. )
  191. class VerifiedHTTPSConnection(HTTPSConnection):
  192. """
  193. Based on httplib.HTTPSConnection but wraps the socket with
  194. SSL certification.
  195. """
  196. cert_reqs = None
  197. ca_certs = None
  198. ca_cert_dir = None
  199. ssl_version = None
  200. assert_fingerprint = None
  201. def set_cert(self, key_file=None, cert_file=None,
  202. cert_reqs=None, ca_certs=None,
  203. assert_hostname=None, assert_fingerprint=None,
  204. ca_cert_dir=None):
  205. """
  206. This method should only be called once, before the connection is used.
  207. """
  208. # If cert_reqs is not provided, we can try to guess. If the user gave
  209. # us a cert database, we assume they want to use it: otherwise, if
  210. # they gave us an SSL Context object we should use whatever is set for
  211. # it.
  212. if cert_reqs is None:
  213. if ca_certs or ca_cert_dir:
  214. cert_reqs = 'CERT_REQUIRED'
  215. elif self.ssl_context is not None:
  216. cert_reqs = self.ssl_context.verify_mode
  217. self.key_file = key_file
  218. self.cert_file = cert_file
  219. self.cert_reqs = cert_reqs
  220. self.assert_hostname = assert_hostname
  221. self.assert_fingerprint = assert_fingerprint
  222. self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
  223. self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
  224. def connect(self):
  225. # Add certificate verification
  226. conn = self._new_conn()
  227. hostname = self.host
  228. if getattr(self, '_tunnel_host', None):
  229. # _tunnel_host was added in Python 2.6.3
  230. # (See: http://hg.python.org/cpython/rev/0f57b30a152f)
  231. self.sock = conn
  232. # Calls self._set_hostport(), so self.host is
  233. # self._tunnel_host below.
  234. self._tunnel()
  235. # Mark this connection as not reusable
  236. self.auto_open = 0
  237. # Override the host with the one we're requesting data from.
  238. hostname = self._tunnel_host
  239. is_time_off = datetime.date.today() < RECENT_DATE
  240. if is_time_off:
  241. warnings.warn((
  242. 'System time is way off (before {0}). This will probably '
  243. 'lead to SSL verification errors').format(RECENT_DATE),
  244. SystemTimeWarning
  245. )
  246. # Wrap socket using verification with the root certs in
  247. # trusted_root_certs
  248. if self.ssl_context is None:
  249. self.ssl_context = create_urllib3_context(
  250. ssl_version=resolve_ssl_version(self.ssl_version),
  251. cert_reqs=resolve_cert_reqs(self.cert_reqs),
  252. )
  253. context = self.ssl_context
  254. context.verify_mode = resolve_cert_reqs(self.cert_reqs)
  255. self.sock = ssl_wrap_socket(
  256. sock=conn,
  257. keyfile=self.key_file,
  258. certfile=self.cert_file,
  259. ca_certs=self.ca_certs,
  260. ca_cert_dir=self.ca_cert_dir,
  261. server_hostname=hostname,
  262. ssl_context=context)
  263. if self.assert_fingerprint:
  264. assert_fingerprint(self.sock.getpeercert(binary_form=True),
  265. self.assert_fingerprint)
  266. elif context.verify_mode != ssl.CERT_NONE \
  267. and not getattr(context, 'check_hostname', False) \
  268. and self.assert_hostname is not False:
  269. # While urllib3 attempts to always turn off hostname matching from
  270. # the TLS library, this cannot always be done. So we check whether
  271. # the TLS Library still thinks it's matching hostnames.
  272. cert = self.sock.getpeercert()
  273. if not cert.get('subjectAltName', ()):
  274. warnings.warn((
  275. 'Certificate for {0} has no `subjectAltName`, falling back to check for a '
  276. '`commonName` for now. This feature is being removed by major browsers and '
  277. 'deprecated by RFC 2818. (See https://github.com/shazow/urllib3/issues/497 '
  278. 'for details.)'.format(hostname)),
  279. SubjectAltNameWarning
  280. )
  281. _match_hostname(cert, self.assert_hostname or hostname)
  282. self.is_verified = (
  283. context.verify_mode == ssl.CERT_REQUIRED or
  284. self.assert_fingerprint is not None
  285. )
  286. def _match_hostname(cert, asserted_hostname):
  287. try:
  288. match_hostname(cert, asserted_hostname)
  289. except CertificateError as e:
  290. log.error(
  291. 'Certificate did not match expected hostname: %s. '
  292. 'Certificate: %s', asserted_hostname, cert
  293. )
  294. # Add cert to exception and reraise so client code can inspect
  295. # the cert when catching the exception, if they want to
  296. e._peer_cert = cert
  297. raise
  298. if ssl:
  299. # Make a copy for testing.
  300. UnverifiedHTTPSConnection = HTTPSConnection
  301. HTTPSConnection = VerifiedHTTPSConnection
  302. else:
  303. HTTPSConnection = DummyConnection