2016-01-06 21:26:29 -07:00
|
|
|
# Copyright 2015, 2016 OpenMarket Ltd
|
2015-04-24 03:36:51 -06:00
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
2018-07-09 00:09:20 -06:00
|
|
|
import logging
|
2022-10-20 09:32:47 -06:00
|
|
|
import re
|
2023-08-18 04:05:01 -06:00
|
|
|
from typing import TYPE_CHECKING, Dict, Mapping, Optional, Set, Tuple
|
2019-08-21 03:39:45 -06:00
|
|
|
|
|
|
|
from signedjson.sign import sign_json
|
2015-04-22 07:21:08 -06:00
|
|
|
|
2022-10-20 09:32:47 -06:00
|
|
|
from twisted.web.server import Request
|
|
|
|
|
2019-06-03 11:07:19 -06:00
|
|
|
from synapse.crypto.keyring import ServerKeyFetcher
|
2022-10-20 09:32:47 -06:00
|
|
|
from synapse.http.server import HttpServer
|
|
|
|
from synapse.http.servlet import (
|
|
|
|
RestServlet,
|
|
|
|
parse_integer,
|
|
|
|
parse_json_object_from_request,
|
|
|
|
)
|
2023-08-18 04:05:01 -06:00
|
|
|
from synapse.storage.keys import FetchKeyResultForRemote
|
2021-09-15 06:45:32 -06:00
|
|
|
from synapse.types import JsonDict
|
2020-08-19 05:26:03 -06:00
|
|
|
from synapse.util import json_decoder
|
2021-06-02 09:37:59 -06:00
|
|
|
from synapse.util.async_helpers import yieldable_gather_results
|
2015-04-22 07:21:08 -06:00
|
|
|
|
2021-09-15 06:45:32 -06:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from synapse.server import HomeServer
|
|
|
|
|
2015-04-22 07:21:08 -06:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2022-10-20 09:32:47 -06:00
|
|
|
class RemoteKey(RestServlet):
|
2020-08-19 05:26:03 -06:00
|
|
|
"""HTTP resource for retrieving the TLS certificate and NACL signature
|
2015-04-22 07:21:08 -06:00
|
|
|
verification keys for a collection of servers. Checks that the reported
|
|
|
|
X.509 TLS certificate matches the one used in the HTTPS connection. Checks
|
|
|
|
that the NACL signature for the remote server is valid. Returns a dict of
|
|
|
|
JSON signed by both the remote server and by this server.
|
|
|
|
|
|
|
|
Supports individual GET APIs and a bulk query POST API.
|
|
|
|
|
2020-09-14 09:46:58 -06:00
|
|
|
Requests:
|
2015-04-22 07:21:08 -06:00
|
|
|
|
|
|
|
GET /_matrix/key/v2/query/remote.server.example.com HTTP/1.1
|
|
|
|
|
|
|
|
GET /_matrix/key/v2/query/remote.server.example.com/a.key.id HTTP/1.1
|
|
|
|
|
|
|
|
POST /_matrix/v2/query HTTP/1.1
|
|
|
|
Content-Type: application/json
|
|
|
|
{
|
2015-04-29 04:57:26 -06:00
|
|
|
"server_keys": {
|
|
|
|
"remote.server.example.com": {
|
|
|
|
"a.key.id": {
|
|
|
|
"minimum_valid_until_ts": 1234567890123
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-04-22 07:21:08 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
Response:
|
|
|
|
|
|
|
|
HTTP/1.1 200 OK
|
|
|
|
Content-Type: application/json
|
|
|
|
{
|
|
|
|
"server_keys": [
|
|
|
|
{
|
|
|
|
"server_name": "remote.server.example.com"
|
2015-04-23 09:39:13 -06:00
|
|
|
"valid_until_ts": # posix timestamp
|
2015-04-22 07:21:08 -06:00
|
|
|
"verify_keys": {
|
|
|
|
"a.key.id": { # The identifier for a key.
|
|
|
|
key: "" # base64 encoded verification key.
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"old_verify_keys": {
|
|
|
|
"an.old.key.id": { # The identifier for an old key.
|
|
|
|
key: "", # base64 encoded key
|
2015-04-23 09:39:13 -06:00
|
|
|
"expired_ts": 0, # when the key stop being used.
|
2015-04-22 07:21:08 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
"signatures": {
|
|
|
|
"remote.server.example.com": {...}
|
|
|
|
"this.server.example.com": {...}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
]
|
|
|
|
}
|
|
|
|
"""
|
|
|
|
|
2023-03-23 06:11:14 -06:00
|
|
|
CATEGORY = "Federation requests"
|
|
|
|
|
2021-09-15 06:45:32 -06:00
|
|
|
def __init__(self, hs: "HomeServer"):
|
2019-05-23 07:52:13 -06:00
|
|
|
self.fetcher = ServerKeyFetcher(hs)
|
2022-02-23 04:04:02 -07:00
|
|
|
self.store = hs.get_datastores().main
|
2015-04-22 07:21:08 -06:00
|
|
|
self.clock = hs.get_clock()
|
2021-09-23 10:03:01 -06:00
|
|
|
self.federation_domain_whitelist = (
|
|
|
|
hs.config.federation.federation_domain_whitelist
|
|
|
|
)
|
2019-08-21 03:39:45 -06:00
|
|
|
self.config = hs.config
|
2015-04-22 07:21:08 -06:00
|
|
|
|
2022-10-20 09:32:47 -06:00
|
|
|
def register(self, http_server: HttpServer) -> None:
|
|
|
|
http_server.register_paths(
|
|
|
|
"GET",
|
|
|
|
(
|
|
|
|
re.compile(
|
|
|
|
"^/_matrix/key/v2/query/(?P<server>[^/]*)(/(?P<key_id>[^/]*))?$"
|
|
|
|
),
|
|
|
|
),
|
|
|
|
self.on_GET,
|
|
|
|
self.__class__.__name__,
|
|
|
|
)
|
|
|
|
http_server.register_paths(
|
|
|
|
"POST",
|
|
|
|
(re.compile("^/_matrix/key/v2/query$"),),
|
|
|
|
self.on_POST,
|
|
|
|
self.__class__.__name__,
|
|
|
|
)
|
|
|
|
|
|
|
|
async def on_GET(
|
|
|
|
self, request: Request, server: str, key_id: Optional[str] = None
|
|
|
|
) -> Tuple[int, JsonDict]:
|
|
|
|
if server and key_id:
|
2023-05-12 05:31:50 -06:00
|
|
|
# Matrix 1.6 drops support for passing the key_id, this is incompatible
|
|
|
|
# with earlier versions and is allowed in order to support both.
|
|
|
|
# A warning is issued to help determine when it is safe to drop this.
|
|
|
|
logger.warning(
|
|
|
|
"Request for remote server key with deprecated key ID (logging to determine usage level for future removal): %s / %s",
|
|
|
|
server,
|
|
|
|
key_id,
|
|
|
|
)
|
|
|
|
|
2015-04-29 04:57:26 -06:00
|
|
|
minimum_valid_until_ts = parse_integer(request, "minimum_valid_until_ts")
|
|
|
|
arguments = {}
|
|
|
|
if minimum_valid_until_ts is not None:
|
|
|
|
arguments["minimum_valid_until_ts"] = minimum_valid_until_ts
|
2022-10-20 09:32:47 -06:00
|
|
|
query = {server: {key_id: arguments}}
|
2015-04-22 07:21:08 -06:00
|
|
|
else:
|
2022-10-20 09:32:47 -06:00
|
|
|
query = {server: {}}
|
2018-09-12 04:41:31 -06:00
|
|
|
|
2022-10-20 09:32:47 -06:00
|
|
|
return 200, await self.query_keys(query, query_remote_on_cache_miss=True)
|
2015-04-22 07:21:08 -06:00
|
|
|
|
2022-10-20 09:32:47 -06:00
|
|
|
async def on_POST(self, request: Request) -> Tuple[int, JsonDict]:
|
2016-03-11 09:41:03 -07:00
|
|
|
content = parse_json_object_from_request(request)
|
2015-04-22 07:21:08 -06:00
|
|
|
|
|
|
|
query = content["server_keys"]
|
|
|
|
|
2022-10-20 09:32:47 -06:00
|
|
|
return 200, await self.query_keys(query, query_remote_on_cache_miss=True)
|
2015-04-22 07:21:08 -06:00
|
|
|
|
2021-09-15 06:45:32 -06:00
|
|
|
async def query_keys(
|
2022-10-20 09:32:47 -06:00
|
|
|
self, query: JsonDict, query_remote_on_cache_miss: bool = False
|
|
|
|
) -> JsonDict:
|
2015-04-29 04:57:26 -06:00
|
|
|
logger.info("Handling query for keys %r", query)
|
2018-09-12 04:41:31 -06:00
|
|
|
|
2023-08-18 04:05:01 -06:00
|
|
|
server_keys: Dict[Tuple[str, str], Optional[FetchKeyResultForRemote]] = {}
|
2015-04-22 07:21:08 -06:00
|
|
|
for server_name, key_ids in query.items():
|
2023-08-18 04:05:01 -06:00
|
|
|
if key_ids:
|
|
|
|
results: Mapping[
|
|
|
|
str, Optional[FetchKeyResultForRemote]
|
|
|
|
] = await self.store.get_server_keys_json_for_remote(
|
|
|
|
server_name, key_ids
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
results = await self.store.get_all_server_keys_json_for_remote(
|
|
|
|
server_name
|
|
|
|
)
|
2015-04-22 07:21:08 -06:00
|
|
|
|
2023-08-18 04:05:01 -06:00
|
|
|
server_keys.update(
|
|
|
|
((server_name, key_id), res) for key_id, res in results.items()
|
|
|
|
)
|
2015-04-22 07:21:08 -06:00
|
|
|
|
2022-03-29 15:37:50 -06:00
|
|
|
json_results: Set[bytes] = set()
|
2015-04-22 07:21:08 -06:00
|
|
|
|
|
|
|
time_now_ms = self.clock.time_msec()
|
|
|
|
|
2023-05-12 05:31:50 -06:00
|
|
|
# Map server_name->key_id->int. Note that the value of the int is unused.
|
2022-09-01 06:54:02 -06:00
|
|
|
# XXX: why don't we just use a set?
|
2021-07-16 11:22:36 -06:00
|
|
|
cache_misses: Dict[str, Dict[str, int]] = {}
|
2023-08-18 04:05:01 -06:00
|
|
|
for (server_name, key_id), key_result in server_keys.items():
|
|
|
|
if not query[server_name]:
|
2022-09-01 06:54:02 -06:00
|
|
|
# all keys were requested. Just return what we have without worrying
|
|
|
|
# about validity
|
2023-08-18 04:05:01 -06:00
|
|
|
if key_result:
|
|
|
|
json_results.add(key_result.key_json)
|
2015-04-22 07:21:08 -06:00
|
|
|
continue
|
|
|
|
|
2022-09-01 06:54:02 -06:00
|
|
|
miss = False
|
2023-08-18 04:05:01 -06:00
|
|
|
if key_result is None:
|
2022-09-01 06:54:02 -06:00
|
|
|
miss = True
|
|
|
|
else:
|
2023-08-18 04:05:01 -06:00
|
|
|
ts_added_ms = key_result.added_ts
|
|
|
|
ts_valid_until_ms = key_result.valid_until_ts
|
2015-04-29 04:57:26 -06:00
|
|
|
req_key = query.get(server_name, {}).get(key_id, {})
|
|
|
|
req_valid_until = req_key.get("minimum_valid_until_ts")
|
|
|
|
if req_valid_until is not None:
|
|
|
|
if ts_valid_until_ms < req_valid_until:
|
|
|
|
logger.debug(
|
|
|
|
"Cached response for %r/%r is older than requested"
|
|
|
|
": valid_until (%r) < minimum_valid_until (%r)",
|
|
|
|
server_name,
|
|
|
|
key_id,
|
|
|
|
ts_valid_until_ms,
|
|
|
|
req_valid_until,
|
|
|
|
)
|
|
|
|
miss = True
|
|
|
|
else:
|
|
|
|
logger.debug(
|
|
|
|
"Cached response for %r/%r is newer than requested"
|
|
|
|
": valid_until (%r) >= minimum_valid_until (%r)",
|
|
|
|
server_name,
|
|
|
|
key_id,
|
|
|
|
ts_valid_until_ms,
|
|
|
|
req_valid_until,
|
|
|
|
)
|
|
|
|
elif (ts_added_ms + ts_valid_until_ms) / 2 < time_now_ms:
|
|
|
|
logger.debug(
|
|
|
|
"Cached response for %r/%r is too old"
|
|
|
|
": (added (%r) + valid_until (%r)) / 2 < now (%r)",
|
|
|
|
server_name,
|
|
|
|
key_id,
|
|
|
|
ts_added_ms,
|
|
|
|
ts_valid_until_ms,
|
|
|
|
time_now_ms,
|
|
|
|
)
|
2015-04-23 09:39:13 -06:00
|
|
|
# We more than half way through the lifetime of the
|
|
|
|
# response. We should fetch a fresh copy.
|
2015-04-29 04:57:26 -06:00
|
|
|
miss = True
|
|
|
|
else:
|
|
|
|
logger.debug(
|
|
|
|
"Cached response for %r/%r is still valid"
|
|
|
|
": (added (%r) + valid_until (%r)) / 2 < now (%r)",
|
|
|
|
server_name,
|
|
|
|
key_id,
|
|
|
|
ts_added_ms,
|
|
|
|
ts_valid_until_ms,
|
|
|
|
time_now_ms,
|
|
|
|
)
|
2023-08-18 04:05:01 -06:00
|
|
|
|
|
|
|
json_results.add(key_result.key_json)
|
2022-09-01 06:54:02 -06:00
|
|
|
|
|
|
|
if miss and query_remote_on_cache_miss:
|
|
|
|
# only bother attempting to fetch keys from servers on our whitelist
|
|
|
|
if (
|
|
|
|
self.federation_domain_whitelist is None
|
|
|
|
or server_name in self.federation_domain_whitelist
|
|
|
|
):
|
|
|
|
cache_misses.setdefault(server_name, {})[key_id] = 0
|
2015-04-22 07:21:08 -06:00
|
|
|
|
2020-08-19 05:26:03 -06:00
|
|
|
# If there is a cache miss, request the missing keys, then recurse (and
|
|
|
|
# ensure the result is sent).
|
2022-09-01 06:54:02 -06:00
|
|
|
if cache_misses:
|
2021-06-02 09:37:59 -06:00
|
|
|
await yieldable_gather_results(
|
|
|
|
lambda t: self.fetcher.get_keys(*t),
|
|
|
|
(
|
|
|
|
(server_name, list(keys), 0)
|
|
|
|
for server_name, keys in cache_misses.items()
|
|
|
|
),
|
|
|
|
)
|
2022-10-20 09:32:47 -06:00
|
|
|
return await self.query_keys(query, query_remote_on_cache_miss=False)
|
2020-01-08 06:24:10 -07:00
|
|
|
else:
|
|
|
|
signed_keys = []
|
2022-03-29 15:37:50 -06:00
|
|
|
for key_json_raw in json_results:
|
|
|
|
key_json = json_decoder.decode(key_json_raw.decode("utf-8"))
|
2021-09-23 10:03:01 -06:00
|
|
|
for signing_key in self.config.key.key_server_signing_keys:
|
2021-09-13 11:07:12 -06:00
|
|
|
key_json = sign_json(
|
|
|
|
key_json, self.config.server.server_name, signing_key
|
|
|
|
)
|
2019-08-21 03:39:45 -06:00
|
|
|
|
2020-01-08 06:24:10 -07:00
|
|
|
signed_keys.append(key_json)
|
2019-08-21 03:39:45 -06:00
|
|
|
|
2022-10-20 09:32:47 -06:00
|
|
|
return {"server_keys": signed_keys}
|