Monday, June 1, 2020

How to deny execution permission on your shell script for non-root users and sudo privileged users on Linux server.


When you do not want other users to run the script but only root user to run it, you can secure the script the in the below way.

This method will also deny the run permission for users with full sudo access as well.

ddd

 [root@kubernetesmaster]# cat only_root.sh
 #!/bin/bash

 if (( $(id -u) != 0 ))
 then
   echo "$0: This script must be run as root"
   exit 1
 fi

 if [ "$0" = "${SUDO_COMMAND%% *}" ]
 then
   echo "$0: This script should not be executed with sudo privileges"
   exit 1
 fi

 echo "Running the script as ROOT user."


 Running the script as root user will give you the results
 [root@kubernetesmaster]#./only_root.sh
 Running the script as ROOT user.

 To show the permission restriction for sudo privileged users, a testuser account is created with full sudo access.
 [root@kubernetesmaster]# grep -i testuser /etc/sudoers
 testuser ALL=(ALL) NOPASSWD:ALL

 When a testuser run the script it will show an error message.
 [testuser@kubernetesmaster]# ./tmp/only_root.sh
./tmp/only_root.sh: This script must be run as root

 Testuser tried to run the script with his sudo privileges but he is still not able to run the script.   Only root user can run the script and others are not allowed.
 [testuser@kubernetesmaster]#sudo /tmp/only_root.sh
 /tmp/only_root.sh: This script should not be executed with sudo privileges