hooks are not mandatory
[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):
15     global config
16     return os.path.join(config['dirs']['certs'], name + ".crt" )
17
18 def keyfile(name):
19     global config
20     return os.path.join(config['dirs']['keys'], name + ".key")
21
22 def make_backup(fname):
23     if os.path.exists(fname):
24         backupname = os.path.basename(fname) + "." + str(datetime.date.today())
25         i = 0
26         while True:
27             backupfile = os.path.join(config['dirs']['backups'], backupname + "." + str(i))
28             if not os.path.exists(backupfile):
29                 os.rename(fname, backupfile)
30                 break
31             elif i >= 100:
32                 print("Somehow it's really hard to find a name for the backup file...")
33             i += 1
34     assert not os.path.exists(fname)
35
36 def trigger_hook(hook):
37     global config
38     exe = config['hooks'].get(hook)
39     if exe is not None:
40         subprocess.check_call([exe])
41
42 def key_mtime(name):
43     return datetime.datetime.fromtimestamp(os.stat(keyfile(name)).st_mtime)
44
45 def cert_expiry(name):
46     from certcheck import cert_expiry_date
47     return cert_expiry_date(certfile(name))
48
49 ## Work functions, operating on file names
50
51 ## The interesting work
52 def acme(keyfilename, certfilename, domains):
53     global config
54     accountkey = config['acme']['account-key']
55     csrfilename = certfilename + '.csr.tmp'
56     assert os.path.exists(keyfilename)
57     assert accountkey
58     # Generating the CSR is done by a shell script
59     exe = os.path.join(os.path.dirname(__file__), 'gencsr')
60     csr = subprocess.check_output([exe, keyfilename] + domains)
61     assert not os.path.exists(csrfilename)
62     with open(csrfilename, 'wb') as file:
63         file.write(csr)
64     # call acme-tiny as a script
65     acme_tiny = os.path.join(config['acme']['acme-tiny'], 'acme_tiny.py')
66     signed_crt = subprocess.check_output(["python", acme_tiny, "--quiet", "--account-key", accountkey, "--csr", csrfilename, "--acme-dir", config['acme']['challenge-dir']])
67     # save new certificate
68     make_backup(certfilename)
69     with open(certfilename, 'wb') as f:
70         f.write(signed_crt)
71     # clean up
72     os.remove(csrfilename)
73
74 def openssl_genrsa(keyfilename):
75     with subprocess.Popen(["openssl", "genrsa", str(int(config['DEFAULT']['key-length']))], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as f:
76         (stdout, stderr) = f.communicate()
77         if f.returncode:
78             sys.stderr.write(stderr)
79             raise Exception("Error while generating private key")
80     # Now we have a key, save it. This should never overwrite anything.
81     assert not os.path.exists(keyfilename)
82     with open(keyfilename, 'wb') as f:
83         f.write(stdout)
84
85 ## High-level functions, operating on nice key names
86 def request_cert(name):
87     global config
88     if not os.path.exists(keyfile(name)):
89         raise Exception("No such key: {}".format(name))
90     domains = config['DEFAULT']['domains'].split()
91     print("Obtaining certificate '{}' for domains: {}".format(name, ' '.join(domains)))
92     acme(keyfile(name), certfile(name), domains)
93
94 def generate_key(name):
95     print("Generating new private key '{}'".format(name))
96     openssl_genrsa(keyfile(name))
97
98 def check_staging(live, staging):
99     '''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.'''
100     if not os.path.exists(keyfile(staging)):
101         return 0
102     
103     staging_time = datetime.timedelta(hours = int(config['timing'].get('staging-hours', 0)))
104     key_age = datetime.datetime.now() - key_mtime(staging)
105     if key_age < staging_time:
106         return 1
107     print("Unstaging '{}' to '{}'".format(staging, live))
108     # unstage the key!
109     make_backup(keyfile(live))
110     os.rename(keyfile(staging), keyfile(live))
111     make_backup(certfile(live))
112     os.rename(certfile(staging), certfile(live))
113     return 2
114
115 def auto_renewal(live, staging):
116     '''Returns 0 if nothing was done, 1 if only certs were changed, 2 if certs and keys were changed.'''
117     max_key_age = datetime.timedelta(days = int(config['timing']['max-key-age-days']))
118     renew_cert_time = datetime.timedelta(days = int(config['timing']['renew-cert-before-expiry-days']))
119     
120     # determine what to do
121     now = datetime.datetime.now()
122     key_age = now - key_mtime(live)
123     cert_validity = cert_expiry(live) - now
124     need_new_key = key_age >= max_key_age
125     need_new_cert = cert_validity <= renew_cert_time
126     if need_new_cert and key_age + renew_cert_time >= max_key_age:
127         # We are about to request a new certificate, and within <renew_cert_time>, we need a new key: Get the new key now
128         need_new_key = True
129     
130     # Do it
131     if need_new_key:
132         generate_key(staging)
133         request_cert(staging)
134         check_staging(live, staging) # we may want to immediately enable the new key & cert
135         return 2
136     elif need_new_cert:
137         request_cert(live)
138         return 1
139     else:
140         return 0
141
142 ## Main
143 if __name__ == "__main__":
144     # allow overwriting some values on the command-line
145     parser = argparse.ArgumentParser(description='Generate and (automatically) renew certificates, optionally providing staging for new keys')
146     parser.add_argument("-c", "--config",
147                         dest="config",
148                         help="The configuration file")
149     parser.add_argument("-k", "--hooks",
150                         dest="hooks", action="store_true",
151                         help="Trigger hooks.")
152     parser.add_argument("action", metavar='ACTION', nargs=1,
153                         help="The action to perform. Possible values: init, renew, cron")
154     args = parser.parse_args()
155     
156     # read config, sanity check
157     if not os.path.isfile(args.config):
158         raise Exception("The config file does not exist: "+args.config)
159     global config
160     config = readConfig(args.config)
161     
162     live = config['files']['live']
163     staging = config['files']['staging']
164     if args.action[0] == 'renew':
165         request_cert(live)
166         if os.path.exists(keyfile(staging)) and os.path.exists(certfile(staging)):
167             request_cert(staging)
168         # trigger the "new cert" hook
169         if args.hooks:
170             trigger_hook('post-certchange')
171     elif args.action[0] == 'cron':
172         # First, check if we need to unstage a staging key
173         unstaged = check_staging(live, staging)
174         if unstaged >= 1:
175             # A staging key is present, do *not* check for renewal
176             if unstaged >= 2 and args.hooks:
177                 # trigger all the hooks
178                 trigger_hook('post-certchange')
179                 trigger_hook('post-keychange')
180         else:
181             # Check if we need to renew anything
182             renewed = auto_renewal(live, staging)
183             if args.hooks:
184                 if renewed >= 1:
185                     trigger_hook('post-certchange')
186                 if renewed >= 2:
187                     trigger_hook('post-keychange')
188     elif args.action[0] == 'init':
189         # create directories with appropriate permissions
190         try:
191             os.makedirs(config['dirs']['certs'], mode = 0o755, exist_ok = True)
192             os.makedirs(config['dirs']['keys'], mode = 0o710, exist_ok = True)
193             os.makedirs(config['dirs']['backups'], mode = 0o700, exist_ok = True)
194         except OSError:
195             pass
196         # if necessary, generate ACME account key
197         accountkey = config['acme']['account-key']
198         if not os.path.exists(accountkey):
199             print("Generating new ACME key")
200             openssl_genrsa(accountkey)
201         # if necessary, generate key + certificate
202         live = config['files']['live']
203         if not os.path.exists(keyfile(live)):
204             generate_key(live)
205             request_cert(live)
206             if args.hooks:
207                 trigger_hook('post-certchange')
208                 trigger_hook('post-keychange')
209     else:
210         raise Exception("Unknown action {}".format(args.action))