Passwordless SSH login with public key authentication

· — views

SSH is an essential service for remotely maintaining a Linux server, in this blog post I'll talk about hardening the SSH service by enabling passwordless public key authentication.

Create a new user and add to sudoers group

The first step is to create a new non-root user who is capable of running commands with superuser privileges.

sudo adduser username
sudo usermod -aG sudo username

Alternatively, if the user already exists you can add them to the sudo group using the adduser command.

sudo adduser username sudo

Disable root login for SSH

Now that the new user can run commands with superuser privileges there is no need to allow root login for SSH. In subsequent SSH sessions you'll log in using the new user created above.

sudo su
nano /etc/ssh/ssh_config
PermitRootLogin no
systemctl restart sshd

Generate SSH keys

On the client (your computer), create a hidden ssh directory if it doesn't exist then generate the keypair and copy the public key to the server.

cd ~/.ssh
ssh-keygen -t rsa -b 4096
cat ~/.ssh/id_rsa.pub | ssh username@yourserverip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

Set permissions and configure the server

On the server, set the correct permissions for the .ssh directory and authorized_keys file.

chmod 700 ~/.ssh
chmod 644 ~/.ssh/authorized_keys

Next, edit the sshd_config to allow authentication using the public key that was generated earlier.

nano /etc/ssh/sshd_config
PubkeyAuthentication yes
systemctl restart sshd

Test login with public key

The next step is to verify that public key authentication is working as expected, back on the client use the following command.

ssh username@yourserverip -i ~/.ssh/id_rsa

Disable password authentication

Finally, we can disable password authentication since we are using the public key to authenticate.

nano /etc/ssh/sshd_config
PasswordAuthentication no #PermitEmptyPasswords no
systemctl restart sshd

Bonus

Create a config file on the client to make the login process more convenient.

nano ~/.ssh/config
Host somealias HostName yourserverip User username IdentityFile ~/.ssh/id_rsa IdentitiesOnly yes
ssh somealias

Stay in the loop

Subscribe to my newsletter and get notified when I publish more content like this.