attestations.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 Vector Creations 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. """Attestations ensure that users and groups can't lie about their memberships.
  16. When a user joins a group the HS and GS swap attestations, which allow them
  17. both to independently prove to third parties their membership.These
  18. attestations have a validity period so need to be periodically renewed.
  19. If a user leaves (or gets kicked out of) a group, either side can still use
  20. their attestation to "prove" their membership, until the attestation expires.
  21. Therefore attestations shouldn't be relied on to prove membership in important
  22. cases, but can for less important situtations, e.g. showing a users membership
  23. of groups on their profile, showing flairs, etc.
  24. An attestation is a signed blob of json that looks like:
  25. {
  26. "user_id": "@foo:a.example.com",
  27. "group_id": "+bar:b.example.com",
  28. "valid_until_ms": 1507994728530,
  29. "signatures":{"matrix.org":{"ed25519:auto":"..."}}
  30. }
  31. """
  32. import logging
  33. import random
  34. from typing import Tuple
  35. from signedjson.sign import sign_json
  36. from twisted.internet import defer
  37. from synapse.api.errors import HttpResponseException, RequestSendFailed, SynapseError
  38. from synapse.metrics.background_process_metrics import run_as_background_process
  39. from synapse.types import get_domain_from_id
  40. logger = logging.getLogger(__name__)
  41. # Default validity duration for new attestations we create
  42. DEFAULT_ATTESTATION_LENGTH_MS = 3 * 24 * 60 * 60 * 1000
  43. # We add some jitter to the validity duration of attestations so that if we
  44. # add lots of users at once we don't need to renew them all at once.
  45. # The jitter is a multiplier picked randomly between the first and second number
  46. DEFAULT_ATTESTATION_JITTER = (0.9, 1.3)
  47. # Start trying to update our attestations when they come this close to expiring
  48. UPDATE_ATTESTATION_TIME_MS = 1 * 24 * 60 * 60 * 1000
  49. class GroupAttestationSigning(object):
  50. """Creates and verifies group attestations.
  51. """
  52. def __init__(self, hs):
  53. self.keyring = hs.get_keyring()
  54. self.clock = hs.get_clock()
  55. self.server_name = hs.hostname
  56. self.signing_key = hs.signing_key
  57. @defer.inlineCallbacks
  58. def verify_attestation(self, attestation, group_id, user_id, server_name=None):
  59. """Verifies that the given attestation matches the given parameters.
  60. An optional server_name can be supplied to explicitly set which server's
  61. signature is expected. Otherwise assumes that either the group_id or user_id
  62. is local and uses the other's server as the one to check.
  63. """
  64. if not server_name:
  65. if get_domain_from_id(group_id) == self.server_name:
  66. server_name = get_domain_from_id(user_id)
  67. elif get_domain_from_id(user_id) == self.server_name:
  68. server_name = get_domain_from_id(group_id)
  69. else:
  70. raise Exception("Expected either group_id or user_id to be local")
  71. if user_id != attestation["user_id"]:
  72. raise SynapseError(400, "Attestation has incorrect user_id")
  73. if group_id != attestation["group_id"]:
  74. raise SynapseError(400, "Attestation has incorrect group_id")
  75. valid_until_ms = attestation["valid_until_ms"]
  76. # TODO: We also want to check that *new* attestations that people give
  77. # us to store are valid for at least a little while.
  78. now = self.clock.time_msec()
  79. if valid_until_ms < now:
  80. raise SynapseError(400, "Attestation expired")
  81. yield self.keyring.verify_json_for_server(
  82. server_name, attestation, now, "Group attestation"
  83. )
  84. def create_attestation(self, group_id, user_id):
  85. """Create an attestation for the group_id and user_id with default
  86. validity length.
  87. """
  88. validity_period = DEFAULT_ATTESTATION_LENGTH_MS
  89. validity_period *= random.uniform(*DEFAULT_ATTESTATION_JITTER)
  90. valid_until_ms = int(self.clock.time_msec() + validity_period)
  91. return sign_json(
  92. {
  93. "group_id": group_id,
  94. "user_id": user_id,
  95. "valid_until_ms": valid_until_ms,
  96. },
  97. self.server_name,
  98. self.signing_key,
  99. )
  100. class GroupAttestionRenewer(object):
  101. """Responsible for sending and receiving attestation updates.
  102. """
  103. def __init__(self, hs):
  104. self.clock = hs.get_clock()
  105. self.store = hs.get_datastore()
  106. self.assestations = hs.get_groups_attestation_signing()
  107. self.transport_client = hs.get_federation_transport_client()
  108. self.is_mine_id = hs.is_mine_id
  109. self.attestations = hs.get_groups_attestation_signing()
  110. if not hs.config.worker_app:
  111. self._renew_attestations_loop = self.clock.looping_call(
  112. self._start_renew_attestations, 30 * 60 * 1000
  113. )
  114. @defer.inlineCallbacks
  115. def on_renew_attestation(self, group_id, user_id, content):
  116. """When a remote updates an attestation
  117. """
  118. attestation = content["attestation"]
  119. if not self.is_mine_id(group_id) and not self.is_mine_id(user_id):
  120. raise SynapseError(400, "Neither user not group are on this server")
  121. yield self.attestations.verify_attestation(
  122. attestation, user_id=user_id, group_id=group_id
  123. )
  124. yield self.store.update_remote_attestion(group_id, user_id, attestation)
  125. return {}
  126. def _start_renew_attestations(self):
  127. return run_as_background_process("renew_attestations", self._renew_attestations)
  128. async def _renew_attestations(self):
  129. """Called periodically to check if we need to update any of our attestations
  130. """
  131. now = self.clock.time_msec()
  132. rows = await self.store.get_attestations_need_renewals(
  133. now + UPDATE_ATTESTATION_TIME_MS
  134. )
  135. @defer.inlineCallbacks
  136. def _renew_attestation(group_user: Tuple[str, str]):
  137. group_id, user_id = group_user
  138. try:
  139. if not self.is_mine_id(group_id):
  140. destination = get_domain_from_id(group_id)
  141. elif not self.is_mine_id(user_id):
  142. destination = get_domain_from_id(user_id)
  143. else:
  144. logger.warning(
  145. "Incorrectly trying to do attestations for user: %r in %r",
  146. user_id,
  147. group_id,
  148. )
  149. yield self.store.remove_attestation_renewal(group_id, user_id)
  150. return
  151. attestation = self.attestations.create_attestation(group_id, user_id)
  152. yield self.transport_client.renew_group_attestation(
  153. destination, group_id, user_id, content={"attestation": attestation}
  154. )
  155. yield self.store.update_attestation_renewal(
  156. group_id, user_id, attestation
  157. )
  158. except (RequestSendFailed, HttpResponseException) as e:
  159. logger.warning(
  160. "Failed to renew attestation of %r in %r: %s", user_id, group_id, e
  161. )
  162. except Exception:
  163. logger.exception(
  164. "Error renewing attestation of %r in %r", user_id, group_id
  165. )
  166. for row in rows:
  167. await _renew_attestation((row["group_id"], row["user_id"]))