diff --git a/acme_nginx/Acme.py b/acme_nginx/Acme.py index b2ae6d1..5ce38be 100644 --- a/acme_nginx/Acme.py +++ b/acme_nginx/Acme.py @@ -10,6 +10,7 @@ import sys import tempfile import time +from datetime import datetime, timedelta try: from urllib.request import urlopen, Request # Python 3 @@ -32,6 +33,7 @@ def __init__( cert_path='/etc/ssl/private/letsencrypt-domain.pem', dns_provider=None, skip_nginx_reload=False, + renew_days=None, debug=False): """ Params: @@ -60,6 +62,30 @@ def __init__( self.chain = "https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem" self.dns_provider = dns_provider self.skip_nginx_reload = skip_nginx_reload + self.renew_days = renew_days + + self.IsOutOfDate = True + if self.renew_days: + try: + cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, open(self.cert_path).read()) + date_format, encoding = "%Y%m%d%H%M%SZ", "ascii" + not_before = datetime.strptime(cert.get_notBefore().decode(encoding), date_format) + not_after = datetime.strptime(cert.get_notAfter().decode(encoding), date_format) + now = datetime.now() + #self.log.info( 'x509: {0} {1} {2}'.format(cert, not_before, not_after) ) + #certTime = datetime.fromtimestamp(os.path.getmtime(self.cert_path)) + #certTimeThreshold = certTime + timedelta(days=self.renew_days) + certTimeThreshold = not_after - timedelta(days=self.renew_days) + + self.IsOutOfDate = (not_before > now) or (not_after < now) or (certTimeThreshold < now) + self.log.info('Cert file {1} (expiration time {0})'.format( certTimeThreshold, "is out of date" if self.IsOutOfDate else "is not out of date")) + + except OSError as e: + if e.errno == 2: + self.log.info('Cert file {0} not found -> DO UPDATE CERT'.format(self.cert_path)) + except: + pass + def _reload_nginx(self): """ Reload nginx """ diff --git a/acme_nginx/client.py b/acme_nginx/client.py index 7750795..188998f 100644 --- a/acme_nginx/client.py +++ b/acme_nginx/client.py @@ -74,6 +74,11 @@ def set_arguments(): dest='skip_reload', action='store_true', help="don't reload nginx after certificate signing") + parser.add_argument( + '--renew-days', + dest='renew_days', + type=int, + help="expiration threshold in days") return parser.parse_args() @@ -107,6 +112,8 @@ def main(): cert_path=args.cert_path, debug=args.debug, dns_provider=args.dns_provider, - skip_nginx_reload=args.skip_reload + skip_nginx_reload=args.skip_reload, + renew_days=args.renew_days ) - acme.get_certificate() + if acme.IsOutOfDate: + acme.get_certificate()