Skip to content

Instantly share code, notes, and snippets.

@jsleeio
Created October 20, 2018 08:29
Show Gist options
  • Save jsleeio/9e0f068547ebb43f8361056834599386 to your computer and use it in GitHub Desktop.
Save jsleeio/9e0f068547ebb43f8361056834599386 to your computer and use it in GitHub Desktop.
shell script to rip apart CA certificate bundles for inspection/mangling
#!/usr/bin/env ksh
# intended for ripping apart CA certificate bundles
set -e -u
_usage() {
echo "usage: $0 [-a MODE] inputfile.pem"
echo ""
echo "Available modes are:"
echo " cat Default mode. Just emits certificates to stdout."
echo " decode Decode certificates like 'openssl x509 -text' and print to terminal"
echo " decode-save Decode certificates like 'openssl x509 -text' and save to files in CWD"
echo " save Save encoded certificates to files in CWD"
echo ""
echo "Files saved will have the certificate fingerprint in the filename."
echo "(as per: openssl x509 -fingerprint -noout -in cert.pem)"
exit 1
}
_die() {
echo "fatal: $0: $*" >&2
exit 1
}
_fingerprint() {
echo "$1" | openssl x509 -noout -fingerprint | sed 's/.*=//; s/://g' | tr '[:upper:]' '[:lower:]'
}
_invoke() {
_fingerprint=$(_fingerprint "$2")
case "$1" in
cat)
echo "$2"
;;
decode)
echo "$2" | openssl x509 -noout -text
;;
decode-save)
echo "$2" | openssl x509 -noout -text > "$_fingerprint.decoded.txt"
;;
save)
echo "$2" > "$_fingerprint.pem"
;;
*) _die "invalid mode: $_mode" ;;
esac
}
_mode="cat"
_invoke=0
while getopts "a:hi" c; do
case "$c" in
a) _mode=$OPTARG ;;
h) _usage ;;
i) _invoke=1 ;;
*) _usage ;;
esac
done
shift $((OPTIND-1))
if [ -z "$1" ] && [ "$_invoke" = "0" ] ; then
# if the parent invocation, a filename must be supplied
_usage
fi
if [ "$_invoke" = 0 ] ; then
# we are the parent process, split the input up and re-invoke ourselves
awk ' /^[-]+BEGIN CERTIFICATE[-]+$/ { incert = 1 }
/^[-]+END CERTIFICATE[-]+$/ { print ; printf("%c",0); incert = 0 }
incert == 1 { print }' "$1" \
| xargs -n1 -0 -- "$0" -i -a "$_mode" --
else
# we are not the parent process
_invoke "$_mode" "$1"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment