context_factory.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. from twisted.internet import ssl
  15. from OpenSSL import SSL
  16. from twisted.internet._sslverify import _OpenSSLECCurve, _defaultCurveName
  17. import logging
  18. logger = logging.getLogger(__name__)
  19. class ServerContextFactory(ssl.ContextFactory):
  20. """Factory for PyOpenSSL SSL contexts that are used to handle incoming
  21. connections and to make connections to remote servers."""
  22. def __init__(self, config):
  23. self._context = SSL.Context(SSL.SSLv23_METHOD)
  24. self.configure_context(self._context, config)
  25. @staticmethod
  26. def configure_context(context, config):
  27. try:
  28. _ecCurve = _OpenSSLECCurve(_defaultCurveName)
  29. _ecCurve.addECKeyToContext(context)
  30. except:
  31. logger.exception("Failed to enable elliptic curve for TLS")
  32. context.set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3)
  33. context.use_certificate_chain_file(config.tls_certificate_file)
  34. if not config.no_tls:
  35. context.use_privatekey(config.tls_private_key)
  36. context.load_tmp_dh(config.tls_dh_params_path)
  37. context.set_cipher_list("!ADH:HIGH+kEDH:!AECDH:HIGH+kEECDH")
  38. def getContext(self):
  39. return self._context