1
0
Fork 0

Using Python to validate the Certbot expiration date.

This commit is contained in:
Joao Gilberto Magalhaes 2023-07-01 15:30:00 -05:00
parent b26d13cd75
commit 55888752c9
2 changed files with 58 additions and 43 deletions

View file

@ -6,12 +6,14 @@ import time
import os import os
import re import re
import time import time
from OpenSSL import crypto
class Functions: class Functions:
HAPROXY_LOG="HAPROXY" HAPROXY_LOG = "HAPROXY"
EASYHAPROXY_LOG="EASYHAPROXY" EASYHAPROXY_LOG = "EASYHAPROXY"
CERTBOT_LOG="CERTBOT" CERTBOT_LOG = "CERTBOT"
INIT_LOG="INIT" INIT_LOG = "INIT"
TRACE = "TRACE" TRACE = "TRACE"
DEBUG = "DEBUG" DEBUG = "DEBUG"
@ -28,7 +30,7 @@ class Functions:
level_importance = { level_importance = {
Functions.TRACE: 0, Functions.TRACE: 0,
Functions.DEBUG: 1, Functions.DEBUG: 1,
Functions.INFO: 2, Functions.INFO: 2,
Functions.WARN: 3, Functions.WARN: 3,
Functions.ERROR: 4, Functions.ERROR: 4,
Functions.FATAL: 5 Functions.FATAL: 5
@ -57,7 +59,7 @@ class Functions:
if not isinstance(message, (list, tuple)): if not isinstance(message, (list, tuple)):
message = [message] message = [message]
for line in message: for line in message:
log = "[%s] %s [%s]: %s" % (source, datetime.now().strftime("%x %X"), level, line.rstrip()) log = "[%s] %s [%s]: %s" % (source, datetime.now().strftime("%x %X"), level, line.rstrip())
print(log) print(log)
@ -70,10 +72,10 @@ class Functions:
command = shlex.split(command) command = shlex.split(command)
try: try:
process = subprocess.Popen(command, process = subprocess.Popen(command,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True) universal_newlines=True)
output = [] output = []
@ -94,7 +96,7 @@ class Functions:
return output return output
except Exception as e: except Exception as e:
Functions.log(source, Functions.ERROR, "%s" % (e)) Functions.log(source, Functions.ERROR, "%s" % e)
class Consts: class Consts:
@ -103,6 +105,7 @@ class Consts:
certs_letsencrypt = "/certs/letsencrypt" certs_letsencrypt = "/certs/letsencrypt"
certs_haproxy = "/certs/haproxy" certs_haproxy = "/certs/haproxy"
class DaemonizeHAProxy: class DaemonizeHAProxy:
def __init__(self): def __init__(self):
self.process = None self.process = None
@ -111,10 +114,13 @@ class DaemonizeHAProxy:
def haproxy(self, action): def haproxy(self, action):
if action == "start": if action == "start":
self.__prepare("/usr/sbin/haproxy -W -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -S /var/run/haproxy.sock") self.__prepare(
"/usr/sbin/haproxy -W -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -S /var/run/haproxy.sock")
else: else:
pid = "".join(Functions().run_bash(Functions.HAPROXY_LOG, "cat /run/haproxy.pid", log_output=False)) pid = "".join(Functions().run_bash(Functions.HAPROXY_LOG, "cat /run/haproxy.pid", log_output=False))
self.__prepare("/usr/sbin/haproxy -W -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -x /var/run/haproxy.sock -sf %s" % (pid)) self.__prepare(
"/usr/sbin/haproxy -W -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -x /var/run/haproxy.sock -sf %s" % (
pid))
if self.process is None: if self.process is None:
return return
@ -128,29 +134,28 @@ class DaemonizeHAProxy:
command = shlex.split(command) command = shlex.split(command)
try: try:
self.process = subprocess.Popen(command, self.process = subprocess.Popen(command,
shell=False, shell=False,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
bufsize=-1, bufsize=-1,
universal_newlines=True) universal_newlines=True)
except Exception as e: except Exception as e:
Functions.log(source, Functions.ERROR, "%s" % (e)) Functions.log(source, Functions.ERROR, "%s" % e)
def __start(self): def __start(self):
source = Functions.HAPROXY_LOG source = Functions.HAPROXY_LOG
try: try:
with self.process.stdout: with self.process.stdout:
for line in iter(self.process.stdout.readline, b''): for line in iter(self.process.stdout.readline, b''):
Functions.log(source, Functions.INFO, line) Functions.log(source, Functions.INFO, line)
returncode = self.process.wait() returncode = self.process.wait()
Functions.log(source, Functions.DEBUG, "Return code %s" % (returncode)) Functions.log(source, Functions.DEBUG, "Return code %s" % (returncode))
except Exception as e: except Exception as e:
Functions.log(source, Functions.ERROR, "%s" % (e)) Functions.log(source, Functions.ERROR, "%s" % e)
def is_alive(self): def is_alive(self):
return self.thread.is_alive() return self.thread.is_alive()
@ -165,7 +170,7 @@ class DaemonizeHAProxy:
def sleep(self): def sleep(self):
if self.sleep_secs is None: if self.sleep_secs is None:
try: try:
self.sleep_secs = int(os.getenv("EASYHAPROXY_REFRESH_CONF", "10")) self.sleep_secs = int(os.getenv("EASYHAPROXY_REFRESH_CONF", "10"))
except ValueError: except ValueError:
self.sleep_secs = 10 self.sleep_secs = 10
@ -197,18 +202,27 @@ class Certbot:
current_time = time.time() current_time = time.time()
for host in hosts: for host in hosts:
filename = "%s/%s.pem" % (self.certs, host) filename = "%s/%s.pem" % (self.certs, host)
host_arg = '-d %s' % (host) host_arg = '-d %s' % host
if not os.path.exists(filename): if not os.path.exists(filename):
Functions.log(Functions.CERTBOT_LOG, Functions.DEBUG, "Request new certificate for %s" % (host)) Functions.log(Functions.CERTBOT_LOG, Functions.DEBUG, "Request new certificate for %s" % host)
request_certs.append(host_arg) request_certs.append(host_arg)
else: else:
creation_time = os.path.getctime(filename) try:
if (current_time - creation_time) // (24 * 3600) > 90: with open(filename, 'r') as file:
Functions.log(Functions.CERTBOT_LOG, Functions.DEBUG, "Request expired certificate for %s" % (host)) certificate_str = file.read()
request_certs.append(host_arg) certificate = crypto.load_certificate(crypto.FILETYPE_PEM, certificate_str)
if (current_time - creation_time) // (24 * 3600) >= 45: expiration_after = datetime.strptime(certificate.get_notAfter().decode()[:-1],
Functions.log(Functions.CERTBOT_LOG, Functions.DEBUG, "Renew certificate for %s" % (host)) '%Y%m%d%H%M%S').timestamp()
renew_certs.append(host_arg)
if current_time >= expiration_after:
Functions.log(Functions.CERTBOT_LOG, Functions.DEBUG,
"Request expired certificate for %s" % host)
request_certs.append(host_arg)
if (expiration_after - current_time) // (24 * 3600) >= 15:
Functions.log(Functions.CERTBOT_LOG, Functions.DEBUG, "Renew certificate for %s" % host)
renew_certs.append(host_arg)
except Exception as e:
Functions.log(Functions.CERTBOT_LOG, Functions.ERROR, "Certificate %s error %s" % (host, e))
certbot_certonly = ('/usr/bin/certbot certonly {test_server}' certbot_certonly = ('/usr/bin/certbot certonly {test_server}'
' --standalone' ' --standalone'
@ -219,10 +233,10 @@ class Certbot:
' --no-eff-email' ' --no-eff-email'
' --non-interactive' ' --non-interactive'
' --max-log-backups=0' ' --max-log-backups=0'
' {certs} --email {email}'.format(certs = ' '.join(request_certs), ' {certs} --email {email}'.format(certs=' '.join(request_certs),
email = self.email, email=self.email,
test_server = self.test_server) test_server=self.test_server)
) )
ret_reload = False ret_reload = False
if len(request_certs) > 0: if len(request_certs) > 0:
@ -230,7 +244,7 @@ class Certbot:
ret_reload = True ret_reload = True
if len(renew_certs) > 0: if len(renew_certs) > 0:
Functions.run_bash(Functions.CERTBOT_LOG, "/usb/bin/certbot renew", return_result=False) Functions.run_bash(Functions.CERTBOT_LOG, "/usr/bin/certbot renew", return_result=False)
ret_reload = True ret_reload = True
if ret_reload: if ret_reload:
@ -238,12 +252,12 @@ class Certbot:
return ret_reload return ret_reload
except Exception as e: except Exception as e:
Functions.log(Functions.CERTBOT_LOG, Functions.ERROR, "%s" % (e)) Functions.log(Functions.CERTBOT_LOG, Functions.ERROR, "%s" % e)
return False return False
def merge_certificate(self, cert, key, filename): def merge_certificate(self, cert, key, filename):
Functions.save(filename, cert + key) Functions.save(filename, cert + key)
def find_live_certificates(self): def find_live_certificates(self):
letsencrypt_certs = "/etc/letsencrypt/live/" letsencrypt_certs = "/etc/letsencrypt/live/"
if not os.path.exists(letsencrypt_certs): if not os.path.exists(letsencrypt_certs):

View file

@ -4,4 +4,5 @@ jinja2
pytest pytest
docker docker
kubernetes kubernetes
deepdiff deepdiff
pyopenssl