{"id":14706,"date":"2026-11-23T01:01:00","date_gmt":"2026-11-23T06:01:00","guid":{"rendered":"https:\/\/www.both.org\/?p=14706"},"modified":"2026-11-16T07:22:39","modified_gmt":"2026-11-16T12:22:39","slug":"never-be-surprised-by-an-expired-certificate","status":"publish","type":"post","link":"https:\/\/www.both.org\/?p=14706","title":{"rendered":"Never Be Surprised by an Expired Certificate"},"content":{"rendered":"<div class=\"pld-like-dislike-wrap pld-template-1\">\r\n    <div class=\"pld-like-wrap  pld-common-wrap\">\r\n    <a href=\"javascript:void(0)\" class=\"pld-like-trigger pld-like-dislike-trigger  \" title=\"\" data-post-id=\"14706\" data-trigger-type=\"like\" data-restriction=\"cookie\" data-already-liked=\"0\">\r\n                        <i class=\"fas fa-thumbs-up\"><\/i>\r\n                <\/a>\r\n    <span class=\"pld-like-count-wrap pld-count-wrap\">    <\/span>\r\n<\/div><\/div>\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This article builds that check from parts that are already on almost every Linux system: <a href=\"https:\/\/www.openssl.org\/\">OpenSSL<\/a>&#8216;s command-line tool, <a href=\"https:\/\/www.gnu.org\/software\/bash\/\">Bash<\/a>, and a <a href=\"https:\/\/systemd.io\/\">systemd<\/a> 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The Two openssl Commands That Do the Work<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The first command, <code>openssl s_client<\/code>, opens a TLS connection the way a browser would and prints what the server sent. The second, <code>openssl x509<\/code>, reads a certificate and tells you about it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This command fetches the certificate for a site and prints its expiry date:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>echo | openssl s_client -connect www.both.org:443 -servername www.both.org 2&gt;\/dev\/null \\\n    | openssl x509 -noout -enddate<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The output is a single line:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>notAfter=Jan 16 14:24:45 2027 GMT<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>-checkend<\/code> 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 <code>cert.pem<\/code> will survive the next 21 days:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>openssl x509 -noout -checkend $((21 * 86400)) -in cert.pem &amp;&amp; echo fine || echo renew soon<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Because <code>-checkend<\/code> answers with an exit status, there is no date parsing to get wrong for the yes-or-no decision. I only use <code>date<\/code> to turn the expiry date into a friendly &#8220;days left&#8221; number for people to read.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why -servername Matters<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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 (<a href=\"https:\/\/en.wikipedia.org\/wiki\/Server_Name_Indication\">SNI<\/a>), and the server picks the matching certificate. If you leave SNI out, you get whatever the server&#8217;s default certificate is, which may belong to a completely different site.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To see this, I ran a small test server with two certificates, one for <code>default.test<\/code> and one for <code>soon.test<\/code>. Asking without SNI returns the default:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ openssl s_client -connect 127.0.0.1:8443 -noservername &lt;\/dev\/null 2&gt;\/dev\/null | openssl x509 -noout -subject\nsubject=CN=default.test\n$ openssl s_client -connect 127.0.0.1:8443 -servername soon.test &lt;\/dev\/null 2&gt;\/dev\/null | openssl x509 -noout -subject\nsubject=CN=soon.test<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>-servername<\/code>. I also add <code>-verify_hostname<\/code>, 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&#8217;s point of view, as an expired one.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Checking the Full Chain<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>-showcerts<\/code> option prints every certificate the server sent. This loop saves each one to its own file and prints its subject and expiry date:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>openssl s_client -connect expired.badssl.com:443 -servername expired.badssl.com \\\n    -showcerts &lt;\/dev\/null 2&gt;\/dev\/null |\n    awk '\/BEGIN CERT\/{c=1; n++} c{print &gt; (\"chain-\" n \".pem\")} \/END CERT\/{c=0}'\nfor f in chain-*.pem; do openssl x509 -in \"$f\" -noout -subject -enddate; done<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Against the deliberately broken test site <a href=\"https:\/\/expired.badssl.com\/\">expired.badssl.com<\/a>, 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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For day-to-day monitoring, I let OpenSSL do the chain work. <code>s_client<\/code> verifies the chain against the system&#8217;s trusted roots and reports the result in a line such as <code>Verify return code: 0 (ok)<\/code>. Anything other than 0 means a browser would probably complain too, so the script treats it as a problem.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The Script<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># hostname       &#91;port] &#91;sni-name]\nwww.both.org\nkernel.org\nmail.example.com 993\n203.0.113.10     443    www.example.com<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here is <code>certwatch.sh<\/code>, which I keep in <code>\/usr\/local\/bin<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#!\/usr\/bin\/env bash\n# certwatch.sh - report how many days are left on TLS certificates\n# Usage: certwatch.sh &#91;hosts-file] &#91;warn-days]\n# Each line of the hosts file: hostname &#91;port] &#91;sni-name]\n\nHOSTS_FILE=${1:-\/etc\/certwatch\/hosts}\nWARN_DAYS=${2:-21}\nTIMEOUT=10\nca=()                                   # optional private CA: CA_FILE=\/path\/ca.pem\n&#91;&#91; -n \"${CA_FILE:-}\" ]] &amp;&amp; ca=(-CAfile \"$CA_FILE\")\nnow=$(date +%s)\nreport=()\nproblems=0\n\nwhile read -r host port sni; do\n    # Skip blank lines and comments\n    &#91;&#91; -z \"$host\" || \"$host\" == \\#* ]] &amp;&amp; continue\n    port=${port:-443}\n    sni=${sni:-$host}\n    label=\"$host:$port\"\n    &#91;&#91; \"$sni\" != \"$host\" ]] &amp;&amp; label+=\" (SNI $sni)\"\n\n    # One handshake per host (one retry for network hiccups);\n    # keep everything s_client prints\n    for try in 1 2; do\n        out=$(timeout \"$TIMEOUT\" openssl s_client -connect \"$host:$port\" \\\n                -servername \"$sni\" -verify_hostname \"$sni\" \"${ca&#91;@]}\" &lt;\/dev\/null 2&gt;\/dev\/null)\n        cert=$(openssl x509 &lt;&lt;&lt;\"$out\" 2&gt;\/dev\/null)\n        &#91;&#91; -n \"$cert\" ]] &amp;&amp; break\n        sleep 2\n    done\n\n    if &#91;&#91; -z \"$cert\" ]]; then\n        report+=(\"FAIL     $label  no certificate (connection or handshake failed)\")\n        ((problems++))\n        continue\n    fi\n\n    end=$(openssl x509 -noout -enddate &lt;&lt;&lt;\"$cert\" | cut -d= -f2)\n    days=$(( ($(date -d \"$end\" +%s) - now) \/ 86400 ))\n    verify=$(grep -m1 'Verify return code' &lt;&lt;&lt;\"$out\" | sed 's\/.*: \/\/')\n\n    if ! openssl x509 -noout -checkend 0 &lt;&lt;&lt;\"$cert\" &gt;\/dev\/null; then\n        status=EXPIRED\n    elif ! openssl x509 -noout -checkend $((WARN_DAYS * 86400)) &lt;&lt;&lt;\"$cert\" &gt;\/dev\/null; then\n        status=WARN\n    elif &#91;&#91; \"$verify\" != 0* ]]; then\n        status=BADCHAIN\n    else\n        status=OK\n    fi\n\n    line=$(printf '%-8s %s  %s days left (%s)' \"$status\" \"$label\" \"$days\" \"$end\")\n    &#91;&#91; \"$status\" != OK ]] &amp;&amp; { line+=\"  verify: $verify\"; ((problems++)); }\n    report+=(\"$line\")\ndone &lt; \"$HOSTS_FILE\"\n\nprintf '%s\\n' \"${report&#91;@]}\"\n\nif ((problems &gt; 0)); then\n    if &#91;&#91; -n \"${MAILTO:-}\" ]] &amp;&amp; command -v mail &gt;\/dev\/null; then\n        printf '%s\\n' \"${report&#91;@]}\" |\n            mail -s \"certwatch: $problems certificate(s) need attention on $(hostname)\" \"$MAILTO\"\n    fi\n    exit 1\nfi<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A few design choices are worth explaining:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>One handshake per host.<\/strong> The output of <code>s_client<\/code> is kept in a variable, so the certificate and the verification result come from the same connection.<\/li>\n\n\n\n<li><strong><code>timeout<\/code> and one retry.<\/strong> A host that does not answer would otherwise hang the whole run. The single retry stops one dropped packet from turning into an alarm.<\/li>\n\n\n\n<li><strong>Order of checks.<\/strong> Expiry is reported before chain problems, because &#8220;expired&#8221; is the most urgent and clearest message.<\/li>\n\n\n\n<li><strong><code>CA_FILE<\/code>.<\/strong> Internal services often use a private certificate authority. Point <code>CA_FILE<\/code> at its certificate and verification works for those too.<\/li>\n\n\n\n<li><strong>Exit status.<\/strong> The script exits with 1 when anything needs attention, which systemd records as a failed run.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>days left<\/code> figure is rounded down, so a certificate with four and a half days left shows 4. The <code>date -d<\/code> call relies on GNU date, which is standard on Linux distributions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">A Test Run<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">I ran the script against a mix of real sites and the deliberately broken hosts at <a href=\"https:\/\/badssl.com\/\">badssl.com<\/a>, plus an address where nothing is listening (the hosts file asks for the name <code>nothing.example<\/code> there):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ .\/certwatch.sh hosts 21\nOK       www.both.org:443  79 days left (Jan 16 14:24:45 2027 GMT)\nOK       fedoraproject.org:443  168 days left (Apr 15 23:59:59 2027 GMT)\nOK       kernel.org:443  75 days left (Jan 12 10:52:44 2027 GMT)\nEXPIRED  expired.badssl.com:443  -4217 days left (Apr 12 23:59:59 2015 GMT)  verify: 10 (certificate has expired)\nBADCHAIN wrong.host.badssl.com:443  60 days left (Dec 28 20:02:55 2026 GMT)  verify: 62 (hostname mismatch)\nBADCHAIN self-signed.badssl.com:443  728 days left (Oct 26 21:00:20 2028 GMT)  verify: 18 (self-signed certificate)\nFAIL     10.255.255.1:443 (SNI nothing.example)  no certificate (connection or handshake failed)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">To test the warning threshold and the SNI handling, I used <code>openssl s_server<\/code> with a small private CA, one certificate valid for 300 days, and one valid for only five days. With <code>CA_FILE<\/code> set, the results were:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>OK       127.0.0.1:8443 (SNI default.test)  299 days left (Aug 25 05:05:10 2027 GMT)\nWARN     127.0.0.1:8443 (SNI soon.test)  4 days left (Nov  3 05:05:10 2026 GMT)  verify: 0 (ok)\nBADCHAIN 127.0.0.1:8443 (SNI other.test)  299 days left (Aug 25 05:05:10 2027 GMT)  verify: 62 (hostname mismatch)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The last line is the wrong-SNI case: the server had no certificate for <code>other.test<\/code>, so it fell back to its default certificate, and <code>-verify_hostname<\/code> caught the mismatch.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Running It Daily with systemd<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A <a href=\"https:\/\/www.freedesktop.org\/software\/systemd\/man\/latest\/systemd.timer.html\">systemd timer<\/a> needs two unit files: a service that says what to run, and a timer that says when. This is <code>\/etc\/systemd\/system\/certwatch.service<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;Unit]\nDescription=Check TLS certificate expiry for the hosts in \/etc\/certwatch\/hosts\nWants=network-online.target\nAfter=network-online.target\n\n&#91;Service]\nType=oneshot\nEnvironment=MAILTO=root\nExecStart=\/usr\/local\/bin\/certwatch.sh \/etc\/certwatch\/hosts 21<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">And this is <code>\/etc\/systemd\/system\/certwatch.timer<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&#91;Unit]\nDescription=Run certwatch once a day\n\n&#91;Timer]\nOnCalendar=daily\nRandomizedDelaySec=1h\nPersistent=true\n\n&#91;Install]\nWantedBy=timers.target<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Persistent=true<\/code> means that if the machine was off at midnight, the check runs soon after it boots instead of being skipped. <code>RandomizedDelaySec<\/code> 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:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo systemd-analyze verify \/etc\/systemd\/system\/certwatch.service \/etc\/systemd\/system\/certwatch.timer<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then install the hosts file and start the timer:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo mkdir -p \/etc\/certwatch\nsudo cp hosts \/etc\/certwatch\/hosts\nsudo systemctl daemon-reload\nsudo systemctl enable --now certwatch.timer\nsystemctl list-timers certwatch.timer<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You do not have to wait until midnight to try it. Start the service by hand and read what it wrote:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo systemctl start certwatch.service\njournalctl -u certwatch.service --since today<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Everything the script prints goes to the journal, so you have a daily history of every certificate&#8217;s remaining days. Email goes out only when at least one line is not <code>OK<\/code>, which keeps the signal clean: if certwatch writes to you, something really needs doing. The <code>mail<\/code> command needs a working local mail setup, such as the <code>s-nail<\/code> package (which provides <code>mail<\/code> on Fedora) or <code>mailx<\/code> on other distributions, plus a mail transfer agent or relay. If you would rather not run one, the failed unit still shows up in <code>systemctl --failed<\/code>, and you could hook an <code>OnFailure=<\/code> unit to any notification tool you already use.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>systemd-analyze verify<\/code>. On Fedora the <code>mail<\/code> command comes from the <code>s-nail<\/code> 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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Karthikeyan works at ShoHost, a small web hosting company in Erode, India (<a href=\"https:\/\/shohost.com\">https:\/\/shohost.com<\/a>).<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Checking TLS Expiry Across Dozens of Sites with openssl, Bash, and a systemd Timer<\/p>\n","protected":false},"author":512,"featured_media":4837,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","footnotes":""},"categories":[475,990,5,150,89],"tags":[476,991,992,91,683],"class_list":["post-14706","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-automation","category-certificates","category-linux","category-programming","category-system-administration","tag-automation","tag-certificates","tag-expired-certificates","tag-linux","tag-system-administration"],"modified_by":"David Both","_links":{"self":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/14706","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/users\/512"}],"replies":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=14706"}],"version-history":[{"count":1,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/14706\/revisions"}],"predecessor-version":[{"id":14707,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/posts\/14706\/revisions\/14707"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=\/wp\/v2\/media\/4837"}],"wp:attachment":[{"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=14706"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=14706"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.both.org\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=14706"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}