In this guide, we will tackle a common task system administrators face when managing users and permissions on Linux servers environment. For the purposes of this tutorial we have tested all commands/steps on CentOS 7 and AlmaLinux 8 servers.
The sudo command allows users to run programs and access privileged directories but it can also allow the sudo user to login as root. This is a problem as there is no efficient activity logging for each sudo user, i.e. they can all run commands that show up as the ‘root’ user.
The first three steps in this tutorial will demonstrate how to create a user with root-equivalent privileges. Then we will show you how to disable the user from sudo-ing as root.
Step 1 – Create new user account
Create a new user account using the useradd command:
Now set the user ‘johny’ a password with the passwd command:
Once you hit enter, you will be prompted to confirm the password. Make sure you use a strong password.
Changing password for user johny. New password: Retype new password: passwd: all authentication tokens updated successfully.
Step 2 – Grant new user with sudo/root privileges
We are going to use the usermod command to add user ‘johny’ to the ‘wheel’ group. By default on RHEL/CentOS systems, members of the group ‘wheel’ are granted with sudo access.
usermod -aG wheel johny
At this point, user ‘johny’ has been added in wheel group without any restrictions. User johny can, at any time, run the command su root or sudo su to switch as the root user. If you want every user to run sudo-privileged commands under his/her own account (for logging purposes), then follow the last step below.
Step 3 – Modify Sudoers file
First, backup the /etc/sudoers config file as follows:
cp /etc/sudoers /root/sudoers.orig
Now, edit the sudoers config file as follows:
Find this line:
%wheel ALL=(ALL) ALL
Replace it with:
%wheel ALL=(ALL:ALL) ALL, !/bin/su
Save the file and you are done!
Last Step – Verify
To verify if you have correctly disabled the sudo access to the user(s), login to your server as root and then switch to your user, let’s say johny
[root@netshop-server-demo ~]# su johny
Now, as user johny try to sudo as root in 2 ways:
[johny@netshop-server-demo root]$ sudo su Sorry, user johny is not allowed to execute '/bin/su' as root on netshop-server-demo. [johny@netshop-server-demo root]$ su root Password: su: Authentication failure [johny@netshop-server-demo root]$
Hooray! You are done!