Restrict Shell Commands Over SSH

Jan 16, 2024

When you have a GNU/Linux server, and you need to create accounts to allow users to access the server over SSH, it can be a good idea to restrict the commands they can execute.

To restrict commands, you can filter them using a script/program invoked when the user sends a command to the server. This can be done using the option command in the file ~/.ssh/authorized_keys or the parameter ForceCommand in sshd_config file. A good filter is the restricted-ssh-commands.

The restricted-ssh-commands is a bash script that reads the allowed commands from a file. In each file line, you specify an allowed command using regular expressions. If the regex matches, the user command will be executed. It’s easy for this to go wrong, and an unexpected command can be executed. To mitigate this, I created a simple solution that uses restricted-ssh-commands and rbash. Using it, the user cannot execute any commands outside a predefined PATH, in addition to having all available rbash restrictions.

Steps to implement it:

Step 1) Configure SSH server

Edit your sshd_config file and add:

ForceCommand "/usr/local/bin/my-res-bash"

Step 2) Create the file my-res-bash

#!/bin/sh

export PATH=/res-bash-path

if [ -n "$SSH_ORIGINAL_COMMAND" ]; then
    SHELL=rbash /usr/lib/restricted-ssh-commands res-bash
else
    SSH_SHELL=no

    if [ "$SSH_SHELL" = "yes" ]; then
        exec rbash -i
    else
        echo "SSH shell disabled."
    fi
fi
chmod +x /usr/local/bin/my-res-bash

ATTENTION: If you set SSH_SHELL to yes, the users will have an interactive shell, and the rules of restricted-ssh-commands will not work, so the programs in the defined PATH can be executed with any arguments.

mkdir /res-bash-path
ln -s /usr/bin/rbash /res-bash-path
ln -s /usr/bin/logger /res-bash-path
(Link other commands that the users will need.)

Step 4) Install restricted-ssh-commands

If you use a Debian based OS:

apt install restricted-ssh-commands

Last Step) Create the restricted-ssh-commands config

nano /etc/restricted-ssh-commands/res-bash
(Add the regexs of your allowed commands. Below two examples.)
^whoami$
^mkdir /mnt/bkp/[-0-9a-zA-Z+~_./çÇãÃéÉíÍóÓàÀêÊ]+$
shell-scriptSSH

Back to talau's home