federation_client.py 9.5 KB

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