federation_server.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. import six
  18. from six import iteritems
  19. from canonicaljson import json
  20. from prometheus_client import Counter
  21. from twisted.internet import defer
  22. from twisted.internet.abstract import isIPAddress
  23. from twisted.python import failure
  24. from synapse.api.constants import EventTypes
  25. from synapse.api.errors import (
  26. AuthError,
  27. FederationError,
  28. IncompatibleRoomVersionError,
  29. NotFoundError,
  30. SynapseError,
  31. )
  32. from synapse.crypto.event_signing import compute_event_signature
  33. from synapse.federation.federation_base import FederationBase, event_from_pdu_json
  34. from synapse.federation.persistence import TransactionActions
  35. from synapse.federation.units import Edu, Transaction
  36. from synapse.http.endpoint import parse_server_name
  37. from synapse.replication.http.federation import (
  38. ReplicationFederationSendEduRestServlet,
  39. ReplicationGetQueryRestServlet,
  40. )
  41. from synapse.types import get_domain_from_id
  42. from synapse.util import glob_to_regex
  43. from synapse.util.async_helpers import Linearizer, concurrently_execute
  44. from synapse.util.caches.response_cache import ResponseCache
  45. from synapse.util.logcontext import nested_logging_context
  46. from synapse.util.logutils import log_function
  47. # when processing incoming transactions, we try to handle multiple rooms in
  48. # parallel, up to this limit.
  49. TRANSACTION_CONCURRENCY_LIMIT = 10
  50. logger = logging.getLogger(__name__)
  51. received_pdus_counter = Counter("synapse_federation_server_received_pdus", "")
  52. received_edus_counter = Counter("synapse_federation_server_received_edus", "")
  53. received_queries_counter = Counter(
  54. "synapse_federation_server_received_queries", "", ["type"]
  55. )
  56. class FederationServer(FederationBase):
  57. def __init__(self, hs):
  58. super(FederationServer, self).__init__(hs)
  59. self.auth = hs.get_auth()
  60. self.handler = hs.get_handlers().federation_handler
  61. self._server_linearizer = Linearizer("fed_server")
  62. self._transaction_linearizer = Linearizer("fed_txn_handler")
  63. self.transaction_actions = TransactionActions(self.store)
  64. self.registry = hs.get_federation_registry()
  65. # We cache responses to state queries, as they take a while and often
  66. # come in waves.
  67. self._state_resp_cache = ResponseCache(hs, "state_resp", timeout_ms=30000)
  68. @defer.inlineCallbacks
  69. @log_function
  70. def on_backfill_request(self, origin, room_id, versions, limit):
  71. with (yield self._server_linearizer.queue((origin, room_id))):
  72. origin_host, _ = parse_server_name(origin)
  73. yield self.check_server_matches_acl(origin_host, room_id)
  74. pdus = yield self.handler.on_backfill_request(
  75. origin, room_id, versions, limit
  76. )
  77. res = self._transaction_from_pdus(pdus).get_dict()
  78. defer.returnValue((200, res))
  79. @defer.inlineCallbacks
  80. @log_function
  81. def on_incoming_transaction(self, origin, transaction_data):
  82. # keep this as early as possible to make the calculated origin ts as
  83. # accurate as possible.
  84. request_time = self._clock.time_msec()
  85. transaction = Transaction(**transaction_data)
  86. if not transaction.transaction_id:
  87. raise Exception("Transaction missing transaction_id")
  88. logger.debug("[%s] Got transaction", transaction.transaction_id)
  89. # use a linearizer to ensure that we don't process the same transaction
  90. # multiple times in parallel.
  91. with (yield self._transaction_linearizer.queue(
  92. (origin, transaction.transaction_id),
  93. )):
  94. result = yield self._handle_incoming_transaction(
  95. origin, transaction, request_time,
  96. )
  97. defer.returnValue(result)
  98. @defer.inlineCallbacks
  99. def _handle_incoming_transaction(self, origin, transaction, request_time):
  100. """ Process an incoming transaction and return the HTTP response
  101. Args:
  102. origin (unicode): the server making the request
  103. transaction (Transaction): incoming transaction
  104. request_time (int): timestamp that the HTTP request arrived at
  105. Returns:
  106. Deferred[(int, object)]: http response code and body
  107. """
  108. response = yield self.transaction_actions.have_responded(origin, transaction)
  109. if response:
  110. logger.debug(
  111. "[%s] We've already responded to this request",
  112. transaction.transaction_id
  113. )
  114. defer.returnValue(response)
  115. return
  116. logger.debug("[%s] Transaction is new", transaction.transaction_id)
  117. received_pdus_counter.inc(len(transaction.pdus))
  118. origin_host, _ = parse_server_name(origin)
  119. pdus_by_room = {}
  120. for p in transaction.pdus:
  121. if "unsigned" in p:
  122. unsigned = p["unsigned"]
  123. if "age" in unsigned:
  124. p["age"] = unsigned["age"]
  125. if "age" in p:
  126. p["age_ts"] = request_time - int(p["age"])
  127. del p["age"]
  128. event = event_from_pdu_json(p)
  129. room_id = event.room_id
  130. pdus_by_room.setdefault(room_id, []).append(event)
  131. pdu_results = {}
  132. # we can process different rooms in parallel (which is useful if they
  133. # require callouts to other servers to fetch missing events), but
  134. # impose a limit to avoid going too crazy with ram/cpu.
  135. @defer.inlineCallbacks
  136. def process_pdus_for_room(room_id):
  137. logger.debug("Processing PDUs for %s", room_id)
  138. try:
  139. yield self.check_server_matches_acl(origin_host, room_id)
  140. except AuthError as e:
  141. logger.warn(
  142. "Ignoring PDUs for room %s from banned server", room_id,
  143. )
  144. for pdu in pdus_by_room[room_id]:
  145. event_id = pdu.event_id
  146. pdu_results[event_id] = e.error_dict()
  147. return
  148. for pdu in pdus_by_room[room_id]:
  149. event_id = pdu.event_id
  150. with nested_logging_context(event_id):
  151. try:
  152. yield self._handle_received_pdu(
  153. origin, pdu
  154. )
  155. pdu_results[event_id] = {}
  156. except FederationError as e:
  157. logger.warn("Error handling PDU %s: %s", event_id, e)
  158. pdu_results[event_id] = {"error": str(e)}
  159. except Exception as e:
  160. f = failure.Failure()
  161. pdu_results[event_id] = {"error": str(e)}
  162. logger.error(
  163. "Failed to handle PDU %s: %s",
  164. event_id, f.getTraceback().rstrip(),
  165. )
  166. yield concurrently_execute(
  167. process_pdus_for_room, pdus_by_room.keys(),
  168. TRANSACTION_CONCURRENCY_LIMIT,
  169. )
  170. if hasattr(transaction, "edus"):
  171. for edu in (Edu(**x) for x in transaction.edus):
  172. yield self.received_edu(
  173. origin,
  174. edu.edu_type,
  175. edu.content
  176. )
  177. response = {
  178. "pdus": pdu_results,
  179. }
  180. logger.debug("Returning: %s", str(response))
  181. yield self.transaction_actions.set_response(
  182. origin,
  183. transaction,
  184. 200, response
  185. )
  186. defer.returnValue((200, response))
  187. @defer.inlineCallbacks
  188. def received_edu(self, origin, edu_type, content):
  189. received_edus_counter.inc()
  190. yield self.registry.on_edu(edu_type, origin, content)
  191. @defer.inlineCallbacks
  192. @log_function
  193. def on_context_state_request(self, origin, room_id, event_id):
  194. if not event_id:
  195. raise NotImplementedError("Specify an event")
  196. origin_host, _ = parse_server_name(origin)
  197. yield self.check_server_matches_acl(origin_host, room_id)
  198. in_room = yield self.auth.check_host_in_room(room_id, origin)
  199. if not in_room:
  200. raise AuthError(403, "Host not in room.")
  201. # we grab the linearizer to protect ourselves from servers which hammer
  202. # us. In theory we might already have the response to this query
  203. # in the cache so we could return it without waiting for the linearizer
  204. # - but that's non-trivial to get right, and anyway somewhat defeats
  205. # the point of the linearizer.
  206. with (yield self._server_linearizer.queue((origin, room_id))):
  207. resp = yield self._state_resp_cache.wrap(
  208. (room_id, event_id),
  209. self._on_context_state_request_compute,
  210. room_id, event_id,
  211. )
  212. defer.returnValue((200, resp))
  213. @defer.inlineCallbacks
  214. def on_state_ids_request(self, origin, room_id, event_id):
  215. if not event_id:
  216. raise NotImplementedError("Specify an event")
  217. origin_host, _ = parse_server_name(origin)
  218. yield self.check_server_matches_acl(origin_host, room_id)
  219. in_room = yield self.auth.check_host_in_room(room_id, origin)
  220. if not in_room:
  221. raise AuthError(403, "Host not in room.")
  222. state_ids = yield self.handler.get_state_ids_for_pdu(
  223. room_id, event_id,
  224. )
  225. auth_chain_ids = yield self.store.get_auth_chain_ids(state_ids)
  226. defer.returnValue((200, {
  227. "pdu_ids": state_ids,
  228. "auth_chain_ids": auth_chain_ids,
  229. }))
  230. @defer.inlineCallbacks
  231. def _on_context_state_request_compute(self, room_id, event_id):
  232. pdus = yield self.handler.get_state_for_pdu(
  233. room_id, event_id,
  234. )
  235. auth_chain = yield self.store.get_auth_chain(
  236. [pdu.event_id for pdu in pdus]
  237. )
  238. for event in auth_chain:
  239. # We sign these again because there was a bug where we
  240. # incorrectly signed things the first time round
  241. if self.hs.is_mine_id(event.event_id):
  242. event.signatures.update(
  243. compute_event_signature(
  244. event,
  245. self.hs.hostname,
  246. self.hs.config.signing_key[0]
  247. )
  248. )
  249. defer.returnValue({
  250. "pdus": [pdu.get_pdu_json() for pdu in pdus],
  251. "auth_chain": [pdu.get_pdu_json() for pdu in auth_chain],
  252. })
  253. @defer.inlineCallbacks
  254. @log_function
  255. def on_pdu_request(self, origin, event_id):
  256. pdu = yield self.handler.get_persisted_pdu(origin, event_id)
  257. if pdu:
  258. defer.returnValue(
  259. (200, self._transaction_from_pdus([pdu]).get_dict())
  260. )
  261. else:
  262. defer.returnValue((404, ""))
  263. @defer.inlineCallbacks
  264. @log_function
  265. def on_pull_request(self, origin, versions):
  266. raise NotImplementedError("Pull transactions not implemented")
  267. @defer.inlineCallbacks
  268. def on_query_request(self, query_type, args):
  269. received_queries_counter.labels(query_type).inc()
  270. resp = yield self.registry.on_query(query_type, args)
  271. defer.returnValue((200, resp))
  272. @defer.inlineCallbacks
  273. def on_make_join_request(self, origin, room_id, user_id, supported_versions):
  274. origin_host, _ = parse_server_name(origin)
  275. yield self.check_server_matches_acl(origin_host, room_id)
  276. room_version = yield self.store.get_room_version(room_id)
  277. if room_version not in supported_versions:
  278. logger.warn("Room version %s not in %s", room_version, supported_versions)
  279. raise IncompatibleRoomVersionError(room_version=room_version)
  280. pdu = yield self.handler.on_make_join_request(room_id, user_id)
  281. time_now = self._clock.time_msec()
  282. defer.returnValue({
  283. "event": pdu.get_pdu_json(time_now),
  284. "room_version": room_version,
  285. })
  286. @defer.inlineCallbacks
  287. def on_invite_request(self, origin, content):
  288. pdu = event_from_pdu_json(content)
  289. origin_host, _ = parse_server_name(origin)
  290. yield self.check_server_matches_acl(origin_host, pdu.room_id)
  291. ret_pdu = yield self.handler.on_invite_request(origin, pdu)
  292. time_now = self._clock.time_msec()
  293. defer.returnValue((200, {"event": ret_pdu.get_pdu_json(time_now)}))
  294. @defer.inlineCallbacks
  295. def on_send_join_request(self, origin, content):
  296. logger.debug("on_send_join_request: content: %s", content)
  297. pdu = event_from_pdu_json(content)
  298. origin_host, _ = parse_server_name(origin)
  299. yield self.check_server_matches_acl(origin_host, pdu.room_id)
  300. logger.debug("on_send_join_request: pdu sigs: %s", pdu.signatures)
  301. res_pdus = yield self.handler.on_send_join_request(origin, pdu)
  302. time_now = self._clock.time_msec()
  303. defer.returnValue((200, {
  304. "state": [p.get_pdu_json(time_now) for p in res_pdus["state"]],
  305. "auth_chain": [
  306. p.get_pdu_json(time_now) for p in res_pdus["auth_chain"]
  307. ],
  308. }))
  309. @defer.inlineCallbacks
  310. def on_make_leave_request(self, origin, room_id, user_id):
  311. origin_host, _ = parse_server_name(origin)
  312. yield self.check_server_matches_acl(origin_host, room_id)
  313. pdu = yield self.handler.on_make_leave_request(room_id, user_id)
  314. time_now = self._clock.time_msec()
  315. defer.returnValue({"event": pdu.get_pdu_json(time_now)})
  316. @defer.inlineCallbacks
  317. def on_send_leave_request(self, origin, content):
  318. logger.debug("on_send_leave_request: content: %s", content)
  319. pdu = event_from_pdu_json(content)
  320. origin_host, _ = parse_server_name(origin)
  321. yield self.check_server_matches_acl(origin_host, pdu.room_id)
  322. logger.debug("on_send_leave_request: pdu sigs: %s", pdu.signatures)
  323. yield self.handler.on_send_leave_request(origin, pdu)
  324. defer.returnValue((200, {}))
  325. @defer.inlineCallbacks
  326. def on_event_auth(self, origin, room_id, event_id):
  327. with (yield self._server_linearizer.queue((origin, room_id))):
  328. origin_host, _ = parse_server_name(origin)
  329. yield self.check_server_matches_acl(origin_host, room_id)
  330. time_now = self._clock.time_msec()
  331. auth_pdus = yield self.handler.on_event_auth(event_id)
  332. res = {
  333. "auth_chain": [a.get_pdu_json(time_now) for a in auth_pdus],
  334. }
  335. defer.returnValue((200, res))
  336. @defer.inlineCallbacks
  337. def on_query_auth_request(self, origin, content, room_id, event_id):
  338. """
  339. Content is a dict with keys::
  340. auth_chain (list): A list of events that give the auth chain.
  341. missing (list): A list of event_ids indicating what the other
  342. side (`origin`) think we're missing.
  343. rejects (dict): A mapping from event_id to a 2-tuple of reason
  344. string and a proof (or None) of why the event was rejected.
  345. The keys of this dict give the list of events the `origin` has
  346. rejected.
  347. Args:
  348. origin (str)
  349. content (dict)
  350. event_id (str)
  351. Returns:
  352. Deferred: Results in `dict` with the same format as `content`
  353. """
  354. with (yield self._server_linearizer.queue((origin, room_id))):
  355. origin_host, _ = parse_server_name(origin)
  356. yield self.check_server_matches_acl(origin_host, room_id)
  357. auth_chain = [
  358. event_from_pdu_json(e)
  359. for e in content["auth_chain"]
  360. ]
  361. signed_auth = yield self._check_sigs_and_hash_and_fetch(
  362. origin, auth_chain, outlier=True
  363. )
  364. ret = yield self.handler.on_query_auth(
  365. origin,
  366. event_id,
  367. room_id,
  368. signed_auth,
  369. content.get("rejects", []),
  370. content.get("missing", []),
  371. )
  372. time_now = self._clock.time_msec()
  373. send_content = {
  374. "auth_chain": [
  375. e.get_pdu_json(time_now)
  376. for e in ret["auth_chain"]
  377. ],
  378. "rejects": ret.get("rejects", []),
  379. "missing": ret.get("missing", []),
  380. }
  381. defer.returnValue(
  382. (200, send_content)
  383. )
  384. @log_function
  385. def on_query_client_keys(self, origin, content):
  386. return self.on_query_request("client_keys", content)
  387. def on_query_user_devices(self, origin, user_id):
  388. return self.on_query_request("user_devices", user_id)
  389. @defer.inlineCallbacks
  390. @log_function
  391. def on_claim_client_keys(self, origin, content):
  392. query = []
  393. for user_id, device_keys in content.get("one_time_keys", {}).items():
  394. for device_id, algorithm in device_keys.items():
  395. query.append((user_id, device_id, algorithm))
  396. results = yield self.store.claim_e2e_one_time_keys(query)
  397. json_result = {}
  398. for user_id, device_keys in results.items():
  399. for device_id, keys in device_keys.items():
  400. for key_id, json_bytes in keys.items():
  401. json_result.setdefault(user_id, {})[device_id] = {
  402. key_id: json.loads(json_bytes)
  403. }
  404. logger.info(
  405. "Claimed one-time-keys: %s",
  406. ",".join((
  407. "%s for %s:%s" % (key_id, user_id, device_id)
  408. for user_id, user_keys in iteritems(json_result)
  409. for device_id, device_keys in iteritems(user_keys)
  410. for key_id, _ in iteritems(device_keys)
  411. )),
  412. )
  413. defer.returnValue({"one_time_keys": json_result})
  414. @defer.inlineCallbacks
  415. @log_function
  416. def on_get_missing_events(self, origin, room_id, earliest_events,
  417. latest_events, limit):
  418. with (yield self._server_linearizer.queue((origin, room_id))):
  419. origin_host, _ = parse_server_name(origin)
  420. yield self.check_server_matches_acl(origin_host, room_id)
  421. logger.info(
  422. "on_get_missing_events: earliest_events: %r, latest_events: %r,"
  423. " limit: %d",
  424. earliest_events, latest_events, limit,
  425. )
  426. missing_events = yield self.handler.on_get_missing_events(
  427. origin, room_id, earliest_events, latest_events, limit,
  428. )
  429. if len(missing_events) < 5:
  430. logger.info(
  431. "Returning %d events: %r", len(missing_events), missing_events
  432. )
  433. else:
  434. logger.info("Returning %d events", len(missing_events))
  435. time_now = self._clock.time_msec()
  436. defer.returnValue({
  437. "events": [ev.get_pdu_json(time_now) for ev in missing_events],
  438. })
  439. @log_function
  440. def on_openid_userinfo(self, token):
  441. ts_now_ms = self._clock.time_msec()
  442. return self.store.get_user_id_for_open_id_token(token, ts_now_ms)
  443. def _transaction_from_pdus(self, pdu_list):
  444. """Returns a new Transaction containing the given PDUs suitable for
  445. transmission.
  446. """
  447. time_now = self._clock.time_msec()
  448. pdus = [p.get_pdu_json(time_now) for p in pdu_list]
  449. return Transaction(
  450. origin=self.server_name,
  451. pdus=pdus,
  452. origin_server_ts=int(time_now),
  453. destination=None,
  454. )
  455. @defer.inlineCallbacks
  456. def _handle_received_pdu(self, origin, pdu):
  457. """ Process a PDU received in a federation /send/ transaction.
  458. If the event is invalid, then this method throws a FederationError.
  459. (The error will then be logged and sent back to the sender (which
  460. probably won't do anything with it), and other events in the
  461. transaction will be processed as normal).
  462. It is likely that we'll then receive other events which refer to
  463. this rejected_event in their prev_events, etc. When that happens,
  464. we'll attempt to fetch the rejected event again, which will presumably
  465. fail, so those second-generation events will also get rejected.
  466. Eventually, we get to the point where there are more than 10 events
  467. between any new events and the original rejected event. Since we
  468. only try to backfill 10 events deep on received pdu, we then accept the
  469. new event, possibly introducing a discontinuity in the DAG, with new
  470. forward extremities, so normal service is approximately returned,
  471. until we try to backfill across the discontinuity.
  472. Args:
  473. origin (str): server which sent the pdu
  474. pdu (FrozenEvent): received pdu
  475. Returns (Deferred): completes with None
  476. Raises: FederationError if the signatures / hash do not match, or
  477. if the event was unacceptable for any other reason (eg, too large,
  478. too many prev_events, couldn't find the prev_events)
  479. """
  480. # check that it's actually being sent from a valid destination to
  481. # workaround bug #1753 in 0.18.5 and 0.18.6
  482. if origin != get_domain_from_id(pdu.event_id):
  483. # We continue to accept join events from any server; this is
  484. # necessary for the federation join dance to work correctly.
  485. # (When we join over federation, the "helper" server is
  486. # responsible for sending out the join event, rather than the
  487. # origin. See bug #1893).
  488. if not (
  489. pdu.type == 'm.room.member' and
  490. pdu.content and
  491. pdu.content.get("membership", None) == 'join'
  492. ):
  493. logger.info(
  494. "Discarding PDU %s from invalid origin %s",
  495. pdu.event_id, origin
  496. )
  497. return
  498. else:
  499. logger.info(
  500. "Accepting join PDU %s from %s",
  501. pdu.event_id, origin
  502. )
  503. # Check signature.
  504. try:
  505. pdu = yield self._check_sigs_and_hash(pdu)
  506. except SynapseError as e:
  507. raise FederationError(
  508. "ERROR",
  509. e.code,
  510. e.msg,
  511. affected=pdu.event_id,
  512. )
  513. yield self.handler.on_receive_pdu(
  514. origin, pdu, sent_to_us_directly=True,
  515. )
  516. def __str__(self):
  517. return "<ReplicationLayer(%s)>" % self.server_name
  518. @defer.inlineCallbacks
  519. def exchange_third_party_invite(
  520. self,
  521. sender_user_id,
  522. target_user_id,
  523. room_id,
  524. signed,
  525. ):
  526. ret = yield self.handler.exchange_third_party_invite(
  527. sender_user_id,
  528. target_user_id,
  529. room_id,
  530. signed,
  531. )
  532. defer.returnValue(ret)
  533. @defer.inlineCallbacks
  534. def on_exchange_third_party_invite_request(self, origin, room_id, event_dict):
  535. ret = yield self.handler.on_exchange_third_party_invite_request(
  536. origin, room_id, event_dict
  537. )
  538. defer.returnValue(ret)
  539. @defer.inlineCallbacks
  540. def check_server_matches_acl(self, server_name, room_id):
  541. """Check if the given server is allowed by the server ACLs in the room
  542. Args:
  543. server_name (str): name of server, *without any port part*
  544. room_id (str): ID of the room to check
  545. Raises:
  546. AuthError if the server does not match the ACL
  547. """
  548. state_ids = yield self.store.get_current_state_ids(room_id)
  549. acl_event_id = state_ids.get((EventTypes.ServerACL, ""))
  550. if not acl_event_id:
  551. return
  552. acl_event = yield self.store.get_event(acl_event_id)
  553. if server_matches_acl_event(server_name, acl_event):
  554. return
  555. raise AuthError(code=403, msg="Server is banned from room")
  556. def server_matches_acl_event(server_name, acl_event):
  557. """Check if the given server is allowed by the ACL event
  558. Args:
  559. server_name (str): name of server, without any port part
  560. acl_event (EventBase): m.room.server_acl event
  561. Returns:
  562. bool: True if this server is allowed by the ACLs
  563. """
  564. logger.debug("Checking %s against acl %s", server_name, acl_event.content)
  565. # first of all, check if literal IPs are blocked, and if so, whether the
  566. # server name is a literal IP
  567. allow_ip_literals = acl_event.content.get("allow_ip_literals", True)
  568. if not isinstance(allow_ip_literals, bool):
  569. logger.warn("Ignorning non-bool allow_ip_literals flag")
  570. allow_ip_literals = True
  571. if not allow_ip_literals:
  572. # check for ipv6 literals. These start with '['.
  573. if server_name[0] == '[':
  574. return False
  575. # check for ipv4 literals. We can just lift the routine from twisted.
  576. if isIPAddress(server_name):
  577. return False
  578. # next, check the deny list
  579. deny = acl_event.content.get("deny", [])
  580. if not isinstance(deny, (list, tuple)):
  581. logger.warn("Ignorning non-list deny ACL %s", deny)
  582. deny = []
  583. for e in deny:
  584. if _acl_entry_matches(server_name, e):
  585. # logger.info("%s matched deny rule %s", server_name, e)
  586. return False
  587. # then the allow list.
  588. allow = acl_event.content.get("allow", [])
  589. if not isinstance(allow, (list, tuple)):
  590. logger.warn("Ignorning non-list allow ACL %s", allow)
  591. allow = []
  592. for e in allow:
  593. if _acl_entry_matches(server_name, e):
  594. # logger.info("%s matched allow rule %s", server_name, e)
  595. return True
  596. # everything else should be rejected.
  597. # logger.info("%s fell through", server_name)
  598. return False
  599. def _acl_entry_matches(server_name, acl_entry):
  600. if not isinstance(acl_entry, six.string_types):
  601. logger.warn("Ignoring non-str ACL entry '%s' (is %s)", acl_entry, type(acl_entry))
  602. return False
  603. regex = glob_to_regex(acl_entry)
  604. return regex.match(server_name)
  605. class FederationHandlerRegistry(object):
  606. """Allows classes to register themselves as handlers for a given EDU or
  607. query type for incoming federation traffic.
  608. """
  609. def __init__(self):
  610. self.edu_handlers = {}
  611. self.query_handlers = {}
  612. def register_edu_handler(self, edu_type, handler):
  613. """Sets the handler callable that will be used to handle an incoming
  614. federation EDU of the given type.
  615. Args:
  616. edu_type (str): The type of the incoming EDU to register handler for
  617. handler (Callable[[str, dict]]): A callable invoked on incoming EDU
  618. of the given type. The arguments are the origin server name and
  619. the EDU contents.
  620. """
  621. if edu_type in self.edu_handlers:
  622. raise KeyError("Already have an EDU handler for %s" % (edu_type,))
  623. logger.info("Registering federation EDU handler for %r", edu_type)
  624. self.edu_handlers[edu_type] = handler
  625. def register_query_handler(self, query_type, handler):
  626. """Sets the handler callable that will be used to handle an incoming
  627. federation query of the given type.
  628. Args:
  629. query_type (str): Category name of the query, which should match
  630. the string used by make_query.
  631. handler (Callable[[dict], Deferred[dict]]): Invoked to handle
  632. incoming queries of this type. The return will be yielded
  633. on and the result used as the response to the query request.
  634. """
  635. if query_type in self.query_handlers:
  636. raise KeyError(
  637. "Already have a Query handler for %s" % (query_type,)
  638. )
  639. logger.info("Registering federation query handler for %r", query_type)
  640. self.query_handlers[query_type] = handler
  641. @defer.inlineCallbacks
  642. def on_edu(self, edu_type, origin, content):
  643. handler = self.edu_handlers.get(edu_type)
  644. if not handler:
  645. logger.warn("No handler registered for EDU type %s", edu_type)
  646. try:
  647. yield handler(origin, content)
  648. except SynapseError as e:
  649. logger.info("Failed to handle edu %r: %r", edu_type, e)
  650. except Exception:
  651. logger.exception("Failed to handle edu %r", edu_type)
  652. def on_query(self, query_type, args):
  653. handler = self.query_handlers.get(query_type)
  654. if not handler:
  655. logger.warn("No handler registered for query type %s", query_type)
  656. raise NotFoundError("No handler for Query type '%s'" % (query_type,))
  657. return handler(args)
  658. class ReplicationFederationHandlerRegistry(FederationHandlerRegistry):
  659. """A FederationHandlerRegistry for worker processes.
  660. When receiving EDU or queries it will check if an appropriate handler has
  661. been registered on the worker, if there isn't one then it calls off to the
  662. master process.
  663. """
  664. def __init__(self, hs):
  665. self.config = hs.config
  666. self.http_client = hs.get_simple_http_client()
  667. self.clock = hs.get_clock()
  668. self._get_query_client = ReplicationGetQueryRestServlet.make_client(hs)
  669. self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs)
  670. super(ReplicationFederationHandlerRegistry, self).__init__()
  671. def on_edu(self, edu_type, origin, content):
  672. """Overrides FederationHandlerRegistry
  673. """
  674. handler = self.edu_handlers.get(edu_type)
  675. if handler:
  676. return super(ReplicationFederationHandlerRegistry, self).on_edu(
  677. edu_type, origin, content,
  678. )
  679. return self._send_edu(
  680. edu_type=edu_type,
  681. origin=origin,
  682. content=content,
  683. )
  684. def on_query(self, query_type, args):
  685. """Overrides FederationHandlerRegistry
  686. """
  687. handler = self.query_handlers.get(query_type)
  688. if handler:
  689. return handler(args)
  690. return self._get_query_client(
  691. query_type=query_type,
  692. args=args,
  693. )