1
0

federation_client.py 8.4 KB

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