federation_base.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. # Copyright 2020 The Matrix.org Foundation C.I.C.
  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. from collections import namedtuple
  18. from typing import Iterable, List
  19. from twisted.internet import defer
  20. from twisted.internet.defer import Deferred, DeferredList
  21. from twisted.python.failure import Failure
  22. from synapse.api.constants import MAX_DEPTH, EventTypes, Membership
  23. from synapse.api.errors import Codes, SynapseError
  24. from synapse.api.room_versions import EventFormatVersions, RoomVersion
  25. from synapse.crypto.event_signing import check_event_content_hash
  26. from synapse.crypto.keyring import Keyring
  27. from synapse.events import EventBase, make_event_from_dict
  28. from synapse.events.utils import prune_event, validate_canonicaljson
  29. from synapse.http.servlet import assert_params_in_dict
  30. from synapse.logging.context import (
  31. PreserveLoggingContext,
  32. current_context,
  33. make_deferred_yieldable,
  34. )
  35. from synapse.types import JsonDict, get_domain_from_id
  36. logger = logging.getLogger(__name__)
  37. class FederationBase:
  38. def __init__(self, hs):
  39. self.hs = hs
  40. self.server_name = hs.hostname
  41. self.keyring = hs.get_keyring()
  42. self.spam_checker = hs.get_spam_checker()
  43. self.store = hs.get_datastore()
  44. self._clock = hs.get_clock()
  45. def _check_sigs_and_hash(
  46. self, room_version: RoomVersion, pdu: EventBase
  47. ) -> Deferred:
  48. return make_deferred_yieldable(
  49. self._check_sigs_and_hashes(room_version, [pdu])[0]
  50. )
  51. def _check_sigs_and_hashes(
  52. self, room_version: RoomVersion, pdus: List[EventBase]
  53. ) -> List[Deferred]:
  54. """Checks that each of the received events is correctly signed by the
  55. sending server.
  56. Args:
  57. room_version: The room version of the PDUs
  58. pdus: the events to be checked
  59. Returns:
  60. For each input event, a deferred which:
  61. * returns the original event if the checks pass
  62. * returns a redacted version of the event (if the signature
  63. matched but the hash did not)
  64. * throws a SynapseError if the signature check failed.
  65. The deferreds run their callbacks in the sentinel
  66. """
  67. deferreds = _check_sigs_on_pdus(self.keyring, room_version, pdus)
  68. ctx = current_context()
  69. @defer.inlineCallbacks
  70. def callback(_, pdu: EventBase):
  71. with PreserveLoggingContext(ctx):
  72. if not check_event_content_hash(pdu):
  73. # let's try to distinguish between failures because the event was
  74. # redacted (which are somewhat expected) vs actual ball-tampering
  75. # incidents.
  76. #
  77. # This is just a heuristic, so we just assume that if the keys are
  78. # about the same between the redacted and received events, then the
  79. # received event was probably a redacted copy (but we then use our
  80. # *actual* redacted copy to be on the safe side.)
  81. redacted_event = prune_event(pdu)
  82. if set(redacted_event.keys()) == set(pdu.keys()) and set(
  83. redacted_event.content.keys()
  84. ) == set(pdu.content.keys()):
  85. logger.info(
  86. "Event %s seems to have been redacted; using our redacted "
  87. "copy",
  88. pdu.event_id,
  89. )
  90. else:
  91. logger.warning(
  92. "Event %s content has been tampered, redacting",
  93. pdu.event_id,
  94. )
  95. return redacted_event
  96. result = yield defer.ensureDeferred(
  97. self.spam_checker.check_event_for_spam(pdu)
  98. )
  99. if result:
  100. logger.warning(
  101. "Event contains spam, redacting %s: %s",
  102. pdu.event_id,
  103. pdu.get_pdu_json(),
  104. )
  105. return prune_event(pdu)
  106. return pdu
  107. def errback(failure: Failure, pdu: EventBase):
  108. failure.trap(SynapseError)
  109. with PreserveLoggingContext(ctx):
  110. logger.warning(
  111. "Signature check failed for %s: %s",
  112. pdu.event_id,
  113. failure.getErrorMessage(),
  114. )
  115. return failure
  116. for deferred, pdu in zip(deferreds, pdus):
  117. deferred.addCallbacks(
  118. callback, errback, callbackArgs=[pdu], errbackArgs=[pdu]
  119. )
  120. return deferreds
  121. class PduToCheckSig(
  122. namedtuple(
  123. "PduToCheckSig", ["pdu", "redacted_pdu_json", "sender_domain", "deferreds"]
  124. )
  125. ):
  126. pass
  127. def _check_sigs_on_pdus(
  128. keyring: Keyring, room_version: RoomVersion, pdus: Iterable[EventBase]
  129. ) -> List[Deferred]:
  130. """Check that the given events are correctly signed
  131. Args:
  132. keyring: keyring object to do the checks
  133. room_version: the room version of the PDUs
  134. pdus: the events to be checked
  135. Returns:
  136. A Deferred for each event in pdus, which will either succeed if
  137. the signatures are valid, or fail (with a SynapseError) if not.
  138. """
  139. # we want to check that the event is signed by:
  140. #
  141. # (a) the sender's server
  142. #
  143. # - except in the case of invites created from a 3pid invite, which are exempt
  144. # from this check, because the sender has to match that of the original 3pid
  145. # invite, but the event may come from a different HS, for reasons that I don't
  146. # entirely grok (why do the senders have to match? and if they do, why doesn't the
  147. # joining server ask the inviting server to do the switcheroo with
  148. # exchange_third_party_invite?).
  149. #
  150. # That's pretty awful, since redacting such an invite will render it invalid
  151. # (because it will then look like a regular invite without a valid signature),
  152. # and signatures are *supposed* to be valid whether or not an event has been
  153. # redacted. But this isn't the worst of the ways that 3pid invites are broken.
  154. #
  155. # (b) for V1 and V2 rooms, the server which created the event_id
  156. #
  157. # let's start by getting the domain for each pdu, and flattening the event back
  158. # to JSON.
  159. pdus_to_check = [
  160. PduToCheckSig(
  161. pdu=p,
  162. redacted_pdu_json=prune_event(p).get_pdu_json(),
  163. sender_domain=get_domain_from_id(p.sender),
  164. deferreds=[],
  165. )
  166. for p in pdus
  167. ]
  168. # First we check that the sender event is signed by the sender's domain
  169. # (except if its a 3pid invite, in which case it may be sent by any server)
  170. pdus_to_check_sender = [p for p in pdus_to_check if not _is_invite_via_3pid(p.pdu)]
  171. more_deferreds = keyring.verify_json_objects_for_server(
  172. [
  173. (
  174. p.sender_domain,
  175. p.redacted_pdu_json,
  176. p.pdu.origin_server_ts if room_version.enforce_key_validity else 0,
  177. p.pdu.event_id,
  178. )
  179. for p in pdus_to_check_sender
  180. ]
  181. )
  182. def sender_err(e, pdu_to_check):
  183. errmsg = "event id %s: unable to verify signature for sender %s: %s" % (
  184. pdu_to_check.pdu.event_id,
  185. pdu_to_check.sender_domain,
  186. e.getErrorMessage(),
  187. )
  188. raise SynapseError(403, errmsg, Codes.FORBIDDEN)
  189. for p, d in zip(pdus_to_check_sender, more_deferreds):
  190. d.addErrback(sender_err, p)
  191. p.deferreds.append(d)
  192. # now let's look for events where the sender's domain is different to the
  193. # event id's domain (normally only the case for joins/leaves), and add additional
  194. # checks. Only do this if the room version has a concept of event ID domain
  195. # (ie, the room version uses old-style non-hash event IDs).
  196. if room_version.event_format == EventFormatVersions.V1:
  197. pdus_to_check_event_id = [
  198. p
  199. for p in pdus_to_check
  200. if p.sender_domain != get_domain_from_id(p.pdu.event_id)
  201. ]
  202. more_deferreds = keyring.verify_json_objects_for_server(
  203. [
  204. (
  205. get_domain_from_id(p.pdu.event_id),
  206. p.redacted_pdu_json,
  207. p.pdu.origin_server_ts if room_version.enforce_key_validity else 0,
  208. p.pdu.event_id,
  209. )
  210. for p in pdus_to_check_event_id
  211. ]
  212. )
  213. def event_err(e, pdu_to_check):
  214. errmsg = (
  215. "event id %s: unable to verify signature for event id domain: %s"
  216. % (pdu_to_check.pdu.event_id, e.getErrorMessage())
  217. )
  218. raise SynapseError(403, errmsg, Codes.FORBIDDEN)
  219. for p, d in zip(pdus_to_check_event_id, more_deferreds):
  220. d.addErrback(event_err, p)
  221. p.deferreds.append(d)
  222. # replace lists of deferreds with single Deferreds
  223. return [_flatten_deferred_list(p.deferreds) for p in pdus_to_check]
  224. def _flatten_deferred_list(deferreds: List[Deferred]) -> Deferred:
  225. """Given a list of deferreds, either return the single deferred,
  226. combine into a DeferredList, or return an already resolved deferred.
  227. """
  228. if len(deferreds) > 1:
  229. return DeferredList(deferreds, fireOnOneErrback=True, consumeErrors=True)
  230. elif len(deferreds) == 1:
  231. return deferreds[0]
  232. else:
  233. return defer.succeed(None)
  234. def _is_invite_via_3pid(event: EventBase) -> bool:
  235. return (
  236. event.type == EventTypes.Member
  237. and event.membership == Membership.INVITE
  238. and "third_party_invite" in event.content
  239. )
  240. def event_from_pdu_json(
  241. pdu_json: JsonDict, room_version: RoomVersion, outlier: bool = False
  242. ) -> EventBase:
  243. """Construct an EventBase from an event json received over federation
  244. Args:
  245. pdu_json: pdu as received over federation
  246. room_version: The version of the room this event belongs to
  247. outlier: True to mark this event as an outlier
  248. Raises:
  249. SynapseError: if the pdu is missing required fields or is otherwise
  250. not a valid matrix event
  251. """
  252. # we could probably enforce a bunch of other fields here (room_id, sender,
  253. # origin, etc etc)
  254. assert_params_in_dict(pdu_json, ("type", "depth"))
  255. depth = pdu_json["depth"]
  256. if not isinstance(depth, int):
  257. raise SynapseError(400, "Depth %r not an intger" % (depth,), Codes.BAD_JSON)
  258. if depth < 0:
  259. raise SynapseError(400, "Depth too small", Codes.BAD_JSON)
  260. elif depth > MAX_DEPTH:
  261. raise SynapseError(400, "Depth too large", Codes.BAD_JSON)
  262. # Validate that the JSON conforms to the specification.
  263. if room_version.strict_canonicaljson:
  264. validate_canonicaljson(pdu_json)
  265. event = make_event_from_dict(pdu_json, room_version)
  266. event.internal_metadata.outlier = outlier
  267. return event