federation_server.py 30 KB

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