2 ## See <https://www.ralfj.de/blog/2017/12/26/lets-encrypt.html> 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")
22 def make_backup(fname):
23 if os.path.exists(fname):
24 os.makedirs(config['dirs']['backups'], exist_ok = True)
25 backupname = os.path.basename(fname) + "." + str(datetime.date.today())
28 backupfile = os.path.join(config['dirs']['backups'], backupname + "." + str(i))
29 if not os.path.exists(backupfile):
30 os.rename(fname, backupfile)
33 print("Somehow it's really hard to find a name for the backup file...")
35 assert not os.path.exists(fname)
37 def trigger_hook(hook):
39 exe = config['hooks'].get(hook)
41 subprocess.check_call([exe])
44 return datetime.datetime.fromtimestamp(os.stat(keyfile(name)).st_mtime)
46 def cert_expiry(name):
47 from certcheck import cert_expiry_date
48 return cert_expiry_date(certfile(name))
50 ## Work functions, operating on file names
52 ## The interesting work
53 def acme(keyfilename, certfilename, domains):
55 accountkey = config['acme']['account-key']
56 csrfilename = certfilename + '.csr.tmp'
57 assert os.path.exists(keyfilename)
59 # Generating the CSR is done by a shell script
60 exe = os.path.join(os.path.dirname(__file__), 'gencsr')
61 csr = subprocess.check_output([exe, keyfilename] + domains)
62 assert not os.path.exists(csrfilename), "The temporary CSR file {} still exists. It seems something went wrong on a previous request. You may want to remove the file manually.".format(csrfilename)
63 with open(csrfilename, 'wb') as file:
66 # call acme-tiny as a script
67 acme_tiny = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'acme-tiny', 'acme_tiny.py')
68 signed_crt = subprocess.check_output(["python3", acme_tiny, "--quiet", "--account-key", accountkey, "--csr", csrfilename, "--acme-dir", config['acme']['challenge-dir']])
69 # save new certificate
70 make_backup(certfilename)
71 with open(certfilename, 'wb') as f:
75 os.remove(csrfilename)
77 def openssl_genrsa(keyfilename):
78 with subprocess.Popen(["openssl", "genrsa", str(int(config['DEFAULT']['key-length']))], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as f:
79 (stdout, stderr) = f.communicate()
81 sys.stderr.write(stderr)
82 raise Exception("Error while generating private key")
83 # Now we have a key, save it. This should never overwrite anything.
84 assert not os.path.exists(keyfilename)
85 with open(keyfilename, 'wb') as f:
88 ## High-level functions, operating on nice key names
89 def request_cert(name):
91 if not os.path.exists(keyfile(name)):
92 raise Exception("No such key: {}".format(name))
93 domains = config['DEFAULT']['domains'].split()
94 print("Obtaining certificate '{}' for domains: {}".format(name, ' '.join(domains)))
95 acme(keyfile(name), certfile(name), domains)
97 def generate_key(name):
98 assert not os.path.exists(certfile(name)), "Don't make create a new key for an old cert"
99 print("Generating new private key '{}'".format(name))
100 openssl_genrsa(keyfile(name))
102 def check_staging(live, staging):
103 '''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.'''
104 if not os.path.exists(keyfile(staging)):
107 staging_time = datetime.timedelta(hours = int(config['timing'].get('staging-hours', 0)))
108 key_age = datetime.datetime.now() - key_mtime(staging)
109 if key_age < staging_time:
111 print("Unstaging '{}' to '{}'".format(staging, live))
113 make_backup(keyfile(live))
114 os.rename(keyfile(staging), keyfile(live))
115 make_backup(certfile(live))
116 os.rename(certfile(staging), certfile(live))
119 def auto_renewal(live, staging):
120 '''Returns 0 if nothing was done, 1 if only certs were changed, 2 if certs and keys were changed.'''
121 max_key_age = datetime.timedelta(days = int(config['timing']['max-key-age-days']))
122 renew_cert_time = datetime.timedelta(days = int(config['timing']['renew-cert-before-expiry-days']))
124 # determine what to do
125 now = datetime.datetime.now()
126 key_age = now - key_mtime(live)
127 need_new_key = key_age >= max_key_age
128 if os.path.exists(certfile(live)):
129 cert_validity = cert_expiry(live) - now
130 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 generate_key(staging)
140 request_cert(staging)
141 check_staging(live, staging) # we may want to immediately enable the new key & cert
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()
163 # read config, sanity check
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 live = config['files']['live']
170 staging = config['files']['staging']
171 if args.action[0] == 'renew':
173 if os.path.exists(keyfile(staging)) and os.path.exists(certfile(staging)):
174 request_cert(staging)
175 # trigger the "new cert" hook
177 trigger_hook('post-certchange')
178 elif args.action[0] == 'cron':
179 # First, check if we need to unstage a staging key
180 unstaged = check_staging(live, staging)
182 # A staging key is present, do *not* check for renewal
183 if unstaged >= 2 and args.hooks:
184 # trigger all the hooks
185 trigger_hook('post-certchange')
186 trigger_hook('post-keychange')
188 # Check if we need to renew anything
189 renewed = auto_renewal(live, staging)
192 trigger_hook('post-certchange')
194 trigger_hook('post-keychange')
195 elif args.action[0] == 'init':
196 # create directories with appropriate permissions
198 os.makedirs(config['dirs']['certs'], mode = 0o755, exist_ok = True)
199 os.makedirs(config['dirs']['keys'], mode = 0o710, exist_ok = True)
200 os.makedirs(config['dirs']['backups'], mode = 0o700, exist_ok = True)
203 # if necessary, generate ACME account key
204 accountkey = config['acme']['account-key']
205 if not os.path.exists(accountkey):
206 print("Generating new ACME key")
207 openssl_genrsa(accountkey)
208 # if necessary, generate key + certificate
209 live = config['files']['live']
210 if not os.path.exists(keyfile(live)):
212 if not os.path.exists(certfile(live)):
215 trigger_hook('post-certchange')
216 trigger_hook('post-keychange')
218 raise Exception("Unknown action {}".format(args.action))