By default SSH will allow any valid user account to login to the remote system and that includes root user as well. Though root user is set with strong password, it can only limit its exposure to brute force attacks. But as said it only limits, still a malicious access to root account is possible. So it’s always a best practice to disable root user login via SSH and use non privileged user account for accessing the remote system. Once you gain access to the remote system as non-privileged user, su - can be used to switch to root account. This tutorial will explain how to disable root user login via SSH on CentOS 7.
Step 1: Login to system as root user. Don’t worry, you will be using root account for remote login only in this step.
Step 2: Create an alternate user account. For example, administrator.
[root@root ~]# adduser administrator
Step 3: Set a strong password for user account created in step 2.
[root@root ~]# passwd administrator
Step 4 : Open another terminal & login to the system as the new user created in step 2. This step will allow you to test if the new account works properly.
Step 5: Test that you can switch to root account.
[administrator@administrator ~]$ su -
Enter root account password and check if you have gained root access.
[root@root ~]# whoami root
Step 6: Disable root user login via SSH.
[root@root ~]# vi /etc/ssh/sshd_config
Step 7: Lookout for '#PermitRootLogin yes'. By default, root login is allowed by SSH.
Step 8 : Change '#PermitRootLogin yes' to 'PermitRootLogin no'
Step 9: Save the file & exit
Step 10: Make sure sshd_config does not have any syntax errors.
[root@root ~]# /usr/sbin/sshd -t [root@root ~]# echo $? 0
The above output suggests, sshd_config does not have any syntax error. In case, if there is an error, you would see non-zero output.
Step 11: Restart SSH to read the new configuration change.
# service sshd restart
Step 12: Make sure root login via SSH is disabled.
ssh root@<ip-address>
The access should be denied in spite of entering valid password for root user. It means, SSH has denied access to the root account.
Step 13: Login as non-privileged user account created in Step 2.
Step 14: When needed, switch to root account as below:
[administrator@administrator ~]$ su -
That’s it! You have successfully disabled root login to remote system via SSH.
