Securing SSH with Key-Based Authentication
Protecting SSH access is critical for server security. Password-based logins are vulnerable to brute force attacks. The recommended method is using SSH keys (Ed25519, RSA, or ECDSA).
1. Generate an SSH Key Pair
Run the following command on your local machine (Linux/macOS/Git Bash on Windows):
ssh-keygen -t ed25519 -C "[email protected]"
Press Enter to accept the default path and optionally set a passphrase.
2. Copy the Public Key to the Server
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@your-server-ip
If ssh-copy-id
is not available, use this instead:
cat ~/.ssh/id_ed25519.pub | ssh user@your-server-ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
3. Test Login via SSH Key
Try logging in:
ssh user@your-server-ip
If you can log in without a password, it’s working.
4. Disable Password Authentication
Only do this if key login works correctly.
sudo nano /etc/ssh/sshd_config
Find and change:
PasswordAuthentication no
Also ensure:
PubkeyAuthentication yes
Then restart SSH:
sudo systemctl restart sshd
5. Improve SSH Security (Optional)
- Change the default port (e.g., 22 → 2222)
- Disable root login:
PermitRootLogin no
- Limit login to specific users:
AllowUsers youruser
Summary
SSH key authentication significantly improves your server's security and helps prevent brute force attacks.