tls.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. from datetime import datetime
  17. from typing import List, Optional, Pattern
  18. from OpenSSL import SSL, crypto
  19. from twisted.internet._sslverify import Certificate, trustRootFromCertificates
  20. from synapse.config._base import Config, ConfigError
  21. from synapse.util import glob_to_regex
  22. logger = logging.getLogger(__name__)
  23. class TlsConfig(Config):
  24. section = "tls"
  25. def read_config(self, config: dict, config_dir_path: str, **kwargs):
  26. self.tls_certificate_file = self.abspath(config.get("tls_certificate_path"))
  27. self.tls_private_key_file = self.abspath(config.get("tls_private_key_path"))
  28. if self.root.server.has_tls_listener():
  29. if not self.tls_certificate_file:
  30. raise ConfigError(
  31. "tls_certificate_path must be specified if TLS-enabled listeners are "
  32. "configured."
  33. )
  34. if not self.tls_private_key_file:
  35. raise ConfigError(
  36. "tls_private_key_path must be specified if TLS-enabled listeners are "
  37. "configured."
  38. )
  39. # Whether to verify certificates on outbound federation traffic
  40. self.federation_verify_certificates = config.get(
  41. "federation_verify_certificates", True
  42. )
  43. # Minimum TLS version to use for outbound federation traffic
  44. self.federation_client_minimum_tls_version = str(
  45. config.get("federation_client_minimum_tls_version", 1)
  46. )
  47. if self.federation_client_minimum_tls_version not in ["1", "1.1", "1.2", "1.3"]:
  48. raise ConfigError(
  49. "federation_client_minimum_tls_version must be one of: 1, 1.1, 1.2, 1.3"
  50. )
  51. # Prevent people shooting themselves in the foot here by setting it to
  52. # the biggest number blindly
  53. if self.federation_client_minimum_tls_version == "1.3":
  54. if getattr(SSL, "OP_NO_TLSv1_3", None) is None:
  55. raise ConfigError(
  56. "federation_client_minimum_tls_version cannot be 1.3, "
  57. "your OpenSSL does not support it"
  58. )
  59. # Whitelist of domains to not verify certificates for
  60. fed_whitelist_entries = config.get(
  61. "federation_certificate_verification_whitelist", []
  62. )
  63. if fed_whitelist_entries is None:
  64. fed_whitelist_entries = []
  65. # Support globs (*) in whitelist values
  66. self.federation_certificate_verification_whitelist: List[Pattern] = []
  67. for entry in fed_whitelist_entries:
  68. try:
  69. entry_regex = glob_to_regex(entry.encode("ascii").decode("ascii"))
  70. except UnicodeEncodeError:
  71. raise ConfigError(
  72. "IDNA domain names are not allowed in the "
  73. "federation_certificate_verification_whitelist: %s" % (entry,)
  74. )
  75. # Convert globs to regex
  76. self.federation_certificate_verification_whitelist.append(entry_regex)
  77. # List of custom certificate authorities for federation traffic validation
  78. custom_ca_list = config.get("federation_custom_ca_list", None)
  79. # Read in and parse custom CA certificates
  80. self.federation_ca_trust_root = None
  81. if custom_ca_list is not None:
  82. if len(custom_ca_list) == 0:
  83. # A trustroot cannot be generated without any CA certificates.
  84. # Raise an error if this option has been specified without any
  85. # corresponding certificates.
  86. raise ConfigError(
  87. "federation_custom_ca_list specified without "
  88. "any certificate files"
  89. )
  90. certs = []
  91. for ca_file in custom_ca_list:
  92. logger.debug("Reading custom CA certificate file: %s", ca_file)
  93. content = self.read_file(ca_file, "federation_custom_ca_list")
  94. # Parse the CA certificates
  95. try:
  96. cert_base = Certificate.loadPEM(content)
  97. certs.append(cert_base)
  98. except Exception as e:
  99. raise ConfigError(
  100. "Error parsing custom CA certificate file %s: %s" % (ca_file, e)
  101. )
  102. self.federation_ca_trust_root = trustRootFromCertificates(certs)
  103. # This config option applies to non-federation HTTP clients
  104. # (e.g. for talking to recaptcha, identity servers, and such)
  105. # It should never be used in production, and is intended for
  106. # use only when running tests.
  107. self.use_insecure_ssl_client_just_for_testing_do_not_use = config.get(
  108. "use_insecure_ssl_client_just_for_testing_do_not_use"
  109. )
  110. self.tls_certificate: Optional[crypto.X509] = None
  111. self.tls_private_key: Optional[crypto.PKey] = None
  112. def is_disk_cert_valid(self, allow_self_signed=True):
  113. """
  114. Is the certificate we have on disk valid, and if so, for how long?
  115. Args:
  116. allow_self_signed (bool): Should we allow the certificate we
  117. read to be self signed?
  118. Returns:
  119. int: Days remaining of certificate validity.
  120. None: No certificate exists.
  121. """
  122. if not os.path.exists(self.tls_certificate_file):
  123. return None
  124. try:
  125. with open(self.tls_certificate_file, "rb") as f:
  126. cert_pem = f.read()
  127. except Exception as e:
  128. raise ConfigError(
  129. "Failed to read existing certificate file %s: %s"
  130. % (self.tls_certificate_file, e)
  131. )
  132. try:
  133. tls_certificate = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem)
  134. except Exception as e:
  135. raise ConfigError(
  136. "Failed to parse existing certificate file %s: %s"
  137. % (self.tls_certificate_file, e)
  138. )
  139. if not allow_self_signed:
  140. if tls_certificate.get_subject() == tls_certificate.get_issuer():
  141. raise ValueError(
  142. "TLS Certificate is self signed, and this is not permitted"
  143. )
  144. # YYYYMMDDhhmmssZ -- in UTC
  145. expiry_data = tls_certificate.get_notAfter()
  146. if expiry_data is None:
  147. raise ValueError(
  148. "TLS Certificate has no expiry date, and this is not permitted"
  149. )
  150. expires_on = datetime.strptime(expiry_data.decode("ascii"), "%Y%m%d%H%M%SZ")
  151. now = datetime.utcnow()
  152. days_remaining = (expires_on - now).days
  153. return days_remaining
  154. def read_certificate_from_disk(self):
  155. """
  156. Read the certificates and private key from disk.
  157. """
  158. self.tls_private_key = self.read_tls_private_key()
  159. self.tls_certificate = self.read_tls_certificate()
  160. def generate_config_section(
  161. self,
  162. config_dir_path,
  163. server_name,
  164. data_dir_path,
  165. tls_certificate_path,
  166. tls_private_key_path,
  167. **kwargs,
  168. ):
  169. """If the TLS paths are not specified the default will be certs in the
  170. config directory"""
  171. base_key_name = os.path.join(config_dir_path, server_name)
  172. if bool(tls_certificate_path) != bool(tls_private_key_path):
  173. raise ConfigError(
  174. "Please specify both a cert path and a key path or neither."
  175. )
  176. tls_enabled = "" if tls_certificate_path and tls_private_key_path else "#"
  177. if not tls_certificate_path:
  178. tls_certificate_path = base_key_name + ".tls.crt"
  179. if not tls_private_key_path:
  180. tls_private_key_path = base_key_name + ".tls.key"
  181. # flake8 doesn't recognise that variables are used in the below string
  182. _ = tls_enabled
  183. return (
  184. """\
  185. ## TLS ##
  186. # PEM-encoded X509 certificate for TLS.
  187. # This certificate, as of Synapse 1.0, will need to be a valid and verifiable
  188. # certificate, signed by a recognised Certificate Authority.
  189. #
  190. # Be sure to use a `.pem` file that includes the full certificate chain including
  191. # any intermediate certificates (for instance, if using certbot, use
  192. # `fullchain.pem` as your certificate, not `cert.pem`).
  193. #
  194. %(tls_enabled)stls_certificate_path: "%(tls_certificate_path)s"
  195. # PEM-encoded private key for TLS
  196. #
  197. %(tls_enabled)stls_private_key_path: "%(tls_private_key_path)s"
  198. # Whether to verify TLS server certificates for outbound federation requests.
  199. #
  200. # Defaults to `true`. To disable certificate verification, uncomment the
  201. # following line.
  202. #
  203. #federation_verify_certificates: false
  204. # The minimum TLS version that will be used for outbound federation requests.
  205. #
  206. # Defaults to `1`. Configurable to `1`, `1.1`, `1.2`, or `1.3`. Note
  207. # that setting this value higher than `1.2` will prevent federation to most
  208. # of the public Matrix network: only configure it to `1.3` if you have an
  209. # entirely private federation setup and you can ensure TLS 1.3 support.
  210. #
  211. #federation_client_minimum_tls_version: 1.2
  212. # Skip federation certificate verification on the following whitelist
  213. # of domains.
  214. #
  215. # This setting should only be used in very specific cases, such as
  216. # federation over Tor hidden services and similar. For private networks
  217. # of homeservers, you likely want to use a private CA instead.
  218. #
  219. # Only effective if federation_verify_certicates is `true`.
  220. #
  221. #federation_certificate_verification_whitelist:
  222. # - lon.example.com
  223. # - *.domain.com
  224. # - *.onion
  225. # List of custom certificate authorities for federation traffic.
  226. #
  227. # This setting should only normally be used within a private network of
  228. # homeservers.
  229. #
  230. # Note that this list will replace those that are provided by your
  231. # operating environment. Certificates must be in PEM format.
  232. #
  233. #federation_custom_ca_list:
  234. # - myCA1.pem
  235. # - myCA2.pem
  236. # - myCA3.pem
  237. """
  238. # Lowercase the string representation of boolean values
  239. % {
  240. x[0]: str(x[1]).lower() if isinstance(x[1], bool) else x[1]
  241. for x in locals().items()
  242. }
  243. )
  244. def read_tls_certificate(self) -> crypto.X509:
  245. """Reads the TLS certificate from the configured file, and returns it
  246. Returns:
  247. The certificate
  248. """
  249. cert_path = self.tls_certificate_file
  250. logger.info("Loading TLS certificate from %s", cert_path)
  251. cert_pem = self.read_file(cert_path, "tls_certificate_path")
  252. cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem)
  253. return cert
  254. def read_tls_private_key(self) -> crypto.PKey:
  255. """Reads the TLS private key from the configured file, and returns it
  256. Returns:
  257. The private key
  258. """
  259. private_key_path = self.tls_private_key_file
  260. logger.info("Loading TLS key from %s", private_key_path)
  261. private_key_pem = self.read_file(private_key_path, "tls_private_key_path")
  262. return crypto.load_privatekey(crypto.FILETYPE_PEM, private_key_pem)