__init__.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. # Copyright 2019 New Vector 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 os.path
  15. import subprocess
  16. from zope.interface import implementer
  17. from OpenSSL import SSL
  18. from OpenSSL.SSL import Connection
  19. from twisted.internet.interfaces import IOpenSSLServerConnectionCreator
  20. from twisted.internet.ssl import Certificate, trustRootFromCertificates
  21. from twisted.web.client import BrowserLikePolicyForHTTPS # noqa: F401
  22. from twisted.web.iweb import IPolicyForHTTPS # noqa: F401
  23. def get_test_https_policy():
  24. """Get a test IPolicyForHTTPS which trusts the test CA cert
  25. Returns:
  26. IPolicyForHTTPS
  27. """
  28. ca_file = get_test_ca_cert_file()
  29. with open(ca_file) as stream:
  30. content = stream.read()
  31. cert = Certificate.loadPEM(content)
  32. trust_root = trustRootFromCertificates([cert])
  33. return BrowserLikePolicyForHTTPS(trustRoot=trust_root)
  34. def get_test_ca_cert_file():
  35. """Get the path to the test CA cert
  36. The keypair is generated with:
  37. openssl genrsa -out ca.key 2048
  38. openssl req -new -x509 -key ca.key -days 3650 -out ca.crt \
  39. -subj '/CN=synapse test CA'
  40. """
  41. return os.path.join(os.path.dirname(__file__), "ca.crt")
  42. def get_test_key_file():
  43. """get the path to the test key
  44. The key file is made with:
  45. openssl genrsa -out server.key 2048
  46. """
  47. return os.path.join(os.path.dirname(__file__), "server.key")
  48. cert_file_count = 0
  49. CONFIG_TEMPLATE = b"""\
  50. [default]
  51. basicConstraints = CA:FALSE
  52. keyUsage=nonRepudiation, digitalSignature, keyEncipherment
  53. subjectAltName = %(sanentries)s
  54. """
  55. def create_test_cert_file(sanlist):
  56. """build an x509 certificate file
  57. Args:
  58. sanlist: list[bytes]: a list of subjectAltName values for the cert
  59. Returns:
  60. str: the path to the file
  61. """
  62. global cert_file_count
  63. csr_filename = "server.csr"
  64. cnf_filename = "server.%i.cnf" % (cert_file_count,)
  65. cert_filename = "server.%i.crt" % (cert_file_count,)
  66. cert_file_count += 1
  67. # first build a CSR
  68. subprocess.check_call(
  69. [
  70. "openssl",
  71. "req",
  72. "-new",
  73. "-key",
  74. get_test_key_file(),
  75. "-subj",
  76. "/",
  77. "-out",
  78. csr_filename,
  79. ]
  80. )
  81. # now a config file describing the right SAN entries
  82. sanentries = b",".join(sanlist)
  83. with open(cnf_filename, "wb") as f:
  84. f.write(CONFIG_TEMPLATE % {b"sanentries": sanentries})
  85. # finally the cert
  86. ca_key_filename = os.path.join(os.path.dirname(__file__), "ca.key")
  87. ca_cert_filename = get_test_ca_cert_file()
  88. subprocess.check_call(
  89. [
  90. "openssl",
  91. "x509",
  92. "-req",
  93. "-in",
  94. csr_filename,
  95. "-CA",
  96. ca_cert_filename,
  97. "-CAkey",
  98. ca_key_filename,
  99. "-set_serial",
  100. "1",
  101. "-extfile",
  102. cnf_filename,
  103. "-out",
  104. cert_filename,
  105. ]
  106. )
  107. return cert_filename
  108. @implementer(IOpenSSLServerConnectionCreator)
  109. class TestServerTLSConnectionFactory:
  110. """An SSL connection creator which returns connections which present a certificate
  111. signed by our test CA."""
  112. def __init__(self, sanlist):
  113. """
  114. Args:
  115. sanlist: list[bytes]: a list of subjectAltName values for the cert
  116. """
  117. self._cert_file = create_test_cert_file(sanlist)
  118. def serverConnectionForTLS(self, tlsProtocol):
  119. ctx = SSL.Context(SSL.SSLv23_METHOD)
  120. ctx.use_certificate_file(self._cert_file)
  121. ctx.use_privatekey_file(get_test_key_file())
  122. return Connection(ctx, None)