In this post you will see how to restrict commands executed on a remote server accessed via ssh for a particular user. You can have multiple reasons to do this:
- you may want some accounts to be able to do some interactive stuff but not everything and access only some files and directories.
- you may want to use an ssh key without password (look at a previous article to setup ssh keys) to automate things like backup or version control but you don’t want to expose other commands
Restricting ssh remote session
One way to do it is to use rbash (restricted bash) as login shell for your remote user:
# chsh user -s /bin/rbash
This will restrict commands to be executed to the ones available in the command search paths and forbid to change directory using an absolute path (relative directory changes are still allowed). So to let your user access some files, you can create symlinks in his home directory and point his PATH variable to a restricted set of commands.
To setup the restricted environment, you need to change the path for the rbash users. For example you can do this in the /etc/profile file to allow only commands from the /usr/rbin directory:
if [ "$SHELL" = /bin/rbash ]; then PATH=/usr/rbin else # do the normal setup for other shells ... fi
and in the /usr/rbin directory you put the symlinks to the allowed commands.
Restricting ssh remote commands
One way to restrict non interactive commands is to use the command keyword in the authorized_keys file in the .ssh directory of your user like this:
command="/usr/bin/restricted-command",no-port-forwarding,\ no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa \ AAAAB3NzaC1yc2EA...cBYAwXd3L user@host
By the way, we restrict also other possibilities like forwarding.
The /usr/bin/restricted-command can be a simple shell script where you handle the SSH_ORIGINAL_COMMAND environment variable passed by ssh. This variable contains the arguments passed on the ssh command line. In the sample implementation bellow, you will check that only rsync is authorized and execute rsync with arguments passed or fail with an error code 1. Failure and success will be logged to syslog by the way.
#!/bin/sh set $SSH_ORIGINAL_COMMAND case "$1" in rsync) ;; *) logger -s -t restricted-command -- "Invalid command $@" exit 1 ;; esac logger -t restricted-command -- "Executing $@" exec "$@"
Of course, you can also check arguments if you want more control over what is requested, manipulate the arguments, add multiple authorized commands or do whatever you want in the script.
Let us know if you use other ways to restrict remote access via ssh !
Incoming search terms:
- ssh restrict commands
- rbash commands
- ssh remote command
- restrict ssh commands
- ssh restrict command
- rbash ssh
- ssh limit commands
- ssh allowed commands
- restricted ssh
- ssh key restrict commands