attestations.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. # Copyright 2017 Vector Creations Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Attestations ensure that users and groups can't lie about their memberships.
  15. When a user joins a group the HS and GS swap attestations, which allow them
  16. both to independently prove to third parties their membership.These
  17. attestations have a validity period so need to be periodically renewed.
  18. If a user leaves (or gets kicked out of) a group, either side can still use
  19. their attestation to "prove" their membership, until the attestation expires.
  20. Therefore attestations shouldn't be relied on to prove membership in important
  21. cases, but can for less important situations, e.g. showing a users membership
  22. of groups on their profile, showing flairs, etc.
  23. An attestation is a signed blob of json that looks like:
  24. {
  25. "user_id": "@foo:a.example.com",
  26. "group_id": "+bar:b.example.com",
  27. "valid_until_ms": 1507994728530,
  28. "signatures":{"matrix.org":{"ed25519:auto":"..."}}
  29. }
  30. """
  31. import logging
  32. import random
  33. from typing import TYPE_CHECKING, Optional, Tuple
  34. from signedjson.sign import sign_json
  35. from synapse.api.errors import HttpResponseException, RequestSendFailed, SynapseError
  36. from synapse.metrics.background_process_metrics import run_as_background_process
  37. from synapse.types import JsonDict, get_domain_from_id
  38. if TYPE_CHECKING:
  39. from synapse.server import HomeServer
  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:
  50. """Creates and verifies group attestations."""
  51. def __init__(self, hs: "HomeServer"):
  52. self.keyring = hs.get_keyring()
  53. self.clock = hs.get_clock()
  54. self.server_name = hs.hostname
  55. self.signing_key = hs.signing_key
  56. async def verify_attestation(
  57. self,
  58. attestation: JsonDict,
  59. group_id: str,
  60. user_id: str,
  61. server_name: Optional[str] = None,
  62. ) -> None:
  63. """Verifies that the given attestation matches the given parameters.
  64. An optional server_name can be supplied to explicitly set which server's
  65. signature is expected. Otherwise assumes that either the group_id or user_id
  66. is local and uses the other's server as the one to check.
  67. """
  68. if not server_name:
  69. if get_domain_from_id(group_id) == self.server_name:
  70. server_name = get_domain_from_id(user_id)
  71. elif get_domain_from_id(user_id) == self.server_name:
  72. server_name = get_domain_from_id(group_id)
  73. else:
  74. raise Exception("Expected either group_id or user_id to be local")
  75. if user_id != attestation["user_id"]:
  76. raise SynapseError(400, "Attestation has incorrect user_id")
  77. if group_id != attestation["group_id"]:
  78. raise SynapseError(400, "Attestation has incorrect group_id")
  79. valid_until_ms = attestation["valid_until_ms"]
  80. # TODO: We also want to check that *new* attestations that people give
  81. # us to store are valid for at least a little while.
  82. now = self.clock.time_msec()
  83. if valid_until_ms < now:
  84. raise SynapseError(400, "Attestation expired")
  85. assert server_name is not None
  86. await self.keyring.verify_json_for_server(
  87. server_name, attestation, now, "Group attestation"
  88. )
  89. def create_attestation(self, group_id: str, user_id: str) -> JsonDict:
  90. """Create an attestation for the group_id and user_id with default
  91. validity length.
  92. """
  93. validity_period = DEFAULT_ATTESTATION_LENGTH_MS * random.uniform(
  94. *DEFAULT_ATTESTATION_JITTER
  95. )
  96. valid_until_ms = int(self.clock.time_msec() + validity_period)
  97. return sign_json(
  98. {
  99. "group_id": group_id,
  100. "user_id": user_id,
  101. "valid_until_ms": valid_until_ms,
  102. },
  103. self.server_name,
  104. self.signing_key,
  105. )
  106. class GroupAttestionRenewer:
  107. """Responsible for sending and receiving attestation updates."""
  108. def __init__(self, hs: "HomeServer"):
  109. self.clock = hs.get_clock()
  110. self.store = hs.get_datastore()
  111. self.assestations = hs.get_groups_attestation_signing()
  112. self.transport_client = hs.get_federation_transport_client()
  113. self.is_mine_id = hs.is_mine_id
  114. self.attestations = hs.get_groups_attestation_signing()
  115. if not hs.config.worker_app:
  116. self._renew_attestations_loop = self.clock.looping_call(
  117. self._start_renew_attestations, 30 * 60 * 1000
  118. )
  119. async def on_renew_attestation(
  120. self, group_id: str, user_id: str, content: JsonDict
  121. ) -> JsonDict:
  122. """When a remote updates an attestation"""
  123. attestation = content["attestation"]
  124. if not self.is_mine_id(group_id) and not self.is_mine_id(user_id):
  125. raise SynapseError(400, "Neither user not group are on this server")
  126. await self.attestations.verify_attestation(
  127. attestation, user_id=user_id, group_id=group_id
  128. )
  129. await self.store.update_remote_attestion(group_id, user_id, attestation)
  130. return {}
  131. def _start_renew_attestations(self) -> None:
  132. return run_as_background_process("renew_attestations", self._renew_attestations)
  133. async def _renew_attestations(self) -> None:
  134. """Called periodically to check if we need to update any of our attestations"""
  135. now = self.clock.time_msec()
  136. rows = await self.store.get_attestations_need_renewals(
  137. now + UPDATE_ATTESTATION_TIME_MS
  138. )
  139. async def _renew_attestation(group_user: Tuple[str, str]) -> None:
  140. group_id, user_id = group_user
  141. try:
  142. if not self.is_mine_id(group_id):
  143. destination = get_domain_from_id(group_id)
  144. elif not self.is_mine_id(user_id):
  145. destination = get_domain_from_id(user_id)
  146. else:
  147. logger.warning(
  148. "Incorrectly trying to do attestations for user: %r in %r",
  149. user_id,
  150. group_id,
  151. )
  152. await self.store.remove_attestation_renewal(group_id, user_id)
  153. return
  154. attestation = self.attestations.create_attestation(group_id, user_id)
  155. await self.transport_client.renew_group_attestation(
  156. destination, group_id, user_id, content={"attestation": attestation}
  157. )
  158. await self.store.update_attestation_renewal(
  159. group_id, user_id, attestation
  160. )
  161. except (RequestSendFailed, HttpResponseException) as e:
  162. logger.warning(
  163. "Failed to renew attestation of %r in %r: %s", user_id, group_id, e
  164. )
  165. except Exception:
  166. logger.exception(
  167. "Error renewing attestation of %r in %r", user_id, group_id
  168. )
  169. for row in rows:
  170. await _renew_attestation((row["group_id"], row["user_id"]))