federation_base.py 6.5 KB

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