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.
 
 
 
 
 
 

454 lines
16 KiB

  1. # Copyright 2019 New Vector Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. import urllib.parse
  16. from typing import Any, Generator, List, Optional
  17. from urllib.request import ( # type: ignore[attr-defined]
  18. getproxies_environment,
  19. proxy_bypass_environment,
  20. )
  21. from netaddr import AddrFormatError, IPAddress, IPSet
  22. from zope.interface import implementer
  23. from twisted.internet import defer
  24. from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS
  25. from twisted.internet.interfaces import (
  26. IProtocol,
  27. IProtocolFactory,
  28. IReactorCore,
  29. IStreamClientEndpoint,
  30. )
  31. from twisted.web.client import URI, Agent, HTTPConnectionPool
  32. from twisted.web.http_headers import Headers
  33. from twisted.web.iweb import IAgent, IAgentEndpointFactory, IBodyProducer, IResponse
  34. from synapse.crypto.context_factory import FederationPolicyForHTTPS
  35. from synapse.http import proxyagent
  36. from synapse.http.client import BlocklistingAgentWrapper, BlocklistingReactorWrapper
  37. from synapse.http.connectproxyclient import HTTPConnectProxyEndpoint
  38. from synapse.http.federation.srv_resolver import Server, SrvResolver
  39. from synapse.http.federation.well_known_resolver import WellKnownResolver
  40. from synapse.http.proxyagent import ProxyAgent
  41. from synapse.logging.context import make_deferred_yieldable, run_in_background
  42. from synapse.types import ISynapseReactor
  43. from synapse.util import Clock
  44. logger = logging.getLogger(__name__)
  45. @implementer(IAgent)
  46. class MatrixFederationAgent:
  47. """An Agent-like thing which provides a `request` method which correctly
  48. handles resolving matrix server names when using `matrix-federation://`. Handles
  49. standard https URIs as normal. The `matrix-federation://` scheme is internal to
  50. Synapse and we purposely want to avoid colliding with the `matrix://` URL scheme
  51. which is now specced.
  52. Doesn't implement any retries. (Those are done in MatrixFederationHttpClient.)
  53. Args:
  54. reactor: twisted reactor to use for underlying requests
  55. tls_client_options_factory:
  56. factory to use for fetching client tls options, or none to disable TLS.
  57. user_agent:
  58. The user agent header to use for federation requests.
  59. ip_allowlist: Allowed IP addresses.
  60. ip_blocklist: Disallowed IP addresses.
  61. proxy_reactor: twisted reactor to use for connections to the proxy server
  62. reactor might have some blocking applied (i.e. for DNS queries),
  63. but we need unblocked access to the proxy.
  64. _srv_resolver:
  65. SrvResolver implementation to use for looking up SRV records. None
  66. to use a default implementation.
  67. _well_known_resolver:
  68. WellKnownResolver to use to perform well-known lookups. None to use a
  69. default implementation.
  70. """
  71. def __init__(
  72. self,
  73. reactor: ISynapseReactor,
  74. tls_client_options_factory: Optional[FederationPolicyForHTTPS],
  75. user_agent: bytes,
  76. ip_allowlist: Optional[IPSet],
  77. ip_blocklist: IPSet,
  78. _srv_resolver: Optional[SrvResolver] = None,
  79. _well_known_resolver: Optional[WellKnownResolver] = None,
  80. ):
  81. # proxy_reactor is not blocklisting reactor
  82. proxy_reactor = reactor
  83. # We need to use a DNS resolver which filters out blocked IP
  84. # addresses, to prevent DNS rebinding.
  85. reactor = BlocklistingReactorWrapper(reactor, ip_allowlist, ip_blocklist)
  86. self._clock = Clock(reactor)
  87. self._pool = HTTPConnectionPool(reactor)
  88. self._pool.retryAutomatically = False
  89. self._pool.maxPersistentPerHost = 5
  90. self._pool.cachedConnectionTimeout = 2 * 60
  91. self._agent = Agent.usingEndpointFactory(
  92. reactor,
  93. MatrixHostnameEndpointFactory(
  94. reactor,
  95. proxy_reactor,
  96. tls_client_options_factory,
  97. _srv_resolver,
  98. ),
  99. pool=self._pool,
  100. )
  101. self.user_agent = user_agent
  102. if _well_known_resolver is None:
  103. _well_known_resolver = WellKnownResolver(
  104. reactor,
  105. agent=BlocklistingAgentWrapper(
  106. ProxyAgent(
  107. reactor,
  108. proxy_reactor,
  109. pool=self._pool,
  110. contextFactory=tls_client_options_factory,
  111. use_proxy=True,
  112. ),
  113. ip_blocklist=ip_blocklist,
  114. ),
  115. user_agent=self.user_agent,
  116. )
  117. self._well_known_resolver = _well_known_resolver
  118. @defer.inlineCallbacks
  119. def request(
  120. self,
  121. method: bytes,
  122. uri: bytes,
  123. headers: Optional[Headers] = None,
  124. bodyProducer: Optional[IBodyProducer] = None,
  125. ) -> Generator[defer.Deferred, Any, IResponse]:
  126. """
  127. Args:
  128. method: HTTP method: GET/POST/etc
  129. uri: Absolute URI to be retrieved
  130. headers:
  131. HTTP headers to send with the request, or None to send no extra headers.
  132. bodyProducer:
  133. An object which can generate bytes to make up the
  134. body of this request (for example, the properly encoded contents of
  135. a file for a file upload). Or None if the request is to have
  136. no body.
  137. Returns:
  138. A deferred which fires when the header of the response has been received
  139. (regardless of the response status code). Fails if there is any problem
  140. which prevents that response from being received (including problems that
  141. prevent the request from being sent).
  142. """
  143. # We use urlparse as that will set `port` to None if there is no
  144. # explicit port.
  145. parsed_uri = urllib.parse.urlparse(uri)
  146. # There must be a valid hostname.
  147. assert parsed_uri.hostname
  148. # If this is a matrix-federation:// URI check if the server has delegated matrix
  149. # traffic using well-known delegation.
  150. #
  151. # We have to do this here and not in the endpoint as we need to rewrite
  152. # the host header with the delegated server name.
  153. delegated_server = None
  154. if (
  155. parsed_uri.scheme == b"matrix-federation"
  156. and not _is_ip_literal(parsed_uri.hostname)
  157. and not parsed_uri.port
  158. ):
  159. well_known_result = yield defer.ensureDeferred(
  160. self._well_known_resolver.get_well_known(parsed_uri.hostname)
  161. )
  162. delegated_server = well_known_result.delegated_server
  163. if delegated_server:
  164. # Ok, the server has delegated matrix traffic to somewhere else, so
  165. # lets rewrite the URL to replace the server with the delegated
  166. # server name.
  167. uri = urllib.parse.urlunparse(
  168. (
  169. parsed_uri.scheme,
  170. delegated_server,
  171. parsed_uri.path,
  172. parsed_uri.params,
  173. parsed_uri.query,
  174. parsed_uri.fragment,
  175. )
  176. )
  177. parsed_uri = urllib.parse.urlparse(uri)
  178. # We need to make sure the host header is set to the netloc of the
  179. # server and that a user-agent is provided.
  180. if headers is None:
  181. request_headers = Headers()
  182. else:
  183. request_headers = headers.copy()
  184. if not request_headers.hasHeader(b"host"):
  185. request_headers.addRawHeader(b"host", parsed_uri.netloc)
  186. if not request_headers.hasHeader(b"user-agent"):
  187. request_headers.addRawHeader(b"user-agent", self.user_agent)
  188. res = yield make_deferred_yieldable(
  189. self._agent.request(method, uri, request_headers, bodyProducer)
  190. )
  191. return res
  192. @implementer(IAgentEndpointFactory)
  193. class MatrixHostnameEndpointFactory:
  194. """Factory for MatrixHostnameEndpoint for parsing to an Agent."""
  195. def __init__(
  196. self,
  197. reactor: IReactorCore,
  198. proxy_reactor: IReactorCore,
  199. tls_client_options_factory: Optional[FederationPolicyForHTTPS],
  200. srv_resolver: Optional[SrvResolver],
  201. ):
  202. self._reactor = reactor
  203. self._proxy_reactor = proxy_reactor
  204. self._tls_client_options_factory = tls_client_options_factory
  205. if srv_resolver is None:
  206. srv_resolver = SrvResolver()
  207. self._srv_resolver = srv_resolver
  208. def endpointForURI(self, parsed_uri: URI) -> "MatrixHostnameEndpoint":
  209. return MatrixHostnameEndpoint(
  210. self._reactor,
  211. self._proxy_reactor,
  212. self._tls_client_options_factory,
  213. self._srv_resolver,
  214. parsed_uri,
  215. )
  216. @implementer(IStreamClientEndpoint)
  217. class MatrixHostnameEndpoint:
  218. """An endpoint that resolves matrix-federation:// URLs using Matrix server name
  219. resolution (i.e. via SRV). Does not check for well-known delegation.
  220. Args:
  221. reactor: twisted reactor to use for underlying requests
  222. proxy_reactor: twisted reactor to use for connections to the proxy server.
  223. 'reactor' might have some blocking applied (i.e. for DNS queries),
  224. but we need unblocked access to the proxy.
  225. tls_client_options_factory:
  226. factory to use for fetching client tls options, or none to disable TLS.
  227. srv_resolver: The SRV resolver to use
  228. parsed_uri: The parsed URI that we're wanting to connect to.
  229. Raises:
  230. ValueError if the environment variables contain an invalid proxy specification.
  231. RuntimeError if no tls_options_factory is given for a https connection
  232. """
  233. def __init__(
  234. self,
  235. reactor: IReactorCore,
  236. proxy_reactor: IReactorCore,
  237. tls_client_options_factory: Optional[FederationPolicyForHTTPS],
  238. srv_resolver: SrvResolver,
  239. parsed_uri: URI,
  240. ):
  241. self._reactor = reactor
  242. self._parsed_uri = parsed_uri
  243. # http_proxy is not needed because federation is always over TLS
  244. proxies = getproxies_environment()
  245. https_proxy = proxies["https"].encode() if "https" in proxies else None
  246. self.no_proxy = proxies["no"] if "no" in proxies else None
  247. # endpoint and credentials to use to connect to the outbound https proxy, if any.
  248. (
  249. self._https_proxy_endpoint,
  250. self._https_proxy_creds,
  251. ) = proxyagent.http_proxy_endpoint(
  252. https_proxy,
  253. proxy_reactor,
  254. tls_client_options_factory,
  255. )
  256. # set up the TLS connection params
  257. #
  258. # XXX disabling TLS is really only supported here for the benefit of the
  259. # unit tests. We should make the UTs cope with TLS rather than having to make
  260. # the code support the unit tests.
  261. if tls_client_options_factory is None:
  262. self._tls_options = None
  263. else:
  264. self._tls_options = tls_client_options_factory.get_options(
  265. self._parsed_uri.host
  266. )
  267. self._srv_resolver = srv_resolver
  268. def connect(
  269. self, protocol_factory: IProtocolFactory
  270. ) -> "defer.Deferred[IProtocol]":
  271. """Implements IStreamClientEndpoint interface"""
  272. return run_in_background(self._do_connect, protocol_factory)
  273. async def _do_connect(self, protocol_factory: IProtocolFactory) -> IProtocol:
  274. first_exception = None
  275. server_list = await self._resolve_server()
  276. for server in server_list:
  277. host = server.host
  278. port = server.port
  279. should_skip_proxy = False
  280. if self.no_proxy is not None:
  281. should_skip_proxy = proxy_bypass_environment(
  282. host.decode(),
  283. proxies={"no": self.no_proxy},
  284. )
  285. endpoint: IStreamClientEndpoint
  286. try:
  287. if self._https_proxy_endpoint and not should_skip_proxy:
  288. logger.debug(
  289. "Connecting to %s:%i via %s",
  290. host.decode("ascii"),
  291. port,
  292. self._https_proxy_endpoint,
  293. )
  294. endpoint = HTTPConnectProxyEndpoint(
  295. self._reactor,
  296. self._https_proxy_endpoint,
  297. host,
  298. port,
  299. proxy_creds=self._https_proxy_creds,
  300. )
  301. else:
  302. logger.debug("Connecting to %s:%i", host.decode("ascii"), port)
  303. # not using a proxy
  304. endpoint = HostnameEndpoint(self._reactor, host, port)
  305. if self._tls_options:
  306. endpoint = wrapClientTLS(self._tls_options, endpoint)
  307. result = await make_deferred_yieldable(
  308. endpoint.connect(protocol_factory)
  309. )
  310. return result
  311. except Exception as e:
  312. logger.info(
  313. "Failed to connect to %s:%i: %s", host.decode("ascii"), port, e
  314. )
  315. if not first_exception:
  316. first_exception = e
  317. # We return the first failure because that's probably the most interesting.
  318. if first_exception:
  319. raise first_exception
  320. # This shouldn't happen as we should always have at least one host/port
  321. # to try and if that doesn't work then we'll have an exception.
  322. raise Exception("Failed to resolve server %r" % (self._parsed_uri.netloc,))
  323. async def _resolve_server(self) -> List[Server]:
  324. """Resolves the server name to a list of hosts and ports to attempt to
  325. connect to.
  326. """
  327. if self._parsed_uri.scheme != b"matrix-federation":
  328. return [Server(host=self._parsed_uri.host, port=self._parsed_uri.port)]
  329. # Note: We don't do well-known lookup as that needs to have happened
  330. # before now, due to needing to rewrite the Host header of the HTTP
  331. # request.
  332. # We reparse the URI so that defaultPort is -1 rather than 80
  333. parsed_uri = urllib.parse.urlparse(self._parsed_uri.toBytes())
  334. host = parsed_uri.hostname
  335. port = parsed_uri.port
  336. # If there is an explicit port or the host is an IP address we bypass
  337. # SRV lookups and just use the given host/port.
  338. if port or _is_ip_literal(host):
  339. return [Server(host, port or 8448)]
  340. # Check _matrix-fed._tcp SRV record.
  341. logger.debug("Looking up SRV record for %s", host.decode(errors="replace"))
  342. server_list = await self._srv_resolver.resolve_service(
  343. b"_matrix-fed._tcp." + host
  344. )
  345. if server_list:
  346. if logger.isEnabledFor(logging.DEBUG):
  347. logger.debug(
  348. "Got %s from SRV lookup for %s",
  349. ", ".join(map(str, server_list)),
  350. host.decode(errors="replace"),
  351. )
  352. return server_list
  353. # No _matrix-fed._tcp SRV record, fallback to legacy _matrix._tcp SRV record.
  354. logger.debug(
  355. "Looking up deprecated SRV record for %s", host.decode(errors="replace")
  356. )
  357. server_list = await self._srv_resolver.resolve_service(b"_matrix._tcp." + host)
  358. if server_list:
  359. if logger.isEnabledFor(logging.DEBUG):
  360. logger.debug(
  361. "Got %s from deprecated SRV lookup for %s",
  362. ", ".join(map(str, server_list)),
  363. host.decode(errors="replace"),
  364. )
  365. return server_list
  366. # No SRV records, so we fallback to host and 8448
  367. logger.debug("No SRV records for %s", host.decode(errors="replace"))
  368. return [Server(host, 8448)]
  369. def _is_ip_literal(host: bytes) -> bool:
  370. """Test if the given host name is either an IPv4 or IPv6 literal.
  371. Args:
  372. host: The host name to check
  373. Returns:
  374. True if the hostname is an IP address literal.
  375. """
  376. host_str = host.decode("ascii")
  377. try:
  378. IPAddress(host_str)
  379. return True
  380. except AddrFormatError:
  381. return False