Last Updated: February 25, 2016
· destructuring

Restrict commands under an ssh key

To restrict commands run under an ssh key (unless you like giving shell access to batch jobs) amend the ssh key in authorized_keys so it runs a restrictive wrapper (let's call this script restrict-ssh):

no-port-forwarding,no-X11-forwarding,no-pty,command="/usr/local/bin/restrict-ssh" ssh-rsa ....

It's neat you can turn off forwarding and the tty. I usually run the script with a shebang that turns on bash restrictions:

#!/bin/bash -fue

This disables file globbing, dies on unknown variables, and dies on error codes.

Whenever this key is used , restrict-ssh is run with two environment variables: SSHCLIENT (IP address), SSHORIGINAL_COMMAND (the command and arguments to be run).

Here's an example to limit execution to scp and rsync:

#!/bin/bash -fue
cmd="$1"; shift
case "$cmd" in
  scp|rsync) exec "$cmd" "$@" ;;
          *) echo "ERROR: request not permitted" ;;

You can add as much error checking, inputs validation as you need.

I don't know how secure this is. It's one of my quests to find out.