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.

391 lines
14 KiB

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