Limiting sudo Access with the sudoers File
In this step, you will learn how to restrict a user's sudo privileges to specific commands using the sudoers file. This implements the principle of least privilege, which states that users should only have the minimum privileges necessary to perform their tasks.
Understanding the sudoers File
The /etc/sudoers file controls who can use the sudo command and what commands they can run. This file should never be edited directly with a regular text editor, as syntax errors could lock you out of the system. Instead, always use the visudo command, which checks for syntax errors before saving.
Editing the sudoers File
To edit the sudoers file safely, use the visudo command:
sudo visudo
This will open the sudoers file in the default editor (usually nano or vi).
Understanding sudoers Syntax
The basic syntax for a sudo entry in the sudoers file is:
user_or_group host=(run_as_user:run_as_group) NOPASSWD: commands
Where:
user_or_group: The user or group this rule applies to
host: The hostname where this rule applies (usually ALL)
run_as_user: The user that commands will be executed as (usually ALL, meaning root)
run_as_group: The group that commands will be executed as (can be omitted)
NOPASSWD: Optional tag that allows commands to be run without entering a password
commands: The specific commands that can be executed with sudo
Adding Restricted sudo Access
Scroll to the end of the file and add the following line to grant trusted_advisor permissions to run only the cp and mv commands without password:
trusted_advisor ALL=(ALL) NOPASSWD: /bin/cp, /bin/mv
To save the file in nano, press Ctrl+O, then Enter, and to exit, press Ctrl+X.
Testing the Restricted sudo Access
Now let's test if the restricted sudo access works as expected. First, let's create a test file in the current directory:
echo "This is a test file" > important_file.txt
Now, switch to the trusted_advisor user:
su - trusted_advisor
Enter the password when prompted.
Try copying the file to the root directory, which should be allowed:
sudo cp /home/labex/project/important_file.txt /root/
This should succeed without asking for a password.
Now, try to run a command that is not in the allowed list, such as cat:
sudo cat /root/important_file.txt
You should get a permission denied error because cat is not in the allowed list of commands.
Finally, verify that the file was copied to the root directory:
sudo ls /root/
You should see important_file.txt in the output.
Exit the trusted_advisor user session:
exit
Removing the Test File
To clean up, remove the test file:
sudo rm important_file.txt