2.5 Extracting Remote Certificates
When you connect to a remote secure server using s_client
, it will dump the server’s PEM-encoded certificate to standard output. If you need the certificate for any reason, you can copy it from the scroll-back buffer. If you know in advance you only want to retrieve the certificate, you can use this command line as a shortcut:
$ echo | openssl s_client -connect www.feistyduck.com:443 2>&1 | sed --quiet '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > feistyduck.crt
The purpose of the echo
command at the beginning is to separate your shell from s_client
. If you don’t do that, s_client
will wait for your input until the server times out (which may potentially take a very long time).
By default, s_client
will print only the leaf certificate; if you want to print the entire chain, give it the -showcerts
switch. With that switch enabled, the previous command line will place all the certificates in the same file.
$ echo | openssl s_client -showcerts -connect www.feistyduck.com:443 2>&1 | sed --quiet '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > feistyduck.chain
Another useful trick is to pipe the output of s_client
directly to the x509
tool. The following command shows detailed server information, along with its SHA256 fingerprint:
$ echo | openssl s_client -connect www.feistyduck.com:443 2>&1 | openssl x509 -noout -text -fingerprint -sha256
Sometimes you will need to take the certificate fingerprint and use it with other tools. Unfortunately, OpenSSL outputs certificates in a format that shows individual bytes and separates them using colons. This handy command line normalizes certificate fingerprints by removing the colons and converting the hexadecimal characters to lowercase:
$ echo | openssl s_client -connect www.feistyduck.com:443 2>&1 | openssl x509 -noout -fingerprint -sha256 | sed 's/://g' | tr '[:upper:]' '[:lower:]' | sed 's/sha256 fingerprint=//g'
Connecting to remote TLS servers and reviewing their certificates is a pretty common operation, but you shouldn’t spend your time remembering and typing these long commands. Instead, invest in writing a couple of shell functions that will package this functionality into easy-to-use commands.