federation_client.py 8.9 KB

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