tls.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 os
  16. import subprocess
  17. from hashlib import sha256
  18. from unpaddedbase64 import encode_base64
  19. from OpenSSL import crypto
  20. from ._base import Config
  21. GENERATE_DH_PARAMS = False
  22. class TlsConfig(Config):
  23. def read_config(self, config):
  24. self.tls_certificate = self.read_tls_certificate(
  25. config.get("tls_certificate_path")
  26. )
  27. self.tls_certificate_file = config.get("tls_certificate_path")
  28. self.no_tls = config.get("no_tls", False)
  29. if self.no_tls:
  30. self.tls_private_key = None
  31. else:
  32. self.tls_private_key = self.read_tls_private_key(
  33. config.get("tls_private_key_path")
  34. )
  35. self.tls_dh_params_path = self.check_file(
  36. config.get("tls_dh_params_path"), "tls_dh_params"
  37. )
  38. self.tls_fingerprints = config["tls_fingerprints"]
  39. # Check that our own certificate is included in the list of fingerprints
  40. # and include it if it is not.
  41. x509_certificate_bytes = crypto.dump_certificate(
  42. crypto.FILETYPE_ASN1,
  43. self.tls_certificate
  44. )
  45. sha256_fingerprint = encode_base64(sha256(x509_certificate_bytes).digest())
  46. sha256_fingerprints = set(f["sha256"] for f in self.tls_fingerprints)
  47. if sha256_fingerprint not in sha256_fingerprints:
  48. self.tls_fingerprints.append({u"sha256": sha256_fingerprint})
  49. # This config option applies to non-federation HTTP clients
  50. # (e.g. for talking to recaptcha, identity servers, and such)
  51. # It should never be used in production, and is intended for
  52. # use only when running tests.
  53. self.use_insecure_ssl_client_just_for_testing_do_not_use = config.get(
  54. "use_insecure_ssl_client_just_for_testing_do_not_use"
  55. )
  56. def default_config(self, config_dir_path, server_name, **kwargs):
  57. base_key_name = os.path.join(config_dir_path, server_name)
  58. tls_certificate_path = base_key_name + ".tls.crt"
  59. tls_private_key_path = base_key_name + ".tls.key"
  60. tls_dh_params_path = base_key_name + ".tls.dh"
  61. return """\
  62. # PEM encoded X509 certificate for TLS.
  63. # You can replace the self-signed certificate that synapse
  64. # autogenerates on launch with your own SSL certificate + key pair
  65. # if you like. Any required intermediary certificates can be
  66. # appended after the primary certificate in hierarchical order.
  67. tls_certificate_path: "%(tls_certificate_path)s"
  68. # PEM encoded private key for TLS
  69. tls_private_key_path: "%(tls_private_key_path)s"
  70. # PEM dh parameters for ephemeral keys
  71. tls_dh_params_path: "%(tls_dh_params_path)s"
  72. # Don't bind to the https port
  73. no_tls: False
  74. # List of allowed TLS fingerprints for this server to publish along
  75. # with the signing keys for this server. Other matrix servers that
  76. # make HTTPS requests to this server will check that the TLS
  77. # certificates returned by this server match one of the fingerprints.
  78. #
  79. # Synapse automatically adds the fingerprint of its own certificate
  80. # to the list. So if federation traffic is handled directly by synapse
  81. # then no modification to the list is required.
  82. #
  83. # If synapse is run behind a load balancer that handles the TLS then it
  84. # will be necessary to add the fingerprints of the certificates used by
  85. # the loadbalancers to this list if they are different to the one
  86. # synapse is using.
  87. #
  88. # Homeservers are permitted to cache the list of TLS fingerprints
  89. # returned in the key responses up to the "valid_until_ts" returned in
  90. # key. It may be necessary to publish the fingerprints of a new
  91. # certificate and wait until the "valid_until_ts" of the previous key
  92. # responses have passed before deploying it.
  93. #
  94. # You can calculate a fingerprint from a given TLS listener via:
  95. # openssl s_client -connect $host:$port < /dev/null 2> /dev/null |
  96. # openssl x509 -outform DER | openssl sha256 -binary | base64 | tr -d '='
  97. # or by checking matrix.org/federationtester/api/report?server_name=$host
  98. #
  99. tls_fingerprints: []
  100. # tls_fingerprints: [{"sha256": "<base64_encoded_sha256_fingerprint>"}]
  101. """ % locals()
  102. def read_tls_certificate(self, cert_path):
  103. cert_pem = self.read_file(cert_path, "tls_certificate")
  104. return crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem)
  105. def read_tls_private_key(self, private_key_path):
  106. private_key_pem = self.read_file(private_key_path, "tls_private_key")
  107. return crypto.load_privatekey(crypto.FILETYPE_PEM, private_key_pem)
  108. def generate_files(self, config):
  109. tls_certificate_path = config["tls_certificate_path"]
  110. tls_private_key_path = config["tls_private_key_path"]
  111. tls_dh_params_path = config["tls_dh_params_path"]
  112. if not self.path_exists(tls_private_key_path):
  113. with open(tls_private_key_path, "wb") as private_key_file:
  114. tls_private_key = crypto.PKey()
  115. tls_private_key.generate_key(crypto.TYPE_RSA, 2048)
  116. private_key_pem = crypto.dump_privatekey(
  117. crypto.FILETYPE_PEM, tls_private_key
  118. )
  119. private_key_file.write(private_key_pem)
  120. else:
  121. with open(tls_private_key_path) as private_key_file:
  122. private_key_pem = private_key_file.read()
  123. tls_private_key = crypto.load_privatekey(
  124. crypto.FILETYPE_PEM, private_key_pem
  125. )
  126. if not self.path_exists(tls_certificate_path):
  127. with open(tls_certificate_path, "wb") as certificate_file:
  128. cert = crypto.X509()
  129. subject = cert.get_subject()
  130. subject.CN = config["server_name"]
  131. cert.set_serial_number(1000)
  132. cert.gmtime_adj_notBefore(0)
  133. cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)
  134. cert.set_issuer(cert.get_subject())
  135. cert.set_pubkey(tls_private_key)
  136. cert.sign(tls_private_key, 'sha256')
  137. cert_pem = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
  138. certificate_file.write(cert_pem)
  139. if not self.path_exists(tls_dh_params_path):
  140. if GENERATE_DH_PARAMS:
  141. subprocess.check_call([
  142. "openssl", "dhparam",
  143. "-outform", "PEM",
  144. "-out", tls_dh_params_path,
  145. "2048"
  146. ])
  147. else:
  148. with open(tls_dh_params_path, "w") as dh_params_file:
  149. dh_params_file.write(
  150. "2048-bit DH parameters taken from rfc3526\n"
  151. "-----BEGIN DH PARAMETERS-----\n"
  152. "MIIBCAKCAQEA///////////JD9qiIWjC"
  153. "NMTGYouA3BzRKQJOCIpnzHQCC76mOxOb\n"
  154. "IlFKCHmONATd75UZs806QxswKwpt8l8U"
  155. "N0/hNW1tUcJF5IW1dmJefsb0TELppjft\n"
  156. "awv/XLb0Brft7jhr+1qJn6WunyQRfEsf"
  157. "5kkoZlHs5Fs9wgB8uKFjvwWY2kg2HFXT\n"
  158. "mmkWP6j9JM9fg2VdI9yjrZYcYvNWIIVS"
  159. "u57VKQdwlpZtZww1Tkq8mATxdGwIyhgh\n"
  160. "fDKQXkYuNs474553LBgOhgObJ4Oi7Aei"
  161. "j7XFXfBvTFLJ3ivL9pVYFxg5lUl86pVq\n"
  162. "5RXSJhiY+gUQFXKOWoqsqmj/////////"
  163. "/wIBAg==\n"
  164. "-----END DH PARAMETERS-----\n"
  165. )