Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

1664 rader
67 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. if any(
  471. not self.is_mine(UserID.from_string(user_id))
  472. for user_id in device_keys_query
  473. ):
  474. raise SynapseError(400, "User is not hosted on this homeserver")
  475. res = await self.query_local_devices(
  476. device_keys_query,
  477. include_displaynames=(
  478. self.config.federation.allow_device_name_lookup_over_federation
  479. ),
  480. )
  481. # add in the cross-signing keys
  482. cross_signing_keys = await self.get_cross_signing_keys_from_cache(
  483. device_keys_query, None
  484. )
  485. return {"device_keys": res, **cross_signing_keys}
  486. async def claim_local_one_time_keys(
  487. self,
  488. local_query: List[Tuple[str, str, str, int]],
  489. always_include_fallback_keys: bool,
  490. ) -> Iterable[Dict[str, Dict[str, Dict[str, JsonDict]]]]:
  491. """Claim one time keys for local users.
  492. 1. Attempt to claim OTKs from the database.
  493. 2. Ask application services if they provide OTKs.
  494. 3. Attempt to fetch fallback keys from the database.
  495. Args:
  496. local_query: An iterable of tuples of (user ID, device ID, algorithm).
  497. always_include_fallback_keys: True to always include fallback keys.
  498. Returns:
  499. An iterable of maps of user ID -> a map device ID -> a map of key ID -> JSON bytes.
  500. """
  501. # Cap the number of OTKs that can be claimed at once to avoid abuse.
  502. local_query = [
  503. (user_id, device_id, algorithm, min(count, 5))
  504. for user_id, device_id, algorithm, count in local_query
  505. ]
  506. otk_results, not_found = await self.store.claim_e2e_one_time_keys(local_query)
  507. # If the application services have not provided any keys via the C-S
  508. # API, query it directly for one-time keys.
  509. if self._query_appservices_for_otks:
  510. # TODO Should this query for fallback keys of uploaded OTKs if
  511. # always_include_fallback_keys is True? The MSC is ambiguous.
  512. (
  513. appservice_results,
  514. not_found,
  515. ) = await self._appservice_handler.claim_e2e_one_time_keys(not_found)
  516. else:
  517. appservice_results = {}
  518. # Calculate which user ID / device ID / algorithm tuples to get fallback
  519. # keys for. This can be either only missing results *or* all results
  520. # (which don't already have a fallback key).
  521. if always_include_fallback_keys:
  522. # Build the fallback query as any part of the original query where
  523. # the appservice didn't respond with a fallback key.
  524. fallback_query = []
  525. # Iterate each item in the original query and search the results
  526. # from the appservice for that user ID / device ID. If it is found,
  527. # check if any of the keys match the requested algorithm & are a
  528. # fallback key.
  529. for user_id, device_id, algorithm, _count in local_query:
  530. # Check if the appservice responded for this query.
  531. as_result = appservice_results.get(user_id, {}).get(device_id, {})
  532. found_otk = False
  533. for key_id, key_json in as_result.items():
  534. if key_id.startswith(f"{algorithm}:"):
  535. # A OTK or fallback key was found for this query.
  536. found_otk = True
  537. # A fallback key was found for this query, no need to
  538. # query further.
  539. if key_json.get("fallback", False):
  540. break
  541. else:
  542. # No fallback key was found from appservices, query for it.
  543. # Only mark the fallback key as used if no OTK was found
  544. # (from either the database or appservices).
  545. mark_as_used = not found_otk and not any(
  546. key_id.startswith(f"{algorithm}:")
  547. for key_id in otk_results.get(user_id, {})
  548. .get(device_id, {})
  549. .keys()
  550. )
  551. # Note that it doesn't make sense to request more than 1 fallback key
  552. # per (user_id, device_id, algorithm).
  553. fallback_query.append((user_id, device_id, algorithm, mark_as_used))
  554. else:
  555. # All fallback keys get marked as used.
  556. fallback_query = [
  557. # Note that it doesn't make sense to request more than 1 fallback key
  558. # per (user_id, device_id, algorithm).
  559. (user_id, device_id, algorithm, True)
  560. for user_id, device_id, algorithm, count in not_found
  561. ]
  562. # For each user that does not have a one-time keys available, see if
  563. # there is a fallback key.
  564. fallback_results = await self.store.claim_e2e_fallback_keys(fallback_query)
  565. # Return the results in order, each item from the input query should
  566. # only appear once in the combined list.
  567. return (otk_results, appservice_results, fallback_results)
  568. @trace
  569. async def claim_one_time_keys(
  570. self,
  571. query: Dict[str, Dict[str, Dict[str, int]]],
  572. user: UserID,
  573. timeout: Optional[int],
  574. always_include_fallback_keys: bool,
  575. ) -> JsonDict:
  576. """
  577. Args:
  578. query: A chain of maps from (user_id, device_id, algorithm) to the requested
  579. number of keys to claim.
  580. user: The user who is claiming these keys.
  581. timeout: How long to wait for any federation key claim requests before
  582. giving up.
  583. always_include_fallback_keys: always include a fallback key for local users'
  584. devices, even if we managed to claim a one-time-key.
  585. Returns: a heterogeneous dict with two keys:
  586. one_time_keys: chain of maps user ID -> device ID -> key ID -> key.
  587. failures: map from remote destination to a JsonDict describing the error.
  588. """
  589. local_query: List[Tuple[str, str, str, int]] = []
  590. remote_queries: Dict[str, Dict[str, Dict[str, Dict[str, int]]]] = {}
  591. for user_id, one_time_keys in query.items():
  592. # we use UserID.from_string to catch invalid user ids
  593. if self.is_mine(UserID.from_string(user_id)):
  594. for device_id, algorithms in one_time_keys.items():
  595. for algorithm, count in algorithms.items():
  596. local_query.append((user_id, device_id, algorithm, count))
  597. else:
  598. domain = get_domain_from_id(user_id)
  599. remote_queries.setdefault(domain, {})[user_id] = one_time_keys
  600. set_tag("local_key_query", str(local_query))
  601. set_tag("remote_key_query", str(remote_queries))
  602. results = await self.claim_local_one_time_keys(
  603. local_query, always_include_fallback_keys
  604. )
  605. # A map of user ID -> device ID -> key ID -> key.
  606. json_result: Dict[str, Dict[str, Dict[str, JsonDict]]] = {}
  607. for result in results:
  608. for user_id, device_keys in result.items():
  609. for device_id, keys in device_keys.items():
  610. for key_id, key in keys.items():
  611. json_result.setdefault(user_id, {}).setdefault(
  612. device_id, {}
  613. ).update({key_id: key})
  614. # Remote failures.
  615. failures: Dict[str, JsonDict] = {}
  616. @trace
  617. async def claim_client_keys(destination: str) -> None:
  618. set_tag("destination", destination)
  619. device_keys = remote_queries[destination]
  620. try:
  621. remote_result = await self.federation.claim_client_keys(
  622. user, destination, device_keys, timeout=timeout
  623. )
  624. for user_id, keys in remote_result["one_time_keys"].items():
  625. if user_id in device_keys:
  626. json_result[user_id] = keys
  627. except Exception as e:
  628. failure = _exception_to_failure(e)
  629. failures[destination] = failure
  630. set_tag("error", True)
  631. set_tag("reason", str(failure))
  632. await make_deferred_yieldable(
  633. defer.gatherResults(
  634. [
  635. run_in_background(claim_client_keys, destination)
  636. for destination in remote_queries
  637. ],
  638. consumeErrors=True,
  639. )
  640. )
  641. logger.info(
  642. "Claimed one-time-keys: %s",
  643. ",".join(
  644. (
  645. "%s for %s:%s" % (key_id, user_id, device_id)
  646. for user_id, user_keys in json_result.items()
  647. for device_id, device_keys in user_keys.items()
  648. for key_id, _ in device_keys.items()
  649. )
  650. ),
  651. )
  652. log_kv({"one_time_keys": json_result, "failures": failures})
  653. return {"one_time_keys": json_result, "failures": failures}
  654. @tag_args
  655. async def upload_keys_for_user(
  656. self, user_id: str, device_id: str, keys: JsonDict
  657. ) -> JsonDict:
  658. """
  659. Args:
  660. user_id: user whose keys are being uploaded.
  661. device_id: device whose keys are being uploaded.
  662. keys: the body of a /keys/upload request.
  663. Returns a dictionary with one field:
  664. "one_time_keys": A mapping from algorithm to number of keys for that
  665. algorithm, including those previously persisted.
  666. """
  667. # This can only be called from the main process.
  668. assert isinstance(self.device_handler, DeviceHandler)
  669. time_now = self.clock.time_msec()
  670. # TODO: Validate the JSON to make sure it has the right keys.
  671. device_keys = keys.get("device_keys", None)
  672. if device_keys:
  673. logger.info(
  674. "Updating device_keys for device %r for user %s at %d",
  675. device_id,
  676. user_id,
  677. time_now,
  678. )
  679. log_kv(
  680. {
  681. "message": "Updating device_keys for user.",
  682. "user_id": user_id,
  683. "device_id": device_id,
  684. }
  685. )
  686. # TODO: Sign the JSON with the server key
  687. changed = await self.store.set_e2e_device_keys(
  688. user_id, device_id, time_now, device_keys
  689. )
  690. if changed:
  691. # Only notify about device updates *if* the keys actually changed
  692. await self.device_handler.notify_device_update(user_id, [device_id])
  693. else:
  694. log_kv({"message": "Not updating device_keys for user", "user_id": user_id})
  695. one_time_keys = keys.get("one_time_keys", None)
  696. if one_time_keys:
  697. log_kv(
  698. {
  699. "message": "Updating one_time_keys for device.",
  700. "user_id": user_id,
  701. "device_id": device_id,
  702. }
  703. )
  704. await self._upload_one_time_keys_for_user(
  705. user_id, device_id, time_now, one_time_keys
  706. )
  707. else:
  708. log_kv(
  709. {"message": "Did not update one_time_keys", "reason": "no keys given"}
  710. )
  711. fallback_keys = keys.get("fallback_keys") or keys.get(
  712. "org.matrix.msc2732.fallback_keys"
  713. )
  714. if fallback_keys and isinstance(fallback_keys, dict):
  715. log_kv(
  716. {
  717. "message": "Updating fallback_keys for device.",
  718. "user_id": user_id,
  719. "device_id": device_id,
  720. }
  721. )
  722. await self.store.set_e2e_fallback_keys(user_id, device_id, fallback_keys)
  723. elif fallback_keys:
  724. log_kv({"message": "Did not update fallback_keys", "reason": "not a dict"})
  725. else:
  726. log_kv(
  727. {"message": "Did not update fallback_keys", "reason": "no keys given"}
  728. )
  729. # the device should have been registered already, but it may have been
  730. # deleted due to a race with a DELETE request. Or we may be using an
  731. # old access_token without an associated device_id. Either way, we
  732. # need to double-check the device is registered to avoid ending up with
  733. # keys without a corresponding device.
  734. await self.device_handler.check_device_registered(user_id, device_id)
  735. result = await self.store.count_e2e_one_time_keys(user_id, device_id)
  736. set_tag("one_time_key_counts", str(result))
  737. return {"one_time_key_counts": result}
  738. async def _upload_one_time_keys_for_user(
  739. self, user_id: str, device_id: str, time_now: int, one_time_keys: JsonDict
  740. ) -> None:
  741. logger.info(
  742. "Adding one_time_keys %r for device %r for user %r at %d",
  743. one_time_keys.keys(),
  744. device_id,
  745. user_id,
  746. time_now,
  747. )
  748. # make a list of (alg, id, key) tuples
  749. key_list = []
  750. for key_id, key_obj in one_time_keys.items():
  751. algorithm, key_id = key_id.split(":")
  752. key_list.append((algorithm, key_id, key_obj))
  753. # First we check if we have already persisted any of the keys.
  754. existing_key_map = await self.store.get_e2e_one_time_keys(
  755. user_id, device_id, [k_id for _, k_id, _ in key_list]
  756. )
  757. new_keys = [] # Keys that we need to insert. (alg, id, json) tuples.
  758. for algorithm, key_id, key in key_list:
  759. ex_json = existing_key_map.get((algorithm, key_id), None)
  760. if ex_json:
  761. if not _one_time_keys_match(ex_json, key):
  762. raise SynapseError(
  763. 400,
  764. (
  765. "One time key %s:%s already exists. "
  766. "Old key: %s; new key: %r"
  767. )
  768. % (algorithm, key_id, ex_json, key),
  769. )
  770. else:
  771. new_keys.append(
  772. (algorithm, key_id, encode_canonical_json(key).decode("ascii"))
  773. )
  774. log_kv({"message": "Inserting new one_time_keys.", "keys": new_keys})
  775. await self.store.add_e2e_one_time_keys(user_id, device_id, time_now, new_keys)
  776. async def upload_signing_keys_for_user(
  777. self, user_id: str, keys: JsonDict
  778. ) -> JsonDict:
  779. """Upload signing keys for cross-signing
  780. Args:
  781. user_id: the user uploading the keys
  782. keys: the signing keys
  783. """
  784. # This can only be called from the main process.
  785. assert isinstance(self.device_handler, DeviceHandler)
  786. # if a master key is uploaded, then check it. Otherwise, load the
  787. # stored master key, to check signatures on other keys
  788. if "master_key" in keys:
  789. master_key = keys["master_key"]
  790. _check_cross_signing_key(master_key, user_id, "master")
  791. else:
  792. master_key = await self.store.get_e2e_cross_signing_key(user_id, "master")
  793. # if there is no master key, then we can't do anything, because all the
  794. # other cross-signing keys need to be signed by the master key
  795. if not master_key:
  796. raise SynapseError(400, "No master key available", Codes.MISSING_PARAM)
  797. try:
  798. master_key_id, master_verify_key = get_verify_key_from_cross_signing_key(
  799. master_key
  800. )
  801. except ValueError:
  802. if "master_key" in keys:
  803. # the invalid key came from the request
  804. raise SynapseError(400, "Invalid master key", Codes.INVALID_PARAM)
  805. else:
  806. # the invalid key came from the database
  807. logger.error("Invalid master key found for user %s", user_id)
  808. raise SynapseError(500, "Invalid master key")
  809. # for the other cross-signing keys, make sure that they have valid
  810. # signatures from the master key
  811. if "self_signing_key" in keys:
  812. self_signing_key = keys["self_signing_key"]
  813. _check_cross_signing_key(
  814. self_signing_key, user_id, "self_signing", master_verify_key
  815. )
  816. if "user_signing_key" in keys:
  817. user_signing_key = keys["user_signing_key"]
  818. _check_cross_signing_key(
  819. user_signing_key, user_id, "user_signing", master_verify_key
  820. )
  821. # if everything checks out, then store the keys and send notifications
  822. deviceids = []
  823. if "master_key" in keys:
  824. await self.store.set_e2e_cross_signing_key(user_id, "master", master_key)
  825. deviceids.append(master_verify_key.version)
  826. if "self_signing_key" in keys:
  827. await self.store.set_e2e_cross_signing_key(
  828. user_id, "self_signing", self_signing_key
  829. )
  830. try:
  831. deviceids.append(
  832. get_verify_key_from_cross_signing_key(self_signing_key)[1].version
  833. )
  834. except ValueError:
  835. raise SynapseError(400, "Invalid self-signing key", Codes.INVALID_PARAM)
  836. if "user_signing_key" in keys:
  837. await self.store.set_e2e_cross_signing_key(
  838. user_id, "user_signing", user_signing_key
  839. )
  840. # the signature stream matches the semantics that we want for
  841. # user-signing key updates: only the user themselves is notified of
  842. # their own user-signing key updates
  843. await self.device_handler.notify_user_signature_update(user_id, [user_id])
  844. # master key and self-signing key updates match the semantics of device
  845. # list updates: all users who share an encrypted room are notified
  846. if len(deviceids):
  847. await self.device_handler.notify_device_update(user_id, deviceids)
  848. return {}
  849. async def upload_signatures_for_device_keys(
  850. self, user_id: str, signatures: JsonDict
  851. ) -> JsonDict:
  852. """Upload device signatures for cross-signing
  853. Args:
  854. user_id: the user uploading the signatures
  855. signatures: map of users to devices to signed keys. This is the submission
  856. from the user; an exception will be raised if it is malformed.
  857. Returns:
  858. The response to be sent back to the client. The response will have
  859. a "failures" key, which will be a dict mapping users to devices
  860. to errors for the signatures that failed.
  861. Raises:
  862. SynapseError: if the signatures dict is not valid.
  863. """
  864. # This can only be called from the main process.
  865. assert isinstance(self.device_handler, DeviceHandler)
  866. failures = {}
  867. # signatures to be stored. Each item will be a SignatureListItem
  868. signature_list = []
  869. # split between checking signatures for own user and signatures for
  870. # other users, since we verify them with different keys
  871. self_signatures = signatures.get(user_id, {})
  872. other_signatures = {k: v for k, v in signatures.items() if k != user_id}
  873. self_signature_list, self_failures = await self._process_self_signatures(
  874. user_id, self_signatures
  875. )
  876. signature_list.extend(self_signature_list)
  877. failures.update(self_failures)
  878. other_signature_list, other_failures = await self._process_other_signatures(
  879. user_id, other_signatures
  880. )
  881. signature_list.extend(other_signature_list)
  882. failures.update(other_failures)
  883. # store the signature, and send the appropriate notifications for sync
  884. logger.debug("upload signature failures: %r", failures)
  885. await self.store.store_e2e_cross_signing_signatures(user_id, signature_list)
  886. self_device_ids = [item.target_device_id for item in self_signature_list]
  887. if self_device_ids:
  888. await self.device_handler.notify_device_update(user_id, self_device_ids)
  889. signed_users = [item.target_user_id for item in other_signature_list]
  890. if signed_users:
  891. await self.device_handler.notify_user_signature_update(
  892. user_id, signed_users
  893. )
  894. return {"failures": failures}
  895. async def _process_self_signatures(
  896. self, user_id: str, signatures: JsonDict
  897. ) -> Tuple[List["SignatureListItem"], Dict[str, Dict[str, dict]]]:
  898. """Process uploaded signatures of the user's own keys.
  899. Signatures of the user's own keys from this API come in two forms:
  900. - signatures of the user's devices by the user's self-signing key,
  901. - signatures of the user's master key by the user's devices.
  902. Args:
  903. user_id: the user uploading the keys
  904. signatures (dict[string, dict]): map of devices to signed keys
  905. Returns:
  906. A tuple of a list of signatures to store, and a map of users to
  907. devices to failure reasons
  908. Raises:
  909. SynapseError: if the input is malformed
  910. """
  911. signature_list: List["SignatureListItem"] = []
  912. failures: Dict[str, Dict[str, JsonDict]] = {}
  913. if not signatures:
  914. return signature_list, failures
  915. if not isinstance(signatures, dict):
  916. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  917. try:
  918. # get our self-signing key to verify the signatures
  919. (
  920. _,
  921. self_signing_key_id,
  922. self_signing_verify_key,
  923. ) = await self._get_e2e_cross_signing_verify_key(user_id, "self_signing")
  924. # get our master key, since we may have received a signature of it.
  925. # We need to fetch it here so that we know what its key ID is, so
  926. # that we can check if a signature that was sent is a signature of
  927. # the master key or of a device
  928. (
  929. master_key,
  930. _,
  931. master_verify_key,
  932. ) = await self._get_e2e_cross_signing_verify_key(user_id, "master")
  933. # fetch our stored devices. This is used to 1. verify
  934. # signatures on the master key, and 2. to compare with what
  935. # was sent if the device was signed
  936. devices = await self.store.get_e2e_device_keys_for_cs_api([(user_id, None)])
  937. if user_id not in devices:
  938. raise NotFoundError("No device keys found")
  939. devices = devices[user_id]
  940. except SynapseError as e:
  941. failure = _exception_to_failure(e)
  942. failures[user_id] = {device: failure for device in signatures.keys()}
  943. return signature_list, failures
  944. for device_id, device in signatures.items():
  945. # make sure submitted data is in the right form
  946. if not isinstance(device, dict):
  947. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  948. try:
  949. if "signatures" not in device or user_id not in device["signatures"]:
  950. # no signature was sent
  951. raise SynapseError(
  952. 400, "Invalid signature", Codes.INVALID_SIGNATURE
  953. )
  954. if device_id == master_verify_key.version:
  955. # The signature is of the master key. This needs to be
  956. # handled differently from signatures of normal devices.
  957. master_key_signature_list = self._check_master_key_signature(
  958. user_id, device_id, device, master_key, devices
  959. )
  960. signature_list.extend(master_key_signature_list)
  961. continue
  962. # at this point, we have a device that should be signed
  963. # by the self-signing key
  964. if self_signing_key_id not in device["signatures"][user_id]:
  965. # no signature was sent
  966. raise SynapseError(
  967. 400, "Invalid signature", Codes.INVALID_SIGNATURE
  968. )
  969. try:
  970. stored_device = devices[device_id]
  971. except KeyError:
  972. raise NotFoundError("Unknown device")
  973. if self_signing_key_id in stored_device.get("signatures", {}).get(
  974. user_id, {}
  975. ):
  976. # we already have a signature on this device, so we
  977. # can skip it, since it should be exactly the same
  978. continue
  979. _check_device_signature(
  980. user_id, self_signing_verify_key, device, stored_device
  981. )
  982. signature = device["signatures"][user_id][self_signing_key_id]
  983. signature_list.append(
  984. SignatureListItem(
  985. self_signing_key_id, user_id, device_id, signature
  986. )
  987. )
  988. except SynapseError as e:
  989. failures.setdefault(user_id, {})[device_id] = _exception_to_failure(e)
  990. return signature_list, failures
  991. def _check_master_key_signature(
  992. self,
  993. user_id: str,
  994. master_key_id: str,
  995. signed_master_key: JsonDict,
  996. stored_master_key: JsonMapping,
  997. devices: Dict[str, Dict[str, JsonDict]],
  998. ) -> List["SignatureListItem"]:
  999. """Check signatures of a user's master key made by their devices.
  1000. Args:
  1001. user_id: the user whose master key is being checked
  1002. master_key_id: the ID of the user's master key
  1003. signed_master_key: the user's signed master key that was uploaded
  1004. stored_master_key: our previously-stored copy of the user's master key
  1005. devices: the user's devices
  1006. Returns:
  1007. A list of signatures to store
  1008. Raises:
  1009. SynapseError: if a signature is invalid
  1010. """
  1011. # for each device that signed the master key, check the signature.
  1012. master_key_signature_list = []
  1013. sigs = signed_master_key["signatures"]
  1014. for signing_key_id, signature in sigs[user_id].items():
  1015. _, signing_device_id = signing_key_id.split(":", 1)
  1016. if (
  1017. signing_device_id not in devices
  1018. or signing_key_id not in devices[signing_device_id]["keys"]
  1019. ):
  1020. # signed by an unknown device, or the
  1021. # device does not have the key
  1022. raise SynapseError(400, "Invalid signature", Codes.INVALID_SIGNATURE)
  1023. # get the key and check the signature
  1024. pubkey = devices[signing_device_id]["keys"][signing_key_id]
  1025. verify_key = decode_verify_key_bytes(signing_key_id, decode_base64(pubkey))
  1026. _check_device_signature(
  1027. user_id, verify_key, signed_master_key, stored_master_key
  1028. )
  1029. master_key_signature_list.append(
  1030. SignatureListItem(signing_key_id, user_id, master_key_id, signature)
  1031. )
  1032. return master_key_signature_list
  1033. async def _process_other_signatures(
  1034. self, user_id: str, signatures: Dict[str, dict]
  1035. ) -> Tuple[List["SignatureListItem"], Dict[str, Dict[str, dict]]]:
  1036. """Process uploaded signatures of other users' keys. These will be the
  1037. target user's master keys, signed by the uploading user's user-signing
  1038. key.
  1039. Args:
  1040. user_id: the user uploading the keys
  1041. signatures: map of users to devices to signed keys
  1042. Returns:
  1043. A list of signatures to store, and a map of users to devices to failure
  1044. reasons
  1045. Raises:
  1046. SynapseError: if the input is malformed
  1047. """
  1048. signature_list: List["SignatureListItem"] = []
  1049. failures: Dict[str, Dict[str, JsonDict]] = {}
  1050. if not signatures:
  1051. return signature_list, failures
  1052. try:
  1053. # get our user-signing key to verify the signatures
  1054. (
  1055. user_signing_key,
  1056. user_signing_key_id,
  1057. user_signing_verify_key,
  1058. ) = await self._get_e2e_cross_signing_verify_key(user_id, "user_signing")
  1059. except SynapseError as e:
  1060. failure = _exception_to_failure(e)
  1061. for user, devicemap in signatures.items():
  1062. failures[user] = {device_id: failure for device_id in devicemap.keys()}
  1063. return signature_list, failures
  1064. for target_user, devicemap in signatures.items():
  1065. # make sure submitted data is in the right form
  1066. if not isinstance(devicemap, dict):
  1067. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  1068. for device in devicemap.values():
  1069. if not isinstance(device, dict):
  1070. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  1071. device_id = None
  1072. try:
  1073. # get the target user's master key, to make sure it matches
  1074. # what was sent
  1075. (
  1076. master_key,
  1077. master_key_id,
  1078. _,
  1079. ) = await self._get_e2e_cross_signing_verify_key(
  1080. target_user, "master", user_id
  1081. )
  1082. # make sure that the target user's master key is the one that
  1083. # was signed (and no others)
  1084. device_id = master_key_id.split(":", 1)[1]
  1085. if device_id not in devicemap:
  1086. logger.debug(
  1087. "upload signature: could not find signature for device %s",
  1088. device_id,
  1089. )
  1090. # set device to None so that the failure gets
  1091. # marked on all the signatures
  1092. device_id = None
  1093. raise NotFoundError("Unknown device")
  1094. key = devicemap[device_id]
  1095. other_devices = [k for k in devicemap.keys() if k != device_id]
  1096. if other_devices:
  1097. # other devices were signed -- mark those as failures
  1098. logger.debug("upload signature: too many devices specified")
  1099. failure = _exception_to_failure(NotFoundError("Unknown device"))
  1100. failures[target_user] = {
  1101. device: failure for device in other_devices
  1102. }
  1103. if user_signing_key_id in master_key.get("signatures", {}).get(
  1104. user_id, {}
  1105. ):
  1106. # we already have the signature, so we can skip it
  1107. continue
  1108. _check_device_signature(
  1109. user_id, user_signing_verify_key, key, master_key
  1110. )
  1111. signature = key["signatures"][user_id][user_signing_key_id]
  1112. signature_list.append(
  1113. SignatureListItem(
  1114. user_signing_key_id, target_user, device_id, signature
  1115. )
  1116. )
  1117. except SynapseError as e:
  1118. failure = _exception_to_failure(e)
  1119. if device_id is None:
  1120. failures[target_user] = {
  1121. device_id: failure for device_id in devicemap.keys()
  1122. }
  1123. else:
  1124. failures.setdefault(target_user, {})[device_id] = failure
  1125. return signature_list, failures
  1126. async def _get_e2e_cross_signing_verify_key(
  1127. self, user_id: str, key_type: str, from_user_id: Optional[str] = None
  1128. ) -> Tuple[JsonMapping, str, VerifyKey]:
  1129. """Fetch locally or remotely query for a cross-signing public key.
  1130. First, attempt to fetch the cross-signing public key from storage.
  1131. If that fails, query the keys from the homeserver they belong to
  1132. and update our local copy.
  1133. Args:
  1134. user_id: the user whose key should be fetched
  1135. key_type: the type of key to fetch
  1136. from_user_id: the user that we are fetching the keys for.
  1137. This affects what signatures are fetched.
  1138. Returns:
  1139. The raw key data, the key ID, and the signedjson verify key
  1140. Raises:
  1141. NotFoundError: if the key is not found
  1142. SynapseError: if `user_id` is invalid
  1143. """
  1144. user = UserID.from_string(user_id)
  1145. key = await self.store.get_e2e_cross_signing_key(
  1146. user_id, key_type, from_user_id
  1147. )
  1148. if key:
  1149. # We found a copy of this key in our database. Decode and return it
  1150. key_id, verify_key = get_verify_key_from_cross_signing_key(key)
  1151. return key, key_id, verify_key
  1152. # If we couldn't find the key locally, and we're looking for keys of
  1153. # another user then attempt to fetch the missing key from the remote
  1154. # user's server.
  1155. #
  1156. # We may run into this in possible edge cases where a user tries to
  1157. # cross-sign a remote user, but does not share any rooms with them yet.
  1158. # Thus, we would not have their key list yet. We instead fetch the key,
  1159. # store it and notify clients of new, associated device IDs.
  1160. if self.is_mine(user) or key_type not in ["master", "self_signing"]:
  1161. # Note that master and self_signing keys are the only cross-signing keys we
  1162. # can request over federation
  1163. raise NotFoundError("No %s key found for %s" % (key_type, user_id))
  1164. cross_signing_keys = await self._retrieve_cross_signing_keys_for_remote_user(
  1165. user, key_type
  1166. )
  1167. if cross_signing_keys is None:
  1168. raise NotFoundError("No %s key found for %s" % (key_type, user_id))
  1169. return cross_signing_keys
  1170. async def _retrieve_cross_signing_keys_for_remote_user(
  1171. self,
  1172. user: UserID,
  1173. desired_key_type: str,
  1174. ) -> Optional[Tuple[JsonMapping, str, VerifyKey]]:
  1175. """Queries cross-signing keys for a remote user and saves them to the database
  1176. Only the key specified by `key_type` will be returned, while all retrieved keys
  1177. will be saved regardless
  1178. Args:
  1179. user: The user to query remote keys for
  1180. desired_key_type: The type of key to receive. One of "master", "self_signing"
  1181. Returns:
  1182. A tuple of the retrieved key content, the key's ID and the matching VerifyKey.
  1183. If the key cannot be retrieved, all values in the tuple will instead be None.
  1184. """
  1185. # This can only be called from the main process.
  1186. assert isinstance(self.device_handler, DeviceHandler)
  1187. try:
  1188. remote_result = await self.federation.query_user_devices(
  1189. user.domain, user.to_string()
  1190. )
  1191. except Exception as e:
  1192. logger.warning(
  1193. "Unable to query %s for cross-signing keys of user %s: %s %s",
  1194. user.domain,
  1195. user.to_string(),
  1196. type(e),
  1197. e,
  1198. )
  1199. return None
  1200. # Process each of the retrieved cross-signing keys
  1201. desired_key_data = None
  1202. retrieved_device_ids = []
  1203. for key_type in ["master", "self_signing"]:
  1204. key_content = remote_result.get(key_type + "_key")
  1205. if not key_content:
  1206. continue
  1207. # Ensure these keys belong to the correct user
  1208. if "user_id" not in key_content:
  1209. logger.warning(
  1210. "Invalid %s key retrieved, missing user_id field: %s",
  1211. key_type,
  1212. key_content,
  1213. )
  1214. continue
  1215. if user.to_string() != key_content["user_id"]:
  1216. logger.warning(
  1217. "Found %s key of user %s when querying for keys of user %s",
  1218. key_type,
  1219. key_content["user_id"],
  1220. user.to_string(),
  1221. )
  1222. continue
  1223. # Validate the key contents
  1224. try:
  1225. # verify_key is a VerifyKey from signedjson, which uses
  1226. # .version to denote the portion of the key ID after the
  1227. # algorithm and colon, which is the device ID
  1228. key_id, verify_key = get_verify_key_from_cross_signing_key(key_content)
  1229. except ValueError as e:
  1230. logger.warning(
  1231. "Invalid %s key retrieved: %s - %s %s",
  1232. key_type,
  1233. key_content,
  1234. type(e),
  1235. e,
  1236. )
  1237. continue
  1238. # Note down the device ID attached to this key
  1239. retrieved_device_ids.append(verify_key.version)
  1240. # If this is the desired key type, save it and its ID/VerifyKey
  1241. if key_type == desired_key_type:
  1242. desired_key_data = key_content, key_id, verify_key
  1243. # At the same time, store this key in the db for subsequent queries
  1244. await self.store.set_e2e_cross_signing_key(
  1245. user.to_string(), key_type, key_content
  1246. )
  1247. # Notify clients that new devices for this user have been discovered
  1248. if retrieved_device_ids:
  1249. # XXX is this necessary?
  1250. await self.device_handler.notify_device_update(
  1251. user.to_string(), retrieved_device_ids
  1252. )
  1253. return desired_key_data
  1254. async def check_cross_signing_setup(self, user_id: str) -> Tuple[bool, bool]:
  1255. """Checks if the user has cross-signing set up
  1256. Args:
  1257. user_id: The user to check
  1258. Returns: a 2-tuple of booleans
  1259. - whether the user has cross-signing set up, and
  1260. - whether the user's master cross-signing key may be replaced without UIA.
  1261. """
  1262. (
  1263. exists,
  1264. ts_replacable_without_uia_before,
  1265. ) = await self.store.get_master_cross_signing_key_updatable_before(user_id)
  1266. if ts_replacable_without_uia_before is None:
  1267. return exists, False
  1268. else:
  1269. return exists, self.clock.time_msec() < ts_replacable_without_uia_before
  1270. def _check_cross_signing_key(
  1271. key: JsonDict, user_id: str, key_type: str, signing_key: Optional[VerifyKey] = None
  1272. ) -> None:
  1273. """Check a cross-signing key uploaded by a user. Performs some basic sanity
  1274. checking, and ensures that it is signed, if a signature is required.
  1275. Args:
  1276. key: the key data to verify
  1277. user_id: the user whose key is being checked
  1278. key_type: the type of key that the key should be
  1279. signing_key: the signing key that the key should be signed with. If
  1280. omitted, signatures will not be checked.
  1281. """
  1282. if (
  1283. key.get("user_id") != user_id
  1284. or key_type not in key.get("usage", [])
  1285. or len(key.get("keys", {})) != 1
  1286. ):
  1287. raise SynapseError(400, ("Invalid %s key" % (key_type,)), Codes.INVALID_PARAM)
  1288. if signing_key:
  1289. try:
  1290. verify_signed_json(key, user_id, signing_key)
  1291. except SignatureVerifyException:
  1292. raise SynapseError(
  1293. 400, ("Invalid signature on %s key" % key_type), Codes.INVALID_SIGNATURE
  1294. )
  1295. def _check_device_signature(
  1296. user_id: str,
  1297. verify_key: VerifyKey,
  1298. signed_device: JsonDict,
  1299. stored_device: JsonMapping,
  1300. ) -> None:
  1301. """Check that a signature on a device or cross-signing key is correct and
  1302. matches the copy of the device/key that we have stored. Throws an
  1303. exception if an error is detected.
  1304. Args:
  1305. user_id: the user ID whose signature is being checked
  1306. verify_key: the key to verify the device with
  1307. signed_device: the uploaded signed device data
  1308. stored_device: our previously stored copy of the device
  1309. Raises:
  1310. SynapseError: if the signature was invalid or the sent device is not the
  1311. same as the stored device
  1312. """
  1313. # make sure that the device submitted matches what we have stored
  1314. stripped_signed_device = {
  1315. k: v for k, v in signed_device.items() if k not in ["signatures", "unsigned"]
  1316. }
  1317. stripped_stored_device = {
  1318. k: v for k, v in stored_device.items() if k not in ["signatures", "unsigned"]
  1319. }
  1320. if stripped_signed_device != stripped_stored_device:
  1321. logger.debug(
  1322. "upload signatures: key does not match %s vs %s",
  1323. signed_device,
  1324. stored_device,
  1325. )
  1326. raise SynapseError(400, "Key does not match")
  1327. try:
  1328. verify_signed_json(signed_device, user_id, verify_key)
  1329. except SignatureVerifyException:
  1330. logger.debug("invalid signature on key")
  1331. raise SynapseError(400, "Invalid signature", Codes.INVALID_SIGNATURE)
  1332. def _exception_to_failure(e: Exception) -> JsonDict:
  1333. if isinstance(e, SynapseError):
  1334. return {"status": e.code, "errcode": e.errcode, "message": str(e)}
  1335. if isinstance(e, CodeMessageException):
  1336. return {"status": e.code, "message": str(e)}
  1337. if isinstance(e, NotRetryingDestination):
  1338. return {"status": 503, "message": "Not ready for retry"}
  1339. # include ConnectionRefused and other errors
  1340. #
  1341. # Note that some Exceptions (notably twisted's ResponseFailed etc) don't
  1342. # give a string for e.message, which json then fails to serialize.
  1343. return {"status": 503, "message": str(e)}
  1344. def _one_time_keys_match(old_key_json: str, new_key: JsonDict) -> bool:
  1345. old_key = json_decoder.decode(old_key_json)
  1346. # if either is a string rather than an object, they must match exactly
  1347. if not isinstance(old_key, dict) or not isinstance(new_key, dict):
  1348. return old_key == new_key
  1349. # otherwise, we strip off the 'signatures' if any, because it's legitimate
  1350. # for different upload attempts to have different signatures.
  1351. old_key.pop("signatures", None)
  1352. new_key_copy = dict(new_key)
  1353. new_key_copy.pop("signatures", None)
  1354. return old_key == new_key_copy
  1355. @attr.s(slots=True, auto_attribs=True)
  1356. class SignatureListItem:
  1357. """An item in the signature list as used by upload_signatures_for_device_keys."""
  1358. signing_key_id: str
  1359. target_user_id: str
  1360. target_device_id: str
  1361. signature: JsonDict
  1362. class SigningKeyEduUpdater:
  1363. """Handles incoming signing key updates from federation and updates the DB"""
  1364. def __init__(self, hs: "HomeServer"):
  1365. self.store = hs.get_datastores().main
  1366. self.federation = hs.get_federation_client()
  1367. self.clock = hs.get_clock()
  1368. device_handler = hs.get_device_handler()
  1369. assert isinstance(device_handler, DeviceHandler)
  1370. self._device_handler = device_handler
  1371. self._remote_edu_linearizer = Linearizer(name="remote_signing_key")
  1372. # user_id -> list of updates waiting to be handled.
  1373. self._pending_updates: Dict[str, List[Tuple[JsonDict, JsonDict]]] = {}
  1374. async def incoming_signing_key_update(
  1375. self, origin: str, edu_content: JsonDict
  1376. ) -> None:
  1377. """Called on incoming signing key update from federation. Responsible for
  1378. parsing the EDU and adding to pending updates list.
  1379. Args:
  1380. origin: the server that sent the EDU
  1381. edu_content: the contents of the EDU
  1382. """
  1383. user_id = edu_content.pop("user_id")
  1384. master_key = edu_content.pop("master_key", None)
  1385. self_signing_key = edu_content.pop("self_signing_key", None)
  1386. if get_domain_from_id(user_id) != origin:
  1387. logger.warning("Got signing key update edu for %r from %r", user_id, origin)
  1388. return
  1389. room_ids = await self.store.get_rooms_for_user(user_id)
  1390. if not room_ids:
  1391. # We don't share any rooms with this user. Ignore update, as we
  1392. # probably won't get any further updates.
  1393. return
  1394. self._pending_updates.setdefault(user_id, []).append(
  1395. (master_key, self_signing_key)
  1396. )
  1397. await self._handle_signing_key_updates(user_id)
  1398. async def _handle_signing_key_updates(self, user_id: str) -> None:
  1399. """Actually handle pending updates.
  1400. Args:
  1401. user_id: the user whose updates we are processing
  1402. """
  1403. async with self._remote_edu_linearizer.queue(user_id):
  1404. pending_updates = self._pending_updates.pop(user_id, [])
  1405. if not pending_updates:
  1406. # This can happen since we batch updates
  1407. return
  1408. device_ids: List[str] = []
  1409. logger.info("pending updates: %r", pending_updates)
  1410. for master_key, self_signing_key in pending_updates:
  1411. new_device_ids = await self._device_handler.device_list_updater.process_cross_signing_key_update(
  1412. user_id,
  1413. master_key,
  1414. self_signing_key,
  1415. )
  1416. device_ids = device_ids + new_device_ids
  1417. await self._device_handler.notify_device_update(user_id, device_ids)