key.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. # Copyright 2019 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import hashlib
  17. import logging
  18. import os
  19. import attr
  20. import jsonschema
  21. from signedjson.key import (
  22. NACL_ED25519,
  23. decode_signing_key_base64,
  24. decode_verify_key_bytes,
  25. generate_signing_key,
  26. is_signing_algorithm_supported,
  27. read_signing_keys,
  28. write_signing_keys,
  29. )
  30. from unpaddedbase64 import decode_base64
  31. from synapse.util.stringutils import random_string, random_string_with_symbols
  32. from ._base import Config, ConfigError
  33. INSECURE_NOTARY_ERROR = """\
  34. Your server is configured to accept key server responses without signature
  35. validation or TLS certificate validation. This is likely to be very insecure. If
  36. you are *sure* you want to do this, set 'accept_keys_insecurely' on the
  37. keyserver configuration."""
  38. RELYING_ON_MATRIX_KEY_ERROR = """\
  39. Your server is configured to accept key server responses without TLS certificate
  40. validation, and which are only signed by the old (possibly compromised)
  41. matrix.org signing key 'ed25519:auto'. This likely isn't what you want to do,
  42. and you should enable 'federation_verify_certificates' in your configuration.
  43. If you are *sure* you want to do this, set 'accept_keys_insecurely' on the
  44. trusted_key_server configuration."""
  45. TRUSTED_KEY_SERVER_NOT_CONFIGURED_WARN = """\
  46. Synapse requires that a list of trusted key servers are specified in order to
  47. provide signing keys for other servers in the federation.
  48. This homeserver does not have a trusted key server configured in
  49. homeserver.yaml and will fall back to the default of 'matrix.org'.
  50. Trusted key servers should be long-lived and stable which makes matrix.org a
  51. good choice for many admins, but some admins may wish to choose another. To
  52. suppress this warning, the admin should set 'trusted_key_servers' in
  53. homeserver.yaml to their desired key server and 'suppress_key_server_warning'
  54. to 'true'.
  55. In a future release the software-defined default will be removed entirely and
  56. the trusted key server will be defined exclusively by the value of
  57. 'trusted_key_servers'.
  58. --------------------------------------------------------------------------------"""
  59. TRUSTED_KEY_SERVER_CONFIGURED_AS_M_ORG_WARN = """\
  60. This server is configured to use 'matrix.org' as its trusted key server via the
  61. 'trusted_key_servers' config option. 'matrix.org' is a good choice for a key
  62. server since it is long-lived, stable and trusted. However, some admins may
  63. wish to use another server for this purpose.
  64. To suppress this warning and continue using 'matrix.org', admins should set
  65. 'suppress_key_server_warning' to 'true' in homeserver.yaml.
  66. --------------------------------------------------------------------------------"""
  67. logger = logging.getLogger(__name__)
  68. @attr.s
  69. class TrustedKeyServer(object):
  70. # string: name of the server.
  71. server_name = attr.ib()
  72. # dict[str,VerifyKey]|None: map from key id to key object, or None to disable
  73. # signature verification.
  74. verify_keys = attr.ib(default=None)
  75. class KeyConfig(Config):
  76. section = "key"
  77. def read_config(self, config, config_dir_path, **kwargs):
  78. # the signing key can be specified inline or in a separate file
  79. if "signing_key" in config:
  80. self.signing_key = read_signing_keys([config["signing_key"]])
  81. else:
  82. signing_key_path = config.get("signing_key_path")
  83. if signing_key_path is None:
  84. signing_key_path = os.path.join(
  85. config_dir_path, config["server_name"] + ".signing.key"
  86. )
  87. self.signing_key = self.read_signing_keys(signing_key_path, "signing_key")
  88. self.old_signing_keys = self.read_old_signing_keys(
  89. config.get("old_signing_keys")
  90. )
  91. self.key_refresh_interval = self.parse_duration(
  92. config.get("key_refresh_interval", "1d")
  93. )
  94. suppress_key_server_warning = config.get("suppress_key_server_warning", False)
  95. key_server_signing_keys_path = config.get("key_server_signing_keys_path")
  96. if key_server_signing_keys_path:
  97. self.key_server_signing_keys = self.read_signing_keys(
  98. key_server_signing_keys_path, "key_server_signing_keys_path"
  99. )
  100. else:
  101. self.key_server_signing_keys = list(self.signing_key)
  102. # if neither trusted_key_servers nor perspectives are given, use the default.
  103. if "perspectives" not in config and "trusted_key_servers" not in config:
  104. logger.warning(TRUSTED_KEY_SERVER_NOT_CONFIGURED_WARN)
  105. key_servers = [{"server_name": "matrix.org"}]
  106. else:
  107. key_servers = config.get("trusted_key_servers", [])
  108. if not isinstance(key_servers, list):
  109. raise ConfigError(
  110. "trusted_key_servers, if given, must be a list, not a %s"
  111. % (type(key_servers).__name__,)
  112. )
  113. # merge the 'perspectives' config into the 'trusted_key_servers' config.
  114. key_servers.extend(_perspectives_to_key_servers(config))
  115. if not suppress_key_server_warning and "matrix.org" in (
  116. s["server_name"] for s in key_servers
  117. ):
  118. logger.warning(TRUSTED_KEY_SERVER_CONFIGURED_AS_M_ORG_WARN)
  119. # list of TrustedKeyServer objects
  120. self.key_servers = list(
  121. _parse_key_servers(key_servers, self.federation_verify_certificates)
  122. )
  123. self.macaroon_secret_key = config.get(
  124. "macaroon_secret_key", self.registration_shared_secret
  125. )
  126. if not self.macaroon_secret_key:
  127. # Unfortunately, there are people out there that don't have this
  128. # set. Lets just be "nice" and derive one from their secret key.
  129. logger.warning("Config is missing macaroon_secret_key")
  130. seed = bytes(self.signing_key[0])
  131. self.macaroon_secret_key = hashlib.sha256(seed).digest()
  132. # a secret which is used to calculate HMACs for form values, to stop
  133. # falsification of values
  134. self.form_secret = config.get("form_secret", None)
  135. def generate_config_section(
  136. self, config_dir_path, server_name, generate_secrets=False, **kwargs
  137. ):
  138. base_key_name = os.path.join(config_dir_path, server_name)
  139. if generate_secrets:
  140. macaroon_secret_key = 'macaroon_secret_key: "%s"' % (
  141. random_string_with_symbols(50),
  142. )
  143. form_secret = 'form_secret: "%s"' % random_string_with_symbols(50)
  144. else:
  145. macaroon_secret_key = "#macaroon_secret_key: <PRIVATE STRING>"
  146. form_secret = "#form_secret: <PRIVATE STRING>"
  147. return (
  148. """\
  149. # a secret which is used to sign access tokens. If none is specified,
  150. # the registration_shared_secret is used, if one is given; otherwise,
  151. # a secret key is derived from the signing key.
  152. #
  153. %(macaroon_secret_key)s
  154. # a secret which is used to calculate HMACs for form values, to stop
  155. # falsification of values. Must be specified for the User Consent
  156. # forms to work.
  157. #
  158. %(form_secret)s
  159. ## Signing Keys ##
  160. # Path to the signing key to sign messages with
  161. #
  162. signing_key_path: "%(base_key_name)s.signing.key"
  163. # The keys that the server used to sign messages with but won't use
  164. # to sign new messages.
  165. #
  166. old_signing_keys:
  167. # For each key, `key` should be the base64-encoded public key, and
  168. # `expired_ts`should be the time (in milliseconds since the unix epoch) that
  169. # it was last used.
  170. #
  171. # It is possible to build an entry from an old signing.key file using the
  172. # `export_signing_key` script which is provided with synapse.
  173. #
  174. # For example:
  175. #
  176. #"ed25519:id": { key: "base64string", expired_ts: 123456789123 }
  177. # How long key response published by this server is valid for.
  178. # Used to set the valid_until_ts in /key/v2 APIs.
  179. # Determines how quickly servers will query to check which keys
  180. # are still valid.
  181. #
  182. #key_refresh_interval: 1d
  183. # The trusted servers to download signing keys from.
  184. #
  185. # When we need to fetch a signing key, each server is tried in parallel.
  186. #
  187. # Normally, the connection to the key server is validated via TLS certificates.
  188. # Additional security can be provided by configuring a `verify key`, which
  189. # will make synapse check that the response is signed by that key.
  190. #
  191. # This setting supercedes an older setting named `perspectives`. The old format
  192. # is still supported for backwards-compatibility, but it is deprecated.
  193. #
  194. # 'trusted_key_servers' defaults to matrix.org, but using it will generate a
  195. # warning on start-up. To suppress this warning, set
  196. # 'suppress_key_server_warning' to true.
  197. #
  198. # Options for each entry in the list include:
  199. #
  200. # server_name: the name of the server. required.
  201. #
  202. # verify_keys: an optional map from key id to base64-encoded public key.
  203. # If specified, we will check that the response is signed by at least
  204. # one of the given keys.
  205. #
  206. # accept_keys_insecurely: a boolean. Normally, if `verify_keys` is unset,
  207. # and federation_verify_certificates is not `true`, synapse will refuse
  208. # to start, because this would allow anyone who can spoof DNS responses
  209. # to masquerade as the trusted key server. If you know what you are doing
  210. # and are sure that your network environment provides a secure connection
  211. # to the key server, you can set this to `true` to override this
  212. # behaviour.
  213. #
  214. # An example configuration might look like:
  215. #
  216. #trusted_key_servers:
  217. # - server_name: "my_trusted_server.example.com"
  218. # verify_keys:
  219. # "ed25519:auto": "abcdefghijklmnopqrstuvwxyzabcdefghijklmopqr"
  220. # - server_name: "my_other_trusted_server.example.com"
  221. #
  222. trusted_key_servers:
  223. - server_name: "matrix.org"
  224. # Uncomment the following to disable the warning that is emitted when the
  225. # trusted_key_servers include 'matrix.org'. See above.
  226. #
  227. #suppress_key_server_warning: true
  228. # The signing keys to use when acting as a trusted key server. If not specified
  229. # defaults to the server signing key.
  230. #
  231. # Can contain multiple keys, one per line.
  232. #
  233. #key_server_signing_keys_path: "key_server_signing_keys.key"
  234. """
  235. % locals()
  236. )
  237. def read_signing_keys(self, signing_key_path, name):
  238. """Read the signing keys in the given path.
  239. Args:
  240. signing_key_path (str)
  241. name (str): Associated config key name
  242. Returns:
  243. list[SigningKey]
  244. """
  245. signing_keys = self.read_file(signing_key_path, name)
  246. try:
  247. return read_signing_keys(signing_keys.splitlines(True))
  248. except Exception as e:
  249. raise ConfigError("Error reading %s: %s" % (name, str(e)))
  250. def read_old_signing_keys(self, old_signing_keys):
  251. if old_signing_keys is None:
  252. return {}
  253. keys = {}
  254. for key_id, key_data in old_signing_keys.items():
  255. if is_signing_algorithm_supported(key_id):
  256. key_base64 = key_data["key"]
  257. key_bytes = decode_base64(key_base64)
  258. verify_key = decode_verify_key_bytes(key_id, key_bytes)
  259. verify_key.expired_ts = key_data["expired_ts"]
  260. keys[key_id] = verify_key
  261. else:
  262. raise ConfigError(
  263. "Unsupported signing algorithm for old key: %r" % (key_id,)
  264. )
  265. return keys
  266. def generate_files(self, config, config_dir_path):
  267. if "signing_key" in config:
  268. return
  269. signing_key_path = config.get("signing_key_path")
  270. if signing_key_path is None:
  271. signing_key_path = os.path.join(
  272. config_dir_path, config["server_name"] + ".signing.key"
  273. )
  274. if not self.path_exists(signing_key_path):
  275. print("Generating signing key file %s" % (signing_key_path,))
  276. with open(signing_key_path, "w") as signing_key_file:
  277. key_id = "a_" + random_string(4)
  278. write_signing_keys(signing_key_file, (generate_signing_key(key_id),))
  279. else:
  280. signing_keys = self.read_file(signing_key_path, "signing_key")
  281. if len(signing_keys.split("\n")[0].split()) == 1:
  282. # handle keys in the old format.
  283. key_id = "a_" + random_string(4)
  284. key = decode_signing_key_base64(
  285. NACL_ED25519, key_id, signing_keys.split("\n")[0]
  286. )
  287. with open(signing_key_path, "w") as signing_key_file:
  288. write_signing_keys(signing_key_file, (key,))
  289. def _perspectives_to_key_servers(config):
  290. """Convert old-style 'perspectives' configs into new-style 'trusted_key_servers'
  291. Returns an iterable of entries to add to trusted_key_servers.
  292. """
  293. # 'perspectives' looks like:
  294. #
  295. # {
  296. # "servers": {
  297. # "matrix.org": {
  298. # "verify_keys": {
  299. # "ed25519:auto": {
  300. # "key": "Noi6WqcDj0QmPxCNQqgezwTlBKrfqehY1u2FyWP9uYw"
  301. # }
  302. # }
  303. # }
  304. # }
  305. # }
  306. #
  307. # 'trusted_keys' looks like:
  308. #
  309. # [
  310. # {
  311. # "server_name": "matrix.org",
  312. # "verify_keys": {
  313. # "ed25519:auto": "Noi6WqcDj0QmPxCNQqgezwTlBKrfqehY1u2FyWP9uYw",
  314. # }
  315. # }
  316. # ]
  317. perspectives_servers = config.get("perspectives", {}).get("servers", {})
  318. for server_name, server_opts in perspectives_servers.items():
  319. trusted_key_server_entry = {"server_name": server_name}
  320. verify_keys = server_opts.get("verify_keys")
  321. if verify_keys is not None:
  322. trusted_key_server_entry["verify_keys"] = {
  323. key_id: key_data["key"] for key_id, key_data in verify_keys.items()
  324. }
  325. yield trusted_key_server_entry
  326. TRUSTED_KEY_SERVERS_SCHEMA = {
  327. "$schema": "http://json-schema.org/draft-04/schema#",
  328. "description": "schema for the trusted_key_servers setting",
  329. "type": "array",
  330. "items": {
  331. "type": "object",
  332. "properties": {
  333. "server_name": {"type": "string"},
  334. "verify_keys": {
  335. "type": "object",
  336. # each key must be a base64 string
  337. "additionalProperties": {"type": "string"},
  338. },
  339. },
  340. "required": ["server_name"],
  341. },
  342. }
  343. def _parse_key_servers(key_servers, federation_verify_certificates):
  344. try:
  345. jsonschema.validate(key_servers, TRUSTED_KEY_SERVERS_SCHEMA)
  346. except jsonschema.ValidationError as e:
  347. raise ConfigError("Unable to parse 'trusted_key_servers': " + e.message)
  348. for server in key_servers:
  349. server_name = server["server_name"]
  350. result = TrustedKeyServer(server_name=server_name)
  351. verify_keys = server.get("verify_keys")
  352. if verify_keys is not None:
  353. result.verify_keys = {}
  354. for key_id, key_base64 in verify_keys.items():
  355. if not is_signing_algorithm_supported(key_id):
  356. raise ConfigError(
  357. "Unsupported signing algorithm on key %s for server %s in "
  358. "trusted_key_servers" % (key_id, server_name)
  359. )
  360. try:
  361. key_bytes = decode_base64(key_base64)
  362. verify_key = decode_verify_key_bytes(key_id, key_bytes)
  363. except Exception as e:
  364. raise ConfigError(
  365. "Unable to parse key %s for server %s in "
  366. "trusted_key_servers: %s" % (key_id, server_name, e)
  367. )
  368. result.verify_keys[key_id] = verify_key
  369. if not federation_verify_certificates and not server.get(
  370. "accept_keys_insecurely"
  371. ):
  372. _assert_keyserver_has_verify_keys(result)
  373. yield result
  374. def _assert_keyserver_has_verify_keys(trusted_key_server):
  375. if not trusted_key_server.verify_keys:
  376. raise ConfigError(INSECURE_NOTARY_ERROR)
  377. # also check that they are not blindly checking the old matrix.org key
  378. if trusted_key_server.server_name == "matrix.org" and any(
  379. key_id == "ed25519:auto" for key_id in trusted_key_server.verify_keys
  380. ):
  381. raise ConfigError(RELYING_ON_MATRIX_KEY_ERROR)