]> git.wh0rd.org - home.git/blame - .bin/le-renew
le-renew: switch to cryptography module
[home.git] / .bin / le-renew
CommitLineData
6dbeb0d6
MF
1#!/usr/bin/python
2#-*- coding:utf-8 -*-
ab74211f
MF
3# pylint: disable=invalid-name
4
5"""Renew Let's Encrypt certs!
6
7To generate a new set of certs:
8$ certbot certonly --webroot \\
9 --webroot-path /var/www/wh0rd/ -d wh0rd.org -d www.wh0rd.org \\
10 --webroot-path /var/www/rss/ -d rss.wh0rd.org
11"""
12
13from __future__ import print_function
14
15import argparse
16try:
17 import configparser
18except ImportError:
19 import ConfigParser as configparser
6dbeb0d6
MF
20import cryptography.hazmat.backends
21from cryptography import x509
ab74211f
MF
22try:
23 from cStringIO import StringIO
24except ImportError:
25 from io import StringIO
26import datetime
27import logging
28import logging.handlers
ab74211f 29import os
ab74211f
MF
30import subprocess
31import sys
32
33
34LE_BASE = '/etc/letsencrypt'
35
36
37def get_parser():
38 """Return an ArgumentParser() for this module."""
39 parser = argparse.ArgumentParser(description=__doc__,
40 formatter_class=argparse.RawTextHelpFormatter)
41 parser.add_argument('-n', '--dry-run', default=False,
42 action='store_true',
43 help='Do not actually update certs')
44 parser.add_argument('--cronjob', default=False,
45 action='store_true',
46 help='Exit non-zero if no certs were changed')
47 return parser
48
49
50def setup_logging(debug=False, syslog=None):
51 """Setup the logging module just the way we like it."""
52 if syslog is None:
53 syslog = not os.isatty(sys.stdin.fileno())
54
55 if syslog:
56 handler = logging.handlers.SysLogHandler(address='/dev/log')
57 else:
58 handler = logging.StreamHandler(stream=sys.stdout)
59
60 fmt = '%(asctime)s: %(levelname)-7s: %(message)s'
61
62 datefmt = '%a, %d %b %Y %H:%M:%S letsencrypt'
63
64 level = logging.DEBUG if debug else logging.INFO
65
66 formatter = logging.Formatter(fmt, datefmt)
67 handler.setFormatter(formatter)
68
69 logger = logging.getLogger()
70 logger.addHandler(handler)
71 logger.setLevel(level)
72
73
74def load_cert(path):
75 """Load the cert at |path|"""
6dbeb0d6 76 with open(path, 'rb') as f:
ab74211f 77 data = f.read()
6dbeb0d6
MF
78 return x509.load_pem_x509_certificate(
79 data, cryptography.hazmat.backends.default_backend())
ab74211f
MF
80
81
82def load_live_cert(domain):
83 """Load the live cert for |domain|"""
84 path = os.path.join(LE_BASE, 'live', domain, 'cert.pem')
85 return load_cert(path)
86
87
88def load_conf(domain):
89 """Load the LE config file for |domain|"""
90 path = os.path.join(LE_BASE, 'renewal', domain + '.conf')
91 # The config file format is almost enough for the configparser.
92 # We need to insert a section header for the first few items.
93 fp = StringIO()
94 fp.write('[globals]\n')
95 fp.write(open(path).read())
96 fp.seek(0)
97
98 conf = configparser.RawConfigParser()
99 conf.readfp(fp)
100 return conf
101
102
103def process_domain(domain, dry_run=False):
104 """Update |domain|'s certs as needed."""
105 ret = 0
106
107 logging.info('%s: checking', domain)
108
109 conf = load_conf(domain)
110 webroot_path = conf.get('[webroot_map', domain)
111
112 cert_path = os.path.realpath(conf.get('globals', 'cert'))
113
114 cert = load_cert(cert_path)
6dbeb0d6 115 delta = cert.not_valid_after - datetime.datetime.utcnow()
ab74211f
MF
116 logging.info('%s: expires in %2s days', domain, delta.days)
117
118 cmd = [
119 'certbot',
120 'certonly', '--webroot',
121 '--webroot-path', webroot_path,
122 '-d', domain,
123 ]
6dbeb0d6
MF
124 domains = []
125 try:
126 san = cert.extensions.get_extension_for_oid(
127 x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
128 domains = san.value.get_values_for_type(x509.DNSName)
129 except x509.ExtensionNotFound:
130 pass
ab74211f
MF
131 for d in domains:
132 cmd += ['-d', d]
133 if delta.days < 30:
134 logging.info('%s: renewing', domain)
135 logging.info('%s: %s', domain, cmd)
136 if not dry_run:
137 subprocess.check_call(cmd)
138 ret = 1
139 # Try to revoke the old one.
140 cmd = ['certbot', 'revoke', '--cert-path', cert_path]
141 logging.info('%s: revoking old cert', domain)
142 logging.info('%s: %s', domain, cmd)
143 if not dry_run:
144 subprocess.check_call(cmd)
145 else:
146 logging.info('%s: up-to-date!', domain)
147
148 return ret
149
150
151def main(argv):
152 """The main() entry point!"""
153 parser = get_parser()
154 opts = parser.parse_args(argv)
155 setup_logging()
156
157 cnt = 0
158 domains = [x[:-5] for x in os.listdir('/etc/letsencrypt/renewal')]
159 for domain in domains:
160 cnt += process_domain(domain, dry_run=opts.dry_run)
161
162 if opts.cronjob:
163 if cnt:
164 return 0
165 else:
166 return 1
167
168
169if __name__ == '__main__':
170 sys.exit(main(sys.argv[1:]))