federation_client.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 urlparse import urlparse, urlunparse
  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(bytes(header))
  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,
  128. url=dest,
  129. headers=headers,
  130. verify=False,
  131. data=content,
  132. )
  133. sys.stderr.write("Status Code: %d\n" % (result.status_code,))
  134. return result.json()
  135. def main():
  136. parser = argparse.ArgumentParser(
  137. description="Signs and sends a federation request to a matrix homeserver"
  138. )
  139. parser.add_argument(
  140. "-N",
  141. "--server-name",
  142. help="Name to give as the local homeserver. If unspecified, will be "
  143. "read from the config file.",
  144. )
  145. parser.add_argument(
  146. "-k",
  147. "--signing-key-path",
  148. help="Path to the file containing the private ed25519 key to sign the "
  149. "request with.",
  150. )
  151. parser.add_argument(
  152. "-c",
  153. "--config",
  154. default="homeserver.yaml",
  155. help="Path to server config file. Ignored if --server-name and "
  156. "--signing-key-path are both given.",
  157. )
  158. parser.add_argument(
  159. "-d",
  160. "--destination",
  161. default="matrix.org",
  162. help="name of the remote homeserver. We will do SRV lookups and "
  163. "connect appropriately.",
  164. )
  165. parser.add_argument(
  166. "-X",
  167. "--method",
  168. help="HTTP method to use for the request. Defaults to GET if --body is"
  169. "unspecified, POST if it is.",
  170. )
  171. parser.add_argument("--body", help="Data to send as the body of the HTTP request")
  172. parser.add_argument(
  173. "path", help="request path. We will add '/_matrix/federation/v1/' to this."
  174. )
  175. args = parser.parse_args()
  176. if not args.server_name or not args.signing_key_path:
  177. read_args_from_config(args)
  178. with open(args.signing_key_path) as f:
  179. key = read_signing_keys(f)[0]
  180. result = request_json(
  181. args.method,
  182. args.server_name,
  183. key,
  184. args.destination,
  185. "/_matrix/federation/v1/" + args.path,
  186. content=args.body,
  187. )
  188. json.dump(result, sys.stdout)
  189. print("")
  190. def read_args_from_config(args):
  191. with open(args.config, 'r') as fh:
  192. config = yaml.safe_load(fh)
  193. if not args.server_name:
  194. args.server_name = config['server_name']
  195. if not args.signing_key_path:
  196. args.signing_key_path = config['signing_key_path']
  197. class MatrixConnectionAdapter(HTTPAdapter):
  198. @staticmethod
  199. def lookup(s):
  200. if s[-1] == ']':
  201. # ipv6 literal (with no port)
  202. return s, 8448
  203. if ":" in s:
  204. out = s.rsplit(":", 1)
  205. try:
  206. port = int(out[1])
  207. except ValueError:
  208. raise ValueError("Invalid host:port '%s'" % s)
  209. return out[0], port
  210. try:
  211. srv = srvlookup.lookup("matrix", "tcp", s)[0]
  212. return srv.host, srv.port
  213. except Exception:
  214. return s, 8448
  215. def get_connection(self, url, proxies=None):
  216. parsed = urlparse(url)
  217. (host, port) = self.lookup(parsed.netloc)
  218. netloc = "%s:%d" % (host, port)
  219. print("Connecting to %s" % (netloc,), file=sys.stderr)
  220. url = urlunparse(
  221. ("https", netloc, parsed.path, parsed.params, parsed.query, parsed.fragment)
  222. )
  223. return super(MatrixConnectionAdapter, self).get_connection(url, proxies)
  224. if __name__ == "__main__":
  225. main()