diff --git a/utils/check_cert.py b/utils/check_cert.py index d67182b7..c748a864 100755 --- a/utils/check_cert.py +++ b/utils/check_cert.py @@ -2,7 +2,8 @@ # -*- coding: utf-8 -*- # # check_cert.py -- Petit mail de vérification du certificat d'un serveur -# ce script vérifie principalement la date +# ce script vérifie principalement la date d'expiration et envoie un mail +# d'avertissement si celle-ci est proche (paramétrable) # # Copyright (c) 2013 Daniel STAN # Authors: Daniel STAN @@ -20,7 +21,9 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . + from M2Crypto import SSL +from M2Crypto import X509 import datetime import sys @@ -31,8 +34,9 @@ import smtplib # # Config ! # -host = 'webmail.crans.org' +host = 'localhost' port = 443 +filename = False # if True, port ignored and host is in fact a path # afficher la sortie plutôt que l'envoyer: verb = False # delai d'avertissement @@ -42,46 +46,60 @@ delay = datetime.timedelta(days=15) mail_src = 'root@crans.org' mail_dest = "roots@crans.org" mail_host = 'localhost' + +# +# Argument parsing ! +# +# TODO argparse + doc for arg in sys.argv[1:]: if arg == '-v': verb = True continue + if arg == '--filename': + filename = True try: port = int(arg) except ValueError: host = arg -# TODO: permettre la vérification directement sur un fichier -# get cert: -conn = SSL.Connection(SSL.Context()) -try: - conn.connect((host, port)) -except SSL.Checker.WrongHost: - if host != 'localhost': - raise +# +# Getting cert ! +# +if filename: + cert = X509.load_cert(host) +else: + conn = SSL.Connection(SSL.Context()) + try: + conn.connect((host, port)) + except SSL.Checker.WrongHost: + if host != 'localhost': + raise -cert = conn.get_peer_cert() -conn.close() + cert = conn.get_peer_cert() + conn.close() +# +# Real computation (woah !) +# expire_date = cert.get_not_after().get_datetime() now = datetime.datetime.now(expire_date.tzinfo) -if now + delay > expire_date: +if now + delay > expire_date or verb: subject = cert.get_subject().as_text() short_sub = subject try: subject += "(alt: %s)" % cert.get_ext('subjectAltName').get_value() except LookupError: pass - conn = smtplib.SMTP(mail_host) msg = MIMEText(u"""Attention, le certificat suivant arrive bientôt à expiration :\n%s\n Temps avant expiration: %s""" % (subject,(expire_date - now)), _charset="utf-8") msg['From'] = mail_src msg['To'] = mail_dest msg['Subject'] = u"Expiration imminente du certificat %s" % short_sub if not verb: + conn = smtplib.SMTP(mail_host) conn.sendmail(mail_src, mail_dest, msg.as_string()) + conn.quit() else: - print msg.as_string() - conn.quit() + print msg.get_payload(decode=True)