federation_client.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 nacl.signing
  20. import json
  21. import base64
  22. import requests
  23. import sys
  24. import srvlookup
  25. import yaml
  26. def encode_base64(input_bytes):
  27. """Encode bytes as a base64 string without any padding."""
  28. input_len = len(input_bytes)
  29. output_len = 4 * ((input_len + 2) // 3) + (input_len + 2) % 3 - 2
  30. output_bytes = base64.b64encode(input_bytes)
  31. output_string = output_bytes[:output_len].decode("ascii")
  32. return output_string
  33. def decode_base64(input_string):
  34. """Decode a base64 string to bytes inferring padding from the length of the
  35. string."""
  36. input_bytes = input_string.encode("ascii")
  37. input_len = len(input_bytes)
  38. padding = b"=" * (3 - ((input_len + 3) % 4))
  39. output_len = 3 * ((input_len + 2) // 4) + (input_len + 2) % 4 - 2
  40. output_bytes = base64.b64decode(input_bytes + padding)
  41. return output_bytes[:output_len]
  42. def encode_canonical_json(value):
  43. return json.dumps(
  44. value,
  45. # Encode code-points outside of ASCII as UTF-8 rather than \u escapes
  46. ensure_ascii=False,
  47. # Remove unecessary white space.
  48. separators=(',',':'),
  49. # Sort the keys of dictionaries.
  50. sort_keys=True,
  51. # Encode the resulting unicode as UTF-8 bytes.
  52. ).encode("UTF-8")
  53. def sign_json(json_object, signing_key, signing_name):
  54. signatures = json_object.pop("signatures", {})
  55. unsigned = json_object.pop("unsigned", None)
  56. signed = signing_key.sign(encode_canonical_json(json_object))
  57. signature_base64 = encode_base64(signed.signature)
  58. key_id = "%s:%s" % (signing_key.alg, signing_key.version)
  59. signatures.setdefault(signing_name, {})[key_id] = signature_base64
  60. json_object["signatures"] = signatures
  61. if unsigned is not None:
  62. json_object["unsigned"] = unsigned
  63. return json_object
  64. NACL_ED25519 = "ed25519"
  65. def decode_signing_key_base64(algorithm, version, key_base64):
  66. """Decode a base64 encoded signing key
  67. Args:
  68. algorithm (str): The algorithm the key is for (currently "ed25519").
  69. version (str): Identifies this key out of the keys for this entity.
  70. key_base64 (str): Base64 encoded bytes of the key.
  71. Returns:
  72. A SigningKey object.
  73. """
  74. if algorithm == NACL_ED25519:
  75. key_bytes = decode_base64(key_base64)
  76. key = nacl.signing.SigningKey(key_bytes)
  77. key.version = version
  78. key.alg = NACL_ED25519
  79. return key
  80. else:
  81. raise ValueError("Unsupported algorithm %s" % (algorithm,))
  82. def read_signing_keys(stream):
  83. """Reads a list of keys from a stream
  84. Args:
  85. stream : A stream to iterate for keys.
  86. Returns:
  87. list of SigningKey objects.
  88. """
  89. keys = []
  90. for line in stream:
  91. algorithm, version, key_base64 = line.split()
  92. keys.append(decode_signing_key_base64(algorithm, version, key_base64))
  93. return keys
  94. def lookup(destination, path):
  95. if ":" in destination:
  96. return "https://%s%s" % (destination, path)
  97. else:
  98. try:
  99. srv = srvlookup.lookup("matrix", "tcp", destination)[0]
  100. return "https://%s:%d%s" % (srv.host, srv.port, path)
  101. except:
  102. return "https://%s:%d%s" % (destination, 8448, path)
  103. def request_json(method, origin_name, origin_key, destination, path, content):
  104. if method is None:
  105. if content is None:
  106. method = "GET"
  107. else:
  108. method = "POST"
  109. json_to_sign = {
  110. "method": method,
  111. "uri": path,
  112. "origin": origin_name,
  113. "destination": destination,
  114. }
  115. if content is not None:
  116. json_to_sign["content"] = json.loads(content)
  117. signed_json = sign_json(json_to_sign, origin_key, origin_name)
  118. authorization_headers = []
  119. for key, sig in signed_json["signatures"][origin_name].items():
  120. header = "X-Matrix origin=%s,key=\"%s\",sig=\"%s\"" % (
  121. origin_name, key, sig,
  122. )
  123. authorization_headers.append(bytes(header))
  124. print ("Authorization: %s" % header, file=sys.stderr)
  125. dest = lookup(destination, path)
  126. print ("Requesting %s" % dest, file=sys.stderr)
  127. result = requests.request(
  128. method=method,
  129. url=dest,
  130. headers={"Authorization": authorization_headers[0]},
  131. verify=False,
  132. data=content,
  133. )
  134. sys.stderr.write("Status Code: %d\n" % (result.status_code,))
  135. return result.json()
  136. def main():
  137. parser = argparse.ArgumentParser(
  138. description=
  139. "Signs and sends a federation request to a matrix homeserver",
  140. )
  141. parser.add_argument(
  142. "-N", "--server-name",
  143. help="Name to give as the local homeserver. If unspecified, will be "
  144. "read from the config file.",
  145. )
  146. parser.add_argument(
  147. "-k", "--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", "--config",
  153. default="homeserver.yaml",
  154. help="Path to server config file. Ignored if --server-name and "
  155. "--signing-key-path are both given.",
  156. )
  157. parser.add_argument(
  158. "-d", "--destination",
  159. default="matrix.org",
  160. help="name of the remote homeserver. We will do SRV lookups and "
  161. "connect appropriately.",
  162. )
  163. parser.add_argument(
  164. "-X", "--method",
  165. help="HTTP method to use for the request. Defaults to GET if --data is"
  166. "unspecified, POST if it is."
  167. )
  168. parser.add_argument(
  169. "--body",
  170. help="Data to send as the body of the HTTP request"
  171. )
  172. parser.add_argument(
  173. "path",
  174. help="request path. We will add '/_matrix/federation/v1/' to this."
  175. )
  176. args = parser.parse_args()
  177. if not args.server_name or not args.signing_key_path:
  178. read_args_from_config(args)
  179. with open(args.signing_key_path) as f:
  180. key = read_signing_keys(f)[0]
  181. result = request_json(
  182. args.method,
  183. args.server_name, key, args.destination,
  184. "/_matrix/federation/v1/" + args.path,
  185. content=args.body,
  186. )
  187. json.dump(result, sys.stdout)
  188. print ("")
  189. def read_args_from_config(args):
  190. with open(args.config, 'r') as fh:
  191. config = yaml.safe_load(fh)
  192. if not args.server_name:
  193. args.server_name = config['server_name']
  194. if not args.signing_key_path:
  195. args.signing_key_path = config['signing_key_path']
  196. if __name__ == "__main__":
  197. main()