Restricting SSH access to specific commands

Create usual user on destination server. Make sure it have no password and no expiration set (hint: look into /etc/shadow). This disable remote login using password authentication schema. Check that root can do "su" to it.

Prepare authorized_keys makes magic:

# su - sshruser
$ mkdir -m700 .ssh
$ cat > .ssh/authorized_keys << EOF
#
# This user is restricted to run some commands only.
# using "command" parameter mandatory. This also disallow sftp/scp.
#
command="/usr/local/bin/0000 $SSH_ORIGINAL_COMMAND" ssh-rsa AAAAB3NzaC1yc2EAAAAB
wAAAIEA14L/6GyIiK1AeOiyPTkYmZvl1q4aSvuiA7Wsn7oKL8AUQsiaov8Xu6oVx6WOr1Zsp9Ii3C+ry
J4BZY87++tUgkQFvpf3FiXHFV+q2dYTdIocYC4+MdZYRNgwG+hyzsSN61pZ08PgTPJIVJGqO2Z22xE2Z
elGO+fQfmn0TCJSE= remoteuser@remoteserver
EOF
$

As you see, the SSH public key prepended with command directive. Lets prepare /usr/local/bin/0000 script:

# cat > /usr/local/bin/0000 << EOF
#!/bin/sh

# Log full command
echo "$0" "$@" | logger -t remssh

# Strip previous "sudo -u appuser" :
while [ 'x'"$1" != "xALLOWED-COMMAND" ] ; do
        shift || break
done

[ 'x'"$1" = 'x' ] && { echo "Not allowed command" ; exit 1 ; }

# Additional security level sat by sudo:
sudo -u appuser $(echo $@ | sed -e 's/"//g' )
EOF
# chmod +x /usr/local/bin/0000

Checking

Not suprise, that ALLOWED-COMMAND works; let's see other tries:

$ ssh sshruser@sshserver id
Not allowed command
$ sftp sshruser@sshserver   
Connecting to sshserver...
Received message too long 1315927072
$ scp /bin/bash sshruser@sshserver:/tmp/
Not allowed command

If this was helpfull, please donate
Updated on Thu Sep 13 11:20:19 IDT 2012 by Oleg Volkov More documentations here