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
elGO+fQfmn0TCJSE= remoteuser@remoteserver

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

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

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

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

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

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


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

Restricting SSH for SFTP only

Clone SSH service that will use another, its own sshd_config. Example of mine:

# egrep -v "^$|^#" /etc/ssh/sshd_sftp_config
Port 1234
PermitRootLogin no
AuthorizedKeysFile      .ssh/authorized_keys
PasswordAuthentication no
UsePAM yes
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no
UsePrivilegeSeparation sandbox          # Default for new installations.
ChrootDirectory /srv/www/https/%u
Subsystem       sftp    internal-sftp
ForceCommand internal-sftp -u 002

Create user without password and withot login shell:

# grep voleg /etc/passwd

Paste SSH public key into his .ssh/authorized_keys file and care about ownership and permissions. Checking:

$ ssh -p 1234 sftp-server
X11 forwarding request failed on channel 0
This service allows sftp connections only.
Connection to sftp-server closed.
$ scp -P 1234 sftp-server:/etc/passwd /tmp/
protocol error: mtime.sec not present
$ scp -P 1234 /etc/passwd sftp-server:/tmp/
This service allows sftp connections only.
$ sftp -P 1234 sftp-server
Connected to sftp-server.
sftp> pwd
Remote working directory: /
sftp> ls
sftp> bye

Updated on Thu Sep 13 11:20:19 IDT 2012 More documentations here