SSH is a secure protocol for logging in to remote servers over the network. To improve security and prevent unauthorised logins, SSH allows you to log in using public key authentication. I’ll show you how to set it up in this post.
Generate SSH Keys
Step 1, generate an SSH key pair
# Generate keys if you don't already have one ssh-keygen -t ed25519 -C "your_email@domain.com"
Next, copy the public key to the remote server:
# Linux: Copy public key contents on host server to remote server ssh-copy-id remote_username@server_ip_address
If your system does not have the ssh-copy-id
tool, copy the contents of the public key(file that ends in .pub) manually and paste them into the .ssh/authorized_keys files in the remote server.
# Windows does not have ssh-copy-id, copy pub key contents manually to: vim ~/.ssh/authorized_keys
Disable SSH Password Authentication
For additional security, consider disabling password authentication via SSH. Do this only after verifying you can SSH into the server without being prompted for a password. SSH into the remote server and edit its SSH configuration
ssh user@server_ip_address
Open the SSH config file at /etc/ssh/sshd_config
and find and change these settings to the values below:
# /etc/ssh/sshd_config PasswordAuthentication no ChallengeResponseAuthentication no UsePAM no
Doing this disables all other authentication methods except SSH keys.
Disable Root login
Allowing direct root access to your server over SSH can open you up to malicious users who may brute force your root password and potentially gain access to your server if the password can be guessed. Disabling root login over SSH after setting up Key-based authentication is good practice.
To disable Root SSH Login, edit the /etc/ssh/sshd_config
file and locate the PermitRootLogin
line and uncomment and change it to:
PermitRootLogin no
Save and close the file.
Restart SSH:
sudo systemctl restart ssh
in CentOS/Fedora:
sudo systemctl restart sshd
Conclusion
This article showed you how to connect to remote servers without being prompted for a password using SSH Keys and also showed you how to secure your server by disabling SSH using the root user.