Limiting the commands a user can run over SSH

As a system administrator, my goal is to allow only a predefined set of commands to be run on an SSH server. How can I do this in AlmaLinux / CentOS / Rocky Linux?

Thanks.

Hi,

The ForceCommand directive can be used to intercept and filter commands sent by the SSH client by examining the $SSH_ORIGINAL_COMMAND variable.

However, since ForceCommand runs through the user’s shell, a savvy user could manipulate their ~/.bashrc file to bypass the filtering before it takes effect making this approach insecure on its own.

A more reliable workaround is to handle command filtering inside the /etc/ssh/sshrc script, while ensuring the user cannot create their own ~/.ssh/rc file, which would otherwise take priority over the system-wide script.

In the following example, we will configure the environment to meet these specific conditions:

  • (A1) The root and admin users should have no command restrictions applied
  • (A2) All other users must be limited to running only /usr/local/bin/foo and /usr/local/bin/bar
  • (A3) X11 Forwarding must remain fully functional throughout

Create /etc/ssh/sshrc file

(A1) Create whitelist filter

#
# Whitelist Filter for specific users that should not be restricted
#
if id -un | grep -Eqw "(root|admin)"; then exit 0; fi

(A2) Create filtering for all other users

if [[ $SSH_ORIGINAL_COMMAND == "/usr/local/bin/foo "* ]]; then
    :
elif [[ $SSH_ORIGINAL_COMMAND == "/usr/local/bin/bar "* ]]; then
    :
else
   echo "this server rejects interactive ssh usage" >&2
   kill $PPID
fi

(A3) Create block for X11 forwarding

#
# This block below allows X11 forwarding
#
if read proto cookie && [ -n "$DISPLAY" ]; then
  if [ `echo $DISPLAY | cut -c1-10` = 'localhost:' ]; then
    # X11UseLocalhost=yes
    echo add unix:`echo $DISPLAY |
    cut -c11-` $proto $cookie
  else
    # X11UseLocalhost=no
    echo add $DISPLAY $proto $cookie
  fi | xauth -q -
fi

Make the script executable

# chmod 555 /etc/ssh/sshrc

Modify /etc/ssh/sshd_config configuration file

# Refer to KCS https://access.redhat.com/solutions/7049352

# Disallow users to execute their own ~/.ssh/rc file
PermitUserRC no

# Let the original command execute, unless it got blacklisted through /etc/ssh/sshrc execution
ForceCommand /bin/sh -c "[ -n \"\$SSH_ORIGINAL_COMMAND\" ] && exec \$SSH_ORIGINAL_COMMMAND || exec \$SHELL"

Reload the sshd service

# systemctl reload sshd

In the following example, we will configure the environment to block all users except root and admin from using the sftp and scp commands.
Follow the same procedure outlined above, but replace step (A2) with the excerpt below:

set -- $SSH_ORIGINAL_COMMAND
if [[ $1 == *scp ]] || [[ $1 == *sftp-server ]]; then
    logger "$(id -un): Command '$SSH_ORIGINAL_COMMAND' prohibited"
    kill $PPID
fi