scripts/utils/check_cert.py
Daniel STAN e2611a770a vérification de la peremption d'un certif SSL
En se connectant sur le serveur. Envoie un mail en cas d'expiration
proche. À croner.
2013-02-13 23:35:49 +01:00

87 lines
2.4 KiB
Python
Executable file

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# check_cert.py -- Petit mail de vérification du certificat d'un serveur
# ce script vérifie principalement la date
#
# Copyright (c) 2013 Daniel STAN
# Authors: Daniel STAN <daniel.stan@crans.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from M2Crypto import SSL
import datetime
import sys
# Envoyer des mails
from email.mime.text import MIMEText
import smtplib
#
# Config !
#
host = 'webmail.crans.org'
port = 443
# afficher la sortie plutôt que l'envoyer:
verb = False
# delai d'avertissement
delay = datetime.timedelta(days=15)
# infos mails
mail_src = 'root@crans.org'
mail_dest = "roots@crans.org"
mail_host = 'localhost'
for arg in sys.argv[1:]:
if arg == '-v':
verb = True
continue
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
cert = conn.get_peer_cert()
conn.close()
expire_date = cert.get_not_after().get_datetime()
now = datetime.datetime.now(expire_date.tzinfo)
if now + delay > expire_date:
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.sendmail(mail_src, mail_dest, msg.as_string())
else:
print msg.as_string()
conn.quit()