1
0

federation_client.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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.adapters import HTTPAdapter
  41. from urllib3 import HTTPConnectionPool
  42. # uncomment the following to enable debug logging of http requests
  43. # from httplib import HTTPConnection
  44. # HTTPConnection.debuglevel = 1
  45. def encode_base64(input_bytes: bytes) -> str:
  46. """Encode bytes as a base64 string without any padding."""
  47. input_len = len(input_bytes)
  48. output_len = 4 * ((input_len + 2) // 3) + (input_len + 2) % 3 - 2
  49. output_bytes = base64.b64encode(input_bytes)
  50. output_string = output_bytes[:output_len].decode("ascii")
  51. return output_string
  52. def encode_canonical_json(value: object) -> bytes:
  53. return json.dumps(
  54. value,
  55. # Encode code-points outside of ASCII as UTF-8 rather than \u escapes
  56. ensure_ascii=False,
  57. # Remove unecessary white space.
  58. separators=(",", ":"),
  59. # Sort the keys of dictionaries.
  60. sort_keys=True,
  61. # Encode the resulting unicode as UTF-8 bytes.
  62. ).encode("UTF-8")
  63. def sign_json(
  64. json_object: Any, signing_key: signedjson.types.SigningKey, signing_name: str
  65. ) -> Any:
  66. signatures = json_object.pop("signatures", {})
  67. unsigned = json_object.pop("unsigned", None)
  68. signed = signing_key.sign(encode_canonical_json(json_object))
  69. signature_base64 = encode_base64(signed.signature)
  70. key_id = "%s:%s" % (signing_key.alg, signing_key.version)
  71. signatures.setdefault(signing_name, {})[key_id] = signature_base64
  72. json_object["signatures"] = signatures
  73. if unsigned is not None:
  74. json_object["unsigned"] = unsigned
  75. return json_object
  76. def request(
  77. method: Optional[str],
  78. origin_name: str,
  79. origin_key: signedjson.types.SigningKey,
  80. destination: str,
  81. path: str,
  82. content: Optional[str],
  83. ) -> requests.Response:
  84. if method is None:
  85. if content is None:
  86. method = "GET"
  87. else:
  88. method = "POST"
  89. json_to_sign = {
  90. "method": method,
  91. "uri": path,
  92. "origin": origin_name,
  93. "destination": destination,
  94. }
  95. if content is not None:
  96. json_to_sign["content"] = json.loads(content)
  97. signed_json = sign_json(json_to_sign, origin_key, origin_name)
  98. authorization_headers = []
  99. for key, sig in signed_json["signatures"][origin_name].items():
  100. header = 'X-Matrix origin=%s,key="%s",sig="%s",destination="%s"' % (
  101. origin_name,
  102. key,
  103. sig,
  104. destination,
  105. )
  106. authorization_headers.append(header)
  107. print("Authorization: %s" % header, file=sys.stderr)
  108. dest = "matrix://%s%s" % (destination, path)
  109. print("Requesting %s" % dest, file=sys.stderr)
  110. s = requests.Session()
  111. s.mount("matrix://", MatrixConnectionAdapter())
  112. headers: Dict[str, str] = {
  113. "Host": destination,
  114. "Authorization": authorization_headers[0],
  115. }
  116. if method == "POST":
  117. headers["Content-Type"] = "application/json"
  118. return s.request(
  119. method=method,
  120. url=dest,
  121. headers=headers,
  122. verify=False,
  123. data=content,
  124. stream=True,
  125. )
  126. def main() -> None:
  127. parser = argparse.ArgumentParser(
  128. description="Signs and sends a federation request to a matrix homeserver"
  129. )
  130. parser.add_argument(
  131. "-N",
  132. "--server-name",
  133. help="Name to give as the local homeserver. If unspecified, will be "
  134. "read from the config file.",
  135. )
  136. parser.add_argument(
  137. "-k",
  138. "--signing-key-path",
  139. help="Path to the file containing the private ed25519 key to sign the "
  140. "request with.",
  141. )
  142. parser.add_argument(
  143. "-c",
  144. "--config",
  145. default="homeserver.yaml",
  146. help="Path to server config file. Ignored if --server-name and "
  147. "--signing-key-path are both given.",
  148. )
  149. parser.add_argument(
  150. "-d",
  151. "--destination",
  152. default="matrix.org",
  153. help="name of the remote homeserver. We will do SRV lookups and "
  154. "connect appropriately.",
  155. )
  156. parser.add_argument(
  157. "-X",
  158. "--method",
  159. help="HTTP method to use for the request. Defaults to GET if --body is"
  160. "unspecified, POST if it is.",
  161. )
  162. parser.add_argument("--body", help="Data to send as the body of the HTTP request")
  163. parser.add_argument(
  164. "path", help="request path, including the '/_matrix/federation/...' prefix."
  165. )
  166. args = parser.parse_args()
  167. args.signing_key = None
  168. if args.signing_key_path:
  169. with open(args.signing_key_path) as f:
  170. args.signing_key = f.readline()
  171. if not args.server_name or not args.signing_key:
  172. read_args_from_config(args)
  173. assert isinstance(args.signing_key, str)
  174. algorithm, version, key_base64 = args.signing_key.split()
  175. key = signedjson.key.decode_signing_key_base64(algorithm, version, key_base64)
  176. result = request(
  177. args.method,
  178. args.server_name,
  179. key,
  180. args.destination,
  181. args.path,
  182. content=args.body,
  183. )
  184. sys.stderr.write("Status Code: %d\n" % (result.status_code,))
  185. for chunk in result.iter_content():
  186. # we write raw utf8 to stdout.
  187. sys.stdout.buffer.write(chunk)
  188. print("")
  189. def read_args_from_config(args: argparse.Namespace) -> None:
  190. with open(args.config, "r") as fh:
  191. config = yaml.safe_load(fh)
  192. if not args.server_name:
  193. args.server_name = config["server_name"]
  194. if not args.signing_key:
  195. if "signing_key" in config:
  196. args.signing_key = config["signing_key"]
  197. else:
  198. with open(config["signing_key_path"]) as f:
  199. args.signing_key = f.readline()
  200. class MatrixConnectionAdapter(HTTPAdapter):
  201. @staticmethod
  202. def lookup(s: str, skip_well_known: bool = False) -> Tuple[str, int]:
  203. if s[-1] == "]":
  204. # ipv6 literal (with no port)
  205. return s, 8448
  206. if ":" in s:
  207. out = s.rsplit(":", 1)
  208. try:
  209. port = int(out[1])
  210. except ValueError:
  211. raise ValueError("Invalid host:port '%s'" % s)
  212. return out[0], port
  213. # try a .well-known lookup
  214. if not skip_well_known:
  215. well_known = MatrixConnectionAdapter.get_well_known(s)
  216. if well_known:
  217. return MatrixConnectionAdapter.lookup(well_known, skip_well_known=True)
  218. try:
  219. srv = srvlookup.lookup("matrix", "tcp", s)[0]
  220. return srv.host, srv.port
  221. except Exception:
  222. return s, 8448
  223. @staticmethod
  224. def get_well_known(server_name: str) -> Optional[str]:
  225. uri = "https://%s/.well-known/matrix/server" % (server_name,)
  226. print("fetching %s" % (uri,), file=sys.stderr)
  227. try:
  228. resp = requests.get(uri)
  229. if resp.status_code != 200:
  230. print("%s gave %i" % (uri, resp.status_code), file=sys.stderr)
  231. return None
  232. parsed_well_known = resp.json()
  233. if not isinstance(parsed_well_known, dict):
  234. raise Exception("not a dict")
  235. if "m.server" not in parsed_well_known:
  236. raise Exception("Missing key 'm.server'")
  237. new_name = parsed_well_known["m.server"]
  238. print("well-known lookup gave %s" % (new_name,), file=sys.stderr)
  239. return new_name
  240. except Exception as e:
  241. print("Invalid response from %s: %s" % (uri, e), file=sys.stderr)
  242. return None
  243. def get_connection(
  244. self, url: str, proxies: Optional[Dict[str, str]] = None
  245. ) -> HTTPConnectionPool:
  246. parsed = urlparse.urlparse(url)
  247. (host, port) = self.lookup(parsed.netloc)
  248. netloc = "%s:%d" % (host, port)
  249. print("Connecting to %s" % (netloc,), file=sys.stderr)
  250. url = urlparse.urlunparse(
  251. ("https", netloc, parsed.path, parsed.params, parsed.query, parsed.fragment)
  252. )
  253. return super().get_connection(url, proxies)
  254. if __name__ == "__main__":
  255. main()