1
0

federation_client.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2015, 2016 OpenMarket Ltd
  4. # Copyright 2017 New Vector Ltd
  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. """
  18. Script for signing and sending federation requests.
  19. Some tips on doing the join dance with this:
  20. room_id=...
  21. user_id=...
  22. # make_join
  23. federation_client.py "/_matrix/federation/v1/make_join/$room_id/$user_id?ver=5" > make_join.json
  24. # sign
  25. jq -M .event make_join.json | sign_json --sign-event-room-version=$(jq -r .room_version make_join.json) -o signed-join.json
  26. # send_join
  27. federation_client.py -X PUT "/_matrix/federation/v2/send_join/$room_id/x" --body $(<signed-join.json) > send_join.json
  28. """
  29. import argparse
  30. import base64
  31. import json
  32. import sys
  33. from typing import Any, Dict, Optional, Tuple
  34. from urllib import parse as urlparse
  35. import requests
  36. import signedjson.key
  37. import signedjson.types
  38. import srvlookup
  39. import yaml
  40. from requests import PreparedRequest, Response
  41. from requests.adapters import HTTPAdapter
  42. from urllib3 import HTTPConnectionPool
  43. # uncomment the following to enable debug logging of http requests
  44. # from http.client import HTTPConnection
  45. # HTTPConnection.debuglevel = 1
  46. def encode_base64(input_bytes: bytes) -> str:
  47. """Encode bytes as a base64 string without any padding."""
  48. input_len = len(input_bytes)
  49. output_len = 4 * ((input_len + 2) // 3) + (input_len + 2) % 3 - 2
  50. output_bytes = base64.b64encode(input_bytes)
  51. output_string = output_bytes[:output_len].decode("ascii")
  52. return output_string
  53. def encode_canonical_json(value: object) -> bytes:
  54. return json.dumps(
  55. value,
  56. # Encode code-points outside of ASCII as UTF-8 rather than \u escapes
  57. ensure_ascii=False,
  58. # Remove unecessary white space.
  59. separators=(",", ":"),
  60. # Sort the keys of dictionaries.
  61. sort_keys=True,
  62. # Encode the resulting unicode as UTF-8 bytes.
  63. ).encode("UTF-8")
  64. def sign_json(
  65. json_object: Any, signing_key: signedjson.types.SigningKey, signing_name: str
  66. ) -> Any:
  67. signatures = json_object.pop("signatures", {})
  68. unsigned = json_object.pop("unsigned", None)
  69. signed = signing_key.sign(encode_canonical_json(json_object))
  70. signature_base64 = encode_base64(signed.signature)
  71. key_id = "%s:%s" % (signing_key.alg, signing_key.version)
  72. signatures.setdefault(signing_name, {})[key_id] = signature_base64
  73. json_object["signatures"] = signatures
  74. if unsigned is not None:
  75. json_object["unsigned"] = unsigned
  76. return json_object
  77. def request(
  78. method: Optional[str],
  79. origin_name: str,
  80. origin_key: signedjson.types.SigningKey,
  81. destination: str,
  82. path: str,
  83. content: Optional[str],
  84. verify_tls: bool,
  85. ) -> requests.Response:
  86. if method is None:
  87. if content is None:
  88. method = "GET"
  89. else:
  90. method = "POST"
  91. json_to_sign = {
  92. "method": method,
  93. "uri": path,
  94. "origin": origin_name,
  95. "destination": destination,
  96. }
  97. if content is not None:
  98. json_to_sign["content"] = json.loads(content)
  99. signed_json = sign_json(json_to_sign, origin_key, origin_name)
  100. authorization_headers = []
  101. for key, sig in signed_json["signatures"][origin_name].items():
  102. header = 'X-Matrix origin=%s,key="%s",sig="%s",destination="%s"' % (
  103. origin_name,
  104. key,
  105. sig,
  106. destination,
  107. )
  108. authorization_headers.append(header)
  109. print("Authorization: %s" % header, file=sys.stderr)
  110. dest = "matrix-federation://%s%s" % (destination, path)
  111. print("Requesting %s" % dest, file=sys.stderr)
  112. s = requests.Session()
  113. s.mount("matrix-federation://", MatrixConnectionAdapter())
  114. headers: Dict[str, str] = {
  115. "Authorization": authorization_headers[0],
  116. }
  117. if method == "POST":
  118. headers["Content-Type"] = "application/json"
  119. return s.request(
  120. method=method,
  121. url=dest,
  122. headers=headers,
  123. verify=verify_tls,
  124. data=content,
  125. stream=True,
  126. )
  127. def main() -> None:
  128. parser = argparse.ArgumentParser(
  129. description="Signs and sends a federation request to a matrix homeserver"
  130. )
  131. parser.add_argument(
  132. "-N",
  133. "--server-name",
  134. help="Name to give as the local homeserver. If unspecified, will be "
  135. "read from the config file.",
  136. )
  137. parser.add_argument(
  138. "-k",
  139. "--signing-key-path",
  140. help="Path to the file containing the private ed25519 key to sign the "
  141. "request with.",
  142. )
  143. parser.add_argument(
  144. "-c",
  145. "--config",
  146. default="homeserver.yaml",
  147. help="Path to server config file. Ignored if --server-name and "
  148. "--signing-key-path are both given.",
  149. )
  150. parser.add_argument(
  151. "-d",
  152. "--destination",
  153. default="matrix.org",
  154. help="name of the remote homeserver. We will do SRV lookups and "
  155. "connect appropriately.",
  156. )
  157. parser.add_argument(
  158. "-X",
  159. "--method",
  160. help="HTTP method to use for the request. Defaults to GET if --body is"
  161. "unspecified, POST if it is.",
  162. )
  163. parser.add_argument("--body", help="Data to send as the body of the HTTP request")
  164. parser.add_argument(
  165. "--insecure",
  166. action="store_true",
  167. help="Disable TLS certificate verification",
  168. )
  169. parser.add_argument(
  170. "path", help="request path, including the '/_matrix/federation/...' prefix."
  171. )
  172. args = parser.parse_args()
  173. args.signing_key = None
  174. if args.signing_key_path:
  175. with open(args.signing_key_path) as f:
  176. args.signing_key = f.readline()
  177. if not args.server_name or not args.signing_key:
  178. read_args_from_config(args)
  179. assert isinstance(args.signing_key, str)
  180. algorithm, version, key_base64 = args.signing_key.split()
  181. key = signedjson.key.decode_signing_key_base64(algorithm, version, key_base64)
  182. result = request(
  183. args.method,
  184. args.server_name,
  185. key,
  186. args.destination,
  187. args.path,
  188. content=args.body,
  189. verify_tls=not args.insecure,
  190. )
  191. sys.stderr.write("Status Code: %d\n" % (result.status_code,))
  192. for chunk in result.iter_content():
  193. # we write raw utf8 to stdout.
  194. sys.stdout.buffer.write(chunk)
  195. print("")
  196. def read_args_from_config(args: argparse.Namespace) -> None:
  197. with open(args.config) as fh:
  198. config = yaml.safe_load(fh)
  199. if not args.server_name:
  200. args.server_name = config["server_name"]
  201. if not args.signing_key:
  202. if "signing_key" in config:
  203. args.signing_key = config["signing_key"]
  204. else:
  205. with open(config["signing_key_path"]) as f:
  206. args.signing_key = f.readline()
  207. class MatrixConnectionAdapter(HTTPAdapter):
  208. def send(
  209. self,
  210. request: PreparedRequest,
  211. *args: Any,
  212. **kwargs: Any,
  213. ) -> Response:
  214. # overrides the send() method in the base class.
  215. # We need to look for .well-known redirects before passing the request up to
  216. # HTTPAdapter.send().
  217. assert isinstance(request.url, str)
  218. parsed = urlparse.urlsplit(request.url)
  219. server_name = parsed.netloc
  220. well_known = self._get_well_known(parsed.netloc)
  221. if well_known:
  222. server_name = well_known
  223. # replace the scheme in the uri with https, so that cert verification is done
  224. # also replace the hostname if we got a .well-known result
  225. request.url = urlparse.urlunsplit(
  226. ("https", server_name, parsed.path, parsed.query, parsed.fragment)
  227. )
  228. # at this point we also add the host header (otherwise urllib will add one
  229. # based on the `host` from the connection returned by `get_connection`,
  230. # which will be wrong if there is an SRV record).
  231. request.headers["Host"] = server_name
  232. return super().send(request, *args, **kwargs)
  233. def get_connection(
  234. self, url: str, proxies: Optional[Dict[str, str]] = None
  235. ) -> HTTPConnectionPool:
  236. # overrides the get_connection() method in the base class
  237. parsed = urlparse.urlsplit(url)
  238. (host, port, ssl_server_name) = self._lookup(parsed.netloc)
  239. print(
  240. f"Connecting to {host}:{port} with SNI {ssl_server_name}", file=sys.stderr
  241. )
  242. return self.poolmanager.connection_from_host(
  243. host,
  244. port=port,
  245. scheme="https",
  246. pool_kwargs={"server_hostname": ssl_server_name},
  247. )
  248. @staticmethod
  249. def _lookup(server_name: str) -> Tuple[str, int, str]:
  250. """
  251. Do an SRV lookup on a server name and return the host:port to connect to
  252. Given the server_name (after any .well-known lookup), return the host, port and
  253. the ssl server name
  254. """
  255. if server_name[-1] == "]":
  256. # ipv6 literal (with no port)
  257. return server_name, 8448, server_name
  258. if ":" in server_name:
  259. # explicit port
  260. out = server_name.rsplit(":", 1)
  261. try:
  262. port = int(out[1])
  263. except ValueError:
  264. raise ValueError("Invalid host:port '%s'" % (server_name,))
  265. return out[0], port, out[0]
  266. # Look up SRV for Matrix 1.8 `matrix-fed` service first
  267. try:
  268. srv = srvlookup.lookup("matrix-fed", "tcp", server_name)[0]
  269. print(
  270. f"SRV lookup on _matrix-fed._tcp.{server_name} gave {srv}",
  271. file=sys.stderr,
  272. )
  273. return srv.host, srv.port, server_name
  274. except Exception:
  275. pass
  276. # Fall back to deprecated `matrix` service
  277. try:
  278. srv = srvlookup.lookup("matrix", "tcp", server_name)[0]
  279. print(
  280. f"SRV lookup on _matrix._tcp.{server_name} gave {srv}",
  281. file=sys.stderr,
  282. )
  283. return srv.host, srv.port, server_name
  284. except Exception:
  285. # Fall even further back to just port 8448
  286. return server_name, 8448, server_name
  287. @staticmethod
  288. def _get_well_known(server_name: str) -> Optional[str]:
  289. if ":" in server_name:
  290. # explicit port, or ipv6 literal. Either way, no .well-known
  291. return None
  292. # TODO: check for ipv4 literals
  293. uri = f"https://{server_name}/.well-known/matrix/server"
  294. print(f"fetching {uri}", file=sys.stderr)
  295. try:
  296. resp = requests.get(uri)
  297. if resp.status_code != 200:
  298. print("%s gave %i" % (uri, resp.status_code), file=sys.stderr)
  299. return None
  300. parsed_well_known = resp.json()
  301. if not isinstance(parsed_well_known, dict):
  302. raise Exception("not a dict")
  303. if "m.server" not in parsed_well_known:
  304. raise Exception("Missing key 'm.server'")
  305. new_name = parsed_well_known["m.server"]
  306. print("well-known lookup gave %s" % (new_name,), file=sys.stderr)
  307. return new_name
  308. except Exception as e:
  309. print("Invalid response from %s: %s" % (uri, e), file=sys.stderr)
  310. return None
  311. if __name__ == "__main__":
  312. main()