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.
 
 
 
 
 
 

315 lines
12 KiB

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