Commands.page Logo

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

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 visudo

Step 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/command

For example, to prevent the user john from using the rm command:

john ALL=(ALL:ALL) ALL, !/usr/bin/rm

Step 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