1
0

__init__.py 3.6 KB

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