Something went wrong on our end
-
Nicolas KAROLAK authoredNicolas KAROLAK authored
test_ssl.py 2.29 KiB
#!/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 OpenSSL
import os
import requests
import sys
import ssl
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')
sys.exit(2)
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 = (
('MS_SERVER_NAME', 'mediaserver'),
('MONITOR_SERVER_NAME', 'monitor'),
('CM_SERVER_NAME', 'campusmanager'),
)
with open('/etc/hosts', 'r') as fo:
hosts = fo.read()
for s, d in conf_servers:
v = conf.get(s)
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
continue
try:
# further tests
conn = ssl.create_connection((v, 443))
context = ssl.SSLContext(ssl.PROTOCOL_TLS)
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 TLS certificate of %s' % url)
requests.get(url)
except requests.exceptions.SSLError:
print('%sTLS certificate for %s is not valid%s' % (YELLOW, url, DEF))
sys.exit(3)
sys.exit(0)