2 ## Call with "--help" for documentation.
4 import argparse, configparser, itertools, stat, os, os.path, sys, subprocess, datetime
7 def readConfig(fname, defSection = 'DEFAULT'):
8 config = configparser.ConfigParser()
9 with open(fname) as file:
10 stream = itertools.chain(("["+defSection+"]\n",), file)
11 config.read_file(stream)
14 def certfile(name, suff = None):
16 return os.path.join(config['dirs']['certs'], name + ".crt" + ('' if suff is None else '+'+suff) )
20 return os.path.join(config['dirs']['keys'], name + ".key")
24 return os.path.join(config['dirs']['csrs'], name + ".csr")
26 def make_backup(fname):
27 if os.path.exists(fname):
28 backupname = os.path.basename(fname) + "." + str(datetime.date.today())
31 backupfile = os.path.join(config['dirs']['backups'], backupname + "." + str(i))
32 if not os.path.exists(backupfile):
33 os.rename(src = fname, dst = backupfile)
36 print("Somehow it's really hard to find a name for the backup file...")
38 assert not os.path.exists(fname)
40 def trigger_hook(hook):
42 exe = config['hooks'][hook]
44 subprocess.check_call([exe])
47 return datetime.datetime.fromtimestamp(os.stat(keyfile(name)).st_mtime)
49 def cert_expiry(name):
50 from certcheck import cert_expiry_date
51 return cert_expiry_date(certfile(name))
53 ## The interesting work
54 def acme(name, domains):
56 # Generating the CSR is done by a shell script
57 exe = os.path.join(os.path.dirname(__file__), 'gencsr')
58 csr = subprocess.check_output([exe, keyfile(name)] + domains)
59 with open(csrfile(name), 'wb') as file:
61 # call acme-tiny as a script
62 acme_tiny = os.path.join(config['acme']['acme-tiny'], 'acme_tiny.py')
63 signed_crt = subprocess.check_output([acme_tiny, "--quiet", "--account-key", config['acme']['account-key'], "--csr", csrfile(name), "--acme-dir", config['acme']['challenge-dir']])
64 # save new certificate
65 make_backup(certfile(name))
66 with open(certfile(name), 'wb') as f:
69 dhfile = config['DEFAULT']['dh-params']
70 if dhfile is not None:
71 with open(dhfile, 'rb') as f:
73 with open(certfile(name, 'dh'), 'wb') as f:
77 def request_cert(name):
79 if not os.path.exists(keyfile(name)):
80 raise Exception("No such key: {}".format(name))
81 domains = config['DEFAULT']['domains'].split()
82 print("Obtaining certificate '{}' for domains {}".format(name, ' '.join(domains)))
85 def generate_key(name):
86 print("Generating new private key '{}'".format(name))
87 with subprocess.Popen(["openssl", "genrsa", str(int(config['DEFAULT']['key-length']))], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as f:
88 (stdout, stderr) = f.communicate()
90 sys.stderr.write(stderr)
91 raise Exception("Error while generating private key")
92 # now we have a key, save it
93 make_backup(keyfile(name))
94 with open(keyfile(name), 'wb') as f:
98 '''Returns 0 if nothing was done, 1 if a stage key is present but has to be kept, 2 is a stage key was unstaged.'''
99 live = config['files']['live']
100 staging = config['files']['staging']
101 if staging is None or not os.path.exists(keyfile(staging)):
103 staging_time = datetime.timedelta(hours = int(config['timing']['staging-hours']))
104 key_age = datetime.datetime.now() - key_mtime(staging)
105 if key_age < staging_time:
107 print("Unstaging '{}' to '{}'".format(staging, live))
109 make_backup(keyfile(live))
110 os.rename(src = keyfile(staging), dst = keyfile(live))
111 make_backup(certfile(live))
112 os.rename(src = certfile(staging), dst = certfile(live))
114 os.rename(src = certfile(staging, 'dh'), dst = certfile(live, 'dh'))
115 except FileNotFoundError:
120 '''Returns 0 if nothing was done, 1 if only certs were changed, 2 if certs and keys were changed.'''
121 live = config['files']['live']
122 staging = config['files']['staging']
124 max_key_age = datetime.timedelta(days = int(config['timing']['max-key-age-days']))
125 renew_cert_time = datetime.timedelta(days = int(config['timing']['renew-cert-before-expiry-days']))
127 # determine what to do
128 now = datetime.datetime.now()
129 key_age = now - key_mtime(live)
130 cert_validity = cert_expiry(live) - now
131 need_new_key = key_age >= max_key_age
132 need_new_cert = cert_validity <= renew_cert_time
133 if need_new_cert and key_age + renew_cert_time >= max_key_age:
134 # We are about to request a new certificate, and within <renew_cert_time>, we need a new key: Get the new key now
139 new_key_name = (live if staging is None else staging)
140 generate_key(new_key_name)
141 request_cert(new_key_name)
150 if __name__ == "__main__":
151 # allow overwriting some values on the command-line
152 parser = argparse.ArgumentParser(description='Generate and (automatically) renew certificates, optionally providing staging for new keys')
153 parser.add_argument("-c", "--config",
155 help="The configuration file")
156 parser.add_argument("-k", "--hooks",
157 dest="hooks", action="store_true",
158 help="Trigger hooks.")
159 parser.add_argument("action", metavar='ACTION', nargs=1,
160 help="The action to perform. Possible values: init, renew, cron")
161 args = parser.parse_args()
164 if not os.path.isfile(args.config):
165 raise Exception("The config file does not exist: "+args.config)
167 config = readConfig(args.config)
169 if args.action[0] == 'renew':
170 live = config['files']['live']
171 staging = config['files']['staging']
174 if staging is not None and os.path.exists(keyfile(staging)):
175 request_cert(staging)
176 # trigger the "new cert" hook
178 trigger_hook('post-certchange')
179 elif args.action[0] == 'cron':
180 # First, check if we need to unstage a staging key
181 unstaged = check_staging()
183 # A staging eky is present, do *not* check for renewal
184 if unstaged >= 2 and args.hooks:
185 # trigger all the hooks
186 trigger_hook('post-certchange')
187 trigger_hook('post-keychange')
189 # Check if we need to renew anything
190 renewed = auto_renewal()
193 trigger_hook('post-certchange')
195 trigger_hook('post-keychange')
196 elif args.action[0] == 'init':
197 # create directories with appropriate permissions
199 os.makedirs(config['dirs']['certs'], mode = 0o755, exist_ok = True)
200 os.makedirs(config['dirs']['keys'], mode = 0o710, exist_ok = True)
201 os.makedirs(config['dirs']['csrs'], mode = 0o755, exist_ok = True)
202 os.makedirs(config['dirs']['backups'], mode = 0o700, exist_ok = True)
205 # if necessary, generate key + certificate
206 live = config['files']['live']
207 if not os.path.exists(keyfile(live)):
211 trigger_hook('post-certchange')
212 trigger_hook('post-keychange')
214 raise Exception("Unknown action {}".format(args.action))