Download a sites certificates with openssl

The following snippet can be used to download all the CA certificates from a site, into seperate .crt files. The file name will be the last CN part from the issued information.

openssl s_client -connect $SITE:443 -showcerts \
        </dev/null 2>/dev/null | \
	awk '/^ [0-9] s:/,/^[-]+END CERTIFICATE/' | \
	csplit -q -z -f cert - '/^ [0-9] s:/' '{*}'
for file in cert*; do \
	name="$(awk -F= '/^ [0-9] s:/ {gsub(/[^A-Za-z0-9.]/, "", $NF); print $NF".crt"}' "${file}")"; \
	awk '/^[-]+BEGIN CERTIFICATE/,/^[-]+END CERTIFICATE/' "${file}" > "${name}"; \
	rm "${file}"; \
done

Example, if running the above with SITE=blog.mgor.net:

↳ openssl s_client -connect $SITE:443 -showcerts         </dev/null 2>/dev/null | awk '/^ [0-9] s:/'
 0 s:/CN=blog.mgor.net
 1 s:/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3

Two certificate files will be created:

↳ ls *.crt
blog.mgor.net.crt  LetsEncryptAuthorityX3.crt