federation_base.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 typing import TYPE_CHECKING
  17. from synapse.api.constants import MAX_DEPTH, EventContentFields, EventTypes, Membership
  18. from synapse.api.errors import Codes, SynapseError
  19. from synapse.api.room_versions import EventFormatVersions, RoomVersion
  20. from synapse.crypto.event_signing import check_event_content_hash
  21. from synapse.crypto.keyring import Keyring
  22. from synapse.events import EventBase, make_event_from_dict
  23. from synapse.events.utils import prune_event, validate_canonicaljson
  24. from synapse.http.servlet import assert_params_in_dict
  25. from synapse.types import JsonDict, get_domain_from_id
  26. if TYPE_CHECKING:
  27. from synapse.server import HomeServer
  28. logger = logging.getLogger(__name__)
  29. class FederationBase:
  30. def __init__(self, hs: "HomeServer"):
  31. self.hs = hs
  32. self.server_name = hs.hostname
  33. self.keyring = hs.get_keyring()
  34. self.spam_checker = hs.get_spam_checker()
  35. self.store = hs.get_datastore()
  36. self._clock = hs.get_clock()
  37. async def _check_sigs_and_hash(
  38. self, room_version: RoomVersion, pdu: EventBase
  39. ) -> EventBase:
  40. """Checks that event is correctly signed by the sending server.
  41. Args:
  42. room_version: The room version of the PDU
  43. pdu: the event to be checked
  44. Returns:
  45. * the original event if the checks pass
  46. * a redacted version of the event (if the signature
  47. matched but the hash did not)
  48. * throws a SynapseError if the signature check failed."""
  49. try:
  50. await _check_sigs_on_pdu(self.keyring, room_version, pdu)
  51. except SynapseError as e:
  52. logger.warning(
  53. "Signature check failed for %s: %s",
  54. pdu.event_id,
  55. e,
  56. )
  57. raise
  58. if not check_event_content_hash(pdu):
  59. # let's try to distinguish between failures because the event was
  60. # redacted (which are somewhat expected) vs actual ball-tampering
  61. # incidents.
  62. #
  63. # This is just a heuristic, so we just assume that if the keys are
  64. # about the same between the redacted and received events, then the
  65. # received event was probably a redacted copy (but we then use our
  66. # *actual* redacted copy to be on the safe side.)
  67. redacted_event = prune_event(pdu)
  68. if set(redacted_event.keys()) == set(pdu.keys()) and set(
  69. redacted_event.content.keys()
  70. ) == set(pdu.content.keys()):
  71. logger.info(
  72. "Event %s seems to have been redacted; using our redacted copy",
  73. pdu.event_id,
  74. )
  75. else:
  76. logger.warning(
  77. "Event %s content has been tampered, redacting",
  78. pdu.event_id,
  79. )
  80. return redacted_event
  81. result = await self.spam_checker.check_event_for_spam(pdu)
  82. if result:
  83. logger.warning("Event contains spam, soft-failing %s", pdu.event_id)
  84. # we redact (to save disk space) as well as soft-failing (to stop
  85. # using the event in prev_events).
  86. redacted_event = prune_event(pdu)
  87. redacted_event.internal_metadata.soft_failed = True
  88. return redacted_event
  89. return pdu
  90. async def _check_sigs_on_pdu(
  91. keyring: Keyring, room_version: RoomVersion, pdu: EventBase
  92. ) -> None:
  93. """Check that the given events are correctly signed
  94. Raise a SynapseError if the event wasn't correctly signed.
  95. Args:
  96. keyring: keyring object to do the checks
  97. room_version: the room version of the PDUs
  98. pdus: the events to be checked
  99. """
  100. # we want to check that the event is signed by:
  101. #
  102. # (a) the sender's server
  103. #
  104. # - except in the case of invites created from a 3pid invite, which are exempt
  105. # from this check, because the sender has to match that of the original 3pid
  106. # invite, but the event may come from a different HS, for reasons that I don't
  107. # entirely grok (why do the senders have to match? and if they do, why doesn't the
  108. # joining server ask the inviting server to do the switcheroo with
  109. # exchange_third_party_invite?).
  110. #
  111. # That's pretty awful, since redacting such an invite will render it invalid
  112. # (because it will then look like a regular invite without a valid signature),
  113. # and signatures are *supposed* to be valid whether or not an event has been
  114. # redacted. But this isn't the worst of the ways that 3pid invites are broken.
  115. #
  116. # (b) for V1 and V2 rooms, the server which created the event_id
  117. #
  118. # let's start by getting the domain for each pdu, and flattening the event back
  119. # to JSON.
  120. # First we check that the sender event is signed by the sender's domain
  121. # (except if its a 3pid invite, in which case it may be sent by any server)
  122. if not _is_invite_via_3pid(pdu):
  123. try:
  124. await keyring.verify_event_for_server(
  125. get_domain_from_id(pdu.sender),
  126. pdu,
  127. pdu.origin_server_ts if room_version.enforce_key_validity else 0,
  128. )
  129. except Exception as e:
  130. errmsg = "event id %s: unable to verify signature for sender %s: %s" % (
  131. pdu.event_id,
  132. get_domain_from_id(pdu.sender),
  133. e,
  134. )
  135. raise SynapseError(403, errmsg, Codes.FORBIDDEN)
  136. # now let's look for events where the sender's domain is different to the
  137. # event id's domain (normally only the case for joins/leaves), and add additional
  138. # checks. Only do this if the room version has a concept of event ID domain
  139. # (ie, the room version uses old-style non-hash event IDs).
  140. if room_version.event_format == EventFormatVersions.V1 and get_domain_from_id(
  141. pdu.event_id
  142. ) != get_domain_from_id(pdu.sender):
  143. try:
  144. await keyring.verify_event_for_server(
  145. get_domain_from_id(pdu.event_id),
  146. pdu,
  147. pdu.origin_server_ts if room_version.enforce_key_validity else 0,
  148. )
  149. except Exception as e:
  150. errmsg = (
  151. "event id %s: unable to verify signature for event id domain %s: %s"
  152. % (
  153. pdu.event_id,
  154. get_domain_from_id(pdu.event_id),
  155. e,
  156. )
  157. )
  158. raise SynapseError(403, errmsg, Codes.FORBIDDEN)
  159. # If this is a join event for a restricted room it may have been authorised
  160. # via a different server from the sending server. Check those signatures.
  161. if (
  162. room_version.msc3083_join_rules
  163. and pdu.type == EventTypes.Member
  164. and pdu.membership == Membership.JOIN
  165. and EventContentFields.AUTHORISING_USER in pdu.content
  166. ):
  167. authorising_server = get_domain_from_id(
  168. pdu.content[EventContentFields.AUTHORISING_USER]
  169. )
  170. try:
  171. await keyring.verify_event_for_server(
  172. authorising_server,
  173. pdu,
  174. pdu.origin_server_ts if room_version.enforce_key_validity else 0,
  175. )
  176. except Exception as e:
  177. errmsg = (
  178. "event id %s: unable to verify signature for authorising server %s: %s"
  179. % (
  180. pdu.event_id,
  181. authorising_server,
  182. e,
  183. )
  184. )
  185. raise SynapseError(403, errmsg, Codes.FORBIDDEN)
  186. def _is_invite_via_3pid(event: EventBase) -> bool:
  187. return (
  188. event.type == EventTypes.Member
  189. and event.membership == Membership.INVITE
  190. and "third_party_invite" in event.content
  191. )
  192. def event_from_pdu_json(pdu_json: JsonDict, room_version: RoomVersion) -> EventBase:
  193. """Construct an EventBase from an event json received over federation
  194. Args:
  195. pdu_json: pdu as received over federation
  196. room_version: The version of the room this event belongs to
  197. Raises:
  198. SynapseError: if the pdu is missing required fields or is otherwise
  199. not a valid matrix event
  200. """
  201. # we could probably enforce a bunch of other fields here (room_id, sender,
  202. # origin, etc etc)
  203. assert_params_in_dict(pdu_json, ("type", "depth"))
  204. depth = pdu_json["depth"]
  205. if not isinstance(depth, int):
  206. raise SynapseError(400, "Depth %r not an intger" % (depth,), Codes.BAD_JSON)
  207. if depth < 0:
  208. raise SynapseError(400, "Depth too small", Codes.BAD_JSON)
  209. elif depth > MAX_DEPTH:
  210. raise SynapseError(400, "Depth too large", Codes.BAD_JSON)
  211. # Validate that the JSON conforms to the specification.
  212. if room_version.strict_canonicaljson:
  213. validate_canonicaljson(pdu_json)
  214. event = make_event_from_dict(pdu_json, room_version)
  215. return event