Skip to content
Snippets Groups Projects
Verified Commit 60b041c5 authored by Nicolas KAROLAK's avatar Nicolas KAROLAK
Browse files

test ssl mandatory only for mediaserver

parent 1fad0c77
No related branches found
No related tags found
No related merge requests found
#!/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
from pathlib import Path
import requests
import sys
import ssl
import subprocess
import sys
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')
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', 'mirismanager'),
)
all_ok = True
failure = False
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
# check if custom port is used
v_split = v.split(":")
if len(v_split) > 1:
server_name = v_split[0]
port = int(v_split[1])
else:
server_name = v
port = 443
conn = ssl.create_connection((server_name, port))
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
sock = context.wrap_socket(conn, server_hostname=server_name)
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('\nTLS cert for {} expires at {}'.format(server_name, 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.')
try:
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)
sys.exit(0)
import OpenSSL
sys.path.append(str(Path(__file__).parents[1].resolve()))
# pylint: disable=wrong-import-position
from envsetup import utils as u # noqa: E402
def main():
print("Check TLS settings:")
if subprocess.call(["which", "nginx"], stdout=subprocess.DEVNULL) != 0:
u.info("nginx not found, skipping test")
exit(2)
conf = u.load_conf()
conf_servers = (
("MS_SERVER_NAME", "mediaserver"),
("CM_SERVER_NAME", "mirismanager"),
("MONITOR_SERVER_NAME", "monitor"),
)
all_ok = True
failure = False
with open("/etc/hosts", "r") as fo:
hosts = fo.read()
for setting, default in conf_servers:
name = conf.get(setting)
if name == default:
# vhost is using default value, the service is surely not installed
continue
if name not in hosts:
# the domain is not in the hosts file, the service is surely not installed
continue
# check if custom port is used
v_split = name.split(":")
if len(v_split) > 1:
server_name = v_split[0]
port = int(v_split[1])
else:
server_name = name
port = 443
conn = ssl.create_connection((server_name, port))
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
sock = context.wrap_socket(conn, server_hostname=server_name)
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")
remaining = expires - datetime.datetime.utcnow()
if remaining < datetime.timedelta(days=0):
u.error("{}: expired since {}".format(server_name, str(remaining)))
# if mediaserver (the only cert that is mandatory)
if setting == conf_servers[0]:
failure = True
elif remaining < datetime.timedelta(days=14):
u.warning("{}: expire in {}".format(server_name, str(remaining)))
# if mediaserver (the only cert that is mandatory)
if setting == conf_servers[0]:
all_ok = False
else:
u.success("{}: expire in {}".format(server_name, str(remaining)))
try:
url = "https://{}".format(name)
requests.get(url)
u.success("{}: trusted certificate".format(name))
except requests.exceptions.SSLError:
u.warning("{}: untrusted certificate".format(name))
# if mediaserver (the only cert that is mandatory)
if setting == conf_servers[0]:
all_ok = False
if failure:
exit(1)
if not all_ok:
exit(3)
if __name__ == "__main__":
main()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment