Block interactive SSH sessions while allowing certain commands

How would one only allow certain commands to be run via SSH and block interactive sessions?

rsync.net does this as well as bakop.com.

I.e. this would work:

ssh <user@host> mkdir test
scp <file> <user@host>:test/

And this would not:

ssh <user@host>

You can take advantage of the ability to restrict the key to a particular command using the command= directive in authorized_keys and the SSH_ORIGINAL_COMMAND variable that gets passed to the remote system.

In the authorized_keys file change the line containing the relevant key from

ssh-rsa AAAAB3NzaC1yc...

to

command="/path/to/myscript" ssh-rsa AAAAB3NzaC1yc...

Then create the myscript file like for example

#!/bin/bash

if [  ! -n "$SSH_ORIGINAL_COMMAND" ]
then
    echo "No command supplied"
    exit 1
fi


set $SSH_ORIGINAL_COMMAND

case "$1" in
    ls)
      ;;
    md5)
      ;;
    *)
      echo "invalid command"
      exit 1
      ;;
esac

    exec "$@"

so now if you run ssh [email protected] ls /etc you'll get a listing of the remote /etc directory. You'll probably want to use the case statements to test the supplied parameters to meet whatever your implementation requirements are.


Rather than writing your own shell from scratch, you might want to extend this:

https://github.com/scponly/scponly/wiki

It provides a shell you can set as a user (i.e. usermod or directly in /etc/passwd) which only supports SCP. You'll want to extend this to a few select binaries of your choice, of which none should be an interactive shell (e.g. /bin/bash, /bin/sh). More carefully, they shoudn't be able to upload one (e.g. a busybox binary) and set the executable bit so they can drop in their own shell.


Use a different shell for that user - you may have to write your own if you have specific requirements, but you would need to take a lot of care! Many shells offer restricted operation already but they may not be restricted enough for you.

Scp can make directories though - so what else do you need to allow the user to do through interactive ssh?