Created
July 18, 2019 13:49
-
-
Save jpralves/4da93d4ffb03419c5365cda1b4e06089 to your computer and use it in GitHub Desktop.
check expiration of certificates of Java KeyStore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
######################################################## | |
# | |
# Check certificates inside a java keystore | |
# | |
######################################################## | |
KEYTOOL="keytool" | |
THRESHOLD_IN_DAYS="30" | |
KEYSTORE="" | |
RET=0 | |
ARGS=$(getopt -o "k:t:w" -l "keystore:,threshold:,warnings" -n "$0" -- "$@") | |
usage() { | |
echo "Usage: $0 --keystore <keystore> [--threshold <number of days until expiry>] [--warnings]" | |
exit | |
} | |
start() { | |
CURRENT=$(date +%s) | |
: $(( THRESHOLD=CURRENT + (THRESHOLD_IN_DAYS*24*60*60) )) | |
if [ "$THRESHOLD" -le "$CURRENT" ]; then | |
echo "[ERROR] Invalid date." | |
exit 1 | |
fi | |
if [ -z "$ONLY_WARNINGS" ]; then | |
echo "Looking for certificates inside the keystore $(basename $KEYSTORE) expiring in $THRESHOLD_IN_DAYS day(s)..." | |
fi | |
if ! echo | $KEYTOOL -list -v -keystore "$KEYSTORE" >/dev/null 2>&1; then | |
echo "Error opening the keystore." | |
exit 1 | |
fi | |
echo | $KEYTOOL -list -v -keystore "$KEYSTORE" 2>/dev/null | grep Alias | sed 's/^Alias name: //' | while read ALIAS | |
do | |
#Iterate through all the certificate alias | |
EXPIRACY=$(echo | $KEYTOOL -list -v -keystore "$KEYSTORE" -alias "$ALIAS" 2>/dev/null | grep Valid) | |
UNTIL=$(echo "$EXPIRACY" | perl -ne 'if(/until: (.*?)\n/) { print "$1\n"; }') | |
UNTIL_SECONDS=$(date -d "$UNTIL" +%s) | |
: $(( REMAINING_DAYS=(UNTIL_SECONDS - $(date +%s)) / 60 / 60 / 24 )) | |
if [ -z "$ONLY_WARNINGS" ]; then | |
if [ "$THRESHOLD" -le "$UNTIL_SECONDS" ]; then | |
echo "[OK] Certificate $ALIAS expires in '$UNTIL' ($REMAINING_DAYS day(s) remaining)." | |
else | |
echo "[WARNING] Certificate $ALIAS expires in '$UNTIL' ($REMAINING_DAYS day(s) remaining)." | |
RET=1 | |
fi | |
else | |
if [ "$THRESHOLD" -gt "$UNTIL_SECONDS" ]; then | |
echo "$ALIAS" | |
RET=1 | |
fi | |
fi | |
done | |
if [ -z "$ONLY_WARNINGS" ]; then | |
echo "Finished..." | |
fi | |
exit $RET | |
} | |
eval set -- "$ARGS" | |
while true; do | |
case "$1" in | |
-w|--warnings) | |
ONLY_WARNINGS=1 | |
shift ;; | |
-k|--keystore) | |
if [ ! -f "$2" ]; then echo "Keystore not found: $1"; exit 1; else KEYSTORE=$2; fi | |
shift 2;; | |
-t|--threshold) | |
if [ -n "${2##*[!0-9]*}" ]; then THRESHOLD_IN_DAYS=$2; else echo "Invalid threshold"; exit 1; fi | |
shift 2;; | |
--) | |
shift | |
break;; | |
esac | |
done | |
if [ -n "$KEYSTORE" ] | |
then | |
start | |
else | |
usage | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment