add support for generating crt+chain files
[lets-encrypt-tiny.git] / letsencrypt-tiny
1 #!/usr/bin/env python3
2 ## Call with "--help" for documentation.
3
4 import argparse, configparser, itertools, stat, os, os.path, sys, subprocess, datetime
5
6 ## Helper functions
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)
12     return config
13
14 def certfile(name, suff = None):
15     global config
16     return os.path.join(config['dirs']['certs'], name + ".crt" + ('' if suff is None else '+'+suff) )
17
18 def keyfile(name):
19     global config
20     return os.path.join(config['dirs']['keys'], name + ".key")
21
22 def csrfile(name):
23     global config
24     return os.path.join(config['dirs']['csrs'], name + ".csr")
25
26 def make_backup(fname):
27     if os.path.exists(fname):
28         backupname = os.path.basename(fname) + "." + str(datetime.date.today())
29         i = 0
30         while True:
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)
34                 break
35             elif i >= 100:
36                 print("Somehow it's really hard to find a name for the backup file...")
37             i += 1
38     assert not os.path.exists(fname)
39
40 def trigger_hook(hook):
41     global config
42     exe = config['hooks'][hook]
43     if exe is not None:
44         subprocess.check_call([exe])
45
46 def key_mtime(name):
47     return datetime.datetime.fromtimestamp(os.stat(keyfile(name)).st_mtime)
48
49 def cert_expiry(name):
50     from certcheck import cert_expiry_date
51     return cert_expiry_date(certfile(name))
52
53 ## The interesting work
54 def acme(name, domains):
55     global config
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:
60         file.write(csr)
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:
67         f.write(signed_crt)
68     # append DH params
69     dhfile = config['DEFAULT'].get('dh-params')
70     if dhfile is not None:
71         with open(dhfile, 'rb') as f:
72             dh = f.read()
73         with open(certfile(name, 'dh'), 'wb') as f:
74             f.write(signed_crt)
75             f.write(dh)
76     # append chain
77     chainfile = config['DEFAULT'].get('chain')
78     if chainfile is not None:
79         with open(chainfile, 'rb') as f:
80             chain = f.read()
81         with open(certfile(name, 'chain'), 'wb') as f:
82             f.write(signed_crt)
83             f.write(chain)
84
85 def request_cert(name):
86     global config
87     if not os.path.exists(keyfile(name)):
88         raise Exception("No such key: {}".format(name))
89     domains = config['DEFAULT']['domains'].split()
90     print("Obtaining certificate '{}' for domains: {}".format(name, ' '.join(domains)))
91     acme(name, domains)
92
93 def generate_key(name):
94     print("Generating new private key '{}'".format(name))
95     with subprocess.Popen(["openssl", "genrsa", str(int(config['DEFAULT']['key-length']))], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as f:
96         (stdout, stderr) = f.communicate()
97         if f.returncode:
98             sys.stderr.write(stderr)
99             raise Exception("Error while generating private key")
100     # now we have a key, save it
101     make_backup(keyfile(name))
102     with open(keyfile(name), 'wb') as f:
103         f.write(stdout)
104
105 def check_staging():
106     '''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.'''
107     live = config['files']['live']
108     staging = config['files'].get('staging')
109     if staging is None or not os.path.exists(keyfile(staging)):
110         return 0
111     
112     staging_time = datetime.timedelta(hours = int(config['timing']['staging-hours']))
113     key_age = datetime.datetime.now() - key_mtime(staging)
114     if key_age < staging_time:
115         return 1
116     print("Unstaging '{}' to '{}'".format(staging, live))
117     # unstage the key!
118     make_backup(keyfile(live))
119     os.rename(src = keyfile(staging), dst = keyfile(live))
120     make_backup(certfile(live))
121     os.rename(src = certfile(staging), dst = certfile(live))
122     try:
123         os.rename(src = certfile(staging, 'dh'), dst = certfile(live, 'dh'))
124     except FileNotFoundError:
125         pass
126     try:
127         os.rename(src = certfile(staging, 'chain'), dst = certfile(live, 'chain'))
128     except FileNotFoundError:
129         pass
130     return 2
131
132 def auto_renewal():
133     '''Returns 0 if nothing was done, 1 if only certs were changed, 2 if certs and keys were changed.'''
134     live = config['files']['live']
135     staging = config['files'].get('staging')
136     
137     max_key_age = datetime.timedelta(days = int(config['timing']['max-key-age-days']))
138     renew_cert_time = datetime.timedelta(days = int(config['timing']['renew-cert-before-expiry-days']))
139     
140     # determine what to do
141     now = datetime.datetime.now()
142     key_age = now - key_mtime(live)
143     cert_validity = cert_expiry(live) - now
144     need_new_key = key_age >= max_key_age
145     need_new_cert = cert_validity <= renew_cert_time
146     if need_new_cert and key_age + renew_cert_time >= max_key_age:
147         # We are about to request a new certificate, and within <renew_cert_time>, we need a new key: Get the new key now
148         need_new_key = True
149     
150     # Do it
151     if need_new_key:
152         new_key_name = (live if staging is None else staging)
153         generate_key(new_key_name)
154         request_cert(new_key_name)
155         return 2
156     elif need_new_cert:
157         request_cert(live)
158         return 1
159     else:
160         return 0
161
162 ## Main
163 if __name__ == "__main__":
164     # allow overwriting some values on the command-line
165     parser = argparse.ArgumentParser(description='Generate and (automatically) renew certificates, optionally providing staging for new keys')
166     parser.add_argument("-c", "--config",
167                         dest="config",
168                         help="The configuration file")
169     parser.add_argument("-k", "--hooks",
170                         dest="hooks", action="store_true",
171                         help="Trigger hooks.")
172     parser.add_argument("action", metavar='ACTION', nargs=1,
173                         help="The action to perform. Possible values: init, renew, cron")
174     args = parser.parse_args()
175     
176     # read config
177     if not os.path.isfile(args.config):
178         raise Exception("The config file does not exist: "+args.config)
179     global config
180     config = readConfig(args.config)
181     
182     if args.action[0] == 'renew':
183         live = config['files']['live']
184         staging = config['files'].get('staging')
185         
186         request_cert(live)
187         if staging is not None and os.path.exists(keyfile(staging)):
188             request_cert(staging)
189         # trigger the "new cert" hook
190         if args.hooks:
191             trigger_hook('post-certchange')
192     elif args.action[0] == 'cron':
193         # First, check if we need to unstage a staging key
194         unstaged = check_staging()
195         if unstaged >= 1:
196             # A staging eky is present, do *not* check for renewal
197             if unstaged >= 2 and args.hooks:
198                 # trigger all the hooks
199                 trigger_hook('post-certchange')
200                 trigger_hook('post-keychange')
201         else:
202             # Check if we need to renew anything
203             renewed = auto_renewal()
204             if args.hooks:
205                 if renewed >= 1:
206                     trigger_hook('post-certchange')
207                 if renewed >= 2:
208                     trigger_hook('post-keychange')
209     elif args.action[0] == 'init':
210         # create directories with appropriate permissions
211         try:
212             os.makedirs(config['dirs']['certs'], mode = 0o755, exist_ok = True)
213             os.makedirs(config['dirs']['keys'], mode = 0o710, exist_ok = True)
214             os.makedirs(config['dirs']['csrs'], mode = 0o755, exist_ok = True)
215             os.makedirs(config['dirs']['backups'], mode = 0o700, exist_ok = True)
216         except OSError:
217             pass
218         # if necessary, generate key + certificate
219         live = config['files']['live']
220         if not os.path.exists(keyfile(live)):
221             generate_key(live)
222             request_cert(live)
223             if args.hooks:
224                 trigger_hook('post-certchange')
225                 trigger_hook('post-keychange')
226     else:
227         raise Exception("Unknown action {}".format(args.action))