You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

516 lines
21 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. import os
  16. import warnings
  17. from datetime import datetime
  18. from hashlib import sha256
  19. from typing import List, Optional
  20. from unpaddedbase64 import encode_base64
  21. from OpenSSL import SSL, crypto
  22. from twisted.internet._sslverify import Certificate, trustRootFromCertificates
  23. from synapse.config._base import Config, ConfigError
  24. from synapse.util import glob_to_regex
  25. logger = logging.getLogger(__name__)
  26. ACME_SUPPORT_ENABLED_WARN = """\
  27. This server uses Synapse's built-in ACME support. Note that ACME v1 has been
  28. deprecated by Let's Encrypt, and that Synapse doesn't currently support ACME v2,
  29. which means that this feature will not work with Synapse installs set up after
  30. November 2019, and that it may stop working on June 2020 for installs set up
  31. before that date.
  32. For more info and alternative solutions, see
  33. https://github.com/matrix-org/synapse/blob/master/docs/ACME.md#deprecation-of-acme-v1
  34. --------------------------------------------------------------------------------"""
  35. class TlsConfig(Config):
  36. section = "tls"
  37. def read_config(self, config: dict, config_dir_path: str, **kwargs):
  38. acme_config = config.get("acme", None)
  39. if acme_config is None:
  40. acme_config = {}
  41. self.acme_enabled = acme_config.get("enabled", False)
  42. if self.acme_enabled:
  43. logger.warning(ACME_SUPPORT_ENABLED_WARN)
  44. # hyperlink complains on py2 if this is not a Unicode
  45. self.acme_url = str(
  46. acme_config.get("url", "https://acme-v01.api.letsencrypt.org/directory")
  47. )
  48. self.acme_port = acme_config.get("port", 80)
  49. self.acme_bind_addresses = acme_config.get("bind_addresses", ["::", "0.0.0.0"])
  50. self.acme_reprovision_threshold = acme_config.get("reprovision_threshold", 30)
  51. self.acme_domain = acme_config.get("domain", config.get("server_name"))
  52. self.acme_account_key_file = self.abspath(
  53. acme_config.get("account_key_file", config_dir_path + "/client.key")
  54. )
  55. self.tls_certificate_file = self.abspath(config.get("tls_certificate_path"))
  56. self.tls_private_key_file = self.abspath(config.get("tls_private_key_path"))
  57. if self.root.server.has_tls_listener():
  58. if not self.tls_certificate_file:
  59. raise ConfigError(
  60. "tls_certificate_path must be specified if TLS-enabled listeners are "
  61. "configured."
  62. )
  63. if not self.tls_private_key_file:
  64. raise ConfigError(
  65. "tls_private_key_path must be specified if TLS-enabled listeners are "
  66. "configured."
  67. )
  68. self._original_tls_fingerprints = config.get("tls_fingerprints", [])
  69. if self._original_tls_fingerprints is None:
  70. self._original_tls_fingerprints = []
  71. self.tls_fingerprints = list(self._original_tls_fingerprints)
  72. # Whether to verify certificates on outbound federation traffic
  73. self.federation_verify_certificates = config.get(
  74. "federation_verify_certificates", True
  75. )
  76. # Minimum TLS version to use for outbound federation traffic
  77. self.federation_client_minimum_tls_version = str(
  78. config.get("federation_client_minimum_tls_version", 1)
  79. )
  80. if self.federation_client_minimum_tls_version not in ["1", "1.1", "1.2", "1.3"]:
  81. raise ConfigError(
  82. "federation_client_minimum_tls_version must be one of: 1, 1.1, 1.2, 1.3"
  83. )
  84. # Prevent people shooting themselves in the foot here by setting it to
  85. # the biggest number blindly
  86. if self.federation_client_minimum_tls_version == "1.3":
  87. if getattr(SSL, "OP_NO_TLSv1_3", None) is None:
  88. raise ConfigError(
  89. (
  90. "federation_client_minimum_tls_version cannot be 1.3, "
  91. "your OpenSSL does not support it"
  92. )
  93. )
  94. # Whitelist of domains to not verify certificates for
  95. fed_whitelist_entries = config.get(
  96. "federation_certificate_verification_whitelist", []
  97. )
  98. if fed_whitelist_entries is None:
  99. fed_whitelist_entries = []
  100. # Support globs (*) in whitelist values
  101. self.federation_certificate_verification_whitelist = [] # type: List[str]
  102. for entry in fed_whitelist_entries:
  103. try:
  104. entry_regex = glob_to_regex(entry.encode("ascii").decode("ascii"))
  105. except UnicodeEncodeError:
  106. raise ConfigError(
  107. "IDNA domain names are not allowed in the "
  108. "federation_certificate_verification_whitelist: %s" % (entry,)
  109. )
  110. # Convert globs to regex
  111. self.federation_certificate_verification_whitelist.append(entry_regex)
  112. # List of custom certificate authorities for federation traffic validation
  113. custom_ca_list = config.get("federation_custom_ca_list", None)
  114. # Read in and parse custom CA certificates
  115. self.federation_ca_trust_root = None
  116. if custom_ca_list is not None:
  117. if len(custom_ca_list) == 0:
  118. # A trustroot cannot be generated without any CA certificates.
  119. # Raise an error if this option has been specified without any
  120. # corresponding certificates.
  121. raise ConfigError(
  122. "federation_custom_ca_list specified without "
  123. "any certificate files"
  124. )
  125. certs = []
  126. for ca_file in custom_ca_list:
  127. logger.debug("Reading custom CA certificate file: %s", ca_file)
  128. content = self.read_file(ca_file, "federation_custom_ca_list")
  129. # Parse the CA certificates
  130. try:
  131. cert_base = Certificate.loadPEM(content)
  132. certs.append(cert_base)
  133. except Exception as e:
  134. raise ConfigError(
  135. "Error parsing custom CA certificate file %s: %s" % (ca_file, e)
  136. )
  137. self.federation_ca_trust_root = trustRootFromCertificates(certs)
  138. # This config option applies to non-federation HTTP clients
  139. # (e.g. for talking to recaptcha, identity servers, and such)
  140. # It should never be used in production, and is intended for
  141. # use only when running tests.
  142. self.use_insecure_ssl_client_just_for_testing_do_not_use = config.get(
  143. "use_insecure_ssl_client_just_for_testing_do_not_use"
  144. )
  145. self.tls_certificate = None # type: Optional[crypto.X509]
  146. self.tls_private_key = None # type: Optional[crypto.PKey]
  147. def is_disk_cert_valid(self, allow_self_signed=True):
  148. """
  149. Is the certificate we have on disk valid, and if so, for how long?
  150. Args:
  151. allow_self_signed (bool): Should we allow the certificate we
  152. read to be self signed?
  153. Returns:
  154. int: Days remaining of certificate validity.
  155. None: No certificate exists.
  156. """
  157. if not os.path.exists(self.tls_certificate_file):
  158. return None
  159. try:
  160. with open(self.tls_certificate_file, "rb") as f:
  161. cert_pem = f.read()
  162. except Exception as e:
  163. raise ConfigError(
  164. "Failed to read existing certificate file %s: %s"
  165. % (self.tls_certificate_file, e)
  166. )
  167. try:
  168. tls_certificate = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem)
  169. except Exception as e:
  170. raise ConfigError(
  171. "Failed to parse existing certificate file %s: %s"
  172. % (self.tls_certificate_file, e)
  173. )
  174. if not allow_self_signed:
  175. if tls_certificate.get_subject() == tls_certificate.get_issuer():
  176. raise ValueError(
  177. "TLS Certificate is self signed, and this is not permitted"
  178. )
  179. # YYYYMMDDhhmmssZ -- in UTC
  180. expires_on = datetime.strptime(
  181. tls_certificate.get_notAfter().decode("ascii"), "%Y%m%d%H%M%SZ"
  182. )
  183. now = datetime.utcnow()
  184. days_remaining = (expires_on - now).days
  185. return days_remaining
  186. def read_certificate_from_disk(self, require_cert_and_key: bool):
  187. """
  188. Read the certificates and private key from disk.
  189. Args:
  190. require_cert_and_key: set to True to throw an error if the certificate
  191. and key file are not given
  192. """
  193. if require_cert_and_key:
  194. self.tls_private_key = self.read_tls_private_key()
  195. self.tls_certificate = self.read_tls_certificate()
  196. elif self.tls_certificate_file:
  197. # we only need the certificate for the tls_fingerprints. Reload it if we
  198. # can, but it's not a fatal error if we can't.
  199. try:
  200. self.tls_certificate = self.read_tls_certificate()
  201. except Exception as e:
  202. logger.info(
  203. "Unable to read TLS certificate (%s). Ignoring as no "
  204. "tls listeners enabled.",
  205. e,
  206. )
  207. self.tls_fingerprints = list(self._original_tls_fingerprints)
  208. if self.tls_certificate:
  209. # Check that our own certificate is included in the list of fingerprints
  210. # and include it if it is not.
  211. x509_certificate_bytes = crypto.dump_certificate(
  212. crypto.FILETYPE_ASN1, self.tls_certificate
  213. )
  214. sha256_fingerprint = encode_base64(sha256(x509_certificate_bytes).digest())
  215. sha256_fingerprints = {f["sha256"] for f in self.tls_fingerprints}
  216. if sha256_fingerprint not in sha256_fingerprints:
  217. self.tls_fingerprints.append({"sha256": sha256_fingerprint})
  218. def generate_config_section(
  219. self,
  220. config_dir_path,
  221. server_name,
  222. data_dir_path,
  223. tls_certificate_path,
  224. tls_private_key_path,
  225. acme_domain,
  226. **kwargs,
  227. ):
  228. """If the acme_domain is specified acme will be enabled.
  229. If the TLS paths are not specified the default will be certs in the
  230. config directory"""
  231. base_key_name = os.path.join(config_dir_path, server_name)
  232. if bool(tls_certificate_path) != bool(tls_private_key_path):
  233. raise ConfigError(
  234. "Please specify both a cert path and a key path or neither."
  235. )
  236. tls_enabled = (
  237. "" if tls_certificate_path and tls_private_key_path or acme_domain else "#"
  238. )
  239. if not tls_certificate_path:
  240. tls_certificate_path = base_key_name + ".tls.crt"
  241. if not tls_private_key_path:
  242. tls_private_key_path = base_key_name + ".tls.key"
  243. acme_enabled = bool(acme_domain)
  244. acme_domain = "matrix.example.com"
  245. default_acme_account_file = os.path.join(data_dir_path, "acme_account.key")
  246. # this is to avoid the max line length. Sorrynotsorry
  247. proxypassline = (
  248. "ProxyPass /.well-known/acme-challenge "
  249. "http://localhost:8009/.well-known/acme-challenge"
  250. )
  251. # flake8 doesn't recognise that variables are used in the below string
  252. _ = tls_enabled, proxypassline, acme_enabled, default_acme_account_file
  253. return (
  254. """\
  255. ## TLS ##
  256. # PEM-encoded X509 certificate for TLS.
  257. # This certificate, as of Synapse 1.0, will need to be a valid and verifiable
  258. # certificate, signed by a recognised Certificate Authority.
  259. #
  260. # See 'ACME support' below to enable auto-provisioning this certificate via
  261. # Let's Encrypt.
  262. #
  263. # If supplying your own, be sure to use a `.pem` file that includes the
  264. # full certificate chain including any intermediate certificates (for
  265. # instance, if using certbot, use `fullchain.pem` as your certificate,
  266. # not `cert.pem`).
  267. #
  268. %(tls_enabled)stls_certificate_path: "%(tls_certificate_path)s"
  269. # PEM-encoded private key for TLS
  270. #
  271. %(tls_enabled)stls_private_key_path: "%(tls_private_key_path)s"
  272. # Whether to verify TLS server certificates for outbound federation requests.
  273. #
  274. # Defaults to `true`. To disable certificate verification, uncomment the
  275. # following line.
  276. #
  277. #federation_verify_certificates: false
  278. # The minimum TLS version that will be used for outbound federation requests.
  279. #
  280. # Defaults to `1`. Configurable to `1`, `1.1`, `1.2`, or `1.3`. Note
  281. # that setting this value higher than `1.2` will prevent federation to most
  282. # of the public Matrix network: only configure it to `1.3` if you have an
  283. # entirely private federation setup and you can ensure TLS 1.3 support.
  284. #
  285. #federation_client_minimum_tls_version: 1.2
  286. # Skip federation certificate verification on the following whitelist
  287. # of domains.
  288. #
  289. # This setting should only be used in very specific cases, such as
  290. # federation over Tor hidden services and similar. For private networks
  291. # of homeservers, you likely want to use a private CA instead.
  292. #
  293. # Only effective if federation_verify_certicates is `true`.
  294. #
  295. #federation_certificate_verification_whitelist:
  296. # - lon.example.com
  297. # - *.domain.com
  298. # - *.onion
  299. # List of custom certificate authorities for federation traffic.
  300. #
  301. # This setting should only normally be used within a private network of
  302. # homeservers.
  303. #
  304. # Note that this list will replace those that are provided by your
  305. # operating environment. Certificates must be in PEM format.
  306. #
  307. #federation_custom_ca_list:
  308. # - myCA1.pem
  309. # - myCA2.pem
  310. # - myCA3.pem
  311. # ACME support: This will configure Synapse to request a valid TLS certificate
  312. # for your configured `server_name` via Let's Encrypt.
  313. #
  314. # Note that ACME v1 is now deprecated, and Synapse currently doesn't support
  315. # ACME v2. This means that this feature currently won't work with installs set
  316. # up after November 2019. For more info, and alternative solutions, see
  317. # https://github.com/matrix-org/synapse/blob/master/docs/ACME.md#deprecation-of-acme-v1
  318. #
  319. # Note that provisioning a certificate in this way requires port 80 to be
  320. # routed to Synapse so that it can complete the http-01 ACME challenge.
  321. # By default, if you enable ACME support, Synapse will attempt to listen on
  322. # port 80 for incoming http-01 challenges - however, this will likely fail
  323. # with 'Permission denied' or a similar error.
  324. #
  325. # There are a couple of potential solutions to this:
  326. #
  327. # * If you already have an Apache, Nginx, or similar listening on port 80,
  328. # you can configure Synapse to use an alternate port, and have your web
  329. # server forward the requests. For example, assuming you set 'port: 8009'
  330. # below, on Apache, you would write:
  331. #
  332. # %(proxypassline)s
  333. #
  334. # * Alternatively, you can use something like `authbind` to give Synapse
  335. # permission to listen on port 80.
  336. #
  337. acme:
  338. # ACME support is disabled by default. Set this to `true` and uncomment
  339. # tls_certificate_path and tls_private_key_path above to enable it.
  340. #
  341. enabled: %(acme_enabled)s
  342. # Endpoint to use to request certificates. If you only want to test,
  343. # use Let's Encrypt's staging url:
  344. # https://acme-staging.api.letsencrypt.org/directory
  345. #
  346. #url: https://acme-v01.api.letsencrypt.org/directory
  347. # Port number to listen on for the HTTP-01 challenge. Change this if
  348. # you are forwarding connections through Apache/Nginx/etc.
  349. #
  350. port: 80
  351. # Local addresses to listen on for incoming connections.
  352. # Again, you may want to change this if you are forwarding connections
  353. # through Apache/Nginx/etc.
  354. #
  355. bind_addresses: ['::', '0.0.0.0']
  356. # How many days remaining on a certificate before it is renewed.
  357. #
  358. reprovision_threshold: 30
  359. # The domain that the certificate should be for. Normally this
  360. # should be the same as your Matrix domain (i.e., 'server_name'), but,
  361. # by putting a file at 'https://<server_name>/.well-known/matrix/server',
  362. # you can delegate incoming traffic to another server. If you do that,
  363. # you should give the target of the delegation here.
  364. #
  365. # For example: if your 'server_name' is 'example.com', but
  366. # 'https://example.com/.well-known/matrix/server' delegates to
  367. # 'matrix.example.com', you should put 'matrix.example.com' here.
  368. #
  369. # If not set, defaults to your 'server_name'.
  370. #
  371. domain: %(acme_domain)s
  372. # file to use for the account key. This will be generated if it doesn't
  373. # exist.
  374. #
  375. # If unspecified, we will use CONFDIR/client.key.
  376. #
  377. account_key_file: %(default_acme_account_file)s
  378. # List of allowed TLS fingerprints for this server to publish along
  379. # with the signing keys for this server. Other matrix servers that
  380. # make HTTPS requests to this server will check that the TLS
  381. # certificates returned by this server match one of the fingerprints.
  382. #
  383. # Synapse automatically adds the fingerprint of its own certificate
  384. # to the list. So if federation traffic is handled directly by synapse
  385. # then no modification to the list is required.
  386. #
  387. # If synapse is run behind a load balancer that handles the TLS then it
  388. # will be necessary to add the fingerprints of the certificates used by
  389. # the loadbalancers to this list if they are different to the one
  390. # synapse is using.
  391. #
  392. # Homeservers are permitted to cache the list of TLS fingerprints
  393. # returned in the key responses up to the "valid_until_ts" returned in
  394. # key. It may be necessary to publish the fingerprints of a new
  395. # certificate and wait until the "valid_until_ts" of the previous key
  396. # responses have passed before deploying it.
  397. #
  398. # You can calculate a fingerprint from a given TLS listener via:
  399. # openssl s_client -connect $host:$port < /dev/null 2> /dev/null |
  400. # openssl x509 -outform DER | openssl sha256 -binary | base64 | tr -d '='
  401. # or by checking matrix.org/federationtester/api/report?server_name=$host
  402. #
  403. #tls_fingerprints: [{"sha256": "<base64_encoded_sha256_fingerprint>"}]
  404. """
  405. # Lowercase the string representation of boolean values
  406. % {
  407. x[0]: str(x[1]).lower() if isinstance(x[1], bool) else x[1]
  408. for x in locals().items()
  409. }
  410. )
  411. def read_tls_certificate(self) -> crypto.X509:
  412. """Reads the TLS certificate from the configured file, and returns it
  413. Also checks if it is self-signed, and warns if so
  414. Returns:
  415. The certificate
  416. """
  417. cert_path = self.tls_certificate_file
  418. logger.info("Loading TLS certificate from %s", cert_path)
  419. cert_pem = self.read_file(cert_path, "tls_certificate_path")
  420. cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem)
  421. # Check if it is self-signed, and issue a warning if so.
  422. if cert.get_issuer() == cert.get_subject():
  423. warnings.warn(
  424. (
  425. "Self-signed TLS certificates will not be accepted by Synapse 1.0. "
  426. "Please either provide a valid certificate, or use Synapse's ACME "
  427. "support to provision one."
  428. )
  429. )
  430. return cert
  431. def read_tls_private_key(self) -> crypto.PKey:
  432. """Reads the TLS private key from the configured file, and returns it
  433. Returns:
  434. The private key
  435. """
  436. private_key_path = self.tls_private_key_file
  437. logger.info("Loading TLS key from %s", private_key_path)
  438. private_key_pem = self.read_file(private_key_path, "tls_private_key_path")
  439. return crypto.load_privatekey(crypto.FILETYPE_PEM, private_key_pem)