Skip to content

Instantly share code, notes, and snippets.

@warewolf
Last active May 3, 2018 19:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save warewolf/4b56374b99de6466d68e68ea820be91c to your computer and use it in GitHub Desktop.
Save warewolf/4b56374b99de6466d68e68ea820be91c to your computer and use it in GitHub Desktop.
Guard your SSH keys with this forced command
#!/usr/bin/env bash
# Usage:
#
# place into ~/.ssh/authorized_keys:
# command="/path/to/guardian.sh LOCAL_HOSTNAME PERMITTED_IP_PREFIXES,SEPARATED_BY,COMMAS" ssh-rsa A...
#
# Forced command variant
# command="COMMAND='/usr/bin/rsync -Pavz --server here there' /path/to/guardian.sh LOCAL_HOSTNAME PERMITTED_IP_PREFIXES,SEPARATED_BY,COMMAS" ssh-rsa A...
RESTRICT_HOST=$1
RESTRICT_SOURCE=$2
if [[ "$RESTRICT_HOST" != "$HOSTNAME" ]]; then
echo "Access to $HOSTNAME from $CLIENT_IP unauthorized."
fi
IFS="," read -r -a ALLOWED_IPS <<< $RESTRICT_SOURCE
CLIENT_IP=${SSH_CLIENT// */}
ALLOW=0
for ALLOW in ${ALLOWED_IPS[@]}; do
if [[ "$CLIENT_IP" =~ "$ALLOW" ]]; then
ALLOW=1; break;
fi
done
if [[ "$ALLOW" == "1" ]]; then
if [[ -z "$COMMAND" && -n "$SSH_ORIGINAL_COMMAND" ]]; then
# exec bash -c "original command" fixes stuff like MOSH
exec bash -c "$SSH_ORIGINAL_COMMAND"
elif [[ -z "$COMMAND" && -z "$SSH_ORIGINAL_COMMAND" ]]; then
unset SHLVL # fixes $SHLVL in sub-shells, and exec -l makes the shell a login shell
exec -l $SHELL
elif [[ -n "$COMMAND" ]]; then
exec $COMMAND
fi
else
echo "Access to $HOSTNAME from $CLIENT_IP unauthorized."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment