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)
16 return os.path.join(config['dirs']['certs'], name + ".crt" )
20 return os.path.join(config['dirs']['keys'], name + ".key")
24 return os.path.join(config['dirs']['keys'], name + ".csr.tmp")
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(fname, 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(["python", 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 os.remove(csrfile(name))
71 def request_cert(name):
73 if not os.path.exists(keyfile(name)):
74 raise Exception("No such key: {}".format(name))
75 domains = config['DEFAULT']['domains'].split()
76 print("Obtaining certificate '{}' for domains: {}".format(name, ' '.join(domains)))
79 def generate_key(name):
80 print("Generating new private key '{}'".format(name))
81 with subprocess.Popen(["openssl", "genrsa", str(int(config['DEFAULT']['key-length']))], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as f:
82 (stdout, stderr) = f.communicate()
84 sys.stderr.write(stderr)
85 raise Exception("Error while generating private key")
86 # Now we have a key, save it. This should never overwrite anything.
87 assert not os.path.exists(keyfile(name))
88 with open(keyfile(name), 'wb') as f:
91 def check_staging(live, staging):
92 '''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.'''
93 if not os.path.exists(keyfile(staging)):
96 staging_time = datetime.timedelta(hours = int(config['timing'].get('staging-hours', 0)))
97 key_age = datetime.datetime.now() - key_mtime(staging)
98 if key_age < staging_time:
100 print("Unstaging '{}' to '{}'".format(staging, live))
102 make_backup(keyfile(live))
103 os.rename(keyfile(staging), keyfile(live))
104 make_backup(certfile(live))
105 os.rename(certfile(staging), certfile(live))
108 def auto_renewal(live, staging):
109 '''Returns 0 if nothing was done, 1 if only certs were changed, 2 if certs and keys were changed.'''
110 max_key_age = datetime.timedelta(days = int(config['timing']['max-key-age-days']))
111 renew_cert_time = datetime.timedelta(days = int(config['timing']['renew-cert-before-expiry-days']))
113 # determine what to do
114 now = datetime.datetime.now()
115 key_age = now - key_mtime(live)
116 cert_validity = cert_expiry(live) - now
117 need_new_key = key_age >= max_key_age
118 need_new_cert = cert_validity <= renew_cert_time
119 if need_new_cert and key_age + renew_cert_time >= max_key_age:
120 # We are about to request a new certificate, and within <renew_cert_time>, we need a new key: Get the new key now
125 generate_key(staging)
126 request_cert(staging)
127 check_staging(live, staging) # we may want to immediately enable the new key & cert
136 if __name__ == "__main__":
137 # allow overwriting some values on the command-line
138 parser = argparse.ArgumentParser(description='Generate and (automatically) renew certificates, optionally providing staging for new keys')
139 parser.add_argument("-c", "--config",
141 help="The configuration file")
142 parser.add_argument("-k", "--hooks",
143 dest="hooks", action="store_true",
144 help="Trigger hooks.")
145 parser.add_argument("action", metavar='ACTION', nargs=1,
146 help="The action to perform. Possible values: init, renew, cron")
147 args = parser.parse_args()
150 if not os.path.isfile(args.config):
151 raise Exception("The config file does not exist: "+args.config)
153 config = readConfig(args.config)
155 live = config['files']['live']
156 staging = config['files']['staging']
157 if args.action[0] == 'renew':
159 if os.path.exists(keyfile(staging)) and os.path.exists(certfile(staging)):
160 request_cert(staging)
161 # trigger the "new cert" hook
163 trigger_hook('post-certchange')
164 elif args.action[0] == 'cron':
165 # First, check if we need to unstage a staging key
166 unstaged = check_staging(live, staging)
168 # A staging key is present, do *not* check for renewal
169 if unstaged >= 2 and args.hooks:
170 # trigger all the hooks
171 trigger_hook('post-certchange')
172 trigger_hook('post-keychange')
174 # Check if we need to renew anything
175 renewed = auto_renewal(live, staging)
178 trigger_hook('post-certchange')
180 trigger_hook('post-keychange')
181 elif args.action[0] == 'init':
182 # create directories with appropriate permissions
184 os.makedirs(config['dirs']['certs'], mode = 0o755, exist_ok = True)
185 os.makedirs(config['dirs']['keys'], mode = 0o710, exist_ok = True)
186 os.makedirs(config['dirs']['backups'], mode = 0o700, exist_ok = True)
189 # if necessary, generate key + certificate
190 live = config['files']['live']
191 if not os.path.exists(keyfile(live)):
195 trigger_hook('post-certchange')
196 trigger_hook('post-keychange')
198 raise Exception("Unknown action {}".format(args.action))