Commands.page Logo

How to Restrict Sudo Access to Specific Commands in Ubuntu

Yes, you can restrict sudo access to specific commands in Ubuntu to enhance system security. This guide explains how to configure the sudoers file safely using the visudo command. You will learn how to grant users permission for only certain tasks while preventing full root access. This method ensures least privilege principles are maintained on your server or workstation.

To begin, you must edit the sudoers configuration file. Never open this file with a standard text editor like nano or vim directly, as a syntax error can lock you out of sudo access permanently. Instead, use the visudo command, which checks for syntax errors before saving changes. Open your terminal and run the following command:

sudo visudo

This opens the /etc/sudoers file in a safe environment. By default, you will see a line granting the root user full access. To restrict a specific user, you need to add a new line at the bottom of the file. The syntax follows a specific structure: the username, the host list, the user list, and the command list.

For example, if you want to allow a user named “john” to only restart the apache2 service and nothing else, you would add this line:

john ALL=(ALL) /usr/sbin/service apache2 restart

If you want to allow a user to run a specific script located in a secure directory, specify the absolute path to that script. Avoid using wildcards unless absolutely necessary, as they can introduce security vulnerabilities. For instance, to allow execution of only one specific backup script:

john ALL=(ALL) /opt/scripts/backup.sh

You can also allow a user to run multiple specific commands by separating them with commas. Ensure there are no spaces between the commands and the commas to prevent parsing errors. Here is an example allowing a user to update packages and restart a specific service:

john ALL=(ALL) /usr/bin/apt update, /usr/bin/apt upgrade, /usr/sbin/service nginx restart

After adding the necessary lines, save and exit the editor. If you are using the default nano editor within visudo, press Ctrl + O to write out the file and Ctrl + X to exit. Visudo will automatically check the syntax. If there is an error, it will warn you and allow you to correct it before quitting.

To verify that the restrictions are working, switch to the user account you configured. Attempt to run a command that was not granted permission. You should receive a message stating that the user is not allowed to run that command. Then, attempt to run one of the allowed commands. It should execute successfully after entering the user’s password. This confirms that sudo access is now limited to the specific commands you defined.