Lately I got a message from lets-encrypt stating they are ending the notification mails they send out to remind you of certificates expiring. As I do have lets-encrypt certificates which are not auto renewed because of the challenge mechanism I liked those messages.
But nothing that a small bash script can’t fix.
I wrote the small bash script below to send me a reminder e-mail when one of the lets-encrypt certificates expires. It works locally, scans the certificates in the “live” folder. But it should be quite easy to modify the script so it checks remote certificates with openssl.
#!/bin/bash
#
# Check certification expiry
#
CERT_DIR=/etc/letsencrypt/live
CERT_NAME=cert.pem
MAIL_NAME=root
MAIL_SUBJECT='Certificate %cert% is expiring at %certdate%'
NOW=$(date +%s)
DAYS_TO_WARN=30
WARN_DATE=$(( ${NOW} + ( ${DAYS_TO_WARN} * (3600*24) ) ))
send_mail() {
REPLACEMENT=$(echo ${1}|sed -e 's/\//\\\//g')
SUBJECT=$(echo ${MAIL_SUBJECT} | sed -e "s/%cert%/${REPLACEMENT}/" | sed -e "s/%certdate%/$2/")
mail -s "${SUBJECT}" ${MAIL_NAME} <<HERE
Hi!
This is your friendly certificate expiry check script. I've found a certificate that is going
to expire in less than ${DAYS_TO_WARN} days.
Certificate file: $1
Certificate end date: $2
Current date: $(date --date=@${NOW})
Warning date: $(date --date=@${WARN_DATE})
Please take appropriate action
HERE
}
for cert in $(find ${CERT_DIR} -name ${CERT_NAME}); do
CERT_TO_DATE=$(openssl x509 -noout -enddate < ${cert}|sed -e 's/^notAfter=//')
CERT_TO_DATE_FM=$(date --date="${CERT_TO_DATE}" +%s)
if [ ${WARN_DATE} -gt ${CERT_TO_DATE_FM} ]; then
send_mail "${cert}" "${CERT_TO_DATE}"
fi
done
The script scans through the CERT_DIR folder looking for files named CERT_NAME. It get’s the “Not valid after” date from it via openssl. This date is then converted to a timestamp in seconds and compared to a timestamp of the current date + a number of days to warn in advance. When the warning date is after the certificate “Not valid after date”, the scripts sends out an e-mail.