Skip to content

Instantly share code, notes, and snippets.

@hongkongkiwi
Last active October 3, 2023 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hongkongkiwi/28139e3dfc24051f1bb7f77b182334a7 to your computer and use it in GitHub Desktop.
Save hongkongkiwi/28139e3dfc24051f1bb7f77b182334a7 to your computer and use it in GitHub Desktop.
Shell script to validate all authorized_keys in one or more files or all files in a directory
#!/bin/sh -ue
REMOVE_COMMENTS_SED='/^[[:blank:]]*(#|$)/d; s/#.*//'
SSH_KEYGEN_BIN="ssh-keygen"
if ! command -v "$SSH_KEYGEN_BIN" >/dev/null 2>&1; then
echo >&2 "I require $SSH_KEYGEN_BIN but it's not installed. Aborting."; exit 255
fi
# Assume all keys are valid until told otherwise
ALL_KEYS_VALID="yes"
if [ -z "$@" ]; then
echo >&2 "ERROR: must pass authorized_keys file or override directory"; exit 255
fi
# Loop through every file or directory passed
for AUTHORIZED_KEYS_FILE_OR_DIR in $@; do
if [ ! -f "$AUTHORIZED_KEYS_FILE_OR_DIR" -a ! -d "$AUTHORIZED_KEYS_FILE_OR_DIR" ]; then
echo >&2 "ERROR: invalid file or directory: $AUTHORIZED_KEYS_FILE_OR_DIR"; exit 255
fi
if [ -f "$AUTHORIZED_KEYS_FILE_OR_DIR" ]; then
# Remove comments of file and loop through each line
while read -r KEY; do
# Ignore blank lines
[ -n "$KEY" ] || continue
# Check each key individually
if ! echo "$KEY" | "$SSH_KEYGEN_BIN" -l -f /dev/stdin 2>1 >/dev/null; then
# Format file so it looks better when being printed
echo >&2 "ERROR: invalid key in file \"$AUTHORIZED_KEYS_FILE_OR_DIR\": $KEY"
ALL_KEYS_VALID="no"
fi
done <<<"$(sed -E "$REMOVE_COMMENTS_SED" "$AUTHORIZED_KEYS_FILE_OR_DIR")"
else
# Treat authorized_keys file as directory
cd "$AUTHORIZED_KEYS_FILE_OR_DIR"
# Loop through all files in directory
while read -r FILE; do
# Remove comments of file and loop through each line
while read -r KEY; do
# Ignore blank lines
[ -n "$KEY" ] || continue
# Check each key individually
if ! echo "$KEY" | "$SSH_KEYGEN_BIN" -l -f /dev/stdin 2>1 >/dev/null; then
# Format file so it looks better when being printed
echo >&2 "ERROR: invalid key in file \"$AUTHORIZED_KEYS_FILE_OR_DIR/$FILE\": $KEY"
ALL_KEYS_VALID="no"
fi
done <<<"$(sed -E "$REMOVE_COMMENTS_SED" "$FILE")"
done <<<"$(find * -type f -maxdepth 1)"
fi
done
if [ "$ALL_KEYS_VALID" == "yes" ]; then
exit 0
else
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment