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.

sitegen.py 10.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. #! /usr/bin/env python3
  2. import json
  3. import argparse
  4. import os
  5. import subprocess
  6. from os import path
  7. class SiteGenException(Exception):
  8. error = None
  9. code = None
  10. def __init__(self, error, code):
  11. self.error = error
  12. self.code = code
  13. class SiteGen:
  14. siteConfDir = ""
  15. siteDir = ""
  16. confDir = ""
  17. hooksEnabledDir = ""
  18. hooksAvailableDir = ""
  19. templatesDir = ""
  20. certRenewTime = ""
  21. letsencryptCommand = ""
  22. letsencryptDir = ""
  23. certDir = ""
  24. def __init__(self, config):
  25. self.siteConfDir = config["siteConfDir"]
  26. self.siteDir = config["siteDir"]
  27. self.confDir = config["confDir"]
  28. self.hooksEnabledDir = path.join(self.confDir, "hooks-enabled")
  29. self.hooksAvailableDir = path.join(self.confDir, "hooks-available")
  30. self.templatesDir = path.join(self.confDir, "templates")
  31. self.certRenewTime = config["certRenewTime"]
  32. self.letsencryptCommand = config["letsencryptCommand"]
  33. self.letsencryptDir = config["letsencryptDir"]
  34. self.certDir = config["certDir"]
  35. def make_dirs(self):
  36. if not path.isdir(self.certDir):
  37. os.makedirs(self.certDir)
  38. def get_hook_dir(self, hook_type, is_enabled):
  39. return path.join(self.hooksEnabledDir if is_enabled else self.hooksAvailableDir, hook_type)
  40. def get_hook_file(self, hook_type, hook_name, is_enabled):
  41. return path.join(self.get_hook_dir(hook_type, is_enabled), hook_name)
  42. def get_hook_files(self, hook_type, is_enabled):
  43. hook_dir = self.get_hook_dir(hook_type, is_enabled)
  44. files = os.listdir(hook_dir)
  45. files.sort()
  46. return files
  47. def is_hook_present(self, hook_type, hook_name, is_enabled):
  48. return path.isfile(self.get_hook_file(hook_type, hook_name, is_enabled))
  49. def is_hook_enabled(self, hook_type, hook_name):
  50. return self.is_hook_present(hook_type, hook_name, True)
  51. def get_letsencrypt_dir(self, domain):
  52. return path.join(self.letsencryptDir, domain)
  53. def symlink_letsencrypt_file(self, domain, file, outfile):
  54. letsencrypt_cert_file = path.abspath(self.get_letsencrypt_dir(domain))
  55. my_cert_file = path.join(self.certDir, outfile)
  56. if path.lexists(my_cert_file):
  57. os.remove(my_cert_file)
  58. os.symlink(path.join(letsencrypt_cert_file, file), my_cert_file)
  59. def get_cert_files(self, domain):
  60. return [path.abspath(path.join(self.certDir, domain + ".crt")),
  61. path.abspath(path.join(self.certDir, domain + ".key")),
  62. path.abspath(path.join(self.certDir, domain + "-chain.crt"))]
  63. def execute(self, exe, args, get_output):
  64. args.insert(0, exe)
  65. proc = subprocess.Popen(args, stdout=(subprocess.PIPE if get_output else None))
  66. out = proc.communicate()
  67. return proc.returncode, out[0]
  68. def execute_hooks(self, hook_type, args):
  69. for hook_name in self.get_hook_files(hook_type, True):
  70. self.execute(self.get_hook_file(hook_type, hook_name, True), args, False)
  71. def is_cert_present(self, domain):
  72. cert_files = self.get_cert_files(domain)
  73. for cert_file in cert_files:
  74. if not path.isfile(cert_file):
  75. return False
  76. return True
  77. def get_cert_end_date(self, domain):
  78. cert_files = self.get_cert_files(domain)
  79. res, out = self.execute("openssl", ["x509", "-noout", "-in", cert_files[0], "-enddate"], True)
  80. if res == 0:
  81. return out.decode("UTF-8").split("=")[1][:-1]
  82. return None
  83. def is_cert_gonna_expire(self, domain, checkend):
  84. cert_files = self.get_cert_files(domain)
  85. res, out = self.execute("openssl", ["x509", "-noout", "-in", cert_files[0], "-checkend", str(checkend)], True)
  86. return res == 1
  87. def get_all_domains(self):
  88. files = os.listdir(self.certDir)
  89. files.sort()
  90. domains = []
  91. for file in files:
  92. if file.endswith(".crt") and self.is_cert_present(file[:-4]):
  93. domains.append(file[:-4])
  94. return domains
  95. def cert_request(self, domain, logger):
  96. logger("Requesting: %s" % domain)
  97. res, out = self.execute(self.letsencryptCommand, [domain], False)
  98. if res != 0:
  99. raise SiteGenException("Certificate request failed with code %i" % res, res)
  100. self.symlink_letsencrypt_file(domain, "cert.pem", domain + ".crt")
  101. self.symlink_letsencrypt_file(domain, "privkey.pem", domain + ".key")
  102. self.symlink_letsencrypt_file(domain, "chain.pem", domain + "-chain.crt")
  103. cert_files = self.get_cert_files(domain)
  104. cert_files.insert(0, domain)
  105. self.execute_hooks("cert", cert_files)
  106. def certs_request(self, domains, logger):
  107. for domain in domains:
  108. self.cert_request(domain, logger)
  109. def cert_check(self, domain, logger):
  110. if not self.is_cert_present(domain):
  111. raise SiteGenException("Certificate not present: %s" % domain, 1)
  112. if self.is_cert_gonna_expire(domain, self.certRenewTime):
  113. logger("%s: %s" % (domain, self.get_cert_end_date(domain)))
  114. return True
  115. return False
  116. def certs_check(self, domains, logger):
  117. for domain in domains:
  118. self.cert_check(domain, logger)
  119. def cert_renew(self, domain, logger):
  120. if self.cert_check(domain, logger):
  121. self.cert_request(domain, logger)
  122. def certs_renew(self, domains, logger):
  123. for domain in domains:
  124. self.cert_renew(domain, logger)
  125. def site_create(self, domain, logger):
  126. pass
  127. def site_remove(self, domain, logger):
  128. pass
  129. def hook_enable(self, hook_type, hook_name, logger):
  130. if not self.is_hook_present(hook_type, hook_name, False):
  131. raise SiteGenException("Hook is not present", 1)
  132. if self.is_hook_enabled(hook_type, hook_name):
  133. raise SiteGenException("Hook is already enabled", 0)
  134. logger("Enabling %s %s" % (hook_type, hook_name))
  135. hook_dir = self.get_hook_dir(hook_type, hook_name)
  136. if not path.isdir(hook_dir):
  137. os.makedirs(hook_dir)
  138. hook_file_available = self.get_hook_file(hook_type, hook_name, False)
  139. hook_file_enabled = self.get_hook_file(hook_type, hook_name, True)
  140. hook_relative_file = path.relpath(hook_file_available, self.get_hook_dir(hook_type, True))
  141. os.symlink(hook_relative_file, hook_file_enabled)
  142. def hook_disable(self, hook_type, hook_name, logger):
  143. if not self.is_hook_present(hook_type, hook_name, False):
  144. raise SiteGenException("Hook is not present", 1)
  145. if not self.is_hook_enabled(hook_type, hook_name):
  146. raise SiteGenException("Hook is not enabled", 0)
  147. logger("Disabling %s %s" % (hook_type, hook_name))
  148. os.remove(self.get_hook_file(hook_type, hook_name, True))
  149. def main():
  150. parser = argparse.ArgumentParser(description='Manage apache websites and SSL certificates')
  151. parser.add_argument('--config', dest='config', default='/etc/sitegen/sitegen.json', help='Configuration file path')
  152. parser.add_argument('--cert-request', metavar='cert_request', const='', nargs='?',
  153. help='Request/renew a certificate. Request/renew all certificates if no domain is specified')
  154. parser.add_argument('--cert-check', metavar='cert_check', const='', nargs='?',
  155. help='Check if certificate needs to be renewed. Check all if no domain is specified')
  156. parser.add_argument('--cert-renew', metavar='cert_renew', const='', nargs='?',
  157. help='Renew certificate if it needs to be. Renew all that needs to be if no domain is specified')
  158. parser.add_argument('--site-create', help='Create a site configuration', metavar='site_create')
  159. parser.add_argument('--site-remove', help='Remove a site configuration', metavar='site_remove')
  160. parser.add_argument('--hook-site-enable', help='Enable a site hook', dest='site_hook_enable', metavar='hook')
  161. parser.add_argument('--hook-site-disable', help='Disable a site hook', dest='site_hook_disable', metavar='hook')
  162. parser.add_argument('--hook-cert-enable', help='Enable a certificate hook', dest='hook_cert_enable', metavar='hook')
  163. parser.add_argument('--hook-cert-disable', help='Disable a certificate hook', dest='hook_cert_disable', metavar='hook')
  164. args = parser.parse_args()
  165. with open(args.config, "r") as f:
  166. config = json.load(f)
  167. site_gen = SiteGen(config)
  168. site_gen.make_dirs()
  169. logger = print
  170. try:
  171. if args.cert_request is not None:
  172. if args.cert_request == "":
  173. site_gen.certs_request(site_gen.get_all_domains(), logger)
  174. else:
  175. site_gen.cert_request(args.cert_request, logger)
  176. elif args.cert_check is not None:
  177. if args.cert_check == "":
  178. site_gen.certs_check(site_gen.get_all_domains(), logger)
  179. else:
  180. site_gen.cert_check(args.cert_check, logger)
  181. elif args.cert_renew is not None:
  182. if args.cert_renew == "":
  183. site_gen.certs_renew(site_gen.get_all_domains(), logger)
  184. else:
  185. site_gen.cert_renew(args.cert_renew, logger)
  186. elif args.site_create is not None:
  187. site_gen.site_create(args.site_create, logger)
  188. elif args.site_remove is not None:
  189. site_gen.site_remove(args.site_remove, logger)
  190. elif args.site_hook_enable is not None:
  191. site_gen.hook_enable("site", args.site_hook_enable, logger)
  192. elif args.site_hook_disable is not None:
  193. site_gen.hook_disable("site", args.site_hook_disable, logger)
  194. elif args.hook_cert_enable is not None:
  195. site_gen.hook_enable("cert", args.hook_cert_enable, logger)
  196. elif args.hook_cert_disable is not None:
  197. site_gen.hook_disable("cert", args.hook_cert_disable, logger)
  198. else:
  199. parser.print_help()
  200. except SiteGenException as e:
  201. print(e.error)
  202. exit(e.code)
  203. if __name__ == "__main__":
  204. main()