tls.py 19 KB

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