federation_base.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  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. import six
  17. from twisted.internet import defer
  18. from synapse.api.constants import MAX_DEPTH
  19. from synapse.api.errors import Codes, SynapseError
  20. from synapse.crypto.event_signing import check_event_content_hash
  21. from synapse.events import FrozenEvent
  22. from synapse.events.utils import prune_event
  23. from synapse.http.servlet import assert_params_in_dict
  24. from synapse.util import logcontext, unwrapFirstError
  25. logger = logging.getLogger(__name__)
  26. class FederationBase(object):
  27. def __init__(self, hs):
  28. self.hs = hs
  29. self.server_name = hs.hostname
  30. self.keyring = hs.get_keyring()
  31. self.spam_checker = hs.get_spam_checker()
  32. self.store = hs.get_datastore()
  33. self._clock = hs.get_clock()
  34. @defer.inlineCallbacks
  35. def _check_sigs_and_hash_and_fetch(self, origin, pdus, outlier=False,
  36. include_none=False):
  37. """Takes a list of PDUs and checks the signatures and hashs of each
  38. one. If a PDU fails its signature check then we check if we have it in
  39. the database and if not then request if from the originating server of
  40. that PDU.
  41. If a PDU fails its content hash check then it is redacted.
  42. The given list of PDUs are not modified, instead the function returns
  43. a new list.
  44. Args:
  45. pdu (list)
  46. outlier (bool)
  47. Returns:
  48. Deferred : A list of PDUs that have valid signatures and hashes.
  49. """
  50. deferreds = self._check_sigs_and_hashes(pdus)
  51. @defer.inlineCallbacks
  52. def handle_check_result(pdu, deferred):
  53. try:
  54. res = yield logcontext.make_deferred_yieldable(deferred)
  55. except SynapseError:
  56. res = None
  57. if not res:
  58. # Check local db.
  59. res = yield self.store.get_event(
  60. pdu.event_id,
  61. allow_rejected=True,
  62. allow_none=True,
  63. )
  64. if not res and pdu.origin != origin:
  65. try:
  66. res = yield self.get_pdu(
  67. destinations=[pdu.origin],
  68. event_id=pdu.event_id,
  69. outlier=outlier,
  70. timeout=10000,
  71. )
  72. except SynapseError:
  73. pass
  74. if not res:
  75. logger.warn(
  76. "Failed to find copy of %s with valid signature",
  77. pdu.event_id,
  78. )
  79. defer.returnValue(res)
  80. handle = logcontext.preserve_fn(handle_check_result)
  81. deferreds2 = [
  82. handle(pdu, deferred)
  83. for pdu, deferred in zip(pdus, deferreds)
  84. ]
  85. valid_pdus = yield logcontext.make_deferred_yieldable(
  86. defer.gatherResults(
  87. deferreds2,
  88. consumeErrors=True,
  89. )
  90. ).addErrback(unwrapFirstError)
  91. if include_none:
  92. defer.returnValue(valid_pdus)
  93. else:
  94. defer.returnValue([p for p in valid_pdus if p])
  95. def _check_sigs_and_hash(self, pdu):
  96. return logcontext.make_deferred_yieldable(
  97. self._check_sigs_and_hashes([pdu])[0],
  98. )
  99. def _check_sigs_and_hashes(self, pdus):
  100. """Checks that each of the received events is correctly signed by the
  101. sending server.
  102. Args:
  103. pdus (list[FrozenEvent]): the events to be checked
  104. Returns:
  105. list[Deferred]: for each input event, a deferred which:
  106. * returns the original event if the checks pass
  107. * returns a redacted version of the event (if the signature
  108. matched but the hash did not)
  109. * throws a SynapseError if the signature check failed.
  110. The deferreds run their callbacks in the sentinel logcontext.
  111. """
  112. redacted_pdus = [
  113. prune_event(pdu)
  114. for pdu in pdus
  115. ]
  116. deferreds = self.keyring.verify_json_objects_for_server([
  117. (p.origin, p.get_pdu_json())
  118. for p in redacted_pdus
  119. ])
  120. ctx = logcontext.LoggingContext.current_context()
  121. def callback(_, pdu, redacted):
  122. with logcontext.PreserveLoggingContext(ctx):
  123. if not check_event_content_hash(pdu):
  124. logger.warn(
  125. "Event content has been tampered, redacting %s: %s",
  126. pdu.event_id, pdu.get_pdu_json()
  127. )
  128. return redacted
  129. if self.spam_checker.check_event_for_spam(pdu):
  130. logger.warn(
  131. "Event contains spam, redacting %s: %s",
  132. pdu.event_id, pdu.get_pdu_json()
  133. )
  134. return redacted
  135. return pdu
  136. def errback(failure, pdu):
  137. failure.trap(SynapseError)
  138. with logcontext.PreserveLoggingContext(ctx):
  139. logger.warn(
  140. "Signature check failed for %s",
  141. pdu.event_id,
  142. )
  143. return failure
  144. for deferred, pdu, redacted in zip(deferreds, pdus, redacted_pdus):
  145. deferred.addCallbacks(
  146. callback, errback,
  147. callbackArgs=[pdu, redacted],
  148. errbackArgs=[pdu],
  149. )
  150. return deferreds
  151. def event_from_pdu_json(pdu_json, outlier=False):
  152. """Construct a FrozenEvent from an event json received over federation
  153. Args:
  154. pdu_json (object): pdu as received over federation
  155. outlier (bool): True to mark this event as an outlier
  156. Returns:
  157. FrozenEvent
  158. Raises:
  159. SynapseError: if the pdu is missing required fields or is otherwise
  160. not a valid matrix event
  161. """
  162. # we could probably enforce a bunch of other fields here (room_id, sender,
  163. # origin, etc etc)
  164. assert_params_in_dict(pdu_json, ('event_id', 'type', 'depth'))
  165. depth = pdu_json['depth']
  166. if not isinstance(depth, six.integer_types):
  167. raise SynapseError(400, "Depth %r not an intger" % (depth, ),
  168. Codes.BAD_JSON)
  169. if depth < 0:
  170. raise SynapseError(400, "Depth too small", Codes.BAD_JSON)
  171. elif depth > MAX_DEPTH:
  172. raise SynapseError(400, "Depth too large", Codes.BAD_JSON)
  173. event = FrozenEvent(
  174. pdu_json
  175. )
  176. event.internal_metadata.outlier = outlier
  177. return event