2016-02-13 00:56:47 +01:00
|
|
|
#!/usr/bin/env python
|
2016-01-10 15:00:43 +01:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
# Automated Certificate Manager using ACME
|
2016-04-04 01:17:58 +02:00
|
|
|
# Copyright (c) Markus Hauschild & David Klaftenegger, 2016.
|
|
|
|
# available under the ISC license, see LICENSE
|
2016-01-10 15:00:43 +01:00
|
|
|
|
|
|
|
|
2016-04-04 01:08:24 +02:00
|
|
|
import acertmgr_ssl
|
2016-04-04 01:04:20 +02:00
|
|
|
import acertmgr_web
|
2016-01-10 15:00:43 +01:00
|
|
|
import datetime
|
|
|
|
import dateutil.relativedelta
|
2016-01-21 16:43:49 +01:00
|
|
|
import grp
|
2016-01-10 15:00:43 +01:00
|
|
|
import os
|
2016-01-21 16:43:49 +01:00
|
|
|
import pwd
|
2016-01-10 15:00:43 +01:00
|
|
|
import re
|
2016-01-12 17:43:41 +01:00
|
|
|
import shutil
|
2016-01-10 15:00:43 +01:00
|
|
|
import subprocess
|
2016-01-12 17:41:48 +01:00
|
|
|
import tempfile
|
2016-01-10 15:00:43 +01:00
|
|
|
import yaml
|
|
|
|
|
|
|
|
|
|
|
|
ACME_DIR="/etc/acme/"
|
|
|
|
ACME_CONF=ACME_DIR + "acme.conf"
|
|
|
|
ACME_CONFD=ACME_DIR + "domains.d/"
|
|
|
|
|
2016-01-11 21:31:11 +01:00
|
|
|
|
2016-01-12 17:41:48 +01:00
|
|
|
class FileNotFoundError(OSError):
|
2016-02-13 01:02:34 +01:00
|
|
|
pass
|
2016-01-12 17:41:48 +01:00
|
|
|
|
|
|
|
|
2016-01-11 21:31:11 +01:00
|
|
|
class InvalidCertificateError(Exception):
|
|
|
|
pass
|
|
|
|
|
2016-02-28 14:44:10 +01:00
|
|
|
# @brief check whether existing target file is still valid or source crt has been updated
|
|
|
|
# @param target string containing the path to the target file
|
|
|
|
# @param crt_file string containing the path to the certificate file
|
|
|
|
# @return True if target file is at least as new as the certificate, False otherwise
|
|
|
|
def target_isCurrent(target, crt_file):
|
|
|
|
target_date = os.path.getmtime(target)
|
|
|
|
crt_date = os.path.getmtime(crt_file)
|
|
|
|
return target_date >= crt_date
|
|
|
|
|
2016-01-10 15:43:11 +01:00
|
|
|
# @brief check whether existing certificate is still valid or expiring soon
|
2016-01-10 16:40:22 +01:00
|
|
|
# @param crt_file string containing the path to the certificate file
|
|
|
|
# @param ttl_days the minimum amount of days for which the certificate must be valid
|
|
|
|
# @return True if certificate is still valid for at least ttl_days, False otherwise
|
|
|
|
def cert_isValid(crt_file, ttl_days):
|
2016-01-10 15:00:43 +01:00
|
|
|
if not os.path.isfile(crt_file):
|
|
|
|
return False
|
|
|
|
else:
|
2016-04-04 01:08:24 +02:00
|
|
|
(valid_from, valid_to) = acertmgr_ssl.cert_valid_times(crt_file)
|
2016-01-10 15:00:43 +01:00
|
|
|
|
2016-01-10 15:43:11 +01:00
|
|
|
now = datetime.datetime.now()
|
|
|
|
if valid_from > now:
|
2016-01-11 21:31:11 +01:00
|
|
|
raise InvalidCertificateError("Certificate seems to be from the future")
|
2016-01-10 15:00:43 +01:00
|
|
|
|
2016-01-10 16:40:22 +01:00
|
|
|
expiry_limit = now + dateutil.relativedelta.relativedelta(days=+ttl_days)
|
2016-01-10 15:43:11 +01:00
|
|
|
if valid_to < expiry_limit:
|
2016-01-10 15:00:43 +01:00
|
|
|
return False
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2016-01-10 15:43:11 +01:00
|
|
|
# @brief fetch new certificate from letsencrypt
|
|
|
|
# @param domain string containing the domain name
|
|
|
|
# @param settings the domain's configuration options
|
2016-04-04 01:18:19 +02:00
|
|
|
def cert_get(domains, settings):
|
|
|
|
domain = domains.split(' ')[0]
|
2016-01-11 20:15:31 +01:00
|
|
|
print("Getting certificate for %s." % domain)
|
|
|
|
|
2016-01-10 15:00:43 +01:00
|
|
|
key_file = ACME_DIR + "server.key"
|
2016-01-11 20:56:08 +01:00
|
|
|
if not os.path.isfile(key_file):
|
2016-01-11 21:31:11 +01:00
|
|
|
raise FileNotFoundError("The server key file (%s) is missing!" % key_file)
|
2016-01-11 20:15:31 +01:00
|
|
|
|
|
|
|
acc_file = ACME_DIR + "account.key"
|
2016-01-11 20:56:08 +01:00
|
|
|
if not os.path.isfile(acc_file):
|
2016-01-11 21:31:11 +01:00
|
|
|
raise FileNotFoundError("The account key file (%s) is missing!" % acc_file)
|
2016-01-10 18:07:00 +01:00
|
|
|
|
2016-01-12 17:41:48 +01:00
|
|
|
_, csr_file = tempfile.mkstemp(".csr", "%s." % domain)
|
|
|
|
_, crt_file = tempfile.mkstemp(".crt", "%s." % domain)
|
2016-01-10 15:00:43 +01:00
|
|
|
|
2016-01-12 17:33:20 +01:00
|
|
|
challenge_dir = settings.get("webdir", "/var/www/acme-challenge/")
|
|
|
|
if not os.path.isdir(challenge_dir):
|
|
|
|
raise FileNotFoundError("Challenge directory (%s) does not exist!" % challenge_dir)
|
2016-01-10 15:00:43 +01:00
|
|
|
|
2016-02-13 00:48:38 +01:00
|
|
|
if settings['mode'] == 'standalone':
|
|
|
|
port = settings.get('port', 80)
|
|
|
|
|
|
|
|
current_dir = os.getcwd()
|
|
|
|
os.chdir(challenge_dir)
|
2016-04-04 01:04:20 +02:00
|
|
|
server = acertmgr_web.ACMEHTTPServer(port)
|
|
|
|
server.start()
|
2016-01-11 21:38:09 +01:00
|
|
|
try:
|
2016-04-04 01:08:24 +02:00
|
|
|
key_fd = open(key_file, "r")
|
|
|
|
key = key_fd.read()
|
|
|
|
key_fd.close()
|
|
|
|
cr = acertmgr_ssl.cert_request(domains.split(), key)
|
2016-04-04 01:12:50 +02:00
|
|
|
crt = acertmgr_ssl.get_crt_from_csr(acc_file, cr, domains.split(), challenge_dir)
|
2016-01-11 21:38:09 +01:00
|
|
|
with open(crt_file, "w") as crt_fd:
|
|
|
|
crt_fd.write(crt)
|
2016-01-11 20:51:23 +01:00
|
|
|
|
2016-01-12 17:43:41 +01:00
|
|
|
# if resulting certificate is valid: store in final location
|
|
|
|
if cert_isValid(crt_file, 60):
|
|
|
|
crt_final = ACME_DIR + "%s.crt" % domain
|
|
|
|
shutil.copy2(crt_file, crt_final)
|
2016-01-10 16:40:22 +01:00
|
|
|
|
2016-01-12 17:41:48 +01:00
|
|
|
finally:
|
2016-02-13 00:48:38 +01:00
|
|
|
if settings['mode'] == 'standalone':
|
|
|
|
os.chdir(current_dir)
|
2016-04-04 01:04:20 +02:00
|
|
|
server.stop()
|
2016-01-12 17:41:48 +01:00
|
|
|
os.remove(csr_file)
|
|
|
|
os.remove(crt_file)
|
2016-01-10 18:07:00 +01:00
|
|
|
|
2016-01-10 17:29:26 +01:00
|
|
|
|
2016-01-12 17:41:48 +01:00
|
|
|
# @brief put new certificate in place
|
2016-01-10 17:29:26 +01:00
|
|
|
# @param domain string containing the domain name
|
|
|
|
# @param settings the domain's configuration options
|
2016-02-21 11:18:32 +01:00
|
|
|
# @return the action to be executed after the certificate update
|
2016-01-10 17:29:26 +01:00
|
|
|
def cert_put(domain, settings):
|
2016-01-16 18:58:12 +01:00
|
|
|
# TODO error handling
|
2016-02-21 15:27:46 +01:00
|
|
|
ca_file = settings.get("cafile", "")
|
2016-01-16 18:58:12 +01:00
|
|
|
crt_user = settings['user']
|
|
|
|
crt_group = settings['group']
|
|
|
|
crt_perm = settings['perm']
|
|
|
|
crt_path = settings['path']
|
2016-01-21 16:43:49 +01:00
|
|
|
crt_format = settings['format'].split(",")
|
2016-02-21 11:18:32 +01:00
|
|
|
crt_action = settings['action']
|
2016-01-16 18:58:12 +01:00
|
|
|
|
2016-01-21 16:43:49 +01:00
|
|
|
key_file = ACME_DIR + "server.key"
|
2016-04-04 01:18:19 +02:00
|
|
|
crt_final = ACME_DIR + "%s.crt" % domain.split(' ')[0]
|
2016-01-16 18:58:12 +01:00
|
|
|
|
2016-01-21 16:43:49 +01:00
|
|
|
with open(crt_path, "w+") as crt_fd:
|
|
|
|
for fmt in crt_format:
|
|
|
|
if fmt == "crt":
|
|
|
|
src_fd = open(crt_final, "r")
|
|
|
|
crt_fd.write(src_fd.read())
|
|
|
|
src_fd.close()
|
|
|
|
if fmt == "key":
|
|
|
|
src_fd = open(key_file, "r")
|
|
|
|
crt_fd.write(src_fd.read())
|
|
|
|
src_fd.close()
|
2016-02-21 15:27:46 +01:00
|
|
|
if fmt == "ca":
|
|
|
|
if not os.path.isfile(ca_file):
|
|
|
|
raise FileNotFoundError("The server key file (%s) is missing!" % ca_file)
|
|
|
|
src_fd = open(ca_file, "r")
|
|
|
|
crt_fd.write(src_fd.read())
|
|
|
|
src_fd.close()
|
2016-01-21 16:43:49 +01:00
|
|
|
else:
|
2016-02-21 12:44:24 +01:00
|
|
|
# TODO error handling
|
2016-01-21 16:43:49 +01:00
|
|
|
pass
|
|
|
|
|
|
|
|
# set owner and permissions
|
|
|
|
uid = pwd.getpwnam(crt_user).pw_uid
|
|
|
|
gid = grp.getgrnam(crt_group).gr_gid
|
2016-02-13 00:57:28 +01:00
|
|
|
try:
|
|
|
|
os.chown(crt_path, uid, gid)
|
|
|
|
except OSError:
|
|
|
|
print('Warning: Could not set certificate file ownership!')
|
|
|
|
try:
|
|
|
|
os.chmod(crt_path, int(crt_perm, 8))
|
|
|
|
except OSError:
|
|
|
|
print('Warning: Could not set certificate file permissions!')
|
2016-01-21 16:43:49 +01:00
|
|
|
|
2016-02-21 11:18:32 +01:00
|
|
|
return crt_action
|
2016-01-10 15:00:43 +01:00
|
|
|
|
|
|
|
|
2016-01-10 15:43:11 +01:00
|
|
|
# @brief augment configuration with defaults
|
|
|
|
# @param domainconfig the domain configuration
|
|
|
|
# @param defaults the default configuration
|
|
|
|
# @return the augmented configuration
|
|
|
|
def complete_config(domainconfig, defaults):
|
2016-02-23 17:53:50 +01:00
|
|
|
if defaults:
|
|
|
|
for name, value in defaults.items():
|
|
|
|
if name not in domainconfig:
|
|
|
|
domainconfig[name] = value
|
2016-01-10 15:43:11 +01:00
|
|
|
return domainconfig
|
|
|
|
|
|
|
|
|
2016-01-10 15:00:43 +01:00
|
|
|
if __name__ == "__main__":
|
2016-01-10 15:48:16 +01:00
|
|
|
# load global configuration
|
|
|
|
if os.path.isfile(ACME_CONF):
|
|
|
|
with open(ACME_CONF) as config_fd:
|
|
|
|
config = yaml.load(config_fd)
|
|
|
|
if not config:
|
|
|
|
config = {}
|
2016-01-10 15:43:11 +01:00
|
|
|
if 'defaults' not in config:
|
|
|
|
config['defaults'] = {}
|
2016-01-10 15:48:16 +01:00
|
|
|
|
2016-02-28 14:44:10 +01:00
|
|
|
config['domains'] = []
|
2016-01-10 15:48:16 +01:00
|
|
|
# load domain configuration
|
2016-01-10 15:00:43 +01:00
|
|
|
for config_file in os.listdir(ACME_CONFD):
|
|
|
|
if config_file.endswith(".conf"):
|
|
|
|
with open(ACME_CONFD + config_file) as config_fd:
|
2016-02-28 14:44:10 +01:00
|
|
|
for entry in yaml.load(config_fd).items():
|
|
|
|
config['domains'].append(entry)
|
2016-02-21 11:18:32 +01:00
|
|
|
|
|
|
|
# post-update actions (run only once)
|
|
|
|
actions = set()
|
2016-01-10 15:00:43 +01:00
|
|
|
|
2016-01-10 15:48:16 +01:00
|
|
|
# check certificate validity and obtain/renew certificates if needed
|
2016-04-04 01:18:19 +02:00
|
|
|
for domains, domaincfgs in config['domains']:
|
2016-01-10 18:07:00 +01:00
|
|
|
# skip domains without any output files
|
|
|
|
if domaincfgs is None:
|
|
|
|
continue
|
2016-04-04 01:18:19 +02:00
|
|
|
crt_file = ACME_DIR + "%s.crt" % domains.split(' ')[0]
|
2016-01-10 16:40:22 +01:00
|
|
|
ttl_days = int(config.get('ttl_days', 15))
|
|
|
|
if not cert_isValid(crt_file, ttl_days):
|
2016-04-04 01:18:19 +02:00
|
|
|
cert_get(domains, config)
|
2016-02-28 14:44:10 +01:00
|
|
|
for domaincfg in domaincfgs:
|
|
|
|
cfg = complete_config(domaincfg, config['defaults'])
|
|
|
|
if not target_isCurrent(cfg['path'], crt_file):
|
2016-04-04 01:18:19 +02:00
|
|
|
actions.add(cert_put(domains, cfg))
|
2016-02-21 11:18:32 +01:00
|
|
|
|
|
|
|
# run post-update actions
|
|
|
|
for action in actions:
|
|
|
|
subprocess.call(action.split())
|