You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1628 lines
65 KiB

  1. # Copyright 2016 OpenMarket Ltd
  2. # Copyright 2018-2019 New Vector Ltd
  3. # Copyright 2019 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. from typing import TYPE_CHECKING, Dict, Iterable, List, Mapping, Optional, Tuple
  18. import attr
  19. from canonicaljson import encode_canonical_json
  20. from signedjson.key import VerifyKey, decode_verify_key_bytes
  21. from signedjson.sign import SignatureVerifyException, verify_signed_json
  22. from unpaddedbase64 import decode_base64
  23. from twisted.internet import defer
  24. from synapse.api.constants import EduTypes
  25. from synapse.api.errors import CodeMessageException, Codes, NotFoundError, SynapseError
  26. from synapse.handlers.device import DeviceHandler
  27. from synapse.logging.context import make_deferred_yieldable, run_in_background
  28. from synapse.logging.opentracing import log_kv, set_tag, tag_args, trace
  29. from synapse.types import (
  30. JsonDict,
  31. JsonMapping,
  32. UserID,
  33. get_domain_from_id,
  34. get_verify_key_from_cross_signing_key,
  35. )
  36. from synapse.util import json_decoder
  37. from synapse.util.async_helpers import Linearizer, concurrently_execute
  38. from synapse.util.cancellation import cancellable
  39. from synapse.util.retryutils import NotRetryingDestination
  40. if TYPE_CHECKING:
  41. from synapse.server import HomeServer
  42. logger = logging.getLogger(__name__)
  43. class E2eKeysHandler:
  44. def __init__(self, hs: "HomeServer"):
  45. self.config = hs.config
  46. self.store = hs.get_datastores().main
  47. self.federation = hs.get_federation_client()
  48. self.device_handler = hs.get_device_handler()
  49. self._appservice_handler = hs.get_application_service_handler()
  50. self.is_mine = hs.is_mine
  51. self.clock = hs.get_clock()
  52. federation_registry = hs.get_federation_registry()
  53. is_master = hs.config.worker.worker_app is None
  54. if is_master:
  55. edu_updater = SigningKeyEduUpdater(hs)
  56. # Only register this edu handler on master as it requires writing
  57. # device updates to the db
  58. federation_registry.register_edu_handler(
  59. EduTypes.SIGNING_KEY_UPDATE,
  60. edu_updater.incoming_signing_key_update,
  61. )
  62. # also handle the unstable version
  63. # FIXME: remove this when enough servers have upgraded
  64. federation_registry.register_edu_handler(
  65. EduTypes.UNSTABLE_SIGNING_KEY_UPDATE,
  66. edu_updater.incoming_signing_key_update,
  67. )
  68. # doesn't really work as part of the generic query API, because the
  69. # query request requires an object POST, but we abuse the
  70. # "query handler" interface.
  71. federation_registry.register_query_handler(
  72. "client_keys", self.on_federation_query_client_keys
  73. )
  74. # Limit the number of in-flight requests from a single device.
  75. self._query_devices_linearizer = Linearizer(
  76. name="query_devices",
  77. max_count=10,
  78. )
  79. self._query_appservices_for_otks = (
  80. hs.config.experimental.msc3983_appservice_otk_claims
  81. )
  82. self._query_appservices_for_keys = (
  83. hs.config.experimental.msc3984_appservice_key_query
  84. )
  85. @trace
  86. @cancellable
  87. async def query_devices(
  88. self,
  89. query_body: JsonDict,
  90. timeout: int,
  91. from_user_id: str,
  92. from_device_id: Optional[str],
  93. ) -> JsonDict:
  94. """Handle a device key query from a client
  95. {
  96. "device_keys": {
  97. "<user_id>": ["<device_id>"]
  98. }
  99. }
  100. ->
  101. {
  102. "device_keys": {
  103. "<user_id>": {
  104. "<device_id>": {
  105. ...
  106. }
  107. }
  108. }
  109. }
  110. Args:
  111. from_user_id: the user making the query. This is used when
  112. adding cross-signing signatures to limit what signatures users
  113. can see.
  114. from_device_id: the device making the query. This is used to limit
  115. the number of in-flight queries at a time.
  116. """
  117. async with self._query_devices_linearizer.queue((from_user_id, from_device_id)):
  118. device_keys_query: Dict[str, List[str]] = query_body.get("device_keys", {})
  119. # separate users by domain.
  120. # make a map from domain to user_id to device_ids
  121. local_query = {}
  122. remote_queries = {}
  123. for user_id, device_ids in device_keys_query.items():
  124. # we use UserID.from_string to catch invalid user ids
  125. if self.is_mine(UserID.from_string(user_id)):
  126. local_query[user_id] = device_ids
  127. else:
  128. remote_queries[user_id] = device_ids
  129. set_tag("local_key_query", str(local_query))
  130. set_tag("remote_key_query", str(remote_queries))
  131. # First get local devices.
  132. # A map of destination -> failure response.
  133. failures: Dict[str, JsonDict] = {}
  134. results = {}
  135. if local_query:
  136. local_result = await self.query_local_devices(local_query)
  137. for user_id, keys in local_result.items():
  138. if user_id in local_query:
  139. results[user_id] = keys
  140. # Get cached cross-signing keys
  141. cross_signing_keys = await self.get_cross_signing_keys_from_cache(
  142. device_keys_query, from_user_id
  143. )
  144. # Now attempt to get any remote devices from our local cache.
  145. # A map of destination -> user ID -> device IDs.
  146. remote_queries_not_in_cache: Dict[str, Dict[str, Iterable[str]]] = {}
  147. if remote_queries:
  148. user_ids = set()
  149. user_and_device_ids: List[Tuple[str, str]] = []
  150. for user_id, device_ids in remote_queries.items():
  151. if device_ids:
  152. user_and_device_ids.extend(
  153. (user_id, device_id) for device_id in device_ids
  154. )
  155. else:
  156. user_ids.add(user_id)
  157. (
  158. user_ids_not_in_cache,
  159. remote_results,
  160. ) = await self.store.get_user_devices_from_cache(
  161. user_ids, user_and_device_ids
  162. )
  163. # Check that the homeserver still shares a room with all cached users.
  164. # Note that this check may be slightly racy when a remote user leaves a
  165. # room after we have fetched their cached device list. In the worst case
  166. # we will do extra federation queries for devices that we had cached.
  167. cached_users = set(remote_results.keys())
  168. valid_cached_users = (
  169. await self.store.get_users_server_still_shares_room_with(
  170. remote_results.keys()
  171. )
  172. )
  173. invalid_cached_users = cached_users - valid_cached_users
  174. if invalid_cached_users:
  175. # Fix up results. If we get here, it means there was either a bug in
  176. # device list tracking, or we hit the race mentioned above.
  177. # TODO: In practice, this path is hit fairly often in existing
  178. # deployments when clients query the keys of departed remote
  179. # users. A background update to mark the appropriate device
  180. # lists as unsubscribed is needed.
  181. # https://github.com/matrix-org/synapse/issues/13651
  182. # Note that this currently introduces a failure mode when clients
  183. # are trying to decrypt old messages from a remote user whose
  184. # homeserver is no longer available. We may want to consider falling
  185. # back to the cached data when we fail to retrieve a device list
  186. # over federation for such remote users.
  187. user_ids_not_in_cache.update(invalid_cached_users)
  188. for invalid_user_id in invalid_cached_users:
  189. remote_results.pop(invalid_user_id)
  190. for user_id, devices in remote_results.items():
  191. user_devices = results.setdefault(user_id, {})
  192. for device_id, device in devices.items():
  193. keys = device.get("keys", None)
  194. device_display_name = device.get("device_display_name", None)
  195. if keys:
  196. result = dict(keys)
  197. unsigned = result.setdefault("unsigned", {})
  198. if device_display_name:
  199. unsigned["device_display_name"] = device_display_name
  200. user_devices[device_id] = result
  201. # check for missing cross-signing keys.
  202. for user_id in remote_queries.keys():
  203. cached_cross_master = user_id in cross_signing_keys["master_keys"]
  204. cached_cross_selfsigning = (
  205. user_id in cross_signing_keys["self_signing_keys"]
  206. )
  207. # check if we are missing only one of cross-signing master or
  208. # self-signing key, but the other one is cached.
  209. # as we need both, this will issue a federation request.
  210. # if we don't have any of the keys, either the user doesn't have
  211. # cross-signing set up, or the cached device list
  212. # is not (yet) updated.
  213. if cached_cross_master ^ cached_cross_selfsigning:
  214. user_ids_not_in_cache.add(user_id)
  215. # add those users to the list to fetch over federation.
  216. for user_id in user_ids_not_in_cache:
  217. domain = get_domain_from_id(user_id)
  218. r = remote_queries_not_in_cache.setdefault(domain, {})
  219. r[user_id] = remote_queries[user_id]
  220. # Now fetch any devices that we don't have in our cache
  221. # TODO It might make sense to propagate cancellations into the
  222. # deferreds which are querying remote homeservers.
  223. logger.debug(
  224. "%d destinations to query devices for", len(remote_queries_not_in_cache)
  225. )
  226. async def _query(
  227. destination_queries: Tuple[str, Dict[str, Iterable[str]]]
  228. ) -> None:
  229. destination, queries = destination_queries
  230. return await self._query_devices_for_destination(
  231. results,
  232. cross_signing_keys,
  233. failures,
  234. destination,
  235. queries,
  236. timeout,
  237. )
  238. await concurrently_execute(
  239. _query,
  240. remote_queries_not_in_cache.items(),
  241. 10,
  242. delay_cancellation=True,
  243. )
  244. return {"device_keys": results, "failures": failures, **cross_signing_keys}
  245. @trace
  246. async def _query_devices_for_destination(
  247. self,
  248. results: JsonDict,
  249. cross_signing_keys: JsonDict,
  250. failures: Dict[str, JsonDict],
  251. destination: str,
  252. destination_query: Dict[str, Iterable[str]],
  253. timeout: int,
  254. ) -> None:
  255. """This is called when we are querying the device list of a user on
  256. a remote homeserver and their device list is not in the device list
  257. cache. If we share a room with this user and we're not querying for
  258. specific user we will update the cache with their device list.
  259. Args:
  260. results: A map from user ID to their device keys, which gets
  261. updated with the newly fetched keys.
  262. cross_signing_keys: Map from user ID to their cross signing keys,
  263. which gets updated with the newly fetched keys.
  264. failures: Map of destinations to failures that have occurred while
  265. attempting to fetch keys.
  266. destination: The remote server to query
  267. destination_query: The query dict of devices to query the remote
  268. server for.
  269. timeout: The timeout for remote HTTP requests.
  270. """
  271. # We first consider whether we wish to update the device list cache with
  272. # the users device list. We want to track a user's devices when the
  273. # authenticated user shares a room with the queried user and the query
  274. # has not specified a particular device.
  275. # If we update the cache for the queried user we remove them from further
  276. # queries. We use the more efficient batched query_client_keys for all
  277. # remaining users
  278. user_ids_updated = []
  279. # Perform a user device resync for each user only once and only as long as:
  280. # - they have an empty device_list
  281. # - they are in some rooms that this server can see
  282. users_to_resync_devices = {
  283. user_id
  284. for (user_id, device_list) in destination_query.items()
  285. if (not device_list) and (await self.store.get_rooms_for_user(user_id))
  286. }
  287. logger.debug(
  288. "%d users to resync devices for from destination %s",
  289. len(users_to_resync_devices),
  290. destination,
  291. )
  292. try:
  293. user_resync_results = (
  294. await self.device_handler.device_list_updater.multi_user_device_resync(
  295. list(users_to_resync_devices)
  296. )
  297. )
  298. for user_id in users_to_resync_devices:
  299. resync_results = user_resync_results[user_id]
  300. if resync_results is None:
  301. # TODO: It's weird that we'll store a failure against a
  302. # destination, yet continue processing users from that
  303. # destination.
  304. # We might want to consider changing this, but for now
  305. # I'm leaving it as I found it.
  306. failures[destination] = _exception_to_failure(
  307. ValueError(f"Device resync failed for {user_id!r}")
  308. )
  309. continue
  310. # Add the device keys to the results.
  311. user_devices = resync_results["devices"]
  312. user_results = results.setdefault(user_id, {})
  313. for device in user_devices:
  314. user_results[device["device_id"]] = device["keys"]
  315. user_ids_updated.append(user_id)
  316. # Add any cross signing keys to the results.
  317. master_key = resync_results.get("master_key")
  318. self_signing_key = resync_results.get("self_signing_key")
  319. if master_key:
  320. cross_signing_keys["master_keys"][user_id] = master_key
  321. if self_signing_key:
  322. cross_signing_keys["self_signing_keys"][user_id] = self_signing_key
  323. except Exception as e:
  324. failures[destination] = _exception_to_failure(e)
  325. if len(destination_query) == len(user_ids_updated):
  326. # We've updated all the users in the query and we do not need to
  327. # make any further remote calls.
  328. return
  329. # Remove all the users from the query which we have updated
  330. for user_id in user_ids_updated:
  331. destination_query.pop(user_id)
  332. try:
  333. remote_result = await self.federation.query_client_keys(
  334. destination, {"device_keys": destination_query}, timeout=timeout
  335. )
  336. for user_id, keys in remote_result["device_keys"].items():
  337. if user_id in destination_query:
  338. results[user_id] = keys
  339. if "master_keys" in remote_result:
  340. for user_id, key in remote_result["master_keys"].items():
  341. if user_id in destination_query:
  342. cross_signing_keys["master_keys"][user_id] = key
  343. if "self_signing_keys" in remote_result:
  344. for user_id, key in remote_result["self_signing_keys"].items():
  345. if user_id in destination_query:
  346. cross_signing_keys["self_signing_keys"][user_id] = key
  347. except Exception as e:
  348. failure = _exception_to_failure(e)
  349. failures[destination] = failure
  350. set_tag("error", True)
  351. set_tag("reason", str(failure))
  352. return
  353. @cancellable
  354. async def get_cross_signing_keys_from_cache(
  355. self, query: Iterable[str], from_user_id: Optional[str]
  356. ) -> Dict[str, Dict[str, JsonMapping]]:
  357. """Get cross-signing keys for users from the database
  358. Args:
  359. query: an iterable of user IDs. A dict whose keys
  360. are user IDs satisfies this, so the query format used for
  361. query_devices can be used here.
  362. from_user_id: the user making the query. This is used when
  363. adding cross-signing signatures to limit what signatures users
  364. can see.
  365. Returns:
  366. A map from (master_keys|self_signing_keys|user_signing_keys) -> user_id -> key
  367. """
  368. master_keys = {}
  369. self_signing_keys = {}
  370. user_signing_keys = {}
  371. user_ids = list(query)
  372. keys = await self.store.get_e2e_cross_signing_keys_bulk(user_ids, from_user_id)
  373. for user_id, user_info in keys.items():
  374. if user_info is None:
  375. continue
  376. if "master" in user_info:
  377. master_keys[user_id] = user_info["master"]
  378. if "self_signing" in user_info:
  379. self_signing_keys[user_id] = user_info["self_signing"]
  380. # users can see other users' master and self-signing keys, but can
  381. # only see their own user-signing keys
  382. if from_user_id:
  383. from_user_key = keys.get(from_user_id)
  384. if from_user_key and "user_signing" in from_user_key:
  385. user_signing_keys[from_user_id] = from_user_key["user_signing"]
  386. return {
  387. "master_keys": master_keys,
  388. "self_signing_keys": self_signing_keys,
  389. "user_signing_keys": user_signing_keys,
  390. }
  391. @trace
  392. @cancellable
  393. async def query_local_devices(
  394. self,
  395. query: Mapping[str, Optional[List[str]]],
  396. include_displaynames: bool = True,
  397. ) -> Dict[str, Dict[str, dict]]:
  398. """Get E2E device keys for local users
  399. Args:
  400. query: map from user_id to a list
  401. of devices to query (None for all devices)
  402. include_displaynames: Whether to include device displaynames in the returned
  403. device details.
  404. Returns:
  405. A map from user_id -> device_id -> device details
  406. """
  407. set_tag("local_query", str(query))
  408. local_query: List[Tuple[str, Optional[str]]] = []
  409. result_dict: Dict[str, Dict[str, dict]] = {}
  410. for user_id, device_ids in query.items():
  411. # we use UserID.from_string to catch invalid user ids
  412. if not self.is_mine(UserID.from_string(user_id)):
  413. logger.warning("Request for keys for non-local user %s", user_id)
  414. log_kv(
  415. {
  416. "message": "Requested a local key for a user which"
  417. " was not local to the homeserver",
  418. "user_id": user_id,
  419. }
  420. )
  421. set_tag("error", True)
  422. raise SynapseError(400, "Not a user here")
  423. if not device_ids:
  424. local_query.append((user_id, None))
  425. else:
  426. for device_id in device_ids:
  427. local_query.append((user_id, device_id))
  428. # make sure that each queried user appears in the result dict
  429. result_dict[user_id] = {}
  430. results = await self.store.get_e2e_device_keys_for_cs_api(
  431. local_query, include_displaynames
  432. )
  433. # Check if the application services have any additional results.
  434. if self._query_appservices_for_keys:
  435. # Query the appservices for any keys.
  436. appservice_results = await self._appservice_handler.query_keys(query)
  437. # Merge results, overriding with what the appservice returned.
  438. for user_id, devices in appservice_results.get("device_keys", {}).items():
  439. # Copy the appservice device info over the homeserver device info, but
  440. # don't completely overwrite it.
  441. results.setdefault(user_id, {}).update(devices)
  442. # TODO Handle cross-signing keys.
  443. # Build the result structure
  444. for user_id, device_keys in results.items():
  445. for device_id, device_info in device_keys.items():
  446. result_dict[user_id][device_id] = device_info
  447. log_kv(results)
  448. return result_dict
  449. async def on_federation_query_client_keys(
  450. self, query_body: Dict[str, Dict[str, Optional[List[str]]]]
  451. ) -> JsonDict:
  452. """Handle a device key query from a federated server:
  453. Handles the path: GET /_matrix/federation/v1/users/keys/query
  454. Args:
  455. query_body: The body of the query request. Should contain a key
  456. "device_keys" that map to a dictionary of user ID's -> list of
  457. device IDs. If the list of device IDs is empty, all devices of
  458. that user will be queried.
  459. Returns:
  460. A json dictionary containing the following:
  461. - device_keys: A dictionary containing the requested device information.
  462. - master_keys: An optional dictionary of user ID -> master cross-signing
  463. key info.
  464. - self_signing_key: An optional dictionary of user ID -> self-signing
  465. key info.
  466. """
  467. device_keys_query: Dict[str, Optional[List[str]]] = query_body.get(
  468. "device_keys", {}
  469. )
  470. res = await self.query_local_devices(
  471. device_keys_query,
  472. include_displaynames=(
  473. self.config.federation.allow_device_name_lookup_over_federation
  474. ),
  475. )
  476. # add in the cross-signing keys
  477. cross_signing_keys = await self.get_cross_signing_keys_from_cache(
  478. device_keys_query, None
  479. )
  480. return {"device_keys": res, **cross_signing_keys}
  481. async def claim_local_one_time_keys(
  482. self,
  483. local_query: List[Tuple[str, str, str, int]],
  484. always_include_fallback_keys: bool,
  485. ) -> Iterable[Dict[str, Dict[str, Dict[str, JsonDict]]]]:
  486. """Claim one time keys for local users.
  487. 1. Attempt to claim OTKs from the database.
  488. 2. Ask application services if they provide OTKs.
  489. 3. Attempt to fetch fallback keys from the database.
  490. Args:
  491. local_query: An iterable of tuples of (user ID, device ID, algorithm).
  492. always_include_fallback_keys: True to always include fallback keys.
  493. Returns:
  494. An iterable of maps of user ID -> a map device ID -> a map of key ID -> JSON bytes.
  495. """
  496. # Cap the number of OTKs that can be claimed at once to avoid abuse.
  497. local_query = [
  498. (user_id, device_id, algorithm, min(count, 5))
  499. for user_id, device_id, algorithm, count in local_query
  500. ]
  501. otk_results, not_found = await self.store.claim_e2e_one_time_keys(local_query)
  502. # If the application services have not provided any keys via the C-S
  503. # API, query it directly for one-time keys.
  504. if self._query_appservices_for_otks:
  505. # TODO Should this query for fallback keys of uploaded OTKs if
  506. # always_include_fallback_keys is True? The MSC is ambiguous.
  507. (
  508. appservice_results,
  509. not_found,
  510. ) = await self._appservice_handler.claim_e2e_one_time_keys(not_found)
  511. else:
  512. appservice_results = {}
  513. # Calculate which user ID / device ID / algorithm tuples to get fallback
  514. # keys for. This can be either only missing results *or* all results
  515. # (which don't already have a fallback key).
  516. if always_include_fallback_keys:
  517. # Build the fallback query as any part of the original query where
  518. # the appservice didn't respond with a fallback key.
  519. fallback_query = []
  520. # Iterate each item in the original query and search the results
  521. # from the appservice for that user ID / device ID. If it is found,
  522. # check if any of the keys match the requested algorithm & are a
  523. # fallback key.
  524. for user_id, device_id, algorithm, _count in local_query:
  525. # Check if the appservice responded for this query.
  526. as_result = appservice_results.get(user_id, {}).get(device_id, {})
  527. found_otk = False
  528. for key_id, key_json in as_result.items():
  529. if key_id.startswith(f"{algorithm}:"):
  530. # A OTK or fallback key was found for this query.
  531. found_otk = True
  532. # A fallback key was found for this query, no need to
  533. # query further.
  534. if key_json.get("fallback", False):
  535. break
  536. else:
  537. # No fallback key was found from appservices, query for it.
  538. # Only mark the fallback key as used if no OTK was found
  539. # (from either the database or appservices).
  540. mark_as_used = not found_otk and not any(
  541. key_id.startswith(f"{algorithm}:")
  542. for key_id in otk_results.get(user_id, {})
  543. .get(device_id, {})
  544. .keys()
  545. )
  546. # Note that it doesn't make sense to request more than 1 fallback key
  547. # per (user_id, device_id, algorithm).
  548. fallback_query.append((user_id, device_id, algorithm, mark_as_used))
  549. else:
  550. # All fallback keys get marked as used.
  551. fallback_query = [
  552. # Note that it doesn't make sense to request more than 1 fallback key
  553. # per (user_id, device_id, algorithm).
  554. (user_id, device_id, algorithm, True)
  555. for user_id, device_id, algorithm, count in not_found
  556. ]
  557. # For each user that does not have a one-time keys available, see if
  558. # there is a fallback key.
  559. fallback_results = await self.store.claim_e2e_fallback_keys(fallback_query)
  560. # Return the results in order, each item from the input query should
  561. # only appear once in the combined list.
  562. return (otk_results, appservice_results, fallback_results)
  563. @trace
  564. async def claim_one_time_keys(
  565. self,
  566. query: Dict[str, Dict[str, Dict[str, int]]],
  567. user: UserID,
  568. timeout: Optional[int],
  569. always_include_fallback_keys: bool,
  570. ) -> JsonDict:
  571. local_query: List[Tuple[str, str, str, int]] = []
  572. remote_queries: Dict[str, Dict[str, Dict[str, Dict[str, int]]]] = {}
  573. for user_id, one_time_keys in query.items():
  574. # we use UserID.from_string to catch invalid user ids
  575. if self.is_mine(UserID.from_string(user_id)):
  576. for device_id, algorithms in one_time_keys.items():
  577. for algorithm, count in algorithms.items():
  578. local_query.append((user_id, device_id, algorithm, count))
  579. else:
  580. domain = get_domain_from_id(user_id)
  581. remote_queries.setdefault(domain, {})[user_id] = one_time_keys
  582. set_tag("local_key_query", str(local_query))
  583. set_tag("remote_key_query", str(remote_queries))
  584. results = await self.claim_local_one_time_keys(
  585. local_query, always_include_fallback_keys
  586. )
  587. # A map of user ID -> device ID -> key ID -> key.
  588. json_result: Dict[str, Dict[str, Dict[str, JsonDict]]] = {}
  589. for result in results:
  590. for user_id, device_keys in result.items():
  591. for device_id, keys in device_keys.items():
  592. for key_id, key in keys.items():
  593. json_result.setdefault(user_id, {}).setdefault(
  594. device_id, {}
  595. ).update({key_id: key})
  596. # Remote failures.
  597. failures: Dict[str, JsonDict] = {}
  598. @trace
  599. async def claim_client_keys(destination: str) -> None:
  600. set_tag("destination", destination)
  601. device_keys = remote_queries[destination]
  602. try:
  603. remote_result = await self.federation.claim_client_keys(
  604. user, destination, device_keys, timeout=timeout
  605. )
  606. for user_id, keys in remote_result["one_time_keys"].items():
  607. if user_id in device_keys:
  608. json_result[user_id] = keys
  609. except Exception as e:
  610. failure = _exception_to_failure(e)
  611. failures[destination] = failure
  612. set_tag("error", True)
  613. set_tag("reason", str(failure))
  614. await make_deferred_yieldable(
  615. defer.gatherResults(
  616. [
  617. run_in_background(claim_client_keys, destination)
  618. for destination in remote_queries
  619. ],
  620. consumeErrors=True,
  621. )
  622. )
  623. logger.info(
  624. "Claimed one-time-keys: %s",
  625. ",".join(
  626. (
  627. "%s for %s:%s" % (key_id, user_id, device_id)
  628. for user_id, user_keys in json_result.items()
  629. for device_id, device_keys in user_keys.items()
  630. for key_id, _ in device_keys.items()
  631. )
  632. ),
  633. )
  634. log_kv({"one_time_keys": json_result, "failures": failures})
  635. return {"one_time_keys": json_result, "failures": failures}
  636. @tag_args
  637. async def upload_keys_for_user(
  638. self, user_id: str, device_id: str, keys: JsonDict
  639. ) -> JsonDict:
  640. # This can only be called from the main process.
  641. assert isinstance(self.device_handler, DeviceHandler)
  642. time_now = self.clock.time_msec()
  643. # TODO: Validate the JSON to make sure it has the right keys.
  644. device_keys = keys.get("device_keys", None)
  645. if device_keys:
  646. logger.info(
  647. "Updating device_keys for device %r for user %s at %d",
  648. device_id,
  649. user_id,
  650. time_now,
  651. )
  652. log_kv(
  653. {
  654. "message": "Updating device_keys for user.",
  655. "user_id": user_id,
  656. "device_id": device_id,
  657. }
  658. )
  659. # TODO: Sign the JSON with the server key
  660. changed = await self.store.set_e2e_device_keys(
  661. user_id, device_id, time_now, device_keys
  662. )
  663. if changed:
  664. # Only notify about device updates *if* the keys actually changed
  665. await self.device_handler.notify_device_update(user_id, [device_id])
  666. else:
  667. log_kv({"message": "Not updating device_keys for user", "user_id": user_id})
  668. one_time_keys = keys.get("one_time_keys", None)
  669. if one_time_keys:
  670. log_kv(
  671. {
  672. "message": "Updating one_time_keys for device.",
  673. "user_id": user_id,
  674. "device_id": device_id,
  675. }
  676. )
  677. await self._upload_one_time_keys_for_user(
  678. user_id, device_id, time_now, one_time_keys
  679. )
  680. else:
  681. log_kv(
  682. {"message": "Did not update one_time_keys", "reason": "no keys given"}
  683. )
  684. fallback_keys = keys.get("fallback_keys") or keys.get(
  685. "org.matrix.msc2732.fallback_keys"
  686. )
  687. if fallback_keys and isinstance(fallback_keys, dict):
  688. log_kv(
  689. {
  690. "message": "Updating fallback_keys for device.",
  691. "user_id": user_id,
  692. "device_id": device_id,
  693. }
  694. )
  695. await self.store.set_e2e_fallback_keys(user_id, device_id, fallback_keys)
  696. elif fallback_keys:
  697. log_kv({"message": "Did not update fallback_keys", "reason": "not a dict"})
  698. else:
  699. log_kv(
  700. {"message": "Did not update fallback_keys", "reason": "no keys given"}
  701. )
  702. # the device should have been registered already, but it may have been
  703. # deleted due to a race with a DELETE request. Or we may be using an
  704. # old access_token without an associated device_id. Either way, we
  705. # need to double-check the device is registered to avoid ending up with
  706. # keys without a corresponding device.
  707. await self.device_handler.check_device_registered(user_id, device_id)
  708. result = await self.store.count_e2e_one_time_keys(user_id, device_id)
  709. set_tag("one_time_key_counts", str(result))
  710. return {"one_time_key_counts": result}
  711. async def _upload_one_time_keys_for_user(
  712. self, user_id: str, device_id: str, time_now: int, one_time_keys: JsonDict
  713. ) -> None:
  714. logger.info(
  715. "Adding one_time_keys %r for device %r for user %r at %d",
  716. one_time_keys.keys(),
  717. device_id,
  718. user_id,
  719. time_now,
  720. )
  721. # make a list of (alg, id, key) tuples
  722. key_list = []
  723. for key_id, key_obj in one_time_keys.items():
  724. algorithm, key_id = key_id.split(":")
  725. key_list.append((algorithm, key_id, key_obj))
  726. # First we check if we have already persisted any of the keys.
  727. existing_key_map = await self.store.get_e2e_one_time_keys(
  728. user_id, device_id, [k_id for _, k_id, _ in key_list]
  729. )
  730. new_keys = [] # Keys that we need to insert. (alg, id, json) tuples.
  731. for algorithm, key_id, key in key_list:
  732. ex_json = existing_key_map.get((algorithm, key_id), None)
  733. if ex_json:
  734. if not _one_time_keys_match(ex_json, key):
  735. raise SynapseError(
  736. 400,
  737. (
  738. "One time key %s:%s already exists. "
  739. "Old key: %s; new key: %r"
  740. )
  741. % (algorithm, key_id, ex_json, key),
  742. )
  743. else:
  744. new_keys.append(
  745. (algorithm, key_id, encode_canonical_json(key).decode("ascii"))
  746. )
  747. log_kv({"message": "Inserting new one_time_keys.", "keys": new_keys})
  748. await self.store.add_e2e_one_time_keys(user_id, device_id, time_now, new_keys)
  749. async def upload_signing_keys_for_user(
  750. self, user_id: str, keys: JsonDict
  751. ) -> JsonDict:
  752. """Upload signing keys for cross-signing
  753. Args:
  754. user_id: the user uploading the keys
  755. keys: the signing keys
  756. """
  757. # This can only be called from the main process.
  758. assert isinstance(self.device_handler, DeviceHandler)
  759. # if a master key is uploaded, then check it. Otherwise, load the
  760. # stored master key, to check signatures on other keys
  761. if "master_key" in keys:
  762. master_key = keys["master_key"]
  763. _check_cross_signing_key(master_key, user_id, "master")
  764. else:
  765. master_key = await self.store.get_e2e_cross_signing_key(user_id, "master")
  766. # if there is no master key, then we can't do anything, because all the
  767. # other cross-signing keys need to be signed by the master key
  768. if not master_key:
  769. raise SynapseError(400, "No master key available", Codes.MISSING_PARAM)
  770. try:
  771. master_key_id, master_verify_key = get_verify_key_from_cross_signing_key(
  772. master_key
  773. )
  774. except ValueError:
  775. if "master_key" in keys:
  776. # the invalid key came from the request
  777. raise SynapseError(400, "Invalid master key", Codes.INVALID_PARAM)
  778. else:
  779. # the invalid key came from the database
  780. logger.error("Invalid master key found for user %s", user_id)
  781. raise SynapseError(500, "Invalid master key")
  782. # for the other cross-signing keys, make sure that they have valid
  783. # signatures from the master key
  784. if "self_signing_key" in keys:
  785. self_signing_key = keys["self_signing_key"]
  786. _check_cross_signing_key(
  787. self_signing_key, user_id, "self_signing", master_verify_key
  788. )
  789. if "user_signing_key" in keys:
  790. user_signing_key = keys["user_signing_key"]
  791. _check_cross_signing_key(
  792. user_signing_key, user_id, "user_signing", master_verify_key
  793. )
  794. # if everything checks out, then store the keys and send notifications
  795. deviceids = []
  796. if "master_key" in keys:
  797. await self.store.set_e2e_cross_signing_key(user_id, "master", master_key)
  798. deviceids.append(master_verify_key.version)
  799. if "self_signing_key" in keys:
  800. await self.store.set_e2e_cross_signing_key(
  801. user_id, "self_signing", self_signing_key
  802. )
  803. try:
  804. deviceids.append(
  805. get_verify_key_from_cross_signing_key(self_signing_key)[1].version
  806. )
  807. except ValueError:
  808. raise SynapseError(400, "Invalid self-signing key", Codes.INVALID_PARAM)
  809. if "user_signing_key" in keys:
  810. await self.store.set_e2e_cross_signing_key(
  811. user_id, "user_signing", user_signing_key
  812. )
  813. # the signature stream matches the semantics that we want for
  814. # user-signing key updates: only the user themselves is notified of
  815. # their own user-signing key updates
  816. await self.device_handler.notify_user_signature_update(user_id, [user_id])
  817. # master key and self-signing key updates match the semantics of device
  818. # list updates: all users who share an encrypted room are notified
  819. if len(deviceids):
  820. await self.device_handler.notify_device_update(user_id, deviceids)
  821. return {}
  822. async def upload_signatures_for_device_keys(
  823. self, user_id: str, signatures: JsonDict
  824. ) -> JsonDict:
  825. """Upload device signatures for cross-signing
  826. Args:
  827. user_id: the user uploading the signatures
  828. signatures: map of users to devices to signed keys. This is the submission
  829. from the user; an exception will be raised if it is malformed.
  830. Returns:
  831. The response to be sent back to the client. The response will have
  832. a "failures" key, which will be a dict mapping users to devices
  833. to errors for the signatures that failed.
  834. Raises:
  835. SynapseError: if the signatures dict is not valid.
  836. """
  837. # This can only be called from the main process.
  838. assert isinstance(self.device_handler, DeviceHandler)
  839. failures = {}
  840. # signatures to be stored. Each item will be a SignatureListItem
  841. signature_list = []
  842. # split between checking signatures for own user and signatures for
  843. # other users, since we verify them with different keys
  844. self_signatures = signatures.get(user_id, {})
  845. other_signatures = {k: v for k, v in signatures.items() if k != user_id}
  846. self_signature_list, self_failures = await self._process_self_signatures(
  847. user_id, self_signatures
  848. )
  849. signature_list.extend(self_signature_list)
  850. failures.update(self_failures)
  851. other_signature_list, other_failures = await self._process_other_signatures(
  852. user_id, other_signatures
  853. )
  854. signature_list.extend(other_signature_list)
  855. failures.update(other_failures)
  856. # store the signature, and send the appropriate notifications for sync
  857. logger.debug("upload signature failures: %r", failures)
  858. await self.store.store_e2e_cross_signing_signatures(user_id, signature_list)
  859. self_device_ids = [item.target_device_id for item in self_signature_list]
  860. if self_device_ids:
  861. await self.device_handler.notify_device_update(user_id, self_device_ids)
  862. signed_users = [item.target_user_id for item in other_signature_list]
  863. if signed_users:
  864. await self.device_handler.notify_user_signature_update(
  865. user_id, signed_users
  866. )
  867. return {"failures": failures}
  868. async def _process_self_signatures(
  869. self, user_id: str, signatures: JsonDict
  870. ) -> Tuple[List["SignatureListItem"], Dict[str, Dict[str, dict]]]:
  871. """Process uploaded signatures of the user's own keys.
  872. Signatures of the user's own keys from this API come in two forms:
  873. - signatures of the user's devices by the user's self-signing key,
  874. - signatures of the user's master key by the user's devices.
  875. Args:
  876. user_id: the user uploading the keys
  877. signatures (dict[string, dict]): map of devices to signed keys
  878. Returns:
  879. A tuple of a list of signatures to store, and a map of users to
  880. devices to failure reasons
  881. Raises:
  882. SynapseError: if the input is malformed
  883. """
  884. signature_list: List["SignatureListItem"] = []
  885. failures: Dict[str, Dict[str, JsonDict]] = {}
  886. if not signatures:
  887. return signature_list, failures
  888. if not isinstance(signatures, dict):
  889. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  890. try:
  891. # get our self-signing key to verify the signatures
  892. (
  893. _,
  894. self_signing_key_id,
  895. self_signing_verify_key,
  896. ) = await self._get_e2e_cross_signing_verify_key(user_id, "self_signing")
  897. # get our master key, since we may have received a signature of it.
  898. # We need to fetch it here so that we know what its key ID is, so
  899. # that we can check if a signature that was sent is a signature of
  900. # the master key or of a device
  901. (
  902. master_key,
  903. _,
  904. master_verify_key,
  905. ) = await self._get_e2e_cross_signing_verify_key(user_id, "master")
  906. # fetch our stored devices. This is used to 1. verify
  907. # signatures on the master key, and 2. to compare with what
  908. # was sent if the device was signed
  909. devices = await self.store.get_e2e_device_keys_for_cs_api([(user_id, None)])
  910. if user_id not in devices:
  911. raise NotFoundError("No device keys found")
  912. devices = devices[user_id]
  913. except SynapseError as e:
  914. failure = _exception_to_failure(e)
  915. failures[user_id] = {device: failure for device in signatures.keys()}
  916. return signature_list, failures
  917. for device_id, device in signatures.items():
  918. # make sure submitted data is in the right form
  919. if not isinstance(device, dict):
  920. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  921. try:
  922. if "signatures" not in device or user_id not in device["signatures"]:
  923. # no signature was sent
  924. raise SynapseError(
  925. 400, "Invalid signature", Codes.INVALID_SIGNATURE
  926. )
  927. if device_id == master_verify_key.version:
  928. # The signature is of the master key. This needs to be
  929. # handled differently from signatures of normal devices.
  930. master_key_signature_list = self._check_master_key_signature(
  931. user_id, device_id, device, master_key, devices
  932. )
  933. signature_list.extend(master_key_signature_list)
  934. continue
  935. # at this point, we have a device that should be signed
  936. # by the self-signing key
  937. if self_signing_key_id not in device["signatures"][user_id]:
  938. # no signature was sent
  939. raise SynapseError(
  940. 400, "Invalid signature", Codes.INVALID_SIGNATURE
  941. )
  942. try:
  943. stored_device = devices[device_id]
  944. except KeyError:
  945. raise NotFoundError("Unknown device")
  946. if self_signing_key_id in stored_device.get("signatures", {}).get(
  947. user_id, {}
  948. ):
  949. # we already have a signature on this device, so we
  950. # can skip it, since it should be exactly the same
  951. continue
  952. _check_device_signature(
  953. user_id, self_signing_verify_key, device, stored_device
  954. )
  955. signature = device["signatures"][user_id][self_signing_key_id]
  956. signature_list.append(
  957. SignatureListItem(
  958. self_signing_key_id, user_id, device_id, signature
  959. )
  960. )
  961. except SynapseError as e:
  962. failures.setdefault(user_id, {})[device_id] = _exception_to_failure(e)
  963. return signature_list, failures
  964. def _check_master_key_signature(
  965. self,
  966. user_id: str,
  967. master_key_id: str,
  968. signed_master_key: JsonDict,
  969. stored_master_key: JsonMapping,
  970. devices: Dict[str, Dict[str, JsonDict]],
  971. ) -> List["SignatureListItem"]:
  972. """Check signatures of a user's master key made by their devices.
  973. Args:
  974. user_id: the user whose master key is being checked
  975. master_key_id: the ID of the user's master key
  976. signed_master_key: the user's signed master key that was uploaded
  977. stored_master_key: our previously-stored copy of the user's master key
  978. devices: the user's devices
  979. Returns:
  980. A list of signatures to store
  981. Raises:
  982. SynapseError: if a signature is invalid
  983. """
  984. # for each device that signed the master key, check the signature.
  985. master_key_signature_list = []
  986. sigs = signed_master_key["signatures"]
  987. for signing_key_id, signature in sigs[user_id].items():
  988. _, signing_device_id = signing_key_id.split(":", 1)
  989. if (
  990. signing_device_id not in devices
  991. or signing_key_id not in devices[signing_device_id]["keys"]
  992. ):
  993. # signed by an unknown device, or the
  994. # device does not have the key
  995. raise SynapseError(400, "Invalid signature", Codes.INVALID_SIGNATURE)
  996. # get the key and check the signature
  997. pubkey = devices[signing_device_id]["keys"][signing_key_id]
  998. verify_key = decode_verify_key_bytes(signing_key_id, decode_base64(pubkey))
  999. _check_device_signature(
  1000. user_id, verify_key, signed_master_key, stored_master_key
  1001. )
  1002. master_key_signature_list.append(
  1003. SignatureListItem(signing_key_id, user_id, master_key_id, signature)
  1004. )
  1005. return master_key_signature_list
  1006. async def _process_other_signatures(
  1007. self, user_id: str, signatures: Dict[str, dict]
  1008. ) -> Tuple[List["SignatureListItem"], Dict[str, Dict[str, dict]]]:
  1009. """Process uploaded signatures of other users' keys. These will be the
  1010. target user's master keys, signed by the uploading user's user-signing
  1011. key.
  1012. Args:
  1013. user_id: the user uploading the keys
  1014. signatures: map of users to devices to signed keys
  1015. Returns:
  1016. A list of signatures to store, and a map of users to devices to failure
  1017. reasons
  1018. Raises:
  1019. SynapseError: if the input is malformed
  1020. """
  1021. signature_list: List["SignatureListItem"] = []
  1022. failures: Dict[str, Dict[str, JsonDict]] = {}
  1023. if not signatures:
  1024. return signature_list, failures
  1025. try:
  1026. # get our user-signing key to verify the signatures
  1027. (
  1028. user_signing_key,
  1029. user_signing_key_id,
  1030. user_signing_verify_key,
  1031. ) = await self._get_e2e_cross_signing_verify_key(user_id, "user_signing")
  1032. except SynapseError as e:
  1033. failure = _exception_to_failure(e)
  1034. for user, devicemap in signatures.items():
  1035. failures[user] = {device_id: failure for device_id in devicemap.keys()}
  1036. return signature_list, failures
  1037. for target_user, devicemap in signatures.items():
  1038. # make sure submitted data is in the right form
  1039. if not isinstance(devicemap, dict):
  1040. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  1041. for device in devicemap.values():
  1042. if not isinstance(device, dict):
  1043. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  1044. device_id = None
  1045. try:
  1046. # get the target user's master key, to make sure it matches
  1047. # what was sent
  1048. (
  1049. master_key,
  1050. master_key_id,
  1051. _,
  1052. ) = await self._get_e2e_cross_signing_verify_key(
  1053. target_user, "master", user_id
  1054. )
  1055. # make sure that the target user's master key is the one that
  1056. # was signed (and no others)
  1057. device_id = master_key_id.split(":", 1)[1]
  1058. if device_id not in devicemap:
  1059. logger.debug(
  1060. "upload signature: could not find signature for device %s",
  1061. device_id,
  1062. )
  1063. # set device to None so that the failure gets
  1064. # marked on all the signatures
  1065. device_id = None
  1066. raise NotFoundError("Unknown device")
  1067. key = devicemap[device_id]
  1068. other_devices = [k for k in devicemap.keys() if k != device_id]
  1069. if other_devices:
  1070. # other devices were signed -- mark those as failures
  1071. logger.debug("upload signature: too many devices specified")
  1072. failure = _exception_to_failure(NotFoundError("Unknown device"))
  1073. failures[target_user] = {
  1074. device: failure for device in other_devices
  1075. }
  1076. if user_signing_key_id in master_key.get("signatures", {}).get(
  1077. user_id, {}
  1078. ):
  1079. # we already have the signature, so we can skip it
  1080. continue
  1081. _check_device_signature(
  1082. user_id, user_signing_verify_key, key, master_key
  1083. )
  1084. signature = key["signatures"][user_id][user_signing_key_id]
  1085. signature_list.append(
  1086. SignatureListItem(
  1087. user_signing_key_id, target_user, device_id, signature
  1088. )
  1089. )
  1090. except SynapseError as e:
  1091. failure = _exception_to_failure(e)
  1092. if device_id is None:
  1093. failures[target_user] = {
  1094. device_id: failure for device_id in devicemap.keys()
  1095. }
  1096. else:
  1097. failures.setdefault(target_user, {})[device_id] = failure
  1098. return signature_list, failures
  1099. async def _get_e2e_cross_signing_verify_key(
  1100. self, user_id: str, key_type: str, from_user_id: Optional[str] = None
  1101. ) -> Tuple[JsonMapping, str, VerifyKey]:
  1102. """Fetch locally or remotely query for a cross-signing public key.
  1103. First, attempt to fetch the cross-signing public key from storage.
  1104. If that fails, query the keys from the homeserver they belong to
  1105. and update our local copy.
  1106. Args:
  1107. user_id: the user whose key should be fetched
  1108. key_type: the type of key to fetch
  1109. from_user_id: the user that we are fetching the keys for.
  1110. This affects what signatures are fetched.
  1111. Returns:
  1112. The raw key data, the key ID, and the signedjson verify key
  1113. Raises:
  1114. NotFoundError: if the key is not found
  1115. SynapseError: if `user_id` is invalid
  1116. """
  1117. user = UserID.from_string(user_id)
  1118. key = await self.store.get_e2e_cross_signing_key(
  1119. user_id, key_type, from_user_id
  1120. )
  1121. if key:
  1122. # We found a copy of this key in our database. Decode and return it
  1123. key_id, verify_key = get_verify_key_from_cross_signing_key(key)
  1124. return key, key_id, verify_key
  1125. # If we couldn't find the key locally, and we're looking for keys of
  1126. # another user then attempt to fetch the missing key from the remote
  1127. # user's server.
  1128. #
  1129. # We may run into this in possible edge cases where a user tries to
  1130. # cross-sign a remote user, but does not share any rooms with them yet.
  1131. # Thus, we would not have their key list yet. We instead fetch the key,
  1132. # store it and notify clients of new, associated device IDs.
  1133. if self.is_mine(user) or key_type not in ["master", "self_signing"]:
  1134. # Note that master and self_signing keys are the only cross-signing keys we
  1135. # can request over federation
  1136. raise NotFoundError("No %s key found for %s" % (key_type, user_id))
  1137. cross_signing_keys = await self._retrieve_cross_signing_keys_for_remote_user(
  1138. user, key_type
  1139. )
  1140. if cross_signing_keys is None:
  1141. raise NotFoundError("No %s key found for %s" % (key_type, user_id))
  1142. return cross_signing_keys
  1143. async def _retrieve_cross_signing_keys_for_remote_user(
  1144. self,
  1145. user: UserID,
  1146. desired_key_type: str,
  1147. ) -> Optional[Tuple[JsonMapping, str, VerifyKey]]:
  1148. """Queries cross-signing keys for a remote user and saves them to the database
  1149. Only the key specified by `key_type` will be returned, while all retrieved keys
  1150. will be saved regardless
  1151. Args:
  1152. user: The user to query remote keys for
  1153. desired_key_type: The type of key to receive. One of "master", "self_signing"
  1154. Returns:
  1155. A tuple of the retrieved key content, the key's ID and the matching VerifyKey.
  1156. If the key cannot be retrieved, all values in the tuple will instead be None.
  1157. """
  1158. # This can only be called from the main process.
  1159. assert isinstance(self.device_handler, DeviceHandler)
  1160. try:
  1161. remote_result = await self.federation.query_user_devices(
  1162. user.domain, user.to_string()
  1163. )
  1164. except Exception as e:
  1165. logger.warning(
  1166. "Unable to query %s for cross-signing keys of user %s: %s %s",
  1167. user.domain,
  1168. user.to_string(),
  1169. type(e),
  1170. e,
  1171. )
  1172. return None
  1173. # Process each of the retrieved cross-signing keys
  1174. desired_key_data = None
  1175. retrieved_device_ids = []
  1176. for key_type in ["master", "self_signing"]:
  1177. key_content = remote_result.get(key_type + "_key")
  1178. if not key_content:
  1179. continue
  1180. # Ensure these keys belong to the correct user
  1181. if "user_id" not in key_content:
  1182. logger.warning(
  1183. "Invalid %s key retrieved, missing user_id field: %s",
  1184. key_type,
  1185. key_content,
  1186. )
  1187. continue
  1188. if user.to_string() != key_content["user_id"]:
  1189. logger.warning(
  1190. "Found %s key of user %s when querying for keys of user %s",
  1191. key_type,
  1192. key_content["user_id"],
  1193. user.to_string(),
  1194. )
  1195. continue
  1196. # Validate the key contents
  1197. try:
  1198. # verify_key is a VerifyKey from signedjson, which uses
  1199. # .version to denote the portion of the key ID after the
  1200. # algorithm and colon, which is the device ID
  1201. key_id, verify_key = get_verify_key_from_cross_signing_key(key_content)
  1202. except ValueError as e:
  1203. logger.warning(
  1204. "Invalid %s key retrieved: %s - %s %s",
  1205. key_type,
  1206. key_content,
  1207. type(e),
  1208. e,
  1209. )
  1210. continue
  1211. # Note down the device ID attached to this key
  1212. retrieved_device_ids.append(verify_key.version)
  1213. # If this is the desired key type, save it and its ID/VerifyKey
  1214. if key_type == desired_key_type:
  1215. desired_key_data = key_content, key_id, verify_key
  1216. # At the same time, store this key in the db for subsequent queries
  1217. await self.store.set_e2e_cross_signing_key(
  1218. user.to_string(), key_type, key_content
  1219. )
  1220. # Notify clients that new devices for this user have been discovered
  1221. if retrieved_device_ids:
  1222. # XXX is this necessary?
  1223. await self.device_handler.notify_device_update(
  1224. user.to_string(), retrieved_device_ids
  1225. )
  1226. return desired_key_data
  1227. async def is_cross_signing_set_up_for_user(self, user_id: str) -> bool:
  1228. """Checks if the user has cross-signing set up
  1229. Args:
  1230. user_id: The user to check
  1231. Returns:
  1232. True if the user has cross-signing set up, False otherwise
  1233. """
  1234. existing_master_key = await self.store.get_e2e_cross_signing_key(
  1235. user_id, "master"
  1236. )
  1237. return existing_master_key is not None
  1238. def _check_cross_signing_key(
  1239. key: JsonDict, user_id: str, key_type: str, signing_key: Optional[VerifyKey] = None
  1240. ) -> None:
  1241. """Check a cross-signing key uploaded by a user. Performs some basic sanity
  1242. checking, and ensures that it is signed, if a signature is required.
  1243. Args:
  1244. key: the key data to verify
  1245. user_id: the user whose key is being checked
  1246. key_type: the type of key that the key should be
  1247. signing_key: the signing key that the key should be signed with. If
  1248. omitted, signatures will not be checked.
  1249. """
  1250. if (
  1251. key.get("user_id") != user_id
  1252. or key_type not in key.get("usage", [])
  1253. or len(key.get("keys", {})) != 1
  1254. ):
  1255. raise SynapseError(400, ("Invalid %s key" % (key_type,)), Codes.INVALID_PARAM)
  1256. if signing_key:
  1257. try:
  1258. verify_signed_json(key, user_id, signing_key)
  1259. except SignatureVerifyException:
  1260. raise SynapseError(
  1261. 400, ("Invalid signature on %s key" % key_type), Codes.INVALID_SIGNATURE
  1262. )
  1263. def _check_device_signature(
  1264. user_id: str,
  1265. verify_key: VerifyKey,
  1266. signed_device: JsonDict,
  1267. stored_device: JsonMapping,
  1268. ) -> None:
  1269. """Check that a signature on a device or cross-signing key is correct and
  1270. matches the copy of the device/key that we have stored. Throws an
  1271. exception if an error is detected.
  1272. Args:
  1273. user_id: the user ID whose signature is being checked
  1274. verify_key: the key to verify the device with
  1275. signed_device: the uploaded signed device data
  1276. stored_device: our previously stored copy of the device
  1277. Raises:
  1278. SynapseError: if the signature was invalid or the sent device is not the
  1279. same as the stored device
  1280. """
  1281. # make sure that the device submitted matches what we have stored
  1282. stripped_signed_device = {
  1283. k: v for k, v in signed_device.items() if k not in ["signatures", "unsigned"]
  1284. }
  1285. stripped_stored_device = {
  1286. k: v for k, v in stored_device.items() if k not in ["signatures", "unsigned"]
  1287. }
  1288. if stripped_signed_device != stripped_stored_device:
  1289. logger.debug(
  1290. "upload signatures: key does not match %s vs %s",
  1291. signed_device,
  1292. stored_device,
  1293. )
  1294. raise SynapseError(400, "Key does not match")
  1295. try:
  1296. verify_signed_json(signed_device, user_id, verify_key)
  1297. except SignatureVerifyException:
  1298. logger.debug("invalid signature on key")
  1299. raise SynapseError(400, "Invalid signature", Codes.INVALID_SIGNATURE)
  1300. def _exception_to_failure(e: Exception) -> JsonDict:
  1301. if isinstance(e, SynapseError):
  1302. return {"status": e.code, "errcode": e.errcode, "message": str(e)}
  1303. if isinstance(e, CodeMessageException):
  1304. return {"status": e.code, "message": str(e)}
  1305. if isinstance(e, NotRetryingDestination):
  1306. return {"status": 503, "message": "Not ready for retry"}
  1307. # include ConnectionRefused and other errors
  1308. #
  1309. # Note that some Exceptions (notably twisted's ResponseFailed etc) don't
  1310. # give a string for e.message, which json then fails to serialize.
  1311. return {"status": 503, "message": str(e)}
  1312. def _one_time_keys_match(old_key_json: str, new_key: JsonDict) -> bool:
  1313. old_key = json_decoder.decode(old_key_json)
  1314. # if either is a string rather than an object, they must match exactly
  1315. if not isinstance(old_key, dict) or not isinstance(new_key, dict):
  1316. return old_key == new_key
  1317. # otherwise, we strip off the 'signatures' if any, because it's legitimate
  1318. # for different upload attempts to have different signatures.
  1319. old_key.pop("signatures", None)
  1320. new_key_copy = dict(new_key)
  1321. new_key_copy.pop("signatures", None)
  1322. return old_key == new_key_copy
  1323. @attr.s(slots=True, auto_attribs=True)
  1324. class SignatureListItem:
  1325. """An item in the signature list as used by upload_signatures_for_device_keys."""
  1326. signing_key_id: str
  1327. target_user_id: str
  1328. target_device_id: str
  1329. signature: JsonDict
  1330. class SigningKeyEduUpdater:
  1331. """Handles incoming signing key updates from federation and updates the DB"""
  1332. def __init__(self, hs: "HomeServer"):
  1333. self.store = hs.get_datastores().main
  1334. self.federation = hs.get_federation_client()
  1335. self.clock = hs.get_clock()
  1336. device_handler = hs.get_device_handler()
  1337. assert isinstance(device_handler, DeviceHandler)
  1338. self._device_handler = device_handler
  1339. self._remote_edu_linearizer = Linearizer(name="remote_signing_key")
  1340. # user_id -> list of updates waiting to be handled.
  1341. self._pending_updates: Dict[str, List[Tuple[JsonDict, JsonDict]]] = {}
  1342. async def incoming_signing_key_update(
  1343. self, origin: str, edu_content: JsonDict
  1344. ) -> None:
  1345. """Called on incoming signing key update from federation. Responsible for
  1346. parsing the EDU and adding to pending updates list.
  1347. Args:
  1348. origin: the server that sent the EDU
  1349. edu_content: the contents of the EDU
  1350. """
  1351. user_id = edu_content.pop("user_id")
  1352. master_key = edu_content.pop("master_key", None)
  1353. self_signing_key = edu_content.pop("self_signing_key", None)
  1354. if get_domain_from_id(user_id) != origin:
  1355. logger.warning("Got signing key update edu for %r from %r", user_id, origin)
  1356. return
  1357. room_ids = await self.store.get_rooms_for_user(user_id)
  1358. if not room_ids:
  1359. # We don't share any rooms with this user. Ignore update, as we
  1360. # probably won't get any further updates.
  1361. return
  1362. self._pending_updates.setdefault(user_id, []).append(
  1363. (master_key, self_signing_key)
  1364. )
  1365. await self._handle_signing_key_updates(user_id)
  1366. async def _handle_signing_key_updates(self, user_id: str) -> None:
  1367. """Actually handle pending updates.
  1368. Args:
  1369. user_id: the user whose updates we are processing
  1370. """
  1371. async with self._remote_edu_linearizer.queue(user_id):
  1372. pending_updates = self._pending_updates.pop(user_id, [])
  1373. if not pending_updates:
  1374. # This can happen since we batch updates
  1375. return
  1376. device_ids: List[str] = []
  1377. logger.info("pending updates: %r", pending_updates)
  1378. for master_key, self_signing_key in pending_updates:
  1379. new_device_ids = await self._device_handler.device_list_updater.process_cross_signing_key_update(
  1380. user_id,
  1381. master_key,
  1382. self_signing_key,
  1383. )
  1384. device_ids = device_ids + new_device_ids
  1385. await self._device_handler.notify_device_update(user_id, device_ids)