httpcommon.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 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 logging
  16. import twisted.internet.ssl
  17. logger = logging.getLogger(__name__)
  18. class SslComponents:
  19. def __init__(self, sydent):
  20. self.sydent = sydent
  21. self.myPrivateCertificate = self.makeMyCertificate()
  22. self.trustRoot = self.makeTrustRoot()
  23. def makeMyCertificate(self):
  24. privKeyAndCertFilename = self.sydent.cfg.get('http', 'replication.https.certfile')
  25. if privKeyAndCertFilename == '':
  26. logger.warn("No HTTPS private key / cert found: not starting replication server "
  27. "or doing replication pushes")
  28. return None
  29. try:
  30. fp = open(privKeyAndCertFilename)
  31. except IOError:
  32. logger.warn("Unable to read private key / cert file from %s: not starting the replication HTTPS server "
  33. "or doing replication pushes.",
  34. privKeyAndCertFilename)
  35. return None
  36. authData = fp.read()
  37. fp.close()
  38. return twisted.internet.ssl.PrivateCertificate.loadPEM(authData)
  39. def makeTrustRoot(self):
  40. # If this option is specified, use a specific root CA cert. This is useful for testing when it's not
  41. # practical to get the client cert signed by a real root CA but should never be used on a production server.
  42. caCertFilename = self.sydent.cfg.get('http', 'replication.https.cacert')
  43. if len(caCertFilename) > 0:
  44. try:
  45. fp = open(caCertFilename)
  46. caCert = twisted.internet.ssl.Certificate.loadPEM(fp.read())
  47. fp.close()
  48. except:
  49. logger.warn("Failed to open CA cert file %s", caCertFilename)
  50. raise
  51. logger.warn("Using custom CA cert file: %s", caCertFilename)
  52. return twisted.internet._sslverify.OpenSSLCertificateAuthorities([caCert.original])
  53. else:
  54. return twisted.internet.ssl.OpenSSLDefaultPaths()