add BSD license, update README now that this is just Let's Encrypt Tiny
[lets-encrypt-tiny.git] / letsencrypt-tiny
1 #!/usr/bin/env python3
2 ## See <https://www.ralfj.de/blog/2017/12/26/lets-encrypt.html> 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), "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)
62     with open(csrfilename, 'wb') as file:
63         file.write(csr)
64     try:
65         # call acme-tiny as a script
66         acme_tiny = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'acme-tiny', 'acme_tiny.py')
67         signed_crt = subprocess.check_output(["python", acme_tiny, "--quiet", "--account-key", accountkey, "--csr", csrfilename, "--acme-dir", config['acme']['challenge-dir']])
68         # save new certificate
69         make_backup(certfilename)
70         with open(certfilename, 'wb') as f:
71             f.write(signed_crt)
72     finally:
73         # clean up
74         os.remove(csrfilename)
75
76 def openssl_genrsa(keyfilename):
77     with subprocess.Popen(["openssl", "genrsa", str(int(config['DEFAULT']['key-length']))], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as f:
78         (stdout, stderr) = f.communicate()
79         if f.returncode:
80             sys.stderr.write(stderr)
81             raise Exception("Error while generating private key")
82     # Now we have a key, save it. This should never overwrite anything.
83     assert not os.path.exists(keyfilename)
84     with open(keyfilename, 'wb') as f:
85         f.write(stdout)
86
87 ## High-level functions, operating on nice key names
88 def request_cert(name):
89     global config
90     if not os.path.exists(keyfile(name)):
91         raise Exception("No such key: {}".format(name))
92     domains = config['DEFAULT']['domains'].split()
93     print("Obtaining certificate '{}' for domains: {}".format(name, ' '.join(domains)))
94     acme(keyfile(name), certfile(name), domains)
95
96 def generate_key(name):
97     assert not os.path.exists(certfile(name)), "Don't make create a new key for an old cert"
98     print("Generating new private key '{}'".format(name))
99     openssl_genrsa(keyfile(name))
100
101 def check_staging(live, staging):
102     '''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.'''
103     if not os.path.exists(keyfile(staging)):
104         return 0
105     
106     staging_time = datetime.timedelta(hours = int(config['timing'].get('staging-hours', 0)))
107     key_age = datetime.datetime.now() - key_mtime(staging)
108     if key_age < staging_time:
109         return 1
110     print("Unstaging '{}' to '{}'".format(staging, live))
111     # unstage the key!
112     make_backup(keyfile(live))
113     os.rename(keyfile(staging), keyfile(live))
114     make_backup(certfile(live))
115     os.rename(certfile(staging), certfile(live))
116     return 2
117
118 def auto_renewal(live, staging):
119     '''Returns 0 if nothing was done, 1 if only certs were changed, 2 if certs and keys were changed.'''
120     max_key_age = datetime.timedelta(days = int(config['timing']['max-key-age-days']))
121     renew_cert_time = datetime.timedelta(days = int(config['timing']['renew-cert-before-expiry-days']))
122     
123     # determine what to do
124     now = datetime.datetime.now()
125     key_age = now - key_mtime(live)
126     cert_validity = cert_expiry(live) - now
127     need_new_key = key_age >= max_key_age
128     need_new_cert = cert_validity <= renew_cert_time
129     if need_new_cert and key_age + renew_cert_time >= max_key_age:
130         # We are about to request a new certificate, and within <renew_cert_time>, we need a new key: Get the new key now
131         need_new_key = True
132     
133     # Do it
134     if need_new_key:
135         generate_key(staging)
136         request_cert(staging)
137         check_staging(live, staging) # we may want to immediately enable the new key & cert
138         return 2
139     elif need_new_cert:
140         request_cert(live)
141         return 1
142     else:
143         return 0
144
145 ## Main
146 if __name__ == "__main__":
147     # allow overwriting some values on the command-line
148     parser = argparse.ArgumentParser(description='Generate and (automatically) renew certificates, optionally providing staging for new keys')
149     parser.add_argument("-c", "--config",
150                         dest="config",
151                         help="The configuration file")
152     parser.add_argument("-k", "--hooks",
153                         dest="hooks", action="store_true",
154                         help="Trigger hooks.")
155     parser.add_argument("action", metavar='ACTION', nargs=1,
156                         help="The action to perform. Possible values: init, renew, cron")
157     args = parser.parse_args()
158     
159     # read config, sanity check
160     if not os.path.isfile(args.config):
161         raise Exception("The config file does not exist: "+args.config)
162     global config
163     config = readConfig(args.config)
164     
165     live = config['files']['live']
166     staging = config['files']['staging']
167     if args.action[0] == 'renew':
168         request_cert(live)
169         if os.path.exists(keyfile(staging)) and os.path.exists(certfile(staging)):
170             request_cert(staging)
171         # trigger the "new cert" hook
172         if args.hooks:
173             trigger_hook('post-certchange')
174     elif args.action[0] == 'cron':
175         # First, check if we need to unstage a staging key
176         unstaged = check_staging(live, staging)
177         if unstaged >= 1:
178             # A staging key is present, do *not* check for renewal
179             if unstaged >= 2 and args.hooks:
180                 # trigger all the hooks
181                 trigger_hook('post-certchange')
182                 trigger_hook('post-keychange')
183         else:
184             # Check if we need to renew anything
185             renewed = auto_renewal(live, staging)
186             if args.hooks:
187                 if renewed >= 1:
188                     trigger_hook('post-certchange')
189                 if renewed >= 2:
190                     trigger_hook('post-keychange')
191     elif args.action[0] == 'init':
192         # create directories with appropriate permissions
193         try:
194             os.makedirs(config['dirs']['certs'], mode = 0o755, exist_ok = True)
195             os.makedirs(config['dirs']['keys'], mode = 0o710, exist_ok = True)
196             os.makedirs(config['dirs']['backups'], mode = 0o700, exist_ok = True)
197         except OSError:
198             pass
199         # if necessary, generate ACME account key
200         accountkey = config['acme']['account-key']
201         if not os.path.exists(accountkey):
202             print("Generating new ACME key")
203             openssl_genrsa(accountkey)
204         # if necessary, generate key + certificate
205         live = config['files']['live']
206         if not os.path.exists(keyfile(live)):
207             generate_key(live)
208         if not os.path.exists(certfile(live)):
209             request_cert(live)
210             if args.hooks:
211                 trigger_hook('post-certchange')
212                 trigger_hook('post-keychange')
213     else:
214         raise Exception("Unknown action {}".format(args.action))