Allow root ssh login with public key authentication only

The Basics

SSH server has multiple ways of authenticating a client connecting to it. The most popular method is password-based authentication as it is the easiest one, however it is not so secure. Passwords are exchanged with secure mechanisms, however, due to ease of use they are generally not complex or long. This enables the attacker to break the password using brute-force or dictionary attacks. In such scenarios, the SSH keys can provide a secure and reliable means of authentication for clients.

SSH server uses a public key cryptography scheme to authenticate users. In this scheme, a pair of keys are generated, a public key and a private key, for authentication. As the name suggests, a private key is kept secret by the client as its compromise can lead to someone logging in to the server without any additional authentication.

The corresponding public key for the secret private key of the client is not kept as secret and is copied to systems the user logs in to. The private key is used to decrypt the message encrypted using the associated public key of the client. Using the key pair, we can also enable password-less authentication. The trusted public key of the client is stored in a special file named authorized_keys in the home directory of the user account.

When a client attempts to authenticate the SSH server using keys, a challenge is issued using the public key of the client stored in the server. On successfully decrypting the challenge using the client’s private key, the user gets access to the shell of the server.

Configure public key only authentication for ssh

1. As root, edit the sshd daemon configuration file (/etc/ssh/sshd_config).

2. Modify the PermitRootLogin and the PubkeyAuthentication parameters to have the following values:

PermitRootLogin without-password
PubkeyAuthentication yes

Allow only key-based ssh login in the root account by setting the directive PermitRootLogin value as without-password as shown above.

3. Verify the syntax of the configuration file sshd_config is correct before restarting sshd deamon.

# sshd -t

The above command should return nothing. This means the config file is syntactically correct and you are sure of restarting sshd daemon without any issue.

4. Restart the sshd daemon:

# service sshd restart

or

# systemctl restart sshd
Related Post