Reading TLS certificates with openssl
What a certificate and its chain are, how to pull them off a live server and read them with openssl, a tested script that warns before certificates expire, a practice CA to experiment on, and the mistakes that make openssl give the wrong answer.
Contents
Why certificates exist
Encryption alone says nothing about who is at the other end; a browser can set up a perfectly encrypted session with an attacker. Something has to prove that the server’s key belongs to the name in the address bar, and that something is the certificate.
Netscape designed SSL in 1994 so that people would type card numbers into a browser. Version 1.0 never shipped; SSL 2.0 went out with Netscape Navigator in 1995 and SSL 3.0 replaced it in 1996. The IETF then took the design over and renamed it: TLS 1.0 is RFC 2246, published in January 1999. TLS 1.1 and 1.2 followed in 2006 and 2008. TLS 1.3, RFC 8446 from August 2018, removed RSA key exchange and the weak ciphers and cut the handshake to one round trip. RFC 8996 formally retired TLS 1.0 and 1.1 in 2021.
The certificate format is older. X.509 was published by the CCITT (now the ITU-T) in 1988 for the X.500 directory, and TLS borrowed it. Version 3, from 1996, added the extensions where the useful parts now live. The internet’s profile of X.509 is RFC 5280.
Certificates are also getting shorter. In April 2025 the CA/Browser Forum passed ballot SC-081v3: the maximum lifetime of a public TLS certificate fell from 398 days to 200 days on 15 March 2026, drops to 100 days in March 2027 and to 47 days in March 2029. Renewal has to be automated, and the automation has to be checked.
What a certificate and a chain are
A certificate is a signed statement: “this public key belongs to these names, from this date until that date”, signed by an issuer. The subject says who it is for; on a web server certificate that is usually only a common name (CN), which browsers ignore. The names clients actually check are in the Subject Alternative Name (SAN) extension, a list of DNS names. The issuer is whoever signed it. The validity period is two timestamps in UTC, notBefore and notAfter. Then come the public key and extensions such as CA:TRUE, which lets a certificate sign others.
A browser does not know the issuer of a server certificate directly. It knows a few hundred root certificates shipped with the operating system or browser. Roots sign intermediates, intermediates sign server certificates, and the server sends its own certificate plus the intermediates. The client builds a path from there up to a root it already trusts, checking each signature and date on the way. That path is the chain. The root itself is not sent: a root the client does not already have is worthless.
Fetching a server’s chain
s_client is a bare TLS client. This prints every certificate the server sent:
openssl s_client -connect example.com:443 -servername example.com -showcerts </dev/null
-servername sets SNI, the name the client asks for during the handshake. One IP address often serves hundreds of sites, and SNI is how the server picks which certificate to send. </dev/null is there because after the handshake s_client waits for input to send to the server, and without it the command sits there until you press Ctrl-D.
Trimmed output from OpenSSL 3.5 (the PEM blocks are cut):
...
Certificate chain
0 s:CN=example.com
i:C=US, O=SSL Corporation, CN=Cloudflare TLS Issuing ECC CA 3
a:PKEY: EC, (prime256v1); sigalg: ecdsa-with-SHA256
v:NotBefore: Sep 26 22:49:11 2026 GMT; NotAfter: Dec 25 22:56:35 2026 GMT
-----BEGIN CERTIFICATE-----
...
1 s:C=US, O=SSL Corporation, CN=Cloudflare TLS Issuing ECC CA 3
i:C=US, O=SSL Corporation, CN=SSL.com TLS Transit ECC CA R2
...
---
...
Protocol: TLSv1.3
...
Verify return code: 0 (ok)
Read the s: (subject) and i: (issuer) lines as pairs: each certificate’s issuer should be the subject of the next one down. Certificate 0 is the server’s own. Verify return code: 0 (ok) means openssl reached a trusted root, not that the name matched.
To save the server certificate, pipe it through x509, which keeps the first PEM block:
openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null \
| openssl x509 > example.pem
Reading a certificate
openssl x509 -in example.pem -noout -text prints every field, decoded. Usually one or two fields are enough, and x509 has a flag for each:
openssl x509 -in example.pem -noout -subject -issuer -dates
openssl x509 -in example.pem -noout -ext subjectAltName
openssl x509 -in example.pem -noout -fingerprint -sha256
subject=CN=example.com
issuer=C=US, O=SSL Corporation, CN=Cloudflare TLS Issuing ECC CA 3
notBefore=Sep 26 22:49:11 2026 GMT
notAfter=Dec 25 22:56:35 2026 GMT
X509v3 Subject Alternative Name:
DNS:example.com, DNS:*.example.com
sha256 Fingerprint=85:CA:6A:B0:68:E9:BC:CE:88:B6:C4:AA:3C:47:F7:D1:72:28:13:4A:45:7F:87:0D:38:00:E6:22:3A:0D:F0:7A
The fingerprint is a SHA-256 hash of the whole certificate in DER form, the value to compare when you pin a certificate or check one by hand. -ext arrived in OpenSSL 3.0; older versions and LibreSSL need -text and grep.
Checking expiry in a script
-checkend N asks whether the certificate will still be valid N seconds from now. It exits 0 if yes and 1 if no, which is all a script needs:
openssl x509 -in example.pem -noout -checkend $((30*86400)) # 30 days
On 15 November that certificate has 40 days left, so 30 days passes and 45 days fails. OpenSSL also prints Certificate will not expire or Certificate will expire; LibreSSL prints nothing. Test the exit status, never the text.
The script below takes a number of days and a list of hosts, and reports each:
#!/usr/bin/env bash
# certwatch.sh: warn when TLS certificates expire within N days.
# Usage: certwatch.sh DAYS host[:port] ...
# Exit status: 0 all fine, 1 at least one expiring, 2 at least one unreachable.
set -u
OPENSSL=${OPENSSL:-openssl}
if [ $# -lt 2 ]; then
echo "usage: $0 DAYS host[:port] ..." >&2
exit 64
fi
days=$1
shift
status=0
fetch() {
"$OPENSSL" s_client -connect "$1:$2" -servername "$1" </dev/null 2>/dev/null \
| "$OPENSSL" x509 2>/dev/null
}
for target in "$@"; do
host=${target%%:*}
port=${target#*:}
[ "$port" = "$target" ] && port=443
cert=$(fetch "$host" "$port")
[ -z "$cert" ] && cert=$(fetch "$host" "$port") # one retry for a dropped handshake
if [ -z "$cert" ]; then
echo "ERROR $target: no certificate received"
status=2
continue
fi
end=$(printf '%s\n' "$cert" | "$OPENSSL" x509 -noout -enddate | cut -d= -f2)
if printf '%s\n' "$cert" | "$OPENSSL" x509 -noout -checkend $((days * 86400)) >/dev/null; then
echo "OK $target: expires $end"
else
echo "WARN $target: expires $end"
[ "$status" -eq 0 ] && status=1
fi
done
exit "$status"
$ ./certwatch.sh 30 example.com expired.badssl.com badssl.com wikipedia.org:443 no-such-host.example
OK example.com: expires Dec 25 22:56:35 2026 GMT
WARN expired.badssl.com: expires Apr 12 23:59:59 2015 GMT
OK badssl.com: expires Dec 28 20:02:55 2026 GMT
OK wikipedia.org:443: expires Jan 2 18:34:50 2027 GMT
ERROR no-such-host.example: no certificate received
$ echo $?
2
A host that sends no certificate is an error, so a dead server does not pass silently. The script always sends SNI and runs unchanged on LibreSSL, OpenSSL 3.5 and OpenSSL 4.1. It does not parse IPv6 literals, and an unreachable host waits out the system’s connect timeout. Run it from cron with a threshold longer than your renewal interval.
Verifying a chain
openssl verify checks a certificate against the system trust store. Given the server certificate alone, it fails, because the intermediates are missing:
$ openssl verify example.pem
CN=example.com
error 20 at 0 depth lookup: unable to get local issuer certificate
error example.pem: verification failed
-untrusted supplies them: they help build the path, but the path still has to end at a root in the trust store. Save everything after the first certificate from -showcerts into chain.pem, then:
$ openssl verify -untrusted chain.pem example.pem
example.pem: OK
-CAfile replaces the trust store with a file of your own, which is how you check against a private CA.
Does the key match the certificate
A certificate and a private key belong together only if they share a public key, and a server that refuses a newly installed certificate usually has the wrong key. Extract the public key from each and compare hashes:
openssl x509 -in site.crt -noout -pubkey | openssl sha256
openssl pkey -in site.key -pubout | openssl sha256
Identical hashes mean a pair. The common advice to compare -modulus works only for RSA keys; the -pubkey form works for EC and Ed25519 as well.
A practice CA of your own
Everything above can be tried without touching a real server. A throwaway self-signed certificate, valid for 30 days, with a SAN:
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \
-keyout test.key -out test.crt -days 30 \
-subj "/CN=test.local" -addext "subjectAltName=DNS:test.local,DNS:localhost"
-nodes leaves the key unencrypted: fine for practice, wrong for anything else.
A self-signed certificate has no chain. For a chain, make a tiny CA and sign a server certificate with it:
# the root
openssl req -x509 -newkey rsa:2048 -nodes -keyout ca.key -out ca.crt -days 365 \
-subj "/CN=Practice Root CA" \
-addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign"
# a key and signing request for the server
openssl req -newkey rsa:2048 -nodes -keyout site.key -out site.csr -subj "/CN=site.test"
# the root signs it
printf 'subjectAltName=DNS:site.test\nbasicConstraints=CA:FALSE\nextendedKeyUsage=serverAuth\n' > site.ext
openssl x509 -req -in site.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
-out site.crt -days 30 -extfile site.ext
openssl verify -CAfile ca.crt site.crt
The last line prints site.crt: OK. Without -CAfile it fails with error 20. -extfile is needed because x509 -req drops the extensions in a request unless told otherwise, and a server certificate without a SAN is rejected by every current browser.
Which TLS versions a server accepts
s_client takes one flag per version, -tls1, -tls1_1, -tls1_2 and -tls1_3, and offers only that version. Look at the New, line:
$ openssl s_client -connect example.com:443 -servername example.com -tls1_2 </dev/null 2>&1 | grep '^New,'
New, TLSv1.2, Cipher is ECDHE-ECDSA-CHACHA20-POLY1305
$ openssl s_client -connect tls-v1-2.badssl.com:1012 -servername tls-v1-2.badssl.com -tls1_3 </dev/null 2>&1 | grep -E '^New,|alert'
...ssl/tls alert handshake failure...SSL alert number 40
New, (NONE), Cipher is (NONE)
A cipher name means the version was accepted; (NONE) and an alert mean it was refused. Ignore the Protocol: line: OpenSSL 3.5 printed Protocol: TLSv1.3 for handshakes that never happened.
On OpenSSL 3 and later, -tls1 alone fails before anything is sent, with no protocols available, because the default security level forbids TLS 1.0 and 1.1. Lower it for the test:
$ openssl s_client -connect example.com:443 -servername example.com -tls1 -cipher 'DEFAULT@SECLEVEL=0' </dev/null 2>&1 | grep '^New,'
New, TLSv1.0, Cipher is ECDHE-RSA-AES128-SHA
So example.com still accepts TLS 1.0. LibreSSL offers it without the extra flag.
Gotchas
Missing SNI returns the wrong certificate. OpenSSL 1.1.1 and later send SNI from the -connect host automatically. The LibreSSL 3.3.6 that macOS ships at /usr/bin/openssl does not, and gets whatever the server sends to nameless clients:
$ /usr/bin/openssl s_client -connect badssl.com:443 </dev/null 2>/dev/null | grep ^subject
subject=/C=US/ST=California/L=San Francisco/O=BadSSL Fallback. Unknown subdomain or no SNI./CN=badssl-fallback-unknown-subdomain-or-no-sni
Connecting by IP address does the same on any version. Always pass -servername.
LibreSSL is not OpenSSL. Besides SNI, /usr/bin/openssl on macOS has no x509 -ext and no s_client -verify_hostname, prints names as /C=US/O=..., and prints nothing for -checkend. Install OpenSSL with Homebrew and call it by path: plain openssl there is now 4.1, and $(brew --prefix openssl@3)/bin/openssl is 3.5. Ask for fingerprints in a command of their own. OpenSSL 4.1.0 printed a wrong SHA-256 fingerprint when -ext subjectAltName was in the same command; 3.5 and LibreSSL printed the right one, which openssl x509 -outform DER | shasum -a 256 confirms.
s_client does not check the name. For wrong.host.badssl.com, whose certificate does not cover that name, plain s_client says 0 (ok), while adding -verify_hostname wrong.host.badssl.com gives 62 (hostname mismatch).
0 (ok) can come with no certificate at all. When the server drops the connection mid-handshake, OpenSSL 3.5 prints no peer certificate available and then Verify return code: 0 (ok). The badssl.com servers did this intermittently to OpenSSL 3’s larger post-quantum ClientHello. A script that greps for 0 (ok) reports a dead server as healthy. Check that a certificate came back, as certwatch.sh does.
Servers that leave out the intermediate break most clients. Browsers often hide this by caching intermediates or fetching them from the certificate’s Authority Information Access URL. Most other clients, curl and Python included, do neither and fail:
$ openssl s_client -connect incomplete-chain.badssl.com:443 -servername incomplete-chain.badssl.com </dev/null 2>&1 | grep -E 'depth|Verify return'
depth=0 CN=*.badssl.com
Verify return code: 21 (unable to verify the first certificate)
Only depth 0 came back. The fix is on the server: configure the full chain file, not the bare certificate.
Clock skew breaks validation both ways. A machine whose clock is behind sees a freshly issued certificate as not yet valid (error 9), and one whose clock is ahead sees a current one as expired (error 10). openssl verify -attime with a Unix timestamp shows what such a client sees. Check date -u before you blame the server.
Certificate transparency logs show everything a CA has issued. Since April 2018 Chrome has required every new public certificate to appear in the public logs defined by RFC 6962. crt.sh, run by Sectigo, searches them:
curl -s 'https://crt.sh/?q=example.com&output=json' \
| jq -r '.[] | [.not_before, .not_after, .name_value] | @tsv' | sort -r | head
Each certificate usually appears twice, as precertificate and final certificate. The logs show certificates for your names that you did not ask for, and every hostname you have ever put in a SAN, so keep private hostnames off public certificates.
Sources
- Dierks, T. and C. Allen. RFC 2246, “The TLS Protocol Version 1.0.” January 1999.
- Rescorla, E. RFC 8446, “The Transport Layer Security (TLS) Protocol Version 1.3.” August 2018.
- Freier, A., P. Karlton and P. Kocher. RFC 6101, “The Secure Sockets Layer (SSL) Protocol Version 3.0.” August 2011 (historic record of the 1996 protocol).
- Moriarty, K. and S. Farrell. RFC 8996, “Deprecating TLS 1.0 and TLS 1.1.” March 2021.
- Cooper, D., S. Santesson, S. Farrell, S. Boeyen, R. Housley and W. Polk. RFC 5280, “Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile.” May 2008.
- Eastlake, D. RFC 6066, “Transport Layer Security (TLS) Extensions: Extension Definitions” (Server Name Indication, section 3). January 2011.
- Laurie, B., A. Langley and E. Kasper. RFC 6962, “Certificate Transparency.” June 2013.
- CA/Browser Forum. Ballot SC-081v3, “Introduce Schedule of Reducing Validity and Data Reuse Periods.” April 2025.
- OpenSSL Project. openssl-s_client(1), openssl-x509(1), openssl-verify(1), openssl-req(1) and openssl-s_server(1) manual pages, OpenSSL 3.5.
- LibreSSL. openssl(1) manual page.
- badssl.com test hosts and crt.sh certificate search.