#!/bin/sh
#
# Author: Jason Haar <jhaar@users.sourceforge.net>
# Date: 09-Nov-2004
# Version: 1.0
# Copyright: GPL
#
# This script simply checks the status of the certificates used by
# Qmail with Frederik Vermeulen's TLS patch - to ensure they are 
# valid, non-expired certs with the appropriate KeyUsage extensions
# required to get their jobs done.
# This script can be run on a nightly basis to check the cert status.
# Note that when it marked as cert as "bad" (typically because it's 
# expired), it will be renamed, a syslog event generated, and probably
# Qmail will STOP WORKING FOR NEW TLS SESSIONS. 
#
# That may sound bad, but the alternative is that Qmail will stop working
# for new TLS sessions *anyway* - it's just that this script will tell
# you why...

LOGGER="logger -i -t qmail-tls-check_certs"

for cert in servercert.pem clientcert.pem
do
	if [ -f "/etc/qmail/control/$cert" ]; then
		#First, check that it's a valid cert for the task
		TEMP_PURPOSE=`openssl x509 -in /etc/qmail/control/$cert -noout -purpose 2>/dev/null`
		if [ "$?" != "0" ]; then
			echo "/etc/qmail/control/$cert is a broken cert. Disabled"
			mv -f /etc/qmail/control/$cert /etc/qmail/control/BROKEN-${cert}
			$LOGGER "/etc/qmail/control/$cert is a broken cert. Disabled"
		fi

		#Now check it hasn't expired
		TEMP_DATE=`openssl x509 -in /etc/qmail/control/$cert -noout -dates 2>/dev/null|grep -i after|cut -d= -f2`
		EXPIRE_IN_SECS=`date +%s --date $TEMP_DATE 2>/dev/null`
		if [ "`echo $EXPIRE_IN_SECS|egrep '^[0-9]+$'`" != "" ]; then
			NOW_IN_SECS=`date +%s 2>/dev/null`
			if [ "`echo $NOW_IN_SECS|egrep '^[0-9]+$'`" != "" ]; then
				if [ $NOW_IN_SECS -gt $EXPIRE_IN_SECS ]; then
				 echo "/etc/qmail/control/$cert has EXPIRED. Disabling"
				 mv -f /etc/qmail/control/$cert /etc/qmail/control/EXPIRED-${cert}
				 $LOGGER "/etc/qmail/control/$cert has EXPIRED. Disabling"
				fi
			fi
		fi

		if [ "`echo $cert|grep server`" != "" ];then
			if [ "`echo $TEMP_PURPOSE|egrep -i '(any purpose|server).* yes'`" = "" ]; then
			 echo "/etc/qmail/control/$cert is NOT a server cert. Disabled"
			 mv -f /etc/qmail/control/$cert /etc/qmail/control/NOT-A-SERVER-CERT-${cert}
			 $LOGGER "/etc/qmail/control/$cert is NOT a server cert. Disabled"
			fi
		fi
		if [ "`echo $cert|grep client`" != "" ];then
			if [ "`echo $TEMP_PURPOSE|egrep -i '(any purpose|client).* yes'`" = "" ]; then
			 echo "/etc/qmail/control/$cert is NOT a client cert. Disabled"
			 mv -f /etc/qmail/control/$cert /etc/qmail/control/NOT-A-CLIENT-CERT-${cert}
			 $LOGGER "/etc/qmail/control/$cert is NOT a client cert. Disabled"
			fi		
		fi
	fi

done
