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 #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2017, Florent Thiery """
'''
Criticality: Normal Criticality: Normal
Checks that TLS 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 datetime
import imp from pathlib import Path
import os
import requests import requests
import sys
import ssl import ssl
import subprocess
import sys
try: import OpenSSL
import OpenSSL
except ImportError: sys.path.append(str(Path(__file__).parents[1].resolve()))
import subprocess
subprocess.call(['apt-get', '-qq', '-y', 'install', 'python3-openssl']) # pylint: disable=wrong-import-position
import OpenSSL from envsetup import utils as u # noqa: E402
YELLOW = '\033[93m'
GREEN = '\033[92m' def main():
RED = '\033[91m' print("Check TLS settings:")
DEF = '\033[0m'
if subprocess.call(["which", "nginx"], stdout=subprocess.DEVNULL) != 0:
if not os.path.isdir('/etc/nginx'): u.info("nginx not found, skipping test")
print('Nginx not found, skipping test') exit(2)
sys.exit(2)
conf = u.load_conf()
os.chdir(os.path.dirname(__file__))
if not os.path.isfile('../utils.py'): conf_servers = (
print('conf.sh not found') ("MS_SERVER_NAME", "mediaserver"),
sys.exit(1) ("CM_SERVER_NAME", "mirismanager"),
("MONITOR_SERVER_NAME", "monitor"),
es_utils = imp.load_source('es_utils', '../utils.py') )
conf = es_utils.load_conf()
all_ok = True
conf_servers = ( failure = False
('MS_SERVER_NAME', 'mediaserver'),
('MONITOR_SERVER_NAME', 'monitor'), with open("/etc/hosts", "r") as fo:
('CM_SERVER_NAME', 'mirismanager'), hosts = fo.read()
)
for setting, default in conf_servers:
all_ok = True name = conf.get(setting)
failure = False if name == default:
# vhost is using default value, the service is surely not installed
with open('/etc/hosts', 'r') as fo: continue
hosts = fo.read() if name not in hosts:
# the domain is not in the hosts file, the service is surely not installed
for s, d in conf_servers: continue
v = conf.get(s)
if v == d: # check if custom port is used
# vhost is using default value, the service is surely not installed v_split = name.split(":")
continue if len(v_split) > 1:
if v not in hosts: server_name = v_split[0]
# the domain is not in the hosts file, the service is surely not installed port = int(v_split[1])
continue else:
server_name = name
# check if custom port is used port = 443
v_split = v.split(":")
if len(v_split) > 1: conn = ssl.create_connection((server_name, port))
server_name = v_split[0] context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
port = int(v_split[1]) sock = context.wrap_socket(conn, server_hostname=server_name)
else: cert = ssl.DER_cert_to_PEM_cert(sock.getpeercert(True))
server_name = v x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
port = 443 not_after = x509.get_notAfter().decode("ascii")
conn = ssl.create_connection((server_name, port)) expires = datetime.datetime.strptime(not_after, "%Y%m%d%H%M%SZ")
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) remaining = expires - datetime.datetime.utcnow()
sock = context.wrap_socket(conn, server_hostname=server_name)
cert = ssl.DER_cert_to_PEM_cert(sock.getpeercert(True)) if remaining < datetime.timedelta(days=0):
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) u.error("{}: expired since {}".format(server_name, str(remaining)))
not_after = x509.get_notAfter().decode('ascii') # if mediaserver (the only cert that is mandatory)
if setting == conf_servers[0]:
expires = datetime.datetime.strptime(not_after, '%Y%m%d%H%M%SZ') failure = True
print('\nTLS cert for {} expires at {}'.format(server_name, expires.isoformat())) elif remaining < datetime.timedelta(days=14):
u.warning("{}: expire in {}".format(server_name, str(remaining)))
remaining = expires - datetime.datetime.utcnow() # if mediaserver (the only cert that is mandatory)
if setting == conf_servers[0]:
if remaining < datetime.timedelta(days=0): all_ok = False
print('Error, already expired…') else:
failure = True u.success("{}: expire in {}".format(server_name, str(remaining)))
elif remaining < datetime.timedelta(days=14):
print('Warning, will expire soon!') try:
all_ok = False url = "https://{}".format(name)
else: requests.get(url)
print('Good, enough time before expiration.') u.success("{}: trusted certificate".format(name))
except requests.exceptions.SSLError:
try: u.warning("{}: untrusted certificate".format(name))
url = 'https://%s' % v # if mediaserver (the only cert that is mandatory)
print('Checking TLS certificate of %s' % url) if setting == conf_servers[0]:
requests.get(url) all_ok = False
except requests.exceptions.SSLError:
print('%sTLS certificate for %s is not valid%s' % (YELLOW, url, DEF)) if failure:
all_ok = False exit(1)
if not all_ok:
if failure: exit(3)
sys.exit(1)
if not all_ok:
sys.exit(3) if __name__ == "__main__":
main()
sys.exit(0)
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