How to Enhance Security on Linux Cloud Servers using sudo?

12-01-2024 02:11:23

For Linux system administrators, managing servers and executing commands using a sudo user is a common security practice. Additionally, disabling root user login is a complementary security measure. This article will guide you through creating a sudo user and disabling root user login on Linux cloud servers. It applies to various Linux distributions, including CentOS, Ubuntu, Debian, FreeBSD, and more.

Creating a sudo User

A sudo user is essentially a regular user within the Linux operating system. For instance, let’s create a regular user named 'zhaomu'.

adduser zhaomu

Adding User to the wheel Group

The wheel group is a restricted user group that permits users to execute commands with administrative privileges. Only users in this group can execute sudo commands. In Ubuntu/Debian operating systems, the sudo group usually replaces the wheel group’s function.

CentOS

usermod -aG wheel zhaomu

Ubuntu/Debian

usermod -aG sudo zhaomu

FreeBSD

pw group mod wheel -m zhaomu

Configuring sudoers

The configuration file for sudo is /etc/sudoers. It’s crucial to ensure that this file is correctly set up for the proper execution of sudo commands.

vi /etc/sudoers

Locate the following code:

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

Make sure your Linux cloud server is configured in this manner. Note: Some Linux systems use %wheel instead of %sudo, which is also acceptable.

Restarting SSH Service

If you’ve modified the /etc/sudoers file, it is necessary to restart the SSH service for the changes to take effect.

CentOS 7

systemctl restart sshd.service

Ubuntu/Debian

/etc/init.d/sshd restart

FreeBSD

/etc/rc.d/sshd start

Testing

After completing the aforementioned steps, log out of the remote session and log back in as the sudo user. Execute the following commands to test if sudo is configured correctly.

sudo uptime
sudo whoami

The command sudo whoami should return 'root'.

Using the su command, you can switch from the sudo user to the root user.

su

Disabling Root User Login

Once everything is tested and working correctly, proceed to the final step, which is to disable root user login. This involves editing the SSH configuration file.

sudo vi /etc/ssh/sshd_config

Use the :w/ command to search for the following code, remove the hashtag # from the beginning of the line, and set the value to 'no'.

PermitRootLogin     no

Following the instructions above, restart the SSH service. Attempt to log in with the root user; if unable to log in, the setting is successful.