Something like:
openssl s_client -servername remote.server.net -connect remote.server.net:443 </dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' >/path/to/certificate.pem
That's what I use with fetchmail to retrieve the certificate of an SSL capable IMAP or POP3 server (except obviously I don't use port 443)
(Note that "redundant" -servername
parameter is necessary to make openssl
do a request with SNI support.)
Is it possible that the lines are ^M-terminated? This is a potential issue when moving files from Windows to UNIX systems. One easy way to check is to use vi
in "show me the binary" mode, with vi -b /etc/apache2/domain.ssl/domain.ssl.crt/domain.com.crt
.
If each line ends with a control-M, like this
-----BEGIN CERTIFICATE-----^M
MIIDITCCAoqgAwIBAgIQL9+89q6RUm0PmqPfQDQ+mjANBgkqhkiG9w0BAQUFADBM^M
MQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhhd3RlIENvbnN1bHRpbmcgKFB0eSkg^M
THRkLjEWMBQGA1UEAxMNVGhhd3RlIFNHQyBDQTAeFw0wOTEyMTgwMDAwMDBaFw0x^M
you've got a file in Windows line-terminated format, and apache doesn't love those.
Your options include moving the file over again, taking more care; or using the dos2unix
command to strip those out; you can also remove them inside vi, if you're careful.
Edit: thanks to @dave_thompson_085, who points out that this answer no longer applies in 2019. That is, Apache/OpenSSL are now tolerant of ^M-terminated lines, so they don't cause problems. That said, other formatting errors, several different examples of which appear in the comments, can still cause problems; check carefully for these if the certificate has been moved across systems.
Best Answer
In order to download the certificate, you need to use the client built into openssl like so:
That will save the certificate to
/tmp/$SERVERNAME.cert
.The
-servername
is used to select the correct certificate when multiple are presented, in the case of SNI.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
. Thex509
at the end will strip out the intermediate certs, you will need to usesed -n '/-----BEGIN/,/-----END/p'
instead of the x509 at the end.echo -n
gives a response to the server, so that the connection is releasedopenssl x509
removes information about the certificate chain and connection details. This is the preferred format to import the certificate into other keystores.