Skip to content

Instantly share code, notes, and snippets.

@morawskim
Created March 9, 2024 10:39
Show Gist options
  • Save morawskim/b53c0addae9a8ce59cbb82565ce0f290 to your computer and use it in GitHub Desktop.
Save morawskim/b53c0addae9a8ce59cbb82565ce0f290 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment