#!/bin/sh
# check_cert v1.0.1  (c) 19.3.2020 by Andreas Ley  (u) 24.5.2024
# Check the certificates on all running servers

DAYS=20
MAILFROM="apache@scc.kit.edu"
MAILTO="apache@scc.kit.edu"

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
export PATH

usage()
{
	echo "Usage: `basename $0` [-v] filename" >&2
	echo "-v  verbose mode" >&2
	exit 1
}

set -- `getopt hxv $*` || usage

trace=false
verbose=false
dn='>/dev/null'
while :; do
	case $1 in
		-h)	sed '1d;s/^# *//;/^$/q' $0; usage;;
		-x)	set -x; trace=true; shift;;
		-v)	verbose=true; dn=; shift;;
		--)	shift; break;;
	esac
done

# FIXME: This would only work in multi-vhost environments
test $# -eq 0 && set $(apache2cfg -l)

boundary="you're_geek_when_you're_reading_boundaries"

hostname="$(hostname --fqdn)"

for fqdn; do
	dir="$(mktemp -d)"
	openssl s_client -showcerts -connect "${fqdn}:443" </dev/null 2>/dev/null | csplit -f "${dir}/" -s - '/-----BEGIN CERTIFICATE-----/' '{*}'
	rm -f "${dir}/00"
	ls -1 "${dir}" | while read crt; do
		${verbose} && echo "${fqdn} ${crt}" >&2
		${verbose} && openssl x509 -noout -subject -issuer -dates -in "${dir}/${crt}" >&2
		eval openssl x509 -checkend "$((${DAYS}*86400))" -in "${dir}/${crt}" ${dn} >&2 || echo "${crt}"
	done >"${dir}/.crt"
	if test -s "${dir}/.crt"; then
		(echo "From: ${MAILFROM}"
		echo "To: ${MAILTO}"
		echo "Subject: Expiring certificates for ${fqdn} on $hostname"
		echo "MIME-Version: 1.0"
		echo "Content-Type: multipart/mixed; boundary=${boundary}"
		#echo "Content-Transfer-Encoding: 7bit"
		echo
		echo "--${boundary}"
		echo "Content-Type: text/plain"
		echo
		echo "The process serving ${fqdn}:443 on $hostname delivers certificates expiring in less than $DAYS days"
		echo
		while read crt; do
			openssl x509 -noout -subject -issuer -dates -in "${dir}/${crt}"
			echo
		done <"${dir}/.crt"
		while read crt; do
			echo "--${boundary}"
			echo "Content-Type: text/plain"
			echo "Content-Disposition: attachment"
			subject="$(openssl x509 -noout -subject -in "${dir}/${crt}")"
			echo "Content-Description: ${subject#subject= }"
			echo
			sed -n '1,/-----END CERTIFICATE-----/p' "${dir}/${crt}"
			echo
		done <"${dir}/.crt"
		echo "--${boundary}--") | /usr/lib/sendmail -f "${MAILFROM}" -t -i
	fi
	rm -rf "${dir}"
done

exit 0
