TLS Certificate Expiration Monitoring: OpenSSL CLI & Systemd Timer Automated Checks
Build a dead-simple server watchdog using bash, openssl s_client, and systemd timers to alert before SSL certificates expire.
Key Takeaways & Prerequisites
- Expired TLS certificates cause catastrophic application downtime and shatter customer trust; manual calendar tracking is inherently error-prone.
- Use openssl s_client -connect host:443 -servername host to inspect live remote certificate expiration without browser caching.
- Deploy automated systemd timers to inspect local certificates daily and trigger alerts at 30, 14, and 7 days prior to expiry.
- Export certificate expiration timestamps as Prometheus metrics (tls_cert_expiry_timestamp_seconds) for proactive alerting via Alertmanager.
Architecture & Execution Flow
- 01 →OpenSSL VerificationSNI inspection and expiration check
- 02 →Automated ScannerDaily bash audit script
- 03 →Systemd TimerReliable persistent scheduling
- 04 →Prometheus MetricsProactive alerting before expiry
Table of Contents
Expired TLS certificates represent one of the most preventable failure modes in infrastructure engineering, yet they recur with clockwork regularity: browsers throw full-page security interstitials, API clients terminate connections, webhooks fail silently, and backend host metrics report pristine CPU and memory health. The root cause is rarely an absence of automated renewal tooling; rather, it is a lack of continuous validation of the certificates actively being served on the wire across every port. Certbot may have renewed the certificate files on disk, but the reverse proxy (such as NGINX) was never reloaded; a legacy load balancer may still be serving a stale, manually uploaded certificate; or an internal service might rely on a private CA whose validity period went untracked.
This guide walks through building a lightweight probe using openssl and Bash, classifying endpoint health into OK, WARN, and CRIT states via exit codes, and automating daily execution using a systemd timer.
Scope: This hands-on lab runs entirely under an unprivileged user account, binds strictly to 127.0.0.1, and leverages an ephemeral self-signed private CA—eliminating the need for public domain names, sudo access, or cloud infrastructure. All commands have been validated on Ubuntu 22.04 LTS (OpenSSL 3.0.2, Bash 5.1, systemd 249). The production timer installation and alerting integration sections serve as reference architectures that you can adapt and test in your own environments.
1. Why Proactive Monitoring Is Now Critical
The CA/Browser Forum passed ballot SC-081, introducing an aggressive schedule to reduce maximum certificate validity periods into Section 6.3.2 of the Baseline Requirements[1]:
- Issued before March 15, 2026: 398 days maximum;
- Issued from March 15, 2026 to before March 15, 2027: 200 days maximum;
- Issued from March 15, 2027 to before March 15, 2029: 100 days maximum;
- Issued from March 15, 2029 onward: 47 days maximum.
Let's Encrypt has also published its transition roadmap: the default certificate profile will shorten to 64-day validity starting February 10, 2027, and to 45-day validity starting February 16, 2028. For ACME clients lacking Automated Renewal Information (ARI) support, Let's Encrypt recommends renewing at roughly two-thirds of the certificate lifespan, rather than relying on a static window such as 60 days[2]. Furthermore, Let's Encrypt deprecated and terminated its expiration email notification service on June 4, 2025[3].
The operational implication: the number of automated renewal cycles per host per year will increase substantially. Every renewal event introduces potential failure points in distribution, web server reloads, or cross-fleet synchronization. Blackbox probing from an external client perspective serves as the ultimate line of defense.
2. Selecting a Monitoring Strategy
There are several approaches to TLS monitoring, each with distinct operational trade-offs:
- Inspecting files on disk (
/etc/letsencrypt/live/...): Low friction, but blind to configuration reload failures, runtime cache bugs, or instances where a service serves a mismatched file. - Monitoring exporters (e.g., Prometheus
blackbox_exporter): Well-suited for environments already operating Prometheus and Alertmanager; introduces additional operational surface area and infrastructure to maintain. - Third-party SaaS monitors: Convenient, as referenced by Let's Encrypt[4], but limited strictly to public, internet-facing endpoints.
- Custom
opensslscripts + system timers (this lab): Zero external dependencies beyond standard coreutils and OpenSSL; natively capable of inspecting internal services backed by private CAs. Notification dispatching remains fully customizable.
The script implemented here performs a full TLS handshake against the target endpoint just like a production client, inspecting the exact certificate delivered over the wire.
3. Prerequisites
You need a Linux environment equipped with openssl (version 1.1.1 or later to support -verify_hostname and -checkend), Bash, GNU date, and timeout (GNU coreutils). Verify your toolchain:
openssl version
command -v timeout date
All lab files will reside in ~/tls-lab. Create the workspace and store the subsequent scripts inside it:
mkdir -p ~/tls-lab && cd ~/tls-lab
4. Setting Up a Private CA and Test Certificates
To reliably reproduce failure modes without waiting for real certificates to expire, we will spin up a local CA dedicated to this lab and sign four distinct certificates for app.lab.test: one with 90 days validity, one with 15 days, one with 3 days, and one with 90 days validity but issued for an incorrect hostname. We then run openssl s_server on dedicated loopback ports to serve each certificate.
Save the following as ~/tls-lab/lab.sh:
#!/usr/bin/env bash
# lab.sh: generate a private CA + 4 localhost certs, run s_server on loopback
set -euo pipefail
LAB="${LAB:-$HOME/tls-lab}"
mkdir -p "$LAB" && cd "$LAB"
# Lab-internal CA
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
-keyout ca.key -out ca.pem -days 30 -subj "/CN=Lab Root CA" 2>/dev/null
make_leaf() { # make_leaf <name> <days> <DNS SAN>
local n="$1" days="$2" san="$3"
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
-keyout "$n.key" -out "$n.csr" -subj "/CN=$san" 2>/dev/null
printf 'subjectAltName=DNS:%s\nextendedKeyUsage=serverAuth\n' "$san" > "$n.ext"
openssl x509 -req -in "$n.csr" -CA ca.pem -CAkey ca.key -CAcreateserial \
-days "$days" -extfile "$n.ext" -out "$n.pem" 2>/dev/null
}
make_leaf ok 90 app.lab.test
make_leaf soon 15 app.lab.test
make_leaf urgent 3 app.lab.test
make_leaf wrong 90 other.lab.test
port=8441
for n in ok soon urgent wrong; do
openssl s_server -accept "127.0.0.1:$port" -cert "$n.pem" -key "$n.key" \
-www -quiet >/dev/null 2>&1 &
echo "$!" > "$n.pid"
echo "$n -> 127.0.0.1:$port"
port=$((port + 1))
done
Execute the setup:
bash ~/tls-lab/lab.sh
The script will output four mappings, from ok -> 127.0.0.1:8441 to wrong -> 127.0.0.1:8444. Note that modern TLS verification evaluates the Subject Alternative Name (SAN) extension rather than the deprecated Common Name (CN). Verify this with openssl x509 -ext and -checkhost[5]:
cd ~/tls-lab
openssl x509 -in ok.pem -noout -ext subjectAltName
openssl x509 -in ok.pem -noout -checkhost app.lab.test
openssl x509 -in wrong.pem -noout -checkhost app.lab.test
The second command returns does match certificate, while the third returns does NOT match certificate.
5. Building the Endpoint Probe Script
The probe takes a target host, port, SNI hostname, and an optional custom CA bundle file. It executes two sequential validation steps:
- Performs a TLS handshake using
openssl s_clientwith-verify_return_error(ensuring that trust chain validation failures explicitly abort the handshake rather than issuing a warning and continuing) and-verify_hostnamefor strict SAN matching[6]. The-servernameflag configures SNI, which is essential for virtual hosting environments serving multiple certificates from a single IP. - Extracts the leaf certificate from the output stream, inspects
notBeforeandnotAfter, and computes the remaining validity days alongside the total certificate lifespan. The-checkend Noption returns a non-zero exit code if the certificate expires within the next N seconds[5].
Thresholds:
- CRIT: Remaining validity falls below CRIT_DAYS (default: 7 days) or a TLS handshake/verification error occurs.
- WARN: Remaining validity falls below one-third of the certificate's total lifetime or below WARN_DAYS (default: 21 days). The one-third lifetime ratio aligns with standard industry recommendations to renew at two-thirds of the validity cycle[2], ensuring the probe dynamically adjusts as certificates shift from 90 days down to 45 days.
Save the following as ~/tls-lab/check-cert.sh:
#!/usr/bin/env bash
# check-cert.sh HOST PORT [SNI_NAME] [CAFILE]
# Exit: 0 = OK, 1 = WARN (renewal window reached), 2 = CRIT (handshake failure or imminent expiry)
set -uo pipefail
host="${1:?thiếu host}"
port="${2:?thiếu port}"
name="${3:-$host}"
cafile="${4:-}"
crit_days="${CRIT_DAYS:-7}"
warn_days="${WARN_DAYS:-21}"
ca_opt=()
if [ -n "$cafile" ]; then ca_opt=(-CAfile "$cafile"); fi
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
# 1) TLS handshake with trust chain validation and hostname verification
if ! timeout 10 openssl s_client -connect "$host:$port" -servername "$name" \
-verify_return_error -verify_hostname "$name" "${ca_opt[@]}" \
</dev/null >"$tmp/out" 2>"$tmp/err"; then
reason="$(grep -ohE 'verify error:num=[0-9]+:.*|Connection refused|Connection timed out|No route to host' "$tmp/out" "$tmp/err" | head -n1)"
echo "CRIT $name:$port handshake/verify thất bại: ${reason:-không rõ (timeout?)}"
exit 2
fi
# 2) Extract leaf certificate to evaluate validity dates
openssl x509 -in "$tmp/out" -out "$tmp/leaf.pem" 2>/dev/null || {
echo "CRIT $name:$port không đọc được certificate"; exit 2; }
nb="$(openssl x509 -in "$tmp/leaf.pem" -noout -startdate | cut -d= -f2)"
na="$(openssl x509 -in "$tmp/leaf.pem" -noout -enddate | cut -d= -f2)"
start=$(date -d "$nb" +%s)
end=$(date -d "$na" +%s)
now=$(date +%s)
life_days=$(( (end - start) / 86400 ))
left_days=$(( (end - now) / 86400 ))
renew_at=$(( life_days / 3 )) # Trigger renewal when approximately 1/3 of total lifespan remains
if ! openssl x509 -in "$tmp/leaf.pem" -noout -checkend $(( crit_days * 86400 )) >/dev/null; then
echo "CRIT $name:$port còn ${left_days} ngày (ngưỡng ${crit_days}), hết hạn $na"
exit 2
fi
if [ "$left_days" -lt "$renew_at" ] || [ "$left_days" -lt "$warn_days" ]; then
echo "WARN $name:$port còn ${left_days}/${life_days} ngày, cần gia hạn (mốc 1/3 = ${renew_at} ngày)"
exit 1
fi
echo "OK $name:$port còn ${left_days}/${life_days} ngày, hết hạn $na"
exit 0
Architectural design highlights: The script uses set -uo pipefail but deliberately avoids set -e because it must deterministically evaluate non-zero return codes from s_client and -checkend. A wrapping timeout 10 prevents hanging probe processes when stateful firewalls drop SYN packets. When CAFILE is omitted, OpenSSL defaults to the host operating system's standard trust store, which is the expected behavior for public endpoints.
6. Validating Against the Test Bed
Run the probe sequentially across all four ports, supplying the lab CA:
cd ~/tls-lab
for p in 8441 8442 8443 8444; do
bash check-cert.sh 127.0.0.1 "$p" app.lab.test ca.pem
echo "exit=$?"
done
Expected output in order:
- Port 8441:
OK, ~89/90 days remaining,exit=0; - Port 8442:
WARN, 14 or 15 days remaining (belowWARN_DAYS),exit=1; - Port 8443:
CRIT, 2 or 3 days remaining (belowCRIT_DAYS),exit=2; - Port 8444:
CRIT ... verify error:num=62:hostname mismatch,exit=2.
Two additional negative test cases should be tested:
# Omitting the lab CA: trust chain validation fails
bash check-cert.sh 127.0.0.1 8441 app.lab.test
# Non-listening target port
bash check-cert.sh 127.0.0.1 8449 app.lab.test ca.pem
The first command returns verify error:num=20:unable to get local issuer certificate, mirroring production incidents where an intermediate certificate was omitted from the server's chain file. The second command returns Connection refused. Both correctly terminate with exit code 2.
Note: Computed remaining days may vary by one day depending on execution time due to integer division. The WARN message prints the calculated one-third lifespan threshold even when the alert is triggered by WARN_DAYS.
7. Probing Multiple Endpoints
Manage endpoint inventories using a plain text manifest structured as host port name [cafile]. The batch wrapper script aggregates probe results and exits with the worst-case status encountered across all targets, allowing downstream monitoring systems or timers to evaluate fleet health via a single process exit code.
Save the following as ~/tls-lab/check-all.sh:
#!/usr/bin/env bash
# check-all.sh: ingest endpoint inventory, return worst-case exit code
set -uo pipefail
list="${1:-$HOME/tls-lab/targets.txt}"
dir="$(cd "$(dirname "$0")" && pwd)"
worst=0
while read -r host port name cafile; do
case "$host" in ''|'#'*) continue ;; esac
bash "$dir/check-cert.sh" "$host" "$port" "$name" "${cafile:-}"
rc=$?
[ "$rc" -gt "$worst" ] && worst=$rc
done < "$list"
echo "SUMMARY worst=$worst"
exit "$worst"
Generate a sample target manifest and run the batch probe:
cd ~/tls-lab
printf '# host port name CAfile\n127.0.0.1 8441 app.lab.test %s\n127.0.0.1 8442 app.lab.test %s\n' \
"$PWD/ca.pem" "$PWD/ca.pem" > targets.txt
bash check-all.sh targets.txt; echo "exit=$?"
The script outputs one OK line, one WARN line, followed by SUMMARY worst=1 and exit=1. In a production setting, each row represents an external domain (omitting the CAfile parameter) or an internal service paired with its private CA bundle path. For multi-tenant hosts serving multiple domains via SNI on a single IP, include a distinct row per virtual host.
8. Automating Daily Checks with systemd Timers
The following script writes two systemd user unit files to the user's configuration path without immediately enabling them. OnCalendar controls schedule execution, RandomizedDelaySec applies jitter to eliminate thundering herd problems across large fleets, and Persistent=true ensures the service runs immediately if the node was offline during the scheduled execution window[7].
Save the following as ~/tls-lab/units.sh:
#!/usr/bin/env bash
# units.sh: generate systemd --user units for daily execution (writes files only; does not enable)
set -euo pipefail
UNIT_DIR="${UNIT_DIR:-$HOME/.config/systemd/user}"
mkdir -p "$UNIT_DIR"
cat > "$UNIT_DIR/tls-expiry.service" <<'EOF'
[Unit]
Description=Kiểm tra hạn certificate TLS
[Service]
Type=oneshot
ExecStart=/bin/bash %h/tls-lab/check-all.sh %h/tls-lab/targets.txt
EOF
cat > "$UNIT_DIR/tls-expiry.timer" <<'EOF'
[Unit]
Description=Chạy tls-expiry mỗi sáng
[Timer]
OnCalendar=*-*-* 07:15:00
RandomizedDelaySec=10m
Persistent=true
[Install]
WantedBy=timers.target
EOF
echo "đã ghi unit vào $UNIT_DIR"
To preview the generated configuration and perform syntax validation without modifying the runtime systemd configuration:
cd ~/tls-lab
UNIT_DIR="$PWD/units-preview" bash units.sh
systemd-analyze verify --user units-preview/tls-expiry.service units-preview/tls-expiry.timer
systemd-analyze calendar '*-*-* 07:15:00'
systemd-analyze verify produces no output if unit syntax is valid; calendar displays the computed next execution timestamps. When ready to activate (for reference; adapt to your target environment):
bash ~/tls-lab/units.sh
systemctl --user daemon-reload
systemctl --user enable --now tls-expiry.timer
systemctl --user list-timers tls-expiry.timer
systemctl --user start tls-expiry.service
journalctl --user -u tls-expiry.service -n 20 --no-pager
Because this is a Type=oneshot service, any execution terminating with an exit code of 1 or 2 will transition the unit into a failed state. This is an intentional design choice: you can leverage systemd's OnFailure= directive to trigger notification webhooks, or rely on existing log forwarding agents (such as Vector or Fluentbit) to ingest WARN/CRIT lines into your centralized alerting platform. Note that user-level systemd timers only execute while the user maintains an active session, unless an administrator runs loginctl enable-linger for that account. In production environments, consider running these units as system-level services under a dedicated unprivileged service account.
9. Common Pitfalls and Troubleshooting
unable to get local issuer certificateon public certificates: The web server or load balancer is only presenting the leaf certificate and failing to serve the intermediate CA. Update your server configuration to serve the full certificate chain (fullchain.pem). You can inspect the chain delivered by the server on the wire usingopenssl s_client -showcerts[6].hostname mismatchon an apparently correct domain: Inspect the Subject Alternative Name (SAN) extension, not the deprecated Common Name (CN). Note that standard wildcard certificates (*.example.com) only match single-level subdomains; they do not match the apex (example.com) or multi-level subdomains (a.b.example.com).- Certbot reports successful renewal, but the probe returns
WARN: The automated renewal script succeeded on disk, but the reverse proxy process was not reloaded. Implement a post-renewal deploy hook (e.g.,nginx -s reload) and re-verify from an external client. - Probe process hangs or returns a timeout: A stateful network firewall is likely dropping connection packets, or the port is misconfigured. Verify Layer 4 (TCP) connectivity using standard netcat/ping tools before debugging Layer 7 (TLS) handshakes.
- Inconsistent results across multiple hosts: The systems may have diverging local trust stores (e.g., outdated
ca-certificatespackages) or local clock drift. The probe relies on GNUdate, making accurate NTP orsystemd-timesyncdsynchronization mandatory. - Endpoints utilizing opportunistic TLS (STARTTLS on SMTP, IMAP, PostgreSQL): These protocols require the explicit
-starttls <protocol>flag insides_client. The scripts presented in this guide are designed exclusively for direct TLS handshakes.
10. Teardown & Cleanup
Terminate the background s_server processes using their stored PID files, then clean up the lab directory:
cd ~/tls-lab
for f in ok soon urgent wrong; do kill "$(cat "$f.pid")" 2>/dev/null || true; done
cd ~ && rm -rf ~/tls-lab
If you enabled the systemd timer during the optional testing phase, tear it down prior to removing the files:
systemctl --user disable --now tls-expiry.timer
rm -f ~/.config/systemd/user/tls-expiry.service ~/.config/systemd/user/tls-expiry.timer
systemctl --user daemon-reload
Because this lab runs entirely on local infrastructure, no cloud costs are incurred. The ca.key file was strictly ephemeral for this lab; do not add ca.pem to your system's global trust store.
Conclusion
Automated certificate issuance is a necessary baseline, but it is insufficient without independent runtime validation. Blackbox verification executed from the client perspective surfaces the silent failures of automation: un-reloaded reverse proxies, broken intermediate chains, SAN configuration errors, and unmanaged endpoints. As baseline certificate validity windows compress to 200, 100, and ultimately 47 days over the next few years, implementing dynamic lifetime-ratio thresholds and driving alerting workflows through deterministic exit codes provides a resilient monitoring architecture that adapts seamlessly to evolving PKI standards.
References
Verified on October 25, 2026.
- CA/Browser Forum, TLS Baseline Requirements, Section 6.3.2 (ballot SC-081v3): https://github.com/cabforum/servercert/blob/main/docs/BR.md and https://cabforum.org/2025/04/11/ballot-sc081v3-introduce-schedule-of-reducing-validity-and-data-reuse-periods/
- Let's Encrypt, "Decreasing Certificate Lifetimes to 45 Days": https://letsencrypt.org/2025/12/02/from-90-to-45/
- Let's Encrypt, "Expiration Notification Service Has Ended": https://letsencrypt.org/2025/06/26/expiration-notification-service-has-ended/
- Let's Encrypt, Monitoring options: https://letsencrypt.org/docs/monitoring-options/
- OpenSSL 3.0, openssl-x509(1): https://docs.openssl.org/3.0/man1/openssl-x509/
- OpenSSL 3.0, openssl-s_client(1): https://docs.openssl.org/3.0/man1/openssl-s_client/
- systemd, systemd.timer(5): https://www.freedesktop.org/software/systemd/man/latest/systemd.timer.html