Certificate Expiration Alerts via Webhook (Slack Script)

The easiest certificate to forget is the one that has been working fine for a year. Nothing about it nags you. There’s no warning email you read, no dashboard you open. Then it expires on a Saturday, and you find out from a customer.

The fix people reach for first is a cron job and an email. That’s fine, but email alerts get filtered, and alerts nobody reads are the same as no alerts. A message in the channel your team already watches gets noticed. So here’s a small script that checks a list of hosts and posts to a Slack incoming webhook when anything expires inside your warning window, with a systemd timer to run it daily. I tested the script against a local fake webhook, and I’ll point out the parts I couldn’t test.

What you need

A Linux box with bash, openssl, curl and jq, a text file of hosts, and a Slack incoming webhook URL. Slack’s docs describe the webhook as a URL you POST a JSON body to. The only field they require is text, and the channel is fixed by how the webhook was set up, so you can’t override it per message.

Treat that URL as a password. Slack’s documentation says not to share it online, including in public repos, and that Slack actively revokes webhook URLs it finds leaked. So don’t hard-code it in the script. We’ll keep it in an environment file.

The script

Save this as /usr/local/bin/cert-alert.sh. It reads host:port lines (port defaults to 443), fetches each certificate, and uses openssl x509 -checkend to test the warning window. If the check can’t get a certificate at all, that counts as a problem too, because a host that suddenly stops answering TLS is something you want to hear about.

#!/usr/bin/env bash
# cert-alert.sh - post to a webhook when any cert in hosts.txt expires within WARN_DAYS
# Usage: WEBHOOK_URL=https://hooks.slack.com/services/... ./cert-alert.sh hosts.txt
set -u
HOSTS_FILE="${1:?usage: $0 hosts.txt}"
WARN_DAYS="${WARN_DAYS:-30}"
: "${WEBHOOK_URL:?set WEBHOOK_URL}"
warn_secs=$(( WARN_DAYS * 86400 ))
problems=()

while IFS=: read -r host port; do
  [[ -z "${host// }" || "$host" == \#* ]] && continue
  port="${port:-443}"

  pem=$(timeout 10 openssl s_client -connect "${host}:${port}" -servername "$host" </dev/null 2>/dev/null \
        | openssl x509 2>/dev/null)
  if [[ -z "$pem" ]]; then
    problems+=("${host}:${port} - could not fetch a certificate")
    continue
  fi

  if ! openssl x509 -noout -checkend "$warn_secs" <<<"$pem" >/dev/null; then
    end=$(openssl x509 -noout -enddate <<<"$pem" | cut -d= -f2)
    problems+=("${host}:${port} - expires ${end}")
  fi
done < "$HOSTS_FILE"

(( ${#problems[@]} == 0 )) && exit 0

msg="Certificate check: ${#problems[@]} problem(s) (threshold ${WARN_DAYS} days)"
for p in "${problems[@]}"; do msg+=$'\n'"- ${p}"; done

# jq builds valid JSON for us, including the newlines
payload=$(jq -n --arg text "$msg" '{text: $text}')

curl -fsS --max-time 15 -X POST -H 'Content-type: application/json' --data "$payload" "$WEBHOOK_URL" >/dev/null \
  || { echo "webhook post failed" >&2; exit 1; }

Make it executable with chmod 755 /usr/local/bin/cert-alert.sh.

When I ran it against four test endpoints (one healthy, one with nine days left, one expired, one that wasn’t listening), the receiver got exactly one message:

{
  "text": "Certificate check: 3 problem(s) (threshold 30 days)\n- localhost:9444 - expires Nov  7 12:06:56 2026 GMT\n- localhost:9445 - expires Jan 10 00:00:00 2026 GMT\n- localhost:9999 - could not fetch a certificate"
}

With only healthy hosts it exits quietly and sends nothing. If the webhook POST fails, curl -f makes it exit nonzero, the script prints an error, and exits 1, which matters in a minute.

A couple of choices worth knowing about. I use jq to build the JSON rather than gluing strings together, because a hostname or date with an odd character will otherwise produce an invalid_payload error from Slack, and Slack’s docs say not to retry until you’ve fixed the request. And I pull the certificate with SNI set, so the right certificate comes back: connect by name, not by IP, or you may check the wrong certificate on a shared host.

Run it daily with a systemd timer

Create /etc/cert-alert.env with the webhook (readable only by root):

WEBHOOK_URL=https://hooks.slack.com/services/T000/B000/XXXX
WARN_DAYS=30

Then two unit files. /etc/systemd/system/cert-alert.service:

[Unit]
Description=Check certificate expiry and post to webhook

[Service]
Type=oneshot
EnvironmentFile=/etc/cert-alert.env
ExecStart=/usr/local/bin/cert-alert.sh /etc/cert-hosts.txt

And /etc/systemd/system/cert-alert.timer:

[Unit]
Description=Run the certificate check daily

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

A timer named cert-alert.timer starts the service with the same name, per the systemd.timer documentation, so there’s no Unit= line needed. Persistent=true means that if the box was off at the scheduled time, the check runs when it comes back instead of being skipped. Enable it with systemctl daemon-reload && systemctl enable --now cert-alert.timer. I didn’t run the systemd part in my test environment, so try it on a lab machine first.

The part DIY alerting gets wrong

This script is silent when everything is healthy. That’s the right behavior for a notification, and it’s also a trap. If the timer stops, the host loses network access, or the webhook gets revoked, you get exactly the same thing you get when all is well: nothing.

You can patch that with a weekly “still alive” message, or by monitoring the timer’s last run. Both are more scripts you now own. The same goes for everything else this script doesn’t do. It only checks what’s on your list, so a new server never shows up. It checks one port per entry. It can’t tell you which other servers hold copies of the expiring certificate. And the alert says what, but not how: whoever sees the Slack message has to remember or find out how that particular certificate gets replaced.

I walked through that real cost of the DIY route in build vs. buy, and the discovery gap is covered in certificate discovery. For a small, well-known set of endpoints, the script above is a perfectly good answer. It starts to creak as the list grows.

Where CertMS fits

CertMS’s webhook integration does the same basic job without you maintaining the check: when a certificate is going to expire in a set number of days, CertMS sends a request to the webhook you configure. The help desk integration can open a ticket at the same point. CertMS also lets you write your own documentation on how to replace a specific certificate and attach it to that certificate, and that documentation travels with the help desk ticket or webhook. So the person who gets the alert gets the replacement steps with it. The discovery side comes from monitoring your Windows CA, Windows and Linux servers and URLs, so new certificates show up without anyone editing a hosts file. If you’d like to see it, take a look at CertMS. Or compare the two approaches in manual tracking vs. CertMS.

References

Free 5-Day Email Course

Learn how to automate certificate tracking and avoid costly surprises - one actionable lesson each day