remote_key_resource.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # Copyright 2015, 2016 OpenMarket 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. import logging
  15. from typing import Dict
  16. from signedjson.sign import sign_json
  17. from synapse.api.errors import Codes, SynapseError
  18. from synapse.crypto.keyring import ServerKeyFetcher
  19. from synapse.http.server import DirectServeJsonResource, respond_with_json
  20. from synapse.http.servlet import parse_integer, parse_json_object_from_request
  21. from synapse.util import json_decoder
  22. logger = logging.getLogger(__name__)
  23. class RemoteKey(DirectServeJsonResource):
  24. """HTTP resource for retrieving the TLS certificate and NACL signature
  25. verification keys for a collection of servers. Checks that the reported
  26. X.509 TLS certificate matches the one used in the HTTPS connection. Checks
  27. that the NACL signature for the remote server is valid. Returns a dict of
  28. JSON signed by both the remote server and by this server.
  29. Supports individual GET APIs and a bulk query POST API.
  30. Requests:
  31. GET /_matrix/key/v2/query/remote.server.example.com HTTP/1.1
  32. GET /_matrix/key/v2/query/remote.server.example.com/a.key.id HTTP/1.1
  33. POST /_matrix/v2/query HTTP/1.1
  34. Content-Type: application/json
  35. {
  36. "server_keys": {
  37. "remote.server.example.com": {
  38. "a.key.id": {
  39. "minimum_valid_until_ts": 1234567890123
  40. }
  41. }
  42. }
  43. }
  44. Response:
  45. HTTP/1.1 200 OK
  46. Content-Type: application/json
  47. {
  48. "server_keys": [
  49. {
  50. "server_name": "remote.server.example.com"
  51. "valid_until_ts": # posix timestamp
  52. "verify_keys": {
  53. "a.key.id": { # The identifier for a key.
  54. key: "" # base64 encoded verification key.
  55. }
  56. }
  57. "old_verify_keys": {
  58. "an.old.key.id": { # The identifier for an old key.
  59. key: "", # base64 encoded key
  60. "expired_ts": 0, # when the key stop being used.
  61. }
  62. }
  63. "tls_fingerprints": [
  64. { "sha256": # fingerprint }
  65. ]
  66. "signatures": {
  67. "remote.server.example.com": {...}
  68. "this.server.example.com": {...}
  69. }
  70. }
  71. ]
  72. }
  73. """
  74. isLeaf = True
  75. def __init__(self, hs):
  76. super().__init__()
  77. self.fetcher = ServerKeyFetcher(hs)
  78. self.store = hs.get_datastore()
  79. self.clock = hs.get_clock()
  80. self.federation_domain_whitelist = hs.config.federation_domain_whitelist
  81. self.config = hs.config
  82. async def _async_render_GET(self, request):
  83. if len(request.postpath) == 1:
  84. (server,) = request.postpath
  85. query = {server.decode("ascii"): {}} # type: dict
  86. elif len(request.postpath) == 2:
  87. server, key_id = request.postpath
  88. minimum_valid_until_ts = parse_integer(request, "minimum_valid_until_ts")
  89. arguments = {}
  90. if minimum_valid_until_ts is not None:
  91. arguments["minimum_valid_until_ts"] = minimum_valid_until_ts
  92. query = {server.decode("ascii"): {key_id.decode("ascii"): arguments}}
  93. else:
  94. raise SynapseError(404, "Not found %r" % request.postpath, Codes.NOT_FOUND)
  95. await self.query_keys(request, query, query_remote_on_cache_miss=True)
  96. async def _async_render_POST(self, request):
  97. content = parse_json_object_from_request(request)
  98. query = content["server_keys"]
  99. await self.query_keys(request, query, query_remote_on_cache_miss=True)
  100. async def query_keys(self, request, query, query_remote_on_cache_miss=False):
  101. logger.info("Handling query for keys %r", query)
  102. store_queries = []
  103. for server_name, key_ids in query.items():
  104. if (
  105. self.federation_domain_whitelist is not None
  106. and server_name not in self.federation_domain_whitelist
  107. ):
  108. logger.debug("Federation denied with %s", server_name)
  109. continue
  110. if not key_ids:
  111. key_ids = (None,)
  112. for key_id in key_ids:
  113. store_queries.append((server_name, key_id, None))
  114. cached = await self.store.get_server_keys_json(store_queries)
  115. json_results = set()
  116. time_now_ms = self.clock.time_msec()
  117. # Note that the value is unused.
  118. cache_misses = {} # type: Dict[str, Dict[str, int]]
  119. for (server_name, key_id, from_server), results in cached.items():
  120. results = [(result["ts_added_ms"], result) for result in results]
  121. if not results and key_id is not None:
  122. cache_misses.setdefault(server_name, {})[key_id] = 0
  123. continue
  124. if key_id is not None:
  125. ts_added_ms, most_recent_result = max(results)
  126. ts_valid_until_ms = most_recent_result["ts_valid_until_ms"]
  127. req_key = query.get(server_name, {}).get(key_id, {})
  128. req_valid_until = req_key.get("minimum_valid_until_ts")
  129. miss = False
  130. if req_valid_until is not None:
  131. if ts_valid_until_ms < req_valid_until:
  132. logger.debug(
  133. "Cached response for %r/%r is older than requested"
  134. ": valid_until (%r) < minimum_valid_until (%r)",
  135. server_name,
  136. key_id,
  137. ts_valid_until_ms,
  138. req_valid_until,
  139. )
  140. miss = True
  141. else:
  142. logger.debug(
  143. "Cached response for %r/%r is newer than requested"
  144. ": valid_until (%r) >= minimum_valid_until (%r)",
  145. server_name,
  146. key_id,
  147. ts_valid_until_ms,
  148. req_valid_until,
  149. )
  150. elif (ts_added_ms + ts_valid_until_ms) / 2 < time_now_ms:
  151. logger.debug(
  152. "Cached response for %r/%r is too old"
  153. ": (added (%r) + valid_until (%r)) / 2 < now (%r)",
  154. server_name,
  155. key_id,
  156. ts_added_ms,
  157. ts_valid_until_ms,
  158. time_now_ms,
  159. )
  160. # We more than half way through the lifetime of the
  161. # response. We should fetch a fresh copy.
  162. miss = True
  163. else:
  164. logger.debug(
  165. "Cached response for %r/%r is still valid"
  166. ": (added (%r) + valid_until (%r)) / 2 < now (%r)",
  167. server_name,
  168. key_id,
  169. ts_added_ms,
  170. ts_valid_until_ms,
  171. time_now_ms,
  172. )
  173. if miss:
  174. cache_misses.setdefault(server_name, {})[key_id] = 0
  175. # Cast to bytes since postgresql returns a memoryview.
  176. json_results.add(bytes(most_recent_result["key_json"]))
  177. else:
  178. for ts_added, result in results:
  179. # Cast to bytes since postgresql returns a memoryview.
  180. json_results.add(bytes(result["key_json"]))
  181. # If there is a cache miss, request the missing keys, then recurse (and
  182. # ensure the result is sent).
  183. if cache_misses and query_remote_on_cache_miss:
  184. await self.fetcher.get_keys(cache_misses)
  185. await self.query_keys(request, query, query_remote_on_cache_miss=False)
  186. else:
  187. signed_keys = []
  188. for key_json in json_results:
  189. key_json = json_decoder.decode(key_json.decode("utf-8"))
  190. for signing_key in self.config.key_server_signing_keys:
  191. key_json = sign_json(key_json, self.config.server_name, signing_key)
  192. signed_keys.append(key_json)
  193. results = {"server_keys": signed_keys}
  194. respond_with_json(request, 200, results, canonical_json=True)