Easy CA management
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
2.9 KiB

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from peewee import *
  4. import os
  5. import os.path
  6. import subprocess
  7. from models.authority import Authority
  8. from models.certificate import Certificate
  9. from models.request import SignRequest
  10. from paths import *
  11. class HostSSLRequest(SignRequest):
  12. def __init__(self, req_id, host_name, key_data):
  13. super(HostSSLRequest, self).__init__(req_id)
  14. self.host_name = host_name
  15. self.key_data = key_data
  16. @property
  17. def name(self):
  18. return "Hostname: %s" % self.host_name
  19. @property
  20. def fields(self):
  21. return [
  22. ("Hostname", self.host_name)
  23. ]
  24. class SSLAuthority(Authority):
  25. request_allowed = [ HostSSLRequest, ]
  26. ca_key_algorithm = 'des3'
  27. key_length = '4096'
  28. key_algorithm = 'sha256'
  29. ca_validity = '365'
  30. cert_validity = '365'
  31. def __init__(self, ca_id):
  32. ssl_ca_dir = os.path.join(MANAGER_PATH, 'ssl_ca')
  33. super(SSLAuthority, self).__init__(ca_id, ssl_ca_dir)
  34. def generate(self):
  35. if os.path.exists(self.path):
  36. raise ValueError("A CA with the same id and type already exists")
  37. subprocess.check_output(['openssl',
  38. 'genrsa',
  39. '-%s'%self.ca_key_algorithm,
  40. '-out', '%s'%(self.path),
  41. self.key_length])
  42. subprocess.check_output(['openssl',
  43. 'req',
  44. '-new',
  45. '-x509',
  46. '-days', self.ca_validity,
  47. '-key', self.path,
  48. # '-extensions', 'v3_ca'
  49. '-out', "%s.pub"%self.path,
  50. # '-config', "%s.conf"%self.path
  51. ])
  52. with open(self.path + '.serial', 'w') as stream:
  53. stream.write(str(0))
  54. def sign(self, request):
  55. OUTPUT_PATH
  56. assert type(request) in self.request_allowed
  57. pub_key_path = os.path.join(OUTPUT_PATH, request.req_id + '.pub')
  58. cert_path = os.path.join(OUTPUT_PATH, request.req_id + '-cert.pub')
  59. with open(self.path + '.serial', 'r') as stream:
  60. next_serial = int(stream.read())
  61. with open(self.path + '.serial', 'w') as stream:
  62. stream.write(str(next_serial + 1))
  63. with open(pub_key_path, 'w') as stream:
  64. stream.write(request.key_data)
  65. ca_private_key = self.path
  66. # openssl x509 -req -days 360 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt # print()
  67. subprocess.check_output(['openssl',
  68. 'x509',
  69. '-req',
  70. '-days', self.ca_validity,
  71. '-in', pub_key_path,
  72. '-CA', "%s.pub"%self.path,
  73. '-CAkey', self.path,
  74. '-CAcreateserial',
  75. '-out', cert_path,
  76. '-%s'%self.key_algorithm])
  77. return cert_path