federation_client.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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 get_json(origin_name, origin_key, destination, path):
  104. request_json = {
  105. "method": "GET",
  106. "uri": path,
  107. "origin": origin_name,
  108. "destination": destination,
  109. }
  110. signed_json = sign_json(request_json, origin_key, origin_name)
  111. authorization_headers = []
  112. for key, sig in signed_json["signatures"][origin_name].items():
  113. header = "X-Matrix origin=%s,key=\"%s\",sig=\"%s\"" % (
  114. origin_name, key, sig,
  115. )
  116. authorization_headers.append(bytes(header))
  117. print ("Authorization: %s" % header, file=sys.stderr)
  118. dest = lookup(destination, path)
  119. print ("Requesting %s" % dest, file=sys.stderr)
  120. result = requests.get(
  121. dest,
  122. headers={"Authorization": authorization_headers[0]},
  123. verify=False,
  124. )
  125. sys.stderr.write("Status Code: %d\n" % (result.status_code,))
  126. return result.json()
  127. def main():
  128. parser = argparse.ArgumentParser(
  129. description=
  130. "Signs and sends a federation request to a matrix homeserver",
  131. )
  132. parser.add_argument(
  133. "-N", "--server-name",
  134. help="Name to give as the local homeserver. If unspecified, will be "
  135. "read from the config file.",
  136. )
  137. parser.add_argument(
  138. "-k", "--signing-key-path",
  139. help="Path to the file containing the private ed25519 key to sign the "
  140. "request with.",
  141. )
  142. parser.add_argument(
  143. "-c", "--config",
  144. default="homeserver.yaml",
  145. help="Path to server config file. Ignored if --server-name and "
  146. "--signing-key-path are both given.",
  147. )
  148. parser.add_argument(
  149. "-d", "--destination",
  150. default="matrix.org",
  151. help="name of the remote homeserver. We will do SRV lookups and "
  152. "connect appropriately.",
  153. )
  154. parser.add_argument(
  155. "path",
  156. help="request path. We will add '/_matrix/federation/v1/' to this."
  157. )
  158. args = parser.parse_args()
  159. if not args.server_name or not args.signing_key_path:
  160. read_args_from_config(args)
  161. with open(args.signing_key_path) as f:
  162. key = read_signing_keys(f)[0]
  163. result = get_json(
  164. args.server_name, key, args.destination, "/_matrix/federation/v1/" + args.path
  165. )
  166. json.dump(result, sys.stdout)
  167. print ("")
  168. def read_args_from_config(args):
  169. with open(args.config, 'r') as fh:
  170. config = yaml.safe_load(fh)
  171. if not args.server_name:
  172. args.server_name = config['server_name']
  173. if not args.signing_key_path:
  174. args.signing_key_path = config['signing_key_path']
  175. if __name__ == "__main__":
  176. main()