how to download the ssl certificate from a website?

Solution 1:

In order to download the certificate, you need to use the client built into openssl like so:

echo -n | openssl s_client -connect HOST:PORTNUMBER \
    | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /tmp/$SERVERNAME.cert

That will save the certificate to /tmp/$SERVERNAME.cert.

You can use -showcerts if you want to download all the certificates in the chain. But if you just want to download the server certificate, there is no need to specify -showcerts

echo -n gives a response to the server, so that the connection is released

sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' removes information about the certificate chain and connection details. This is the preferred format to import the certificate into other keystores.

Solution 2:

I found the answer. Openssl provides it.

openssl s_client -connect ${REMHOST}:${REMPORT}


Solution 3:

The GNUTLS client tool, gnutls-cli, can also make this easy:

gnutls-cli --print-cert www.example.com \
        < /dev/null \
        > www.example.com.certs

The program is designed to provide an interactive client to the site, so you need to give it empty input (in this example, from /dev/null) to end the interactive session.


Solution 4:

true | openssl s_client -connect google.com:443 2>/dev/null | openssl x509

this mode of openssl expects stdin, so we provide it via true |, this connects to the server specified in the -connect parameter. 2>/dev/null silences errors (optional), we can pass the whole output into the x509 parser, specifying /dev/stdin to use the shell pipe as the input file. And that will output just the -----BEGIN CERTIFICATE----- to -----END CERTIFICATE----- portion of the s_client output. You can redirect that to a file by adding > google.com.pem to the end of the command.


As best I can tell, this does not verify the certificate chain, it only can tell you what ssl identity the end server provides.


Solution 5:

based on @bignose answer, here is a self-contained version that fits well in e.g. a chef recipe:

sudo apt-get install gnutls-bin 
gnutls-cli --print-cert myserver.com </dev/null| sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > myserver.crt
sudo cp myserver.crt /usr/local/share/ca-certificates/myserver.crt
sudo update-ca-certificates