Skip to content

Instantly share code, notes, and snippets.

@hercynium
Last active August 29, 2015 14:12
Show Gist options
  • Save hercynium/7d3d22d7bc1d08baa38c to your computer and use it in GitHub Desktop.
Save hercynium/7d3d22d7bc1d08baa38c to your computer and use it in GitHub Desktop.
script to save SSL/TLS certs to files
#!/bin/bash
set -o errexit
set -o pipefail
set -o nounset
host="$1"
port="$2"
starttls_prot="${3:-}" # xmpp, smtp, pop3, imap, or ftp (optional)
openssl_args=( -showcerts -connect "$host:$port" )
[[ -n $starttls_prot ]] && openssl_args=( "${openssl_args[@]}" -starttls "$starttls_prot" )
openssl s_client "${openssl_args[@]}" < /dev/null | awk \
'
# from the beginning to the ending marker lines of a cert...
/^-----BEGIN CERTIFICATE-----$/,/^-----END CERTIFICATE-----$/ {
if ( ! cert_out_cmd ) {
# only print the warning when on the first line of the cert
if ( ! got_cert ) print "WARNING: found cert block but no cert name. Skipping."
}
else {
print | cert_out_cmd
}
got_cert = 1
# skip remaining rules in this script
next
}
# after the last line of a cert, clean up and reset for the next one
got_cert {
if ( cert_out_cmd ) {
close( cert_out_cmd )
cert_out_cmd = ""
print "Wrote cert file: " cert_file
}
got_cert = 0
}
# parse the "common name" out of the "subject" line before each cert
# and construct the command to write the cert to a file
/^[[:space:]]*[0-9]+ s:.*CN=/ {
cert_name = gensub( /.*CN=([^/]*).*/, "\\1", 1 )
cert_file = "\"" cert_name ".pem" "\""
cert_out_cmd = "openssl x509 -outform PEM -out " cert_file
}
'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment