Skip to content

Instantly share code, notes, and snippets.

@morawskim
Created June 28, 2015 09:13
Show Gist options
  • Save morawskim/6c9eeb09ad9e4ad6f6e8 to your computer and use it in GitHub Desktop.
Save morawskim/6c9eeb09ad9e4ad6f6e8 to your computer and use it in GitHub Desktop.
Extract x509 cert
#!/bin/sh
#Shell script to extract x509 certificate
#Author: Marcin Morawski <marcin@morawskim.pl>
#Exit immediately if a command exits with a non-zero status.
set -e
#Avoid accidental overwriting of a file
set -o noclobber
#Bin paths, change if these programs are not stored in paths of PATH environment variable
OPENSSL=$(which openssl)
SED=$(which sed)
AWK=$(which awk)
TR=$(which tr)
BASENAME=$(which basename)
if [ $# -eq 0 ]; then
echo 'Usage: ' `$BASENAME $0` ' host:port ' '[outputfile]' >&2
exit 1
fi;
HOST="$1"
if [ -z $2 ]; then
OUTPUT=$(echo $HOST | "$TR" ':/' ':' | "$AWK" -F ':' '{print $1}')
OUTPUT="$OUTPUT.crt"
else
OUTPUT="$2"
fi
#disable temporarily exit on error. We want display openssl error message
set +e
OPENSSL_OUTPUT=$($OPENSSL s_client -connect $HOST 2>&1 </dev/null)
if [ $? -ne 0 ]; then
echo 'openssl failed' >&2
echo "$OPENSSL_OUTPUT"
exit 1
fi
#enable again auto exit on command failure
set -e
echo "$OPENSSL_OUTPUT" | $SED -ne '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/p' > $OUTPUT
@morawskim
Copy link
Author

usage:

extract_x509_cert.sh ip|dnsName:Port

eg.

extract_x509_cert.sh google.com:443

This script create file named google.com.crt in working directory.

You can specify path, where save cert by second argument.
eg.

extract_x509_cert.sh google.com:443 ~/google.crt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment