key.py 17 KB

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