How to Deny Sudo Access to Specific Command in Ubuntu
Managing user privileges is essential for maintaining a secure Ubuntu environment. This article outlines the process of restricting sudo permissions for specific executables while retaining general administrative rights. You will learn how to safely edit the sudoers configuration file to blacklist dangerous commands for specific users without affecting their ability to perform other system tasks.
Prerequisites
- You must have root access or an existing sudo user account.
- You need to know the full path of the command you wish to block.
Step 1: Open the Sudoers File
Never edit the /etc/sudoers file directly with a
standard text editor, as syntax errors can lock you out of sudo access.
Instead, use the visudo command, which checks for syntax
errors before saving.
Open your terminal and run:
sudo visudoStep 2: Add the Denial Rule
Scroll to the bottom of the file. You need to add a rule specifically
for the user you wish to restrict. The syntax requires the username, the
host, the user group, and the command list with an exclusion operator
(!).
Add the following line, replacing username and
/path/to/command with your actual data:
username ALL=(ALL:ALL) ALL, !/path/to/commandFor example, to prevent the user john from using the
rm command:
john ALL=(ALL:ALL) ALL, !/usr/bin/rmStep 3: Ensure Rule Order
In the sudoers file, the last matching rule takes precedence. If the
user is part of the sudo group, there is likely a line like
%sudo ALL=(ALL:ALL) ALL earlier in the file. Ensure your
new user-specific rule appears after the group rule to
guarantee the denial overrides the general permission.
Step 4: Save and Exit
If you are using the default nano editor within visudo:
1. Press Ctrl + O to save. 2. Press Enter to
confirm the filename. 3. Press Ctrl + X to exit.
If visudo detects a syntax error, it will warn you and ask if you want to save anyway. Always choose to edit again to fix the error.
Step 5: Verify the Restriction
Switch to the restricted user account or use su to test
the configuration. Attempt to run the blocked command with sudo. You
should receive a permission denied error. Then, run a different allowed
command to ensure general sudo access remains intact.
Important Notes
- Full Paths: You must use the absolute path to the
command (e.g.,
/usr/bin/apt), not just the command name. Usewhich commandto find the path. - Multiple Commands: To deny multiple commands,
separate them with commas and exclamation marks (e.g.,
!, /bin/cmd1, !/bin/cmd2). - Security: Do not deny access to
visudoorsudoitself, as this may prevent you from fixing configuration errors later.