Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

1296 linhas
50 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 OpenMarket Ltd
  3. # Copyright 2018-2019 New Vector Ltd
  4. # Copyright 2019 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import logging
  18. from typing import Dict, List, Optional, Tuple
  19. import attr
  20. from canonicaljson import encode_canonical_json, json
  21. from signedjson.key import VerifyKey, decode_verify_key_bytes
  22. from signedjson.sign import SignatureVerifyException, verify_signed_json
  23. from unpaddedbase64 import decode_base64
  24. from twisted.internet import defer
  25. from synapse.api.errors import CodeMessageException, Codes, NotFoundError, SynapseError
  26. from synapse.logging.context import make_deferred_yieldable, run_in_background
  27. from synapse.logging.opentracing import log_kv, set_tag, tag_args, trace
  28. from synapse.replication.http.devices import ReplicationUserDevicesResyncRestServlet
  29. from synapse.types import (
  30. UserID,
  31. get_domain_from_id,
  32. get_verify_key_from_cross_signing_key,
  33. )
  34. from synapse.util import unwrapFirstError
  35. from synapse.util.async_helpers import Linearizer
  36. from synapse.util.caches.expiringcache import ExpiringCache
  37. from synapse.util.retryutils import NotRetryingDestination
  38. logger = logging.getLogger(__name__)
  39. class E2eKeysHandler(object):
  40. def __init__(self, hs):
  41. self.store = hs.get_datastore()
  42. self.federation = hs.get_federation_client()
  43. self.device_handler = hs.get_device_handler()
  44. self.is_mine = hs.is_mine
  45. self.clock = hs.get_clock()
  46. self._edu_updater = SigningKeyEduUpdater(hs, self)
  47. federation_registry = hs.get_federation_registry()
  48. self._is_master = hs.config.worker_app is None
  49. if not self._is_master:
  50. self._user_device_resync_client = ReplicationUserDevicesResyncRestServlet.make_client(
  51. hs
  52. )
  53. else:
  54. # Only register this edu handler on master as it requires writing
  55. # device updates to the db
  56. #
  57. # FIXME: switch to m.signing_key_update when MSC1756 is merged into the spec
  58. federation_registry.register_edu_handler(
  59. "org.matrix.signing_key_update",
  60. self._edu_updater.incoming_signing_key_update,
  61. )
  62. # doesn't really work as part of the generic query API, because the
  63. # query request requires an object POST, but we abuse the
  64. # "query handler" interface.
  65. federation_registry.register_query_handler(
  66. "client_keys", self.on_federation_query_client_keys
  67. )
  68. @trace
  69. async def query_devices(self, query_body, timeout, from_user_id):
  70. """ Handle a device key query from a client
  71. {
  72. "device_keys": {
  73. "<user_id>": ["<device_id>"]
  74. }
  75. }
  76. ->
  77. {
  78. "device_keys": {
  79. "<user_id>": {
  80. "<device_id>": {
  81. ...
  82. }
  83. }
  84. }
  85. }
  86. Args:
  87. from_user_id (str): the user making the query. This is used when
  88. adding cross-signing signatures to limit what signatures users
  89. can see.
  90. """
  91. device_keys_query = query_body.get("device_keys", {})
  92. # separate users by domain.
  93. # make a map from domain to user_id to device_ids
  94. local_query = {}
  95. remote_queries = {}
  96. for user_id, device_ids in device_keys_query.items():
  97. # we use UserID.from_string to catch invalid user ids
  98. if self.is_mine(UserID.from_string(user_id)):
  99. local_query[user_id] = device_ids
  100. else:
  101. remote_queries[user_id] = device_ids
  102. set_tag("local_key_query", local_query)
  103. set_tag("remote_key_query", remote_queries)
  104. # First get local devices.
  105. failures = {}
  106. results = {}
  107. if local_query:
  108. local_result = await self.query_local_devices(local_query)
  109. for user_id, keys in local_result.items():
  110. if user_id in local_query:
  111. results[user_id] = keys
  112. # Now attempt to get any remote devices from our local cache.
  113. remote_queries_not_in_cache = {}
  114. if remote_queries:
  115. query_list = []
  116. for user_id, device_ids in remote_queries.items():
  117. if device_ids:
  118. query_list.extend((user_id, device_id) for device_id in device_ids)
  119. else:
  120. query_list.append((user_id, None))
  121. (
  122. user_ids_not_in_cache,
  123. remote_results,
  124. ) = await self.store.get_user_devices_from_cache(query_list)
  125. for user_id, devices in remote_results.items():
  126. user_devices = results.setdefault(user_id, {})
  127. for device_id, device in devices.items():
  128. keys = device.get("keys", None)
  129. device_display_name = device.get("device_display_name", None)
  130. if keys:
  131. result = dict(keys)
  132. unsigned = result.setdefault("unsigned", {})
  133. if device_display_name:
  134. unsigned["device_display_name"] = device_display_name
  135. user_devices[device_id] = result
  136. for user_id in user_ids_not_in_cache:
  137. domain = get_domain_from_id(user_id)
  138. r = remote_queries_not_in_cache.setdefault(domain, {})
  139. r[user_id] = remote_queries[user_id]
  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 fetch any devices that we don't have in our cache
  145. @trace
  146. async def do_remote_query(destination):
  147. """This is called when we are querying the device list of a user on
  148. a remote homeserver and their device list is not in the device list
  149. cache. If we share a room with this user and we're not querying for
  150. specific user we will update the cache with their device list.
  151. """
  152. destination_query = remote_queries_not_in_cache[destination]
  153. # We first consider whether we wish to update the device list cache with
  154. # the users device list. We want to track a user's devices when the
  155. # authenticated user shares a room with the queried user and the query
  156. # has not specified a particular device.
  157. # If we update the cache for the queried user we remove them from further
  158. # queries. We use the more efficient batched query_client_keys for all
  159. # remaining users
  160. user_ids_updated = []
  161. for (user_id, device_list) in destination_query.items():
  162. if user_id in user_ids_updated:
  163. continue
  164. if device_list:
  165. continue
  166. room_ids = await self.store.get_rooms_for_user(user_id)
  167. if not room_ids:
  168. continue
  169. # We've decided we're sharing a room with this user and should
  170. # probably be tracking their device lists. However, we haven't
  171. # done an initial sync on the device list so we do it now.
  172. try:
  173. if self._is_master:
  174. user_devices = await self.device_handler.device_list_updater.user_device_resync(
  175. user_id
  176. )
  177. else:
  178. user_devices = await self._user_device_resync_client(
  179. user_id=user_id
  180. )
  181. user_devices = user_devices["devices"]
  182. user_results = results.setdefault(user_id, {})
  183. for device in user_devices:
  184. user_results[device["device_id"]] = device["keys"]
  185. user_ids_updated.append(user_id)
  186. except Exception as e:
  187. failures[destination] = _exception_to_failure(e)
  188. if len(destination_query) == len(user_ids_updated):
  189. # We've updated all the users in the query and we do not need to
  190. # make any further remote calls.
  191. return
  192. # Remove all the users from the query which we have updated
  193. for user_id in user_ids_updated:
  194. destination_query.pop(user_id)
  195. try:
  196. remote_result = await self.federation.query_client_keys(
  197. destination, {"device_keys": destination_query}, timeout=timeout
  198. )
  199. for user_id, keys in remote_result["device_keys"].items():
  200. if user_id in destination_query:
  201. results[user_id] = keys
  202. if "master_keys" in remote_result:
  203. for user_id, key in remote_result["master_keys"].items():
  204. if user_id in destination_query:
  205. cross_signing_keys["master_keys"][user_id] = key
  206. if "self_signing_keys" in remote_result:
  207. for user_id, key in remote_result["self_signing_keys"].items():
  208. if user_id in destination_query:
  209. cross_signing_keys["self_signing_keys"][user_id] = key
  210. except Exception as e:
  211. failure = _exception_to_failure(e)
  212. failures[destination] = failure
  213. set_tag("error", True)
  214. set_tag("reason", failure)
  215. await make_deferred_yieldable(
  216. defer.gatherResults(
  217. [
  218. run_in_background(do_remote_query, destination)
  219. for destination in remote_queries_not_in_cache
  220. ],
  221. consumeErrors=True,
  222. ).addErrback(unwrapFirstError)
  223. )
  224. ret = {"device_keys": results, "failures": failures}
  225. ret.update(cross_signing_keys)
  226. return ret
  227. async def get_cross_signing_keys_from_cache(
  228. self, query, from_user_id
  229. ) -> Dict[str, Dict[str, dict]]:
  230. """Get cross-signing keys for users from the database
  231. Args:
  232. query (Iterable[string]) an iterable of user IDs. A dict whose keys
  233. are user IDs satisfies this, so the query format used for
  234. query_devices can be used here.
  235. from_user_id (str): the user making the query. This is used when
  236. adding cross-signing signatures to limit what signatures users
  237. can see.
  238. Returns:
  239. A map from (master_keys|self_signing_keys|user_signing_keys) -> user_id -> key
  240. """
  241. master_keys = {}
  242. self_signing_keys = {}
  243. user_signing_keys = {}
  244. user_ids = list(query)
  245. keys = await self.store.get_e2e_cross_signing_keys_bulk(user_ids, from_user_id)
  246. for user_id, user_info in keys.items():
  247. if user_info is None:
  248. continue
  249. if "master" in user_info:
  250. master_keys[user_id] = user_info["master"]
  251. if "self_signing" in user_info:
  252. self_signing_keys[user_id] = user_info["self_signing"]
  253. if (
  254. from_user_id in keys
  255. and keys[from_user_id] is not None
  256. and "user_signing" in keys[from_user_id]
  257. ):
  258. # users can see other users' master and self-signing keys, but can
  259. # only see their own user-signing keys
  260. user_signing_keys[from_user_id] = keys[from_user_id]["user_signing"]
  261. return {
  262. "master_keys": master_keys,
  263. "self_signing_keys": self_signing_keys,
  264. "user_signing_keys": user_signing_keys,
  265. }
  266. @trace
  267. async def query_local_devices(
  268. self, query: Dict[str, Optional[List[str]]]
  269. ) -> Dict[str, Dict[str, dict]]:
  270. """Get E2E device keys for local users
  271. Args:
  272. query: map from user_id to a list
  273. of devices to query (None for all devices)
  274. Returns:
  275. A map from user_id -> device_id -> device details
  276. """
  277. set_tag("local_query", query)
  278. local_query = []
  279. result_dict = {}
  280. for user_id, device_ids in query.items():
  281. # we use UserID.from_string to catch invalid user ids
  282. if not self.is_mine(UserID.from_string(user_id)):
  283. logger.warning("Request for keys for non-local user %s", user_id)
  284. log_kv(
  285. {
  286. "message": "Requested a local key for a user which"
  287. " was not local to the homeserver",
  288. "user_id": user_id,
  289. }
  290. )
  291. set_tag("error", True)
  292. raise SynapseError(400, "Not a user here")
  293. if not device_ids:
  294. local_query.append((user_id, None))
  295. else:
  296. for device_id in device_ids:
  297. local_query.append((user_id, device_id))
  298. # make sure that each queried user appears in the result dict
  299. result_dict[user_id] = {}
  300. results = await self.store.get_e2e_device_keys(local_query)
  301. # Build the result structure
  302. for user_id, device_keys in results.items():
  303. for device_id, device_info in device_keys.items():
  304. result_dict[user_id][device_id] = device_info
  305. log_kv(results)
  306. return result_dict
  307. async def on_federation_query_client_keys(self, query_body):
  308. """ Handle a device key query from a federated server
  309. """
  310. device_keys_query = query_body.get("device_keys", {})
  311. res = await self.query_local_devices(device_keys_query)
  312. ret = {"device_keys": res}
  313. # add in the cross-signing keys
  314. cross_signing_keys = await self.get_cross_signing_keys_from_cache(
  315. device_keys_query, None
  316. )
  317. ret.update(cross_signing_keys)
  318. return ret
  319. @trace
  320. async def claim_one_time_keys(self, query, timeout):
  321. local_query = []
  322. remote_queries = {}
  323. for user_id, device_keys in query.get("one_time_keys", {}).items():
  324. # we use UserID.from_string to catch invalid user ids
  325. if self.is_mine(UserID.from_string(user_id)):
  326. for device_id, algorithm in device_keys.items():
  327. local_query.append((user_id, device_id, algorithm))
  328. else:
  329. domain = get_domain_from_id(user_id)
  330. remote_queries.setdefault(domain, {})[user_id] = device_keys
  331. set_tag("local_key_query", local_query)
  332. set_tag("remote_key_query", remote_queries)
  333. results = await self.store.claim_e2e_one_time_keys(local_query)
  334. json_result = {}
  335. failures = {}
  336. for user_id, device_keys in results.items():
  337. for device_id, keys in device_keys.items():
  338. for key_id, json_bytes in keys.items():
  339. json_result.setdefault(user_id, {})[device_id] = {
  340. key_id: json.loads(json_bytes)
  341. }
  342. @trace
  343. async def claim_client_keys(destination):
  344. set_tag("destination", destination)
  345. device_keys = remote_queries[destination]
  346. try:
  347. remote_result = await self.federation.claim_client_keys(
  348. destination, {"one_time_keys": device_keys}, timeout=timeout
  349. )
  350. for user_id, keys in remote_result["one_time_keys"].items():
  351. if user_id in device_keys:
  352. json_result[user_id] = keys
  353. except Exception as e:
  354. failure = _exception_to_failure(e)
  355. failures[destination] = failure
  356. set_tag("error", True)
  357. set_tag("reason", failure)
  358. await make_deferred_yieldable(
  359. defer.gatherResults(
  360. [
  361. run_in_background(claim_client_keys, destination)
  362. for destination in remote_queries
  363. ],
  364. consumeErrors=True,
  365. )
  366. )
  367. logger.info(
  368. "Claimed one-time-keys: %s",
  369. ",".join(
  370. (
  371. "%s for %s:%s" % (key_id, user_id, device_id)
  372. for user_id, user_keys in json_result.items()
  373. for device_id, device_keys in user_keys.items()
  374. for key_id, _ in device_keys.items()
  375. )
  376. ),
  377. )
  378. log_kv({"one_time_keys": json_result, "failures": failures})
  379. return {"one_time_keys": json_result, "failures": failures}
  380. @tag_args
  381. async def upload_keys_for_user(self, user_id, device_id, keys):
  382. time_now = self.clock.time_msec()
  383. # TODO: Validate the JSON to make sure it has the right keys.
  384. device_keys = keys.get("device_keys", None)
  385. if device_keys:
  386. logger.info(
  387. "Updating device_keys for device %r for user %s at %d",
  388. device_id,
  389. user_id,
  390. time_now,
  391. )
  392. log_kv(
  393. {
  394. "message": "Updating device_keys for user.",
  395. "user_id": user_id,
  396. "device_id": device_id,
  397. }
  398. )
  399. # TODO: Sign the JSON with the server key
  400. changed = await self.store.set_e2e_device_keys(
  401. user_id, device_id, time_now, device_keys
  402. )
  403. if changed:
  404. # Only notify about device updates *if* the keys actually changed
  405. await self.device_handler.notify_device_update(user_id, [device_id])
  406. else:
  407. log_kv({"message": "Not updating device_keys for user", "user_id": user_id})
  408. one_time_keys = keys.get("one_time_keys", None)
  409. if one_time_keys:
  410. log_kv(
  411. {
  412. "message": "Updating one_time_keys for device.",
  413. "user_id": user_id,
  414. "device_id": device_id,
  415. }
  416. )
  417. await self._upload_one_time_keys_for_user(
  418. user_id, device_id, time_now, one_time_keys
  419. )
  420. else:
  421. log_kv(
  422. {"message": "Did not update one_time_keys", "reason": "no keys given"}
  423. )
  424. # the device should have been registered already, but it may have been
  425. # deleted due to a race with a DELETE request. Or we may be using an
  426. # old access_token without an associated device_id. Either way, we
  427. # need to double-check the device is registered to avoid ending up with
  428. # keys without a corresponding device.
  429. await self.device_handler.check_device_registered(user_id, device_id)
  430. result = await self.store.count_e2e_one_time_keys(user_id, device_id)
  431. set_tag("one_time_key_counts", result)
  432. return {"one_time_key_counts": result}
  433. async def _upload_one_time_keys_for_user(
  434. self, user_id, device_id, time_now, one_time_keys
  435. ):
  436. logger.info(
  437. "Adding one_time_keys %r for device %r for user %r at %d",
  438. one_time_keys.keys(),
  439. device_id,
  440. user_id,
  441. time_now,
  442. )
  443. # make a list of (alg, id, key) tuples
  444. key_list = []
  445. for key_id, key_obj in one_time_keys.items():
  446. algorithm, key_id = key_id.split(":")
  447. key_list.append((algorithm, key_id, key_obj))
  448. # First we check if we have already persisted any of the keys.
  449. existing_key_map = await self.store.get_e2e_one_time_keys(
  450. user_id, device_id, [k_id for _, k_id, _ in key_list]
  451. )
  452. new_keys = [] # Keys that we need to insert. (alg, id, json) tuples.
  453. for algorithm, key_id, key in key_list:
  454. ex_json = existing_key_map.get((algorithm, key_id), None)
  455. if ex_json:
  456. if not _one_time_keys_match(ex_json, key):
  457. raise SynapseError(
  458. 400,
  459. (
  460. "One time key %s:%s already exists. "
  461. "Old key: %s; new key: %r"
  462. )
  463. % (algorithm, key_id, ex_json, key),
  464. )
  465. else:
  466. new_keys.append(
  467. (algorithm, key_id, encode_canonical_json(key).decode("ascii"))
  468. )
  469. log_kv({"message": "Inserting new one_time_keys.", "keys": new_keys})
  470. await self.store.add_e2e_one_time_keys(user_id, device_id, time_now, new_keys)
  471. async def upload_signing_keys_for_user(self, user_id, keys):
  472. """Upload signing keys for cross-signing
  473. Args:
  474. user_id (string): the user uploading the keys
  475. keys (dict[string, dict]): the signing keys
  476. """
  477. # if a master key is uploaded, then check it. Otherwise, load the
  478. # stored master key, to check signatures on other keys
  479. if "master_key" in keys:
  480. master_key = keys["master_key"]
  481. _check_cross_signing_key(master_key, user_id, "master")
  482. else:
  483. master_key = await self.store.get_e2e_cross_signing_key(user_id, "master")
  484. # if there is no master key, then we can't do anything, because all the
  485. # other cross-signing keys need to be signed by the master key
  486. if not master_key:
  487. raise SynapseError(400, "No master key available", Codes.MISSING_PARAM)
  488. try:
  489. master_key_id, master_verify_key = get_verify_key_from_cross_signing_key(
  490. master_key
  491. )
  492. except ValueError:
  493. if "master_key" in keys:
  494. # the invalid key came from the request
  495. raise SynapseError(400, "Invalid master key", Codes.INVALID_PARAM)
  496. else:
  497. # the invalid key came from the database
  498. logger.error("Invalid master key found for user %s", user_id)
  499. raise SynapseError(500, "Invalid master key")
  500. # for the other cross-signing keys, make sure that they have valid
  501. # signatures from the master key
  502. if "self_signing_key" in keys:
  503. self_signing_key = keys["self_signing_key"]
  504. _check_cross_signing_key(
  505. self_signing_key, user_id, "self_signing", master_verify_key
  506. )
  507. if "user_signing_key" in keys:
  508. user_signing_key = keys["user_signing_key"]
  509. _check_cross_signing_key(
  510. user_signing_key, user_id, "user_signing", master_verify_key
  511. )
  512. # if everything checks out, then store the keys and send notifications
  513. deviceids = []
  514. if "master_key" in keys:
  515. await self.store.set_e2e_cross_signing_key(user_id, "master", master_key)
  516. deviceids.append(master_verify_key.version)
  517. if "self_signing_key" in keys:
  518. await self.store.set_e2e_cross_signing_key(
  519. user_id, "self_signing", self_signing_key
  520. )
  521. try:
  522. deviceids.append(
  523. get_verify_key_from_cross_signing_key(self_signing_key)[1].version
  524. )
  525. except ValueError:
  526. raise SynapseError(400, "Invalid self-signing key", Codes.INVALID_PARAM)
  527. if "user_signing_key" in keys:
  528. await self.store.set_e2e_cross_signing_key(
  529. user_id, "user_signing", user_signing_key
  530. )
  531. # the signature stream matches the semantics that we want for
  532. # user-signing key updates: only the user themselves is notified of
  533. # their own user-signing key updates
  534. await self.device_handler.notify_user_signature_update(user_id, [user_id])
  535. # master key and self-signing key updates match the semantics of device
  536. # list updates: all users who share an encrypted room are notified
  537. if len(deviceids):
  538. await self.device_handler.notify_device_update(user_id, deviceids)
  539. return {}
  540. async def upload_signatures_for_device_keys(self, user_id, signatures):
  541. """Upload device signatures for cross-signing
  542. Args:
  543. user_id (string): the user uploading the signatures
  544. signatures (dict[string, dict[string, dict]]): map of users to
  545. devices to signed keys. This is the submission from the user; an
  546. exception will be raised if it is malformed.
  547. Returns:
  548. dict: response to be sent back to the client. The response will have
  549. a "failures" key, which will be a dict mapping users to devices
  550. to errors for the signatures that failed.
  551. Raises:
  552. SynapseError: if the signatures dict is not valid.
  553. """
  554. failures = {}
  555. # signatures to be stored. Each item will be a SignatureListItem
  556. signature_list = []
  557. # split between checking signatures for own user and signatures for
  558. # other users, since we verify them with different keys
  559. self_signatures = signatures.get(user_id, {})
  560. other_signatures = {k: v for k, v in signatures.items() if k != user_id}
  561. self_signature_list, self_failures = await self._process_self_signatures(
  562. user_id, self_signatures
  563. )
  564. signature_list.extend(self_signature_list)
  565. failures.update(self_failures)
  566. other_signature_list, other_failures = await self._process_other_signatures(
  567. user_id, other_signatures
  568. )
  569. signature_list.extend(other_signature_list)
  570. failures.update(other_failures)
  571. # store the signature, and send the appropriate notifications for sync
  572. logger.debug("upload signature failures: %r", failures)
  573. await self.store.store_e2e_cross_signing_signatures(user_id, signature_list)
  574. self_device_ids = [item.target_device_id for item in self_signature_list]
  575. if self_device_ids:
  576. await self.device_handler.notify_device_update(user_id, self_device_ids)
  577. signed_users = [item.target_user_id for item in other_signature_list]
  578. if signed_users:
  579. await self.device_handler.notify_user_signature_update(
  580. user_id, signed_users
  581. )
  582. return {"failures": failures}
  583. async def _process_self_signatures(self, user_id, signatures):
  584. """Process uploaded signatures of the user's own keys.
  585. Signatures of the user's own keys from this API come in two forms:
  586. - signatures of the user's devices by the user's self-signing key,
  587. - signatures of the user's master key by the user's devices.
  588. Args:
  589. user_id (string): the user uploading the keys
  590. signatures (dict[string, dict]): map of devices to signed keys
  591. Returns:
  592. (list[SignatureListItem], dict[string, dict[string, dict]]):
  593. a list of signatures to store, and a map of users to devices to failure
  594. reasons
  595. Raises:
  596. SynapseError: if the input is malformed
  597. """
  598. signature_list = []
  599. failures = {}
  600. if not signatures:
  601. return signature_list, failures
  602. if not isinstance(signatures, dict):
  603. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  604. try:
  605. # get our self-signing key to verify the signatures
  606. (
  607. _,
  608. self_signing_key_id,
  609. self_signing_verify_key,
  610. ) = await self._get_e2e_cross_signing_verify_key(user_id, "self_signing")
  611. # get our master key, since we may have received a signature of it.
  612. # We need to fetch it here so that we know what its key ID is, so
  613. # that we can check if a signature that was sent is a signature of
  614. # the master key or of a device
  615. (
  616. master_key,
  617. _,
  618. master_verify_key,
  619. ) = await self._get_e2e_cross_signing_verify_key(user_id, "master")
  620. # fetch our stored devices. This is used to 1. verify
  621. # signatures on the master key, and 2. to compare with what
  622. # was sent if the device was signed
  623. devices = await self.store.get_e2e_device_keys([(user_id, None)])
  624. if user_id not in devices:
  625. raise NotFoundError("No device keys found")
  626. devices = devices[user_id]
  627. except SynapseError as e:
  628. failure = _exception_to_failure(e)
  629. failures[user_id] = {device: failure for device in signatures.keys()}
  630. return signature_list, failures
  631. for device_id, device in signatures.items():
  632. # make sure submitted data is in the right form
  633. if not isinstance(device, dict):
  634. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  635. try:
  636. if "signatures" not in device or user_id not in device["signatures"]:
  637. # no signature was sent
  638. raise SynapseError(
  639. 400, "Invalid signature", Codes.INVALID_SIGNATURE
  640. )
  641. if device_id == master_verify_key.version:
  642. # The signature is of the master key. This needs to be
  643. # handled differently from signatures of normal devices.
  644. master_key_signature_list = self._check_master_key_signature(
  645. user_id, device_id, device, master_key, devices
  646. )
  647. signature_list.extend(master_key_signature_list)
  648. continue
  649. # at this point, we have a device that should be signed
  650. # by the self-signing key
  651. if self_signing_key_id not in device["signatures"][user_id]:
  652. # no signature was sent
  653. raise SynapseError(
  654. 400, "Invalid signature", Codes.INVALID_SIGNATURE
  655. )
  656. try:
  657. stored_device = devices[device_id]
  658. except KeyError:
  659. raise NotFoundError("Unknown device")
  660. if self_signing_key_id in stored_device.get("signatures", {}).get(
  661. user_id, {}
  662. ):
  663. # we already have a signature on this device, so we
  664. # can skip it, since it should be exactly the same
  665. continue
  666. _check_device_signature(
  667. user_id, self_signing_verify_key, device, stored_device
  668. )
  669. signature = device["signatures"][user_id][self_signing_key_id]
  670. signature_list.append(
  671. SignatureListItem(
  672. self_signing_key_id, user_id, device_id, signature
  673. )
  674. )
  675. except SynapseError as e:
  676. failures.setdefault(user_id, {})[device_id] = _exception_to_failure(e)
  677. return signature_list, failures
  678. def _check_master_key_signature(
  679. self, user_id, master_key_id, signed_master_key, stored_master_key, devices
  680. ):
  681. """Check signatures of a user's master key made by their devices.
  682. Args:
  683. user_id (string): the user whose master key is being checked
  684. master_key_id (string): the ID of the user's master key
  685. signed_master_key (dict): the user's signed master key that was uploaded
  686. stored_master_key (dict): our previously-stored copy of the user's master key
  687. devices (iterable(dict)): the user's devices
  688. Returns:
  689. list[SignatureListItem]: a list of signatures to store
  690. Raises:
  691. SynapseError: if a signature is invalid
  692. """
  693. # for each device that signed the master key, check the signature.
  694. master_key_signature_list = []
  695. sigs = signed_master_key["signatures"]
  696. for signing_key_id, signature in sigs[user_id].items():
  697. _, signing_device_id = signing_key_id.split(":", 1)
  698. if (
  699. signing_device_id not in devices
  700. or signing_key_id not in devices[signing_device_id]["keys"]
  701. ):
  702. # signed by an unknown device, or the
  703. # device does not have the key
  704. raise SynapseError(400, "Invalid signature", Codes.INVALID_SIGNATURE)
  705. # get the key and check the signature
  706. pubkey = devices[signing_device_id]["keys"][signing_key_id]
  707. verify_key = decode_verify_key_bytes(signing_key_id, decode_base64(pubkey))
  708. _check_device_signature(
  709. user_id, verify_key, signed_master_key, stored_master_key
  710. )
  711. master_key_signature_list.append(
  712. SignatureListItem(signing_key_id, user_id, master_key_id, signature)
  713. )
  714. return master_key_signature_list
  715. async def _process_other_signatures(self, user_id, signatures):
  716. """Process uploaded signatures of other users' keys. These will be the
  717. target user's master keys, signed by the uploading user's user-signing
  718. key.
  719. Args:
  720. user_id (string): the user uploading the keys
  721. signatures (dict[string, dict]): map of users to devices to signed keys
  722. Returns:
  723. (list[SignatureListItem], dict[string, dict[string, dict]]):
  724. a list of signatures to store, and a map of users to devices to failure
  725. reasons
  726. Raises:
  727. SynapseError: if the input is malformed
  728. """
  729. signature_list = []
  730. failures = {}
  731. if not signatures:
  732. return signature_list, failures
  733. try:
  734. # get our user-signing key to verify the signatures
  735. (
  736. user_signing_key,
  737. user_signing_key_id,
  738. user_signing_verify_key,
  739. ) = await self._get_e2e_cross_signing_verify_key(user_id, "user_signing")
  740. except SynapseError as e:
  741. failure = _exception_to_failure(e)
  742. for user, devicemap in signatures.items():
  743. failures[user] = {device_id: failure for device_id in devicemap.keys()}
  744. return signature_list, failures
  745. for target_user, devicemap in signatures.items():
  746. # make sure submitted data is in the right form
  747. if not isinstance(devicemap, dict):
  748. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  749. for device in devicemap.values():
  750. if not isinstance(device, dict):
  751. raise SynapseError(400, "Invalid parameter", Codes.INVALID_PARAM)
  752. device_id = None
  753. try:
  754. # get the target user's master key, to make sure it matches
  755. # what was sent
  756. (
  757. master_key,
  758. master_key_id,
  759. _,
  760. ) = await self._get_e2e_cross_signing_verify_key(
  761. target_user, "master", user_id
  762. )
  763. # make sure that the target user's master key is the one that
  764. # was signed (and no others)
  765. device_id = master_key_id.split(":", 1)[1]
  766. if device_id not in devicemap:
  767. logger.debug(
  768. "upload signature: could not find signature for device %s",
  769. device_id,
  770. )
  771. # set device to None so that the failure gets
  772. # marked on all the signatures
  773. device_id = None
  774. raise NotFoundError("Unknown device")
  775. key = devicemap[device_id]
  776. other_devices = [k for k in devicemap.keys() if k != device_id]
  777. if other_devices:
  778. # other devices were signed -- mark those as failures
  779. logger.debug("upload signature: too many devices specified")
  780. failure = _exception_to_failure(NotFoundError("Unknown device"))
  781. failures[target_user] = {
  782. device: failure for device in other_devices
  783. }
  784. if user_signing_key_id in master_key.get("signatures", {}).get(
  785. user_id, {}
  786. ):
  787. # we already have the signature, so we can skip it
  788. continue
  789. _check_device_signature(
  790. user_id, user_signing_verify_key, key, master_key
  791. )
  792. signature = key["signatures"][user_id][user_signing_key_id]
  793. signature_list.append(
  794. SignatureListItem(
  795. user_signing_key_id, target_user, device_id, signature
  796. )
  797. )
  798. except SynapseError as e:
  799. failure = _exception_to_failure(e)
  800. if device_id is None:
  801. failures[target_user] = {
  802. device_id: failure for device_id in devicemap.keys()
  803. }
  804. else:
  805. failures.setdefault(target_user, {})[device_id] = failure
  806. return signature_list, failures
  807. async def _get_e2e_cross_signing_verify_key(
  808. self, user_id: str, key_type: str, from_user_id: str = None
  809. ):
  810. """Fetch locally or remotely query for a cross-signing public key.
  811. First, attempt to fetch the cross-signing public key from storage.
  812. If that fails, query the keys from the homeserver they belong to
  813. and update our local copy.
  814. Args:
  815. user_id: the user whose key should be fetched
  816. key_type: the type of key to fetch
  817. from_user_id: the user that we are fetching the keys for.
  818. This affects what signatures are fetched.
  819. Returns:
  820. dict, str, VerifyKey: the raw key data, the key ID, and the
  821. signedjson verify key
  822. Raises:
  823. NotFoundError: if the key is not found
  824. SynapseError: if `user_id` is invalid
  825. """
  826. user = UserID.from_string(user_id)
  827. key = await self.store.get_e2e_cross_signing_key(
  828. user_id, key_type, from_user_id
  829. )
  830. if key:
  831. # We found a copy of this key in our database. Decode and return it
  832. key_id, verify_key = get_verify_key_from_cross_signing_key(key)
  833. return key, key_id, verify_key
  834. # If we couldn't find the key locally, and we're looking for keys of
  835. # another user then attempt to fetch the missing key from the remote
  836. # user's server.
  837. #
  838. # We may run into this in possible edge cases where a user tries to
  839. # cross-sign a remote user, but does not share any rooms with them yet.
  840. # Thus, we would not have their key list yet. We instead fetch the key,
  841. # store it and notify clients of new, associated device IDs.
  842. if self.is_mine(user) or key_type not in ["master", "self_signing"]:
  843. # Note that master and self_signing keys are the only cross-signing keys we
  844. # can request over federation
  845. raise NotFoundError("No %s key found for %s" % (key_type, user_id))
  846. (
  847. key,
  848. key_id,
  849. verify_key,
  850. ) = await self._retrieve_cross_signing_keys_for_remote_user(user, key_type)
  851. if key is None:
  852. raise NotFoundError("No %s key found for %s" % (key_type, user_id))
  853. return key, key_id, verify_key
  854. async def _retrieve_cross_signing_keys_for_remote_user(
  855. self, user: UserID, desired_key_type: str,
  856. ) -> Tuple[Optional[dict], Optional[str], Optional[VerifyKey]]:
  857. """Queries cross-signing keys for a remote user and saves them to the database
  858. Only the key specified by `key_type` will be returned, while all retrieved keys
  859. will be saved regardless
  860. Args:
  861. user: The user to query remote keys for
  862. desired_key_type: The type of key to receive. One of "master", "self_signing"
  863. Returns:
  864. A tuple of the retrieved key content, the key's ID and the matching VerifyKey.
  865. If the key cannot be retrieved, all values in the tuple will instead be None.
  866. """
  867. try:
  868. remote_result = await self.federation.query_user_devices(
  869. user.domain, user.to_string()
  870. )
  871. except Exception as e:
  872. logger.warning(
  873. "Unable to query %s for cross-signing keys of user %s: %s %s",
  874. user.domain,
  875. user.to_string(),
  876. type(e),
  877. e,
  878. )
  879. return None, None, None
  880. # Process each of the retrieved cross-signing keys
  881. desired_key = None
  882. desired_key_id = None
  883. desired_verify_key = None
  884. retrieved_device_ids = []
  885. for key_type in ["master", "self_signing"]:
  886. key_content = remote_result.get(key_type + "_key")
  887. if not key_content:
  888. continue
  889. # Ensure these keys belong to the correct user
  890. if "user_id" not in key_content:
  891. logger.warning(
  892. "Invalid %s key retrieved, missing user_id field: %s",
  893. key_type,
  894. key_content,
  895. )
  896. continue
  897. if user.to_string() != key_content["user_id"]:
  898. logger.warning(
  899. "Found %s key of user %s when querying for keys of user %s",
  900. key_type,
  901. key_content["user_id"],
  902. user.to_string(),
  903. )
  904. continue
  905. # Validate the key contents
  906. try:
  907. # verify_key is a VerifyKey from signedjson, which uses
  908. # .version to denote the portion of the key ID after the
  909. # algorithm and colon, which is the device ID
  910. key_id, verify_key = get_verify_key_from_cross_signing_key(key_content)
  911. except ValueError as e:
  912. logger.warning(
  913. "Invalid %s key retrieved: %s - %s %s",
  914. key_type,
  915. key_content,
  916. type(e),
  917. e,
  918. )
  919. continue
  920. # Note down the device ID attached to this key
  921. retrieved_device_ids.append(verify_key.version)
  922. # If this is the desired key type, save it and its ID/VerifyKey
  923. if key_type == desired_key_type:
  924. desired_key = key_content
  925. desired_verify_key = verify_key
  926. desired_key_id = key_id
  927. # At the same time, store this key in the db for subsequent queries
  928. await self.store.set_e2e_cross_signing_key(
  929. user.to_string(), key_type, key_content
  930. )
  931. # Notify clients that new devices for this user have been discovered
  932. if retrieved_device_ids:
  933. # XXX is this necessary?
  934. await self.device_handler.notify_device_update(
  935. user.to_string(), retrieved_device_ids
  936. )
  937. return desired_key, desired_key_id, desired_verify_key
  938. def _check_cross_signing_key(key, user_id, key_type, signing_key=None):
  939. """Check a cross-signing key uploaded by a user. Performs some basic sanity
  940. checking, and ensures that it is signed, if a signature is required.
  941. Args:
  942. key (dict): the key data to verify
  943. user_id (str): the user whose key is being checked
  944. key_type (str): the type of key that the key should be
  945. signing_key (VerifyKey): (optional) the signing key that the key should
  946. be signed with. If omitted, signatures will not be checked.
  947. """
  948. if (
  949. key.get("user_id") != user_id
  950. or key_type not in key.get("usage", [])
  951. or len(key.get("keys", {})) != 1
  952. ):
  953. raise SynapseError(400, ("Invalid %s key" % (key_type,)), Codes.INVALID_PARAM)
  954. if signing_key:
  955. try:
  956. verify_signed_json(key, user_id, signing_key)
  957. except SignatureVerifyException:
  958. raise SynapseError(
  959. 400, ("Invalid signature on %s key" % key_type), Codes.INVALID_SIGNATURE
  960. )
  961. def _check_device_signature(user_id, verify_key, signed_device, stored_device):
  962. """Check that a signature on a device or cross-signing key is correct and
  963. matches the copy of the device/key that we have stored. Throws an
  964. exception if an error is detected.
  965. Args:
  966. user_id (str): the user ID whose signature is being checked
  967. verify_key (VerifyKey): the key to verify the device with
  968. signed_device (dict): the uploaded signed device data
  969. stored_device (dict): our previously stored copy of the device
  970. Raises:
  971. SynapseError: if the signature was invalid or the sent device is not the
  972. same as the stored device
  973. """
  974. # make sure that the device submitted matches what we have stored
  975. stripped_signed_device = {
  976. k: v for k, v in signed_device.items() if k not in ["signatures", "unsigned"]
  977. }
  978. stripped_stored_device = {
  979. k: v for k, v in stored_device.items() if k not in ["signatures", "unsigned"]
  980. }
  981. if stripped_signed_device != stripped_stored_device:
  982. logger.debug(
  983. "upload signatures: key does not match %s vs %s",
  984. signed_device,
  985. stored_device,
  986. )
  987. raise SynapseError(400, "Key does not match")
  988. try:
  989. verify_signed_json(signed_device, user_id, verify_key)
  990. except SignatureVerifyException:
  991. logger.debug("invalid signature on key")
  992. raise SynapseError(400, "Invalid signature", Codes.INVALID_SIGNATURE)
  993. def _exception_to_failure(e):
  994. if isinstance(e, SynapseError):
  995. return {"status": e.code, "errcode": e.errcode, "message": str(e)}
  996. if isinstance(e, CodeMessageException):
  997. return {"status": e.code, "message": str(e)}
  998. if isinstance(e, NotRetryingDestination):
  999. return {"status": 503, "message": "Not ready for retry"}
  1000. # include ConnectionRefused and other errors
  1001. #
  1002. # Note that some Exceptions (notably twisted's ResponseFailed etc) don't
  1003. # give a string for e.message, which json then fails to serialize.
  1004. return {"status": 503, "message": str(e)}
  1005. def _one_time_keys_match(old_key_json, new_key):
  1006. old_key = json.loads(old_key_json)
  1007. # if either is a string rather than an object, they must match exactly
  1008. if not isinstance(old_key, dict) or not isinstance(new_key, dict):
  1009. return old_key == new_key
  1010. # otherwise, we strip off the 'signatures' if any, because it's legitimate
  1011. # for different upload attempts to have different signatures.
  1012. old_key.pop("signatures", None)
  1013. new_key_copy = dict(new_key)
  1014. new_key_copy.pop("signatures", None)
  1015. return old_key == new_key_copy
  1016. @attr.s
  1017. class SignatureListItem:
  1018. """An item in the signature list as used by upload_signatures_for_device_keys.
  1019. """
  1020. signing_key_id = attr.ib()
  1021. target_user_id = attr.ib()
  1022. target_device_id = attr.ib()
  1023. signature = attr.ib()
  1024. class SigningKeyEduUpdater(object):
  1025. """Handles incoming signing key updates from federation and updates the DB"""
  1026. def __init__(self, hs, e2e_keys_handler):
  1027. self.store = hs.get_datastore()
  1028. self.federation = hs.get_federation_client()
  1029. self.clock = hs.get_clock()
  1030. self.e2e_keys_handler = e2e_keys_handler
  1031. self._remote_edu_linearizer = Linearizer(name="remote_signing_key")
  1032. # user_id -> list of updates waiting to be handled.
  1033. self._pending_updates = {}
  1034. # Recently seen stream ids. We don't bother keeping these in the DB,
  1035. # but they're useful to have them about to reduce the number of spurious
  1036. # resyncs.
  1037. self._seen_updates = ExpiringCache(
  1038. cache_name="signing_key_update_edu",
  1039. clock=self.clock,
  1040. max_len=10000,
  1041. expiry_ms=30 * 60 * 1000,
  1042. iterable=True,
  1043. )
  1044. async def incoming_signing_key_update(self, origin, edu_content):
  1045. """Called on incoming signing key update from federation. Responsible for
  1046. parsing the EDU and adding to pending updates list.
  1047. Args:
  1048. origin (string): the server that sent the EDU
  1049. edu_content (dict): the contents of the EDU
  1050. """
  1051. user_id = edu_content.pop("user_id")
  1052. master_key = edu_content.pop("master_key", None)
  1053. self_signing_key = edu_content.pop("self_signing_key", None)
  1054. if get_domain_from_id(user_id) != origin:
  1055. logger.warning("Got signing key update edu for %r from %r", user_id, origin)
  1056. return
  1057. room_ids = await self.store.get_rooms_for_user(user_id)
  1058. if not room_ids:
  1059. # We don't share any rooms with this user. Ignore update, as we
  1060. # probably won't get any further updates.
  1061. return
  1062. self._pending_updates.setdefault(user_id, []).append(
  1063. (master_key, self_signing_key)
  1064. )
  1065. await self._handle_signing_key_updates(user_id)
  1066. async def _handle_signing_key_updates(self, user_id):
  1067. """Actually handle pending updates.
  1068. Args:
  1069. user_id (string): the user whose updates we are processing
  1070. """
  1071. device_handler = self.e2e_keys_handler.device_handler
  1072. device_list_updater = device_handler.device_list_updater
  1073. with (await self._remote_edu_linearizer.queue(user_id)):
  1074. pending_updates = self._pending_updates.pop(user_id, [])
  1075. if not pending_updates:
  1076. # This can happen since we batch updates
  1077. return
  1078. device_ids = []
  1079. logger.info("pending updates: %r", pending_updates)
  1080. for master_key, self_signing_key in pending_updates:
  1081. new_device_ids = await device_list_updater.process_cross_signing_key_update(
  1082. user_id, master_key, self_signing_key,
  1083. )
  1084. device_ids = device_ids + new_device_ids
  1085. await device_handler.notify_device_update(user_id, device_ids)