federation_base.py 11 KB

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