diff --git a/tests/test_ssl.py b/tests/test_ssl.py index e2ef6caaacfa47f5aaddbcf5d7464d8723ec7272..4da15ddb882d68f858f87fb6d30c68abb80f0b6b 100755 --- a/tests/test_ssl.py +++ b/tests/test_ssl.py @@ -3,12 +3,15 @@ # Copyright 2017, Florent Thiery ''' Criticality: Normal -Checks that SSL certificates are valid; if invalid, the user will have to add an exception in his browser +Checks that TLS certificates are valid; if invalid, the user will have to add an exception in his browser ''' +import datetime +import imp +import OpenSSL import os -import sys import requests -import imp +import sys +import ssl YELLOW = '\033[93m' GREEN = '\033[92m' @@ -27,8 +30,6 @@ if not os.path.isfile('../utils.py'): es_utils = imp.load_source('es_utils', '../utils.py') conf = es_utils.load_conf() -all_ok = True - conf_servers = ( ('MS_SERVER_NAME', 'mediaserver'), ('MONITOR_SERVER_NAME', 'monitor'), @@ -47,13 +48,33 @@ for s, d in conf_servers: # the domain is not in the hosts file, the service is surely not installed continue try: + # further tests + conn = ssl.create_connection((v, 443)) + context = ssl.SSLContext() + sock = context.wrap_socket(conn, server_hostname=v) + cert = ssl.DER_cert_to_PEM_cert(sock.getpeercert(True)) + x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) + not_after = x509.get_notAfter().decode('ascii') + + expires = datetime.datetime.strptime(not_after, '%Y%m%d%H%M%SZ') + print('TLS cert for {} expires at {}'.format(v, expires.isoformat())) + + remaining = expires - datetime.datetime.utcnow() + + if remaining < datetime.timedelta(days=0): + print('Error, already expired…') + sys.exit(1) + elif remaining < datetime.timedelta(days=14): + print('Warning, will expire soon!') + sys.exit(3) + else: + print('Good, enough time before expiration.') + url = 'https://%s' % v - print('Checking SSL certificate of %s' % url) + print('Checking TLS certificate of %s' % url) requests.get(url) except requests.exceptions.SSLError: - print('%sSSL certificate for %s is not valid%s' % (YELLOW, url, DEF)) - all_ok = False -if not all_ok: - sys.exit(3) -else: - sys.exit(0) + print('%sTLS certificate for %s is not valid%s' % (YELLOW, url, DEF)) + sys.exit(3) + +sys.exit(0)