summary refs log tree commit diff
path: root/scripts-dev/federation_client.py
blob: 4c758e5424ed8b489006227e653abdb1df347792 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
#!/usr/bin/env python
#
# This file is licensed under the Affero General Public License (AGPL) version 3.
#
# Copyright 2015, 2016 OpenMarket Ltd
# Copyright (C) 2023 New Vector, Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# See the GNU Affero General Public License for more details:
# <https://www.gnu.org/licenses/agpl-3.0.html>.
#
# Originally licensed under the Apache License, Version 2.0:
# <http://www.apache.org/licenses/LICENSE-2.0>.
#
# [This file includes modifications made by New Vector Limited]
#
#


"""
Script for signing and sending federation requests.

Some tips on doing the join dance with this:

    room_id=...
    user_id=...

    # make_join
    federation_client.py "/_matrix/federation/v1/make_join/$room_id/$user_id?ver=5" > make_join.json

    # sign
    jq -M .event make_join.json | sign_json --sign-event-room-version=$(jq -r .room_version make_join.json) -o signed-join.json

    # send_join
    federation_client.py -X PUT "/_matrix/federation/v2/send_join/$room_id/x" --body $(<signed-join.json) > send_join.json
"""

import argparse
import base64
import json
import sys
from typing import Any, Dict, Optional, Tuple
from urllib import parse as urlparse

import requests
import signedjson.key
import signedjson.types
import srvlookup
import yaml
from requests import PreparedRequest, Response
from requests.adapters import HTTPAdapter
from urllib3 import HTTPConnectionPool

# uncomment the following to enable debug logging of http requests
# from http.client import HTTPConnection
# HTTPConnection.debuglevel = 1


def encode_base64(input_bytes: bytes) -> str:
    """Encode bytes as a base64 string without any padding."""

    input_len = len(input_bytes)
    output_len = 4 * ((input_len + 2) // 3) + (input_len + 2) % 3 - 2
    output_bytes = base64.b64encode(input_bytes)
    output_string = output_bytes[:output_len].decode("ascii")
    return output_string


def encode_canonical_json(value: object) -> bytes:
    return json.dumps(
        value,
        # Encode code-points outside of ASCII as UTF-8 rather than \u escapes
        ensure_ascii=False,
        # Remove unecessary white space.
        separators=(",", ":"),
        # Sort the keys of dictionaries.
        sort_keys=True,
        # Encode the resulting unicode as UTF-8 bytes.
    ).encode("UTF-8")


def sign_json(
    json_object: Any, signing_key: signedjson.types.SigningKey, signing_name: str
) -> Any:
    signatures = json_object.pop("signatures", {})
    unsigned = json_object.pop("unsigned", None)

    signed = signing_key.sign(encode_canonical_json(json_object))
    signature_base64 = encode_base64(signed.signature)

    key_id = "%s:%s" % (signing_key.alg, signing_key.version)
    signatures.setdefault(signing_name, {})[key_id] = signature_base64

    json_object["signatures"] = signatures
    if unsigned is not None:
        json_object["unsigned"] = unsigned

    return json_object


def request(
    method: Optional[str],
    origin_name: str,
    origin_key: signedjson.types.SigningKey,
    destination: str,
    path: str,
    content: Optional[str],
    verify_tls: bool,
) -> requests.Response:
    if method is None:
        if content is None:
            method = "GET"
        else:
            method = "POST"

    json_to_sign = {
        "method": method,
        "uri": path,
        "origin": origin_name,
        "destination": destination,
    }

    if content is not None:
        json_to_sign["content"] = json.loads(content)

    signed_json = sign_json(json_to_sign, origin_key, origin_name)

    authorization_headers = []

    for key, sig in signed_json["signatures"][origin_name].items():
        header = 'X-Matrix origin=%s,key="%s",sig="%s",destination="%s"' % (
            origin_name,
            key,
            sig,
            destination,
        )
        authorization_headers.append(header)
        print("Authorization: %s" % header, file=sys.stderr)

    dest = "matrix-federation://%s%s" % (destination, path)
    print("Requesting %s" % dest, file=sys.stderr)

    s = requests.Session()
    s.mount("matrix-federation://", MatrixConnectionAdapter())

    headers: Dict[str, str] = {
        "Authorization": authorization_headers[0],
    }

    if method == "POST":
        headers["Content-Type"] = "application/json"

    return s.request(
        method=method,
        url=dest,
        headers=headers,
        verify=verify_tls,
        data=content,
        stream=True,
    )


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Signs and sends a federation request to a matrix homeserver"
    )

    parser.add_argument(
        "-N",
        "--server-name",
        help="Name to give as the local homeserver. If unspecified, will be "
        "read from the config file.",
    )

    parser.add_argument(
        "-k",
        "--signing-key-path",
        help="Path to the file containing the private ed25519 key to sign the "
        "request with.",
    )

    parser.add_argument(
        "-c",
        "--config",
        default="homeserver.yaml",
        help="Path to server config file. Ignored if --server-name and "
        "--signing-key-path are both given.",
    )

    parser.add_argument(
        "-d",
        "--destination",
        default="matrix.org",
        help="name of the remote homeserver. We will do SRV lookups and "
        "connect appropriately.",
    )

    parser.add_argument(
        "-X",
        "--method",
        help="HTTP method to use for the request. Defaults to GET if --body is"
        "unspecified, POST if it is.",
    )

    parser.add_argument("--body", help="Data to send as the body of the HTTP request")

    parser.add_argument(
        "--insecure",
        action="store_true",
        help="Disable TLS certificate verification",
    )

    parser.add_argument(
        "path", help="request path, including the '/_matrix/federation/...' prefix."
    )

    args = parser.parse_args()

    args.signing_key = None
    if args.signing_key_path:
        with open(args.signing_key_path) as f:
            args.signing_key = f.readline()

    if not args.server_name or not args.signing_key:
        read_args_from_config(args)

    assert isinstance(args.signing_key, str)
    algorithm, version, key_base64 = args.signing_key.split()
    key = signedjson.key.decode_signing_key_base64(algorithm, version, key_base64)

    result = request(
        args.method,
        args.server_name,
        key,
        args.destination,
        args.path,
        content=args.body,
        verify_tls=not args.insecure,
    )

    sys.stderr.write("Status Code: %d\n" % (result.status_code,))

    for chunk in result.iter_content():
        # we write raw utf8 to stdout.
        sys.stdout.buffer.write(chunk)

    print("")


def read_args_from_config(args: argparse.Namespace) -> None:
    with open(args.config) as fh:
        config = yaml.safe_load(fh)

        if not args.server_name:
            args.server_name = config["server_name"]

        if not args.signing_key:
            if "signing_key" in config:
                args.signing_key = config["signing_key"]
            else:
                with open(config["signing_key_path"]) as f:
                    args.signing_key = f.readline()


class MatrixConnectionAdapter(HTTPAdapter):
    def send(
        self,
        request: PreparedRequest,
        *args: Any,
        **kwargs: Any,
    ) -> Response:
        # overrides the send() method in the base class.

        # We need to look for .well-known redirects before passing the request up to
        # HTTPAdapter.send().
        assert isinstance(request.url, str)
        parsed = urlparse.urlsplit(request.url)
        server_name = parsed.netloc
        well_known = self._get_well_known(parsed.netloc)

        if well_known:
            server_name = well_known

        # replace the scheme in the uri with https, so that cert verification is done
        # also replace the hostname if we got a .well-known result
        request.url = urlparse.urlunsplit(
            ("https", server_name, parsed.path, parsed.query, parsed.fragment)
        )

        # at this point we also add the host header (otherwise urllib will add one
        # based on the `host` from the connection returned by `get_connection`,
        # which will be wrong if there is an SRV record).
        request.headers["Host"] = server_name

        return super().send(request, *args, **kwargs)

    def get_connection(
        self, url: str, proxies: Optional[Dict[str, str]] = None
    ) -> HTTPConnectionPool:
        # overrides the get_connection() method in the base class
        parsed = urlparse.urlsplit(url)
        (host, port, ssl_server_name) = self._lookup(parsed.netloc)
        print(
            f"Connecting to {host}:{port} with SNI {ssl_server_name}", file=sys.stderr
        )
        return self.poolmanager.connection_from_host(
            host,
            port=port,
            scheme="https",
            pool_kwargs={"server_hostname": ssl_server_name},
        )

    @staticmethod
    def _lookup(server_name: str) -> Tuple[str, int, str]:
        """
        Do an SRV lookup on a server name and return the host:port to connect to
        Given the server_name (after any .well-known lookup), return the host, port and
        the ssl server name
        """
        if server_name[-1] == "]":
            # ipv6 literal (with no port)
            return server_name, 8448, server_name

        if ":" in server_name:
            # explicit port
            out = server_name.rsplit(":", 1)
            try:
                port = int(out[1])
            except ValueError:
                raise ValueError("Invalid host:port '%s'" % (server_name,))
            return out[0], port, out[0]

        # Look up SRV for Matrix 1.8 `matrix-fed` service first
        try:
            srv = srvlookup.lookup("matrix-fed", "tcp", server_name)[0]
            print(
                f"SRV lookup on _matrix-fed._tcp.{server_name} gave {srv}",
                file=sys.stderr,
            )
            return srv.host, srv.port, server_name
        except Exception:
            pass
        # Fall back to deprecated `matrix` service
        try:
            srv = srvlookup.lookup("matrix", "tcp", server_name)[0]
            print(
                f"SRV lookup on _matrix._tcp.{server_name} gave {srv}",
                file=sys.stderr,
            )
            return srv.host, srv.port, server_name
        except Exception:
            # Fall even further back to just port 8448
            return server_name, 8448, server_name

    @staticmethod
    def _get_well_known(server_name: str) -> Optional[str]:
        if ":" in server_name:
            # explicit port, or ipv6 literal. Either way, no .well-known
            return None

        # TODO: check for ipv4 literals

        uri = f"https://{server_name}/.well-known/matrix/server"
        print(f"fetching {uri}", file=sys.stderr)

        try:
            resp = requests.get(uri)
            if resp.status_code != 200:
                print("%s gave %i" % (uri, resp.status_code), file=sys.stderr)
                return None

            parsed_well_known = resp.json()
            if not isinstance(parsed_well_known, dict):
                raise Exception("not a dict")
            if "m.server" not in parsed_well_known:
                raise Exception("Missing key 'm.server'")
            new_name = parsed_well_known["m.server"]
            print("well-known lookup gave %s" % (new_name,), file=sys.stderr)
            return new_name

        except Exception as e:
            print("Invalid response from %s: %s" % (uri, e), file=sys.stderr)
        return None


if __name__ == "__main__":
    main()