How to restrict normal user to run only limited set of commands

  • Normal users in Linux are usually given permission to execute a certain command in /bin/ and /usr/local/bin. Follow the below steps to remove those permissions and restrict users to run only specific commands.
  • Enter the following command to generate a restricted shell.

cp /bin/bash /bin/rbash

  • Change the shell as a restricted shell while adding the target user.

useradd -s /bin/rbash user-restrict

  • For present users on the machine.

usermod -s /bin/rbash user-restrict

  • In this way, the user user-restrict is chrooted and will not be able to access the links outside his $HOME directory /home/user-restrict
  • Create a directory under /home/user-restrict as follows:
    mkdir /home/user-restrict/directory
  • At this point, the user user-restrict can access all commands that are allowed to execute. These commands are presented from environment PATH variable set in /home/user-restrict/.bash_profile. Change it as follows:

cat /home/user-restrict/.bash_profile
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
# User specific environment and startup programs
readonly PATH=$HOME/directory
export PATH

  • Now, if the user user-restrict log in, he/she will not be able to run even simple commands.
  • Now make softlinks of commands for user user-restrict to execute in the directory /home/user-restrict/directory

ln -s /bin/date /home/user-restrict/directory/
ln -s /bin/ls /home/user-restrict/directory/
ll /home/user-restrict/directory/
total 8
lrwxrwxrwx 1 root root 10 Aug 17 18:00 date -> /bin/date
lrwxrwxrwx 1 root root 10 Aug 17 18:00 ls -> /bin/ls

  • Logout and login again and execute the following commands

[user-restrict@example ~]$ date
Sun Aug 17 20:00:00 IST 2021
[user-restrict@example ~]$ ls
filea fileb filec filed directory
[user-restrict@example ~]$ tail
-rbash: tail: command not found

  • To restrict user user-restrict for making any modification in their .bash_profile.

chattr +i /home/user-restrict/.bash_profile

  • The above command will make the .bash_profile immutable. Only root will be able to remove the immutable flag from the file.

chattr -i /home/user-restrict/.bash_profile

Leave a Reply