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.
 
 
 
 
 
 

281 line
10 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 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_datastores().main
  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. Also checks the content hash, and redacts the event if there is a mismatch.
  42. Also runs the event through the spam checker; if it fails, redacts the event
  43. and flags it as soft-failed.
  44. Args:
  45. room_version: The room version of the PDU
  46. pdu: the event to be checked
  47. Returns:
  48. * the original event if the checks pass
  49. * a redacted version of the event (if the signature
  50. matched but the hash did not)
  51. Raises:
  52. SynapseError if the signature check failed.
  53. """
  54. try:
  55. await _check_sigs_on_pdu(self.keyring, room_version, pdu)
  56. except SynapseError as e:
  57. logger.warning(
  58. "Signature check failed for %s: %s",
  59. pdu.event_id,
  60. e,
  61. )
  62. raise
  63. if not check_event_content_hash(pdu):
  64. # let's try to distinguish between failures because the event was
  65. # redacted (which are somewhat expected) vs actual ball-tampering
  66. # incidents.
  67. #
  68. # This is just a heuristic, so we just assume that if the keys are
  69. # about the same between the redacted and received events, then the
  70. # received event was probably a redacted copy (but we then use our
  71. # *actual* redacted copy to be on the safe side.)
  72. redacted_event = prune_event(pdu)
  73. if set(redacted_event.keys()) == set(pdu.keys()) and set(
  74. redacted_event.content.keys()
  75. ) == set(pdu.content.keys()):
  76. logger.info(
  77. "Event %s seems to have been redacted; using our redacted copy",
  78. pdu.event_id,
  79. )
  80. else:
  81. logger.warning(
  82. "Event %s content has been tampered, redacting",
  83. pdu.event_id,
  84. )
  85. return redacted_event
  86. spam_check = await self.spam_checker.check_event_for_spam(pdu)
  87. if spam_check != self.spam_checker.NOT_SPAM:
  88. logger.warning("Event contains spam, soft-failing %s", pdu.event_id)
  89. # we redact (to save disk space) as well as soft-failing (to stop
  90. # using the event in prev_events).
  91. redacted_event = prune_event(pdu)
  92. redacted_event.internal_metadata.soft_failed = True
  93. return redacted_event
  94. return pdu
  95. async def _check_sigs_on_pdu(
  96. keyring: Keyring, room_version: RoomVersion, pdu: EventBase
  97. ) -> None:
  98. """Check that the given events are correctly signed
  99. Raise a SynapseError if the event wasn't correctly signed.
  100. Args:
  101. keyring: keyring object to do the checks
  102. room_version: the room version of the PDUs
  103. pdus: the events to be checked
  104. """
  105. # we want to check that the event is signed by:
  106. #
  107. # (a) the sender's server
  108. #
  109. # - except in the case of invites created from a 3pid invite, which are exempt
  110. # from this check, because the sender has to match that of the original 3pid
  111. # invite, but the event may come from a different HS, for reasons that I don't
  112. # entirely grok (why do the senders have to match? and if they do, why doesn't the
  113. # joining server ask the inviting server to do the switcheroo with
  114. # exchange_third_party_invite?).
  115. #
  116. # That's pretty awful, since redacting such an invite will render it invalid
  117. # (because it will then look like a regular invite without a valid signature),
  118. # and signatures are *supposed* to be valid whether or not an event has been
  119. # redacted. But this isn't the worst of the ways that 3pid invites are broken.
  120. #
  121. # (b) for V1 and V2 rooms, the server which created the event_id
  122. #
  123. # let's start by getting the domain for each pdu, and flattening the event back
  124. # to JSON.
  125. # First we check that the sender event is signed by the sender's domain
  126. # (except if its a 3pid invite, in which case it may be sent by any server)
  127. if not _is_invite_via_3pid(pdu):
  128. try:
  129. await keyring.verify_event_for_server(
  130. get_domain_from_id(pdu.sender),
  131. pdu,
  132. pdu.origin_server_ts if room_version.enforce_key_validity else 0,
  133. )
  134. except Exception as e:
  135. errmsg = "event id %s: unable to verify signature for sender %s: %s" % (
  136. pdu.event_id,
  137. get_domain_from_id(pdu.sender),
  138. e,
  139. )
  140. raise SynapseError(403, errmsg, Codes.FORBIDDEN)
  141. # now let's look for events where the sender's domain is different to the
  142. # event id's domain (normally only the case for joins/leaves), and add additional
  143. # checks. Only do this if the room version has a concept of event ID domain
  144. # (ie, the room version uses old-style non-hash event IDs).
  145. if room_version.event_format == EventFormatVersions.V1 and get_domain_from_id(
  146. pdu.event_id
  147. ) != get_domain_from_id(pdu.sender):
  148. try:
  149. await keyring.verify_event_for_server(
  150. get_domain_from_id(pdu.event_id),
  151. pdu,
  152. pdu.origin_server_ts if room_version.enforce_key_validity else 0,
  153. )
  154. except Exception as e:
  155. errmsg = (
  156. "event id %s: unable to verify signature for event id domain %s: %s"
  157. % (
  158. pdu.event_id,
  159. get_domain_from_id(pdu.event_id),
  160. e,
  161. )
  162. )
  163. raise SynapseError(403, errmsg, Codes.FORBIDDEN)
  164. # If this is a join event for a restricted room it may have been authorised
  165. # via a different server from the sending server. Check those signatures.
  166. if (
  167. room_version.msc3083_join_rules
  168. and pdu.type == EventTypes.Member
  169. and pdu.membership == Membership.JOIN
  170. and EventContentFields.AUTHORISING_USER in pdu.content
  171. ):
  172. authorising_server = get_domain_from_id(
  173. pdu.content[EventContentFields.AUTHORISING_USER]
  174. )
  175. try:
  176. await keyring.verify_event_for_server(
  177. authorising_server,
  178. pdu,
  179. pdu.origin_server_ts if room_version.enforce_key_validity else 0,
  180. )
  181. except Exception as e:
  182. errmsg = (
  183. "event id %s: unable to verify signature for authorising server %s: %s"
  184. % (
  185. pdu.event_id,
  186. authorising_server,
  187. e,
  188. )
  189. )
  190. raise SynapseError(403, errmsg, Codes.FORBIDDEN)
  191. def _is_invite_via_3pid(event: EventBase) -> bool:
  192. return (
  193. event.type == EventTypes.Member
  194. and event.membership == Membership.INVITE
  195. and "third_party_invite" in event.content
  196. )
  197. def event_from_pdu_json(pdu_json: JsonDict, room_version: RoomVersion) -> EventBase:
  198. """Construct an EventBase from an event json received over federation
  199. Args:
  200. pdu_json: pdu as received over federation
  201. room_version: The version of the room this event belongs to
  202. Raises:
  203. SynapseError: if the pdu is missing required fields or is otherwise
  204. not a valid matrix event
  205. """
  206. # we could probably enforce a bunch of other fields here (room_id, sender,
  207. # origin, etc etc)
  208. assert_params_in_dict(pdu_json, ("type", "depth"))
  209. # Strip any unauthorized values from "unsigned" if they exist
  210. if "unsigned" in pdu_json:
  211. _strip_unsigned_values(pdu_json)
  212. depth = pdu_json["depth"]
  213. if not isinstance(depth, int):
  214. raise SynapseError(400, "Depth %r not an intger" % (depth,), Codes.BAD_JSON)
  215. if depth < 0:
  216. raise SynapseError(400, "Depth too small", Codes.BAD_JSON)
  217. elif depth > MAX_DEPTH:
  218. raise SynapseError(400, "Depth too large", Codes.BAD_JSON)
  219. # Validate that the JSON conforms to the specification.
  220. if room_version.strict_canonicaljson:
  221. validate_canonicaljson(pdu_json)
  222. event = make_event_from_dict(pdu_json, room_version)
  223. return event
  224. def _strip_unsigned_values(pdu_dict: JsonDict) -> None:
  225. """
  226. Strip any unsigned values unless specifically allowed, as defined by the whitelist.
  227. pdu: the json dict to strip values from. Note that the dict is mutated by this
  228. function
  229. """
  230. unsigned = pdu_dict["unsigned"]
  231. if not isinstance(unsigned, dict):
  232. pdu_dict["unsigned"] = {}
  233. if pdu_dict["type"] == "m.room.member":
  234. whitelist = ["knock_room_state", "invite_room_state", "age"]
  235. else:
  236. whitelist = ["age"]
  237. filtered_unsigned = {k: v for k, v in unsigned.items() if k in whitelist}
  238. pdu_dict["unsigned"] = filtered_unsigned