tls.py 21 KB

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