Skip to content
Snippets Groups Projects
test_ssl.py 2.45 KiB
Newer Older
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2017, Florent Thiery
'''
Criticality: Normal
Checks that TLS certificates are valid; if invalid, the user will have to add an exception in his browser
import datetime
import imp
import os
import requests
import sys
import ssl
try:
    import OpenSSL
except ImportError:
    import subprocess
    subprocess.call(['apt-get', '-qq', '-y', 'install', 'python3-openssl'])
    import OpenSSL

YELLOW = '\033[93m'
GREEN = '\033[92m'
RED = '\033[91m'
DEF = '\033[0m'

if not os.path.isdir('/etc/nginx'):
    print('Nginx not found, skipping test')
os.chdir(os.path.dirname(__file__))
if not os.path.isfile('../utils.py'):
    print('conf.sh not found')
    sys.exit(1)

es_utils = imp.load_source('es_utils', '../utils.py')
conf = es_utils.load_conf()

conf_servers = (
Stéphane Diemer's avatar
Stéphane Diemer committed
    ('MS_SERVER_NAME', 'mediaserver'),
    ('MONITOR_SERVER_NAME', 'monitor'),
    ('CM_SERVER_NAME', 'campusmanager'),
with open('/etc/hosts', 'r') as fo:
    hosts = fo.read()

Stéphane Diemer's avatar
Stéphane Diemer committed
for s, d in conf_servers:
    v = conf.get(s)
Stéphane Diemer's avatar
Stéphane Diemer committed
    if v == d:
        # vhost is using default value, the service is surely not installed
        continue
    if v not in hosts:
        # the domain is not in the hosts file, the service is surely not installed
Stéphane Diemer's avatar
Stéphane Diemer committed
        continue
    conn = ssl.create_connection((v, 443))
    context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    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')
Nicolas KAROLAK's avatar
Nicolas KAROLAK committed
    print('\nTLS cert for {} expires at {}'.format(v, expires.isoformat()))
    remaining = expires - datetime.datetime.utcnow()
    if remaining < datetime.timedelta(days=0):
        print('Error, already expired…')
        failure = True
    elif remaining < datetime.timedelta(days=14):
        print('Warning, will expire soon!')
        all_ok = False
    else:
        print('Good, enough time before expiration.')
Stéphane Diemer's avatar
Stéphane Diemer committed
        url = 'https://%s' % v
        print('Checking TLS certificate of %s' % url)
        requests.get(url)
    except requests.exceptions.SSLError:
        print('%sTLS certificate for %s is not valid%s' % (YELLOW, url, DEF))
        all_ok = False

if failure:
    sys.exit(1)
if not all_ok:
    sys.exit(3)