Skip to content

Instantly share code, notes, and snippets.

@mkg20001
Last active July 8, 2018 10:14
Show Gist options
  • Save mkg20001/680460d6aef181031891fc9cac5e94e7 to your computer and use it in GitHub Desktop.
Save mkg20001/680460d6aef181031891fc9cac5e94e7 to your computer and use it in GitHub Desktop.
A script useful for cleaning up an old certificate archive. Removes orphan keys, ca certs and expired certs.
#!/bin/bash
# A script useful for cleaning up an old certificate archive. Removes orphan keys, ca certs and expired certs.
dir="$(readlink -f $1)"
CLEANUP=false # Enable this AFTER YOU CHECKED IT WORKS! (make backups)
[ -z "$dir" ] && exit 2
cd "$dir"
keys=()
declare -A hashes
declare -A used
hashpubkey() {
openssl x509 -pubkey -noout -in "$1" | openssl "$2" -in /dev/stdin -pubin -outform der 2> /dev/null | openssl dgst -sha256 | grep -o "= .*" | sed "s|= ||g"
}
hashkey() {
openssl "$2" -in "$1" -pubout -outform der 2> /dev/null | openssl dgst -sha256 | grep -o "= .*" | sed "s|= ||g"
}
$CLEANUP && find . -type l -delete -print | sed "s|^|Removed link: |g"
for f in $(find . -type f); do
echo -n "$f: "
del=false
if grep "^-----BEGIN CERTIFICATE REQUEST-----" "$f" > /dev/null; then
echo -n "CSR"
del=true
elif grep "^-----BEGIN CERTIFICATE-----" "$f" > /dev/null; then
echo -n "CERT, "
if openssl x509 -in "$f" -noout -purpose | grep "CRL signing : Yes" > /dev/null; then
echo -n "CA"
del=true
else
if ! openssl x509 -checkend 86400 -noout -in "$f"; then
echo -n "expired"
del=true
else
if openssl x509 -in "$f" -text -noout | grep id-ecPublicKey > /dev/null; then
hash=$(hashpubkey "$f" "ec")
else
hash=$(hashpubkey "$f" "rsa")
fi
used+=(["$hash"]="$f")
echo -n "valid $(openssl x509 -enddate -noout -in $f), keyhash $hash"
fi
fi
elif grep "^-----BEGIN RSA PRIVATE KEY-----" "$f" > /dev/null; then
hash=$(hashkey "$f" "rsa")
echo -n "KEY, rsa, $hash"
keys+=("$f")
hashes+=(["$f"]="$hash")
elif grep "^-----BEGIN EC PRIVATE KEY-----" "$f" > /dev/null; then
hash=$(hashkey "$f" "ec")
echo -n "KEY, ec, $hash"
keys+=("$f")
hashes+=(["$f"]="$hash")
else
mt=$(file -b --mime $f)
echo -n "UNKNOWN, mime=$mt"
if [[ "$mt" == "inode/x-empty"* ]]; then
del=true
fi
fi
echo
$CLEANUP && $del && rm -v "$f"
done
for key in "${keys[@]}"; do
hash="${hashes[${key}]}"
inuse="${used[${hash}]}"
echo -n "KEY $key is "
if [ -z "$inuse" ]; then
echo "ORPHAN"
$CLEANUP && rm -v "$key"
else
echo "associated with CERT $inuse"
fi
done
echo "DONE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment