Automatic renewal has made expired certificates rarer, but they still happen. A renewal hook fails quietly after a package upgrade. DNS moves to a new server, so the ACME challenge stops working. A site that lives on some other machine gets forgotten until a customer phones to say their browser shows a full-page warning. Renewal tools only know about the certificates they manage. What you want is an independent check that looks at every site from the outside, the way a browser does, and complains in good time.
This article builds that check from parts that are already on almost every Linux system: OpenSSL‘s command-line tool, Bash, and a systemd timer. The result is a script of about 60 lines that reads a plain list of hostnames, reports how many days each certificate has left, flags anything under a threshold, logs to the journal every day, and sends email only when something needs attention.
The Two openssl Commands That Do the Work
The first command, openssl s_client, opens a TLS connection the way a browser would and prints what the server sent. The second, openssl x509, reads a certificate and tells you about it.
This command fetches the certificate for a site and prints its expiry date:
echo | openssl s_client -connect www.both.org:443 -servername www.both.org 2>/dev/null \
| openssl x509 -noout -enddate
The output is a single line:
notAfter=Jan 16 14:24:45 2027 GMT
The -checkend option is even more useful for scripts. It takes a number of seconds and sets the exit status: 0 if the certificate will still be valid at that point, 1 if it will have expired. This asks whether a certificate saved in cert.pem will survive the next 21 days:
openssl x509 -noout -checkend $((21 * 86400)) -in cert.pem && echo fine || echo renew soon
Because -checkend answers with an exit status, there is no date parsing to get wrong for the yes-or-no decision. I only use date to turn the expiry date into a friendly “days left” number for people to read.
Why -servername Matters
Most web servers host many sites on one IP address. During the TLS handshake, the client says which name it wants using Server Name Indication (SNI), and the server picks the matching certificate. If you leave SNI out, you get whatever the server’s default certificate is, which may belong to a completely different site.
To see this, I ran a small test server with two certificates, one for default.test and one for soon.test. Asking without SNI returns the default:
$ openssl s_client -connect 127.0.0.1:8443 -noservername </dev/null 2>/dev/null | openssl x509 -noout -subject
subject=CN=default.test
$ openssl s_client -connect 127.0.0.1:8443 -servername soon.test </dev/null 2>/dev/null | openssl x509 -noout -subject
subject=CN=soon.test
Older versions of OpenSSL did not send SNI unless you asked for it, so you will still find scripts on the internet that check the wrong certificate without anyone noticing. Always pass -servername. I also add -verify_hostname, which makes OpenSSL confirm that the certificate is actually valid for the name you asked for. A certificate that is valid for months but issued for the wrong name is just as broken, from the visitor’s point of view, as an expired one.
Checking the Full Chain
A server should send its own certificate plus the intermediate certificates that link it to a root that clients trust. Two things go wrong here: a missing intermediate (some clients cope, others fail) and an old intermediate left in the bundle after the CA has moved on.
The -showcerts option prints every certificate the server sent. This loop saves each one to its own file and prints its subject and expiry date:
openssl s_client -connect expired.badssl.com:443 -servername expired.badssl.com \
-showcerts </dev/null 2>/dev/null |
awk '/BEGIN CERT/{c=1; n++} c{print > ("chain-" n ".pem")} /END CERT/{c=0}'
for f in chain-*.pem; do openssl x509 -in "$f" -noout -subject -enddate; done
Against the deliberately broken test site expired.badssl.com, this shows not only the expired server certificate (April 2015) but also an intermediate in the bundle that expired in May 2020. That second problem is easy to miss if you only ever look at the first certificate.
For day-to-day monitoring, I let OpenSSL do the chain work. s_client verifies the chain against the system’s trusted roots and reports the result in a line such as Verify return code: 0 (ok). Anything other than 0 means a browser would probably complain too, so the script treats it as a problem.
The Script
The script reads a hosts file with one site per line. The port defaults to 443, and an optional third field lets you connect to one address while asking for a different name, which is handy for checking a new server before DNS points at it:
# hostname [port] [sni-name]
www.both.org
kernel.org
mail.example.com 993
203.0.113.10 443 www.example.com
Here is certwatch.sh, which I keep in /usr/local/bin:
#!/usr/bin/env bash
# certwatch.sh - report how many days are left on TLS certificates
# Usage: certwatch.sh [hosts-file] [warn-days]
# Each line of the hosts file: hostname [port] [sni-name]
HOSTS_FILE=${1:-/etc/certwatch/hosts}
WARN_DAYS=${2:-21}
TIMEOUT=10
ca=() # optional private CA: CA_FILE=/path/ca.pem
[[ -n "${CA_FILE:-}" ]] && ca=(-CAfile "$CA_FILE")
now=$(date +%s)
report=()
problems=0
while read -r host port sni; do
# Skip blank lines and comments
[[ -z "$host" || "$host" == \#* ]] && continue
port=${port:-443}
sni=${sni:-$host}
label="$host:$port"
[[ "$sni" != "$host" ]] && label+=" (SNI $sni)"
# One handshake per host (one retry for network hiccups);
# keep everything s_client prints
for try in 1 2; do
out=$(timeout "$TIMEOUT" openssl s_client -connect "$host:$port" \
-servername "$sni" -verify_hostname "$sni" "${ca[@]}" </dev/null 2>/dev/null)
cert=$(openssl x509 <<<"$out" 2>/dev/null)
[[ -n "$cert" ]] && break
sleep 2
done
if [[ -z "$cert" ]]; then
report+=("FAIL $label no certificate (connection or handshake failed)")
((problems++))
continue
fi
end=$(openssl x509 -noout -enddate <<<"$cert" | cut -d= -f2)
days=$(( ($(date -d "$end" +%s) - now) / 86400 ))
verify=$(grep -m1 'Verify return code' <<<"$out" | sed 's/.*: //')
if ! openssl x509 -noout -checkend 0 <<<"$cert" >/dev/null; then
status=EXPIRED
elif ! openssl x509 -noout -checkend $((WARN_DAYS * 86400)) <<<"$cert" >/dev/null; then
status=WARN
elif [[ "$verify" != 0* ]]; then
status=BADCHAIN
else
status=OK
fi
line=$(printf '%-8s %s %s days left (%s)' "$status" "$label" "$days" "$end")
[[ "$status" != OK ]] && { line+=" verify: $verify"; ((problems++)); }
report+=("$line")
done < "$HOSTS_FILE"
printf '%s\n' "${report[@]}"
if ((problems > 0)); then
if [[ -n "${MAILTO:-}" ]] && command -v mail >/dev/null; then
printf '%s\n' "${report[@]}" |
mail -s "certwatch: $problems certificate(s) need attention on $(hostname)" "$MAILTO"
fi
exit 1
fi
A few design choices are worth explaining:
- One handshake per host. The output of
s_clientis kept in a variable, so the certificate and the verification result come from the same connection. timeoutand one retry. A host that does not answer would otherwise hang the whole run. The single retry stops one dropped packet from turning into an alarm.- Order of checks. Expiry is reported before chain problems, because “expired” is the most urgent and clearest message.
CA_FILE. Internal services often use a private certificate authority. PointCA_FILEat its certificate and verification works for those too.- Exit status. The script exits with 1 when anything needs attention, which systemd records as a failed run.
The days left figure is rounded down, so a certificate with four and a half days left shows 4. The date -d call relies on GNU date, which is standard on Linux distributions.
A Test Run
I ran the script against a mix of real sites and the deliberately broken hosts at badssl.com, plus an address where nothing is listening (the hosts file asks for the name nothing.example there):
$ ./certwatch.sh hosts 21
OK www.both.org:443 79 days left (Jan 16 14:24:45 2027 GMT)
OK fedoraproject.org:443 168 days left (Apr 15 23:59:59 2027 GMT)
OK kernel.org:443 75 days left (Jan 12 10:52:44 2027 GMT)
EXPIRED expired.badssl.com:443 -4217 days left (Apr 12 23:59:59 2015 GMT) verify: 10 (certificate has expired)
BADCHAIN wrong.host.badssl.com:443 60 days left (Dec 28 20:02:55 2026 GMT) verify: 62 (hostname mismatch)
BADCHAIN self-signed.badssl.com:443 728 days left (Oct 26 21:00:20 2028 GMT) verify: 18 (self-signed certificate)
FAIL 10.255.255.1:443 (SNI nothing.example) no certificate (connection or handshake failed)
To test the warning threshold and the SNI handling, I used openssl s_server with a small private CA, one certificate valid for 300 days, and one valid for only five days. With CA_FILE set, the results were:
OK 127.0.0.1:8443 (SNI default.test) 299 days left (Aug 25 05:05:10 2027 GMT)
WARN 127.0.0.1:8443 (SNI soon.test) 4 days left (Nov 3 05:05:10 2026 GMT) verify: 0 (ok)
BADCHAIN 127.0.0.1:8443 (SNI other.test) 299 days left (Aug 25 05:05:10 2027 GMT) verify: 62 (hostname mismatch)
The last line is the wrong-SNI case: the server had no certificate for other.test, so it fell back to its default certificate, and -verify_hostname caught the mismatch.
Running It Daily with systemd
A systemd timer needs two unit files: a service that says what to run, and a timer that says when. This is /etc/systemd/system/certwatch.service:
[Unit]
Description=Check TLS certificate expiry for the hosts in /etc/certwatch/hosts
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
Environment=MAILTO=root
ExecStart=/usr/local/bin/certwatch.sh /etc/certwatch/hosts 21
And this is /etc/systemd/system/certwatch.timer:
[Unit]
Description=Run certwatch once a day
[Timer]
OnCalendar=daily
RandomizedDelaySec=1h
Persistent=true
[Install]
WantedBy=timers.target
Persistent=true means that if the machine was off at midnight, the check runs soon after it boots instead of being skipped. RandomizedDelaySec spreads the start time, which is polite if many machines run the same check. Before enabling anything, it is worth asking systemd to check the files for typos:
sudo systemd-analyze verify /etc/systemd/system/certwatch.service /etc/systemd/system/certwatch.timer
Then install the hosts file and start the timer:
sudo mkdir -p /etc/certwatch
sudo cp hosts /etc/certwatch/hosts
sudo systemctl daemon-reload
sudo systemctl enable --now certwatch.timer
systemctl list-timers certwatch.timer
You do not have to wait until midnight to try it. Start the service by hand and read what it wrote:
sudo systemctl start certwatch.service
journalctl -u certwatch.service --since today
Everything the script prints goes to the journal, so you have a daily history of every certificate’s remaining days. Email goes out only when at least one line is not OK, which keeps the signal clean: if certwatch writes to you, something really needs doing. The mail command needs a working local mail setup, such as the s-nail package (which provides mail on Fedora) or mailx on other distributions, plus a mail transfer agent or relay. If you would rather not run one, the failed unit still shows up in systemctl --failed, and you could hook an OnFailure= unit to any notification tool you already use.
Wrapping Up
The whole system is one short script, one text file, and two small unit files. There is nothing to install beyond what your distribution already ships, and anyone on the team can read it and change it. Add a line to the hosts file whenever you add a site, and the next time a renewal quietly breaks, you will hear about it three weeks early instead of from a customer.
I ran the commands, the script and the test server shown here on Fedora 44 with OpenSSL 3.5.9, Bash 5.3.9, GNU coreutils 9.10 and systemd 259, using the default system-wide crypto policy, and both unit files pass systemd-analyze verify. On Fedora the mail command comes from the s-nail package, which is not installed by default. The script uses only standard OpenSSL, GNU coreutils and systemd features, and it gave the same results in an earlier run on Debian 13, so it should behave the same on other current distributions.
Karthikeyan works at ShoHost, a small web hosting company in Erode, India (https://shohost.com).