Skip to content

Instantly share code, notes, and snippets.

@AnthillBeetle
Last active March 6, 2017 22:18
Show Gist options
  • Save AnthillBeetle/1b097ddafd8904eb3a3372ba4e1c6d3e to your computer and use it in GitHub Desktop.
Save AnthillBeetle/1b097ddafd8904eb3a3372ba4e1c6d3e to your computer and use it in GitHub Desktop.
Remember first requested command for the SSH key and refuse to run if command changes.
#!/bin/bash
set -euo pipefail
if [[ $# -ne 1 ]] || [[ "$1" == '--help' ]]; then
cat >&2 <<'EOF'
Insert the following before a key in .ssh/authorized_keys:
command=".ssh/remember_command ID",no-agent-forwarding,no-port-forwarding,no-X11-forwarding,no-user-rc,no-pty
(On newer systems you can replace all these no-* options with single "restrict".)
Put this script into your ~/.ssh/ directory and make it executable.
It will remember the first requested command for the specified ID,
and refuse to execute any other command in the future.
EOF
exit 1
fi
if [[ -z "${SSH_ORIGINAL_COMMAND:-}" ]]; then
echo 'No command specified.' >&2
exit 1
fi
COMMAND_FILE=".ssh/forced-command_$1"
[[ -e "$COMMAND_FILE" ]] || printf "%s\n" "$SSH_ORIGINAL_COMMAND" > "$COMMAND_FILE"
SAVED_COMMAND=$(<"$COMMAND_FILE")
if [[ "$SSH_ORIGINAL_COMMAND" != "$SAVED_COMMAND" ]]; then
echo "Command has changed from \"$SAVED_COMMAND\" to \"$SSH_ORIGINAL_COMMAND\", refusing to execute." >&2
exit 2
fi
/bin/bash "$COMMAND_FILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment