Spacebear Blog

Monitor and alert when TLS certificates expire

Published: September 10, 2020

If you can’t use a tool like Caddy that manages SSL/TLS certificate renewal, there are a few ways you can monitor your certificates to be alerted when they are close to expiring.

If you are using a Letsencrypt certificate then you should have this renew on a schedule using a cronjob so you can “set it and forget it”, although you may want to use some of the monitoring from below in case the renewal fails for whatever reason (perhaps a renewal ratelimit was reached).

The first way you could monitor certificate expiry is to add a script to your crontab that will check expiry each night, and alert you if the certificate expires within a certain pre-defined period. The pre-defined period would likely be however long it takes you to renew a certificate plus a few days buffer.

An example in your crontab might look like where at 05:00 your checks would be run and the script takes an argument that is the domain the script needs to check, and if the scripts fail, then an email to the address defined in the MAILTO environment variable will be sent.

MAILTO="alert@example.com"
00 5 * * * spacebear sh /opt/cron_alert.sh spacebear.ee
00 5 * * * spacebear sh /opt/cron_alert.sh example.ee

The script that cron runs could look like

#!/bin/bash

# Domain defined from argument
DOMAIN=$1
# 15 days in seconds
EXPIREAMOUNT=1296000 
openssl x509 -checkend ${EXPIREAMOUNT} -noout -in <(openssl s_client -showcerts -connect ${DOMAIN}:443 </dev/null 2>/dev/null | openssl x509 -outform PEM)
if [ $? -ne 0 ]; then
  # email content will contain below warning. If you update the time above, you will want to update warning text
  echo "${DOMAIN} will expire within 15 days"
  exit 1
fi

Another way would be to use a Sensu plugin, as you may already be using Sensu to monitor other assets. Assuming you are using Sensu Go, to add the plugin you need run sensuctl asset add sensu-plugins/sensu-plugins-http. Then use the following YAML to create a check that reviews the HTTPS endpoint every hour, and will warn 15 days before expiry and 4 days before expiry the alert level will change to critical.

---
type: CheckConfig
api_version: core/v2
metadata:
  name: spacebear_ee_https_check
  namespace: default
spec:
  command: check-https-cert.rb -u https://spacebear.ee -w 15 -c 4
  handlers: []
  interval: 3600
  publish: true
  subscriptions:
  - system

To add the YAML to sensu use the followinng command sensuctl create --file spacebear-ee-https-check.yaml

If you use Promethues you can follow this Prometheus Guide.