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.

99 lines
2.7 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 generate(self):
  32. if os.path.exists(self.path):
  33. raise ValueError("A CA with the same id and type already exists")
  34. subprocess.check_output(['openssl',
  35. 'genrsa',
  36. '-%s'%self.ca_key_algorithm,
  37. '-out', '%s'%(self.path),
  38. self.key_length])
  39. subprocess.check_output(['openssl',
  40. 'req',
  41. '-new',
  42. '-x509',
  43. '-days', self.ca_validity,
  44. '-key', self.path,
  45. # '-extensions', 'v3_ca'
  46. '-out', "%s.pub"%self.path,
  47. # '-config', "%s.conf"%self.path
  48. ])
  49. with open(self.path + '.serial', 'w') as stream:
  50. stream.write(str(0))
  51. def sign(self, request):
  52. OUTPUT_PATH
  53. assert type(request) in self.request_allowed
  54. pub_key_path = os.path.join(OUTPUT_PATH, request.req_id + '.pub')
  55. cert_path = os.path.join(OUTPUT_PATH, request.req_id + '-cert.pub')
  56. with open(self.path + '.serial', 'r') as stream:
  57. next_serial = int(stream.read())
  58. with open(self.path + '.serial', 'w') as stream:
  59. stream.write(str(next_serial + 1))
  60. with open(pub_key_path, 'w') as stream:
  61. stream.write(request.key_data)
  62. ca_private_key = self.path
  63. # openssl x509 -req -days 360 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt # print()
  64. subprocess.check_output(['openssl',
  65. 'x509',
  66. '-req',
  67. '-days', self.ca_validity,
  68. '-in', pub_key_path,
  69. '-CA', "%s.pub"%self.path,
  70. '-CAkey', self.path,
  71. '-CAcreateserial',
  72. '-out', cert_path,
  73. '-%s'%self.key_algorithm])
  74. return cert_path