Introduction#
Using public-key authentication for SSH login is a more secure alternative to password-based authentication. This guide will walk you through the steps to configure your server to only allow SSH login with a public key.
Generating a Public/Private Key Pair on Windows#
To generate a public/private key pair, run the following command:
ssh-keygen -t rsa -b 4096
Follow the prompts to save the keys. You can choose a password for the private key (optional).
Copying the Public Key from windows to your linux machine#
To copy the contents of ~/.ssh/id_rsa.pub to your Linux machine. Using PowerShell run the following command:
cat ~/.ssh/id_rsa.pub | ssh username@remote_host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
Making sure to update username@remote_host with your actual server’s SSH credentials.
Configuring Authorized Keys File#
1. Create or edit the authorized keys file#
sudo nano /etc/ssh/sshd_config
Locate the line PubkeyAuthentication no and change it to:
PubkeyAuthentication yes
Then, restart the SSH service:
sudo systemctl restart sshd
2. Add the public key to authorized keys#
sudo nano /etc/ssh/authorized_keys
Append the contents of your local machine’s ~/.ssh/id_rsa.pub file to the end of the authorized keys file.
Restricting Access to Key-Based Authentication only#
1. Remove password-based authentication (optional)#
sudo nano /etc/ssh/sshd_config
Locate the line PasswordAuthentication yes and change it to:
PasswordAuthentication no
Then, restart the SSH service:
sudo systemctl restart ssh
If that does not work then try
sudo systemctl restart sshd
2. Limit access with host keys or user limits (optional)#
You can further restrict access by limiting SSH connections to specific hosts or users.
Conclusion#
You have successfully configured your server to only allow SSH login with a public key. Make sure to store the private key securely and never share it with anyone.
