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.
 
 
 
 
 
 

187 lines
7.3 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. from typing import Any, List, Optional, Pattern
  16. from matrix_common.regex import glob_to_regex
  17. from OpenSSL import SSL, crypto
  18. from twisted.internet._sslverify import Certificate, trustRootFromCertificates
  19. from synapse.config._base import Config, ConfigError
  20. from synapse.types import JsonDict
  21. logger = logging.getLogger(__name__)
  22. class TlsConfig(Config):
  23. section = "tls"
  24. def read_config(self, config: JsonDict, **kwargs: Any) -> None:
  25. self.tls_certificate_file = self.abspath(config.get("tls_certificate_path"))
  26. self.tls_private_key_file = self.abspath(config.get("tls_private_key_path"))
  27. if self.root.server.has_tls_listener():
  28. if not self.tls_certificate_file:
  29. raise ConfigError(
  30. "tls_certificate_path must be specified if TLS-enabled listeners are "
  31. "configured."
  32. )
  33. if not self.tls_private_key_file:
  34. raise ConfigError(
  35. "tls_private_key_path must be specified if TLS-enabled listeners are "
  36. "configured."
  37. )
  38. # Whether to verify certificates on outbound federation traffic
  39. self.federation_verify_certificates = config.get(
  40. "federation_verify_certificates", True
  41. )
  42. # Minimum TLS version to use for outbound federation traffic
  43. self.federation_client_minimum_tls_version = str(
  44. config.get("federation_client_minimum_tls_version", 1)
  45. )
  46. if self.federation_client_minimum_tls_version not in ["1", "1.1", "1.2", "1.3"]:
  47. raise ConfigError(
  48. "federation_client_minimum_tls_version must be one of: 1, 1.1, 1.2, 1.3"
  49. )
  50. # Prevent people shooting themselves in the foot here by setting it to
  51. # the biggest number blindly
  52. if self.federation_client_minimum_tls_version == "1.3":
  53. if getattr(SSL, "OP_NO_TLSv1_3", None) is None:
  54. raise ConfigError(
  55. "federation_client_minimum_tls_version cannot be 1.3, "
  56. "your OpenSSL does not support it"
  57. )
  58. # Whitelist of domains to not verify certificates for
  59. fed_whitelist_entries = config.get(
  60. "federation_certificate_verification_whitelist", []
  61. )
  62. if fed_whitelist_entries is None:
  63. fed_whitelist_entries = []
  64. # Support globs (*) in whitelist values
  65. self.federation_certificate_verification_whitelist: List[Pattern] = []
  66. for entry in fed_whitelist_entries:
  67. try:
  68. entry_regex = glob_to_regex(entry.encode("ascii").decode("ascii"))
  69. except UnicodeEncodeError:
  70. raise ConfigError(
  71. "IDNA domain names are not allowed in the "
  72. "federation_certificate_verification_whitelist: %s" % (entry,)
  73. )
  74. # Convert globs to regex
  75. self.federation_certificate_verification_whitelist.append(entry_regex)
  76. # List of custom certificate authorities for federation traffic validation
  77. custom_ca_list = config.get("federation_custom_ca_list", None)
  78. # Read in and parse custom CA certificates
  79. self.federation_ca_trust_root = None
  80. if custom_ca_list is not None:
  81. if len(custom_ca_list) == 0:
  82. # A trustroot cannot be generated without any CA certificates.
  83. # Raise an error if this option has been specified without any
  84. # corresponding certificates.
  85. raise ConfigError(
  86. "federation_custom_ca_list specified without "
  87. "any certificate files"
  88. )
  89. certs = []
  90. for ca_file in custom_ca_list:
  91. logger.debug("Reading custom CA certificate file: %s", ca_file)
  92. content = self.read_file(ca_file, "federation_custom_ca_list")
  93. # Parse the CA certificates
  94. try:
  95. cert_base = Certificate.loadPEM(content)
  96. certs.append(cert_base)
  97. except Exception as e:
  98. raise ConfigError(
  99. "Error parsing custom CA certificate file %s: %s" % (ca_file, e)
  100. )
  101. self.federation_ca_trust_root = trustRootFromCertificates(certs)
  102. # This config option applies to non-federation HTTP clients
  103. # (e.g. for talking to recaptcha, identity servers, and such)
  104. # It should never be used in production, and is intended for
  105. # use only when running tests.
  106. self.use_insecure_ssl_client_just_for_testing_do_not_use = config.get(
  107. "use_insecure_ssl_client_just_for_testing_do_not_use"
  108. )
  109. self.tls_certificate: Optional[crypto.X509] = None
  110. self.tls_private_key: Optional[crypto.PKey] = None
  111. def read_certificate_from_disk(self) -> None:
  112. """
  113. Read the certificates and private key from disk.
  114. """
  115. self.tls_private_key = self.read_tls_private_key()
  116. self.tls_certificate = self.read_tls_certificate()
  117. def generate_config_section(
  118. self,
  119. tls_certificate_path: Optional[str],
  120. tls_private_key_path: Optional[str],
  121. **kwargs: Any,
  122. ) -> str:
  123. """If the TLS paths are not specified the default will be certs in the
  124. config directory"""
  125. if bool(tls_certificate_path) != bool(tls_private_key_path):
  126. raise ConfigError(
  127. "Please specify both a cert path and a key path or neither."
  128. )
  129. if tls_certificate_path and tls_private_key_path:
  130. return f"""\
  131. tls_certificate_path: {tls_certificate_path}
  132. tls_private_key_path: {tls_private_key_path}
  133. """
  134. else:
  135. return ""
  136. def read_tls_certificate(self) -> crypto.X509:
  137. """Reads the TLS certificate from the configured file, and returns it
  138. Returns:
  139. The certificate
  140. """
  141. cert_path = self.tls_certificate_file
  142. logger.info("Loading TLS certificate from %s", cert_path)
  143. cert_pem = self.read_file(cert_path, "tls_certificate_path")
  144. cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem.encode())
  145. return cert
  146. def read_tls_private_key(self) -> crypto.PKey:
  147. """Reads the TLS private key from the configured file, and returns it
  148. Returns:
  149. The private key
  150. """
  151. private_key_path = self.tls_private_key_file
  152. logger.info("Loading TLS key from %s", private_key_path)
  153. private_key_pem = self.read_file(private_key_path, "tls_private_key_path")
  154. return crypto.load_privatekey(crypto.FILETYPE_PEM, private_key_pem)