1
0

federation_client.py 9.3 KB

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