attestations.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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 signedjson.sign import sign_json
  35. from twisted.internet import defer
  36. from synapse.api.errors import SynapseError
  37. from synapse.types import get_domain_from_id
  38. from synapse.util.logcontext import run_in_background
  39. logger = logging.getLogger(__name__)
  40. # Default validity duration for new attestations we create
  41. DEFAULT_ATTESTATION_LENGTH_MS = 3 * 24 * 60 * 60 * 1000
  42. # We add some jitter to the validity duration of attestations so that if we
  43. # add lots of users at once we don't need to renew them all at once.
  44. # The jitter is a multiplier picked randomly between the first and second number
  45. DEFAULT_ATTESTATION_JITTER = (0.9, 1.3)
  46. # Start trying to update our attestations when they come this close to expiring
  47. UPDATE_ATTESTATION_TIME_MS = 1 * 24 * 60 * 60 * 1000
  48. class GroupAttestationSigning(object):
  49. """Creates and verifies group attestations.
  50. """
  51. def __init__(self, hs):
  52. self.keyring = hs.get_keyring()
  53. self.clock = hs.get_clock()
  54. self.server_name = hs.hostname
  55. self.signing_key = hs.config.signing_key[0]
  56. @defer.inlineCallbacks
  57. def verify_attestation(self, attestation, group_id, user_id, server_name=None):
  58. """Verifies that the given attestation matches the given parameters.
  59. An optional server_name can be supplied to explicitly set which server's
  60. signature is expected. Otherwise assumes that either the group_id or user_id
  61. is local and uses the other's server as the one to check.
  62. """
  63. if not server_name:
  64. if get_domain_from_id(group_id) == self.server_name:
  65. server_name = get_domain_from_id(user_id)
  66. elif get_domain_from_id(user_id) == self.server_name:
  67. server_name = get_domain_from_id(group_id)
  68. else:
  69. raise Exception("Expected either group_id or user_id to be local")
  70. if user_id != attestation["user_id"]:
  71. raise SynapseError(400, "Attestation has incorrect user_id")
  72. if group_id != attestation["group_id"]:
  73. raise SynapseError(400, "Attestation has incorrect group_id")
  74. valid_until_ms = attestation["valid_until_ms"]
  75. # TODO: We also want to check that *new* attestations that people give
  76. # us to store are valid for at least a little while.
  77. if valid_until_ms < self.clock.time_msec():
  78. raise SynapseError(400, "Attestation expired")
  79. yield self.keyring.verify_json_for_server(server_name, attestation)
  80. def create_attestation(self, group_id, user_id):
  81. """Create an attestation for the group_id and user_id with default
  82. validity length.
  83. """
  84. validity_period = DEFAULT_ATTESTATION_LENGTH_MS
  85. validity_period *= random.uniform(*DEFAULT_ATTESTATION_JITTER)
  86. valid_until_ms = int(self.clock.time_msec() + validity_period)
  87. return sign_json({
  88. "group_id": group_id,
  89. "user_id": user_id,
  90. "valid_until_ms": valid_until_ms,
  91. }, self.server_name, self.signing_key)
  92. class GroupAttestionRenewer(object):
  93. """Responsible for sending and receiving attestation updates.
  94. """
  95. def __init__(self, hs):
  96. self.clock = hs.get_clock()
  97. self.store = hs.get_datastore()
  98. self.assestations = hs.get_groups_attestation_signing()
  99. self.transport_client = hs.get_federation_transport_client()
  100. self.is_mine_id = hs.is_mine_id
  101. self.attestations = hs.get_groups_attestation_signing()
  102. self._renew_attestations_loop = self.clock.looping_call(
  103. self._renew_attestations, 30 * 60 * 1000,
  104. )
  105. @defer.inlineCallbacks
  106. def on_renew_attestation(self, group_id, user_id, content):
  107. """When a remote updates an attestation
  108. """
  109. attestation = content["attestation"]
  110. if not self.is_mine_id(group_id) and not self.is_mine_id(user_id):
  111. raise SynapseError(400, "Neither user not group are on this server")
  112. yield self.attestations.verify_attestation(
  113. attestation,
  114. user_id=user_id,
  115. group_id=group_id,
  116. )
  117. yield self.store.update_remote_attestion(group_id, user_id, attestation)
  118. defer.returnValue({})
  119. @defer.inlineCallbacks
  120. def _renew_attestations(self):
  121. """Called periodically to check if we need to update any of our attestations
  122. """
  123. now = self.clock.time_msec()
  124. rows = yield self.store.get_attestations_need_renewals(
  125. now + UPDATE_ATTESTATION_TIME_MS
  126. )
  127. @defer.inlineCallbacks
  128. def _renew_attestation(group_id, user_id):
  129. try:
  130. if not self.is_mine_id(group_id):
  131. destination = get_domain_from_id(group_id)
  132. elif not self.is_mine_id(user_id):
  133. destination = get_domain_from_id(user_id)
  134. else:
  135. logger.warn(
  136. "Incorrectly trying to do attestations for user: %r in %r",
  137. user_id, group_id,
  138. )
  139. yield self.store.remove_attestation_renewal(group_id, user_id)
  140. return
  141. attestation = self.attestations.create_attestation(group_id, user_id)
  142. yield self.transport_client.renew_group_attestation(
  143. destination, group_id, user_id,
  144. content={"attestation": attestation},
  145. )
  146. yield self.store.update_attestation_renewal(
  147. group_id, user_id, attestation
  148. )
  149. except Exception:
  150. logger.exception("Error renewing attestation of %r in %r",
  151. user_id, group_id)
  152. for row in rows:
  153. group_id = row["group_id"]
  154. user_id = row["user_id"]
  155. run_in_background(_renew_attestation, group_id, user_id)