A Linux server’s root user has superpowers. A user logged in to the root account can delete any file, including the operating system itself. They can view any data stored on the server. They can install and remove software. In fact, they have complete control over every aspect of the server.
This power should be used with caution. Server administrators have wreaked havoc with a mistyped command when logged in as root. Linux users are advised not to log in as root for this reason. For everyday tasks, they should log in as an ordinary user, elevating their privileges with su or sudo when necessary. But there are some who go further. They make it impossible to log in as root.
The arguments in favor of disabling root logins are persuasive. If root logins are impossible, no one can be tempted to log in as root instead of an ordinary user. The server admin can’t give a root password to an ordinary user if there is no way to log in as root. A disabled root account can’t fall to a brute force or dictionary attack.
Before Restricting Root Logins
You must make sure another account on your server has permission to use sudo or su before removing the ability to log in as root. If there is no way to get root permissions on the server, then you can’t manage or configure it.
Take a look at this guide to setting up sudo on your CentOS server.
Two Ways To Disable Root Logins
One way to stop people from logging in as root is to disable root logins over SSH. Many of the security issues associated with the root account are the result of its being available to external hosts.
Disabling root logins over SSH involves a simple configuration tweak. Run the following command as root to open SSHD’s configuration file in Vim. If you’ve never used Vim before, take a look at our introductory guide.
Find the line in the file that reads “PermitRootLogin”. It may be commented out with a hash (#) at the beginning of the line. Delete the hash and make sure the line reads:
It probably reads yes, so you will have to edit the yes to read no. Save the file and close Vim. Then, to restart SSHD, run:
systemctl restart sshd
You will no longer be able to log in as root over SSH.
An alternative is to prevent any user from being logged in as root by changing the login shell for the root account. If you do this, make sure you have a user with sudo permissions because you will no longer be able to use su to change to the root account.
As root, open the /etc/passwd file in Vim.
sudo vim /etc/passwd
In this file, you’ll find a long list of your server’s users with configuration information next to them, including their default shell. The root user should be at the top with a line that looks like this.
The bit after the last colon is the login shell. Change /bin/bash to /sbin/nologin so that the line reads:
Save the file and close Vim. Now no one will be able to log in as root at all.