TL;DR
Automatically monitor your website’s SSL/TLS certificate to ensure it hasn’t unexpectedly changed. This guide shows you how to use a simple script and cron job to check the certificate authority (CA) regularly and alert you if there’s an issue.
Solution Guide
- Create a Script to Check the Certificate
- We’ll use
openssl, which is usually pre-installed on Linux systems. If not, install it with your package manager (e.g.,sudo apt install opensslon Debian/Ubuntu). - Create a file named
check_certificate.shand add the following script:#!/bin/bash DOMAIN="yourdomain.com" CERT_FILE="/path/to/your/certificate.pem" # Replace with your certificate path CURRENT_CA=$(openssl x509 -in "$CERT_FILE" -noout -issuer) PREVIOUS_CA=$(cat /path/to/previous_ca.txt) # File to store the last known CA if [ "$CURRENT_CA" != "$PREVIOUS_CA" ]; then echo "Certificate authority has changed for $DOMAIN!" echo "Old CA: $PREVIOUS_CA" | mail -s "Website Certificate Change Alert - $DOMAIN" your.email@example.com echo "New CA: $CURRENT_CA" | mail -s "Website Certificate Change Alert - $DOMAIN" your.email@example.com echo "$CURRENT_CA" > /path/to/previous_ca.txt # Update the stored CA fi exit 0 - Important: Replace
yourdomain.comwith your actual domain name,/path/to/your/certificate.pemwith the full path to your certificate file (usually in /etc/ssl/certs/), andyour.email@example.comwith your email address for alerts. - Create an empty file called
previous_ca.txtat/path/to/previous_ca.txt. This will store the CA from the last check. You can create it usingtouch /path/to/previous_ca.txt.
- Make the script executable:
chmod +x check_certificate.sh
- Run the script manually to ensure it works correctly:
./check_certificate.sh. It won’t send an email on the first run because
previous_ca.txtis empty. - To test the alert, temporarily change your certificate (e.g., by renewing it) and then run the script again. You should receive an email notification. Remember to restore your original certificate after testing!
- Edit your crontab using:
crontab -e. If prompted, choose an editor (nano is usually easiest).
- Add a line to run the script regularly. For example, to run it every day at 3 AM:
0 3 * * * /path/to/check_certificate.sh - Save and close the crontab file. The cron job will now run automatically according to your schedule.
- Email not received: Check your spam folder. Ensure that
mailis configured correctly on your server (often requires setting up an SMTP relay). Verify the email address in the script is correct. - Script errors: Check your system logs for any error messages related to the script or
openssl. Make sure the paths to the certificate andprevious_ca.txtare accurate. - Permissions: Ensure the script has execute permissions (
chmod +x check_certificate.sh).