1
0

federation_base.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. from twisted.internet import defer
  16. from synapse.events.utils import prune_event
  17. from synapse.crypto.event_signing import check_event_content_hash
  18. from synapse.api.errors import SynapseError
  19. from synapse.util import unwrapFirstError
  20. import logging
  21. logger = logging.getLogger(__name__)
  22. class FederationBase(object):
  23. @defer.inlineCallbacks
  24. def _check_sigs_and_hash_and_fetch(self, origin, pdus, outlier=False,
  25. include_none=False):
  26. """Takes a list of PDUs and checks the signatures and hashs of each
  27. one. If a PDU fails its signature check then we check if we have it in
  28. the database and if not then request if from the originating server of
  29. that PDU.
  30. If a PDU fails its content hash check then it is redacted.
  31. The given list of PDUs are not modified, instead the function returns
  32. a new list.
  33. Args:
  34. pdu (list)
  35. outlier (bool)
  36. Returns:
  37. Deferred : A list of PDUs that have valid signatures and hashes.
  38. """
  39. deferreds = self._check_sigs_and_hashes(pdus)
  40. def callback(pdu):
  41. return pdu
  42. def errback(failure, pdu):
  43. failure.trap(SynapseError)
  44. return None
  45. def try_local_db(res, pdu):
  46. if not res:
  47. # Check local db.
  48. return self.store.get_event(
  49. pdu.event_id,
  50. allow_rejected=True,
  51. allow_none=True,
  52. )
  53. return res
  54. def try_remote(res, pdu):
  55. if not res and pdu.origin != origin:
  56. return self.get_pdu(
  57. destinations=[pdu.origin],
  58. event_id=pdu.event_id,
  59. outlier=outlier,
  60. timeout=10000,
  61. ).addErrback(lambda e: None)
  62. return res
  63. def warn(res, pdu):
  64. if not res:
  65. logger.warn(
  66. "Failed to find copy of %s with valid signature",
  67. pdu.event_id,
  68. )
  69. return res
  70. for pdu, deferred in zip(pdus, deferreds):
  71. deferred.addCallbacks(
  72. callback, errback, errbackArgs=[pdu]
  73. ).addCallback(
  74. try_local_db, pdu
  75. ).addCallback(
  76. try_remote, pdu
  77. ).addCallback(
  78. warn, pdu
  79. )
  80. valid_pdus = yield defer.gatherResults(
  81. deferreds,
  82. consumeErrors=True
  83. ).addErrback(unwrapFirstError)
  84. if include_none:
  85. defer.returnValue(valid_pdus)
  86. else:
  87. defer.returnValue([p for p in valid_pdus if p])
  88. def _check_sigs_and_hash(self, pdu):
  89. return self._check_sigs_and_hashes([pdu])[0]
  90. def _check_sigs_and_hashes(self, pdus):
  91. """Throws a SynapseError if a PDU does not have the correct
  92. signatures.
  93. Returns:
  94. FrozenEvent: Either the given event or it redacted if it failed the
  95. content hash check.
  96. """
  97. redacted_pdus = [
  98. prune_event(pdu)
  99. for pdu in pdus
  100. ]
  101. deferreds = self.keyring.verify_json_objects_for_server([
  102. (p.origin, p.get_pdu_json())
  103. for p in redacted_pdus
  104. ])
  105. def callback(_, pdu, redacted):
  106. if not check_event_content_hash(pdu):
  107. logger.warn(
  108. "Event content has been tampered, redacting %s: %s",
  109. pdu.event_id, pdu.get_pdu_json()
  110. )
  111. return redacted
  112. return pdu
  113. def errback(failure, pdu):
  114. failure.trap(SynapseError)
  115. logger.warn(
  116. "Signature check failed for %s",
  117. pdu.event_id,
  118. )
  119. return failure
  120. for deferred, pdu, redacted in zip(deferreds, pdus, redacted_pdus):
  121. deferred.addCallbacks(
  122. callback, errback,
  123. callbackArgs=[pdu, redacted],
  124. errbackArgs=[pdu],
  125. )
  126. return deferreds