How to protect your SSH connection
SSH (Secure Shell) is the default way developers manage remote servers, but it's also a prime target for attacks. Whether you're managing a VPS on DigitalOcean, AWS, or your own bare metal server, hardening your SSH configuration is critical.
This guide outlines the most effective ways to protect your SSH connection from brute-force attacks, unauthorized access, and misconfigurations.
⚙️ 1. Use SSH Key Authentication Instead of Passwords
SSH keys are much more secure than passwords.
🔑 Generate an SSH Key Pair
ssh-keygen -t ed25519 -C "your_email@example.com"✅ Use ed25519 over rsa — it's faster and more secure.
You can manually copy it:
ssh-copy-id username@your-server-ip🚫 2. Disable Password Authentication
After confirming key-based login works, disable passwords entirely:
Edit /etc/ssh/sshd_config:
PasswordAuthentication no
ChallengeResponseAuthentication noThen restart SSH:
sudo systemctl restart ssh📛 3. Change the Default SSH Port
Changing from port 22 helps reduce automated bot attacks:
Edit sshd_config:
Port 2222Then restart SSH and open the new port in your firewall:
sudo ufw allow 2222/tcpImportant: Don’t lock yourself out. Keep the old SSH session open during testing.
🚫 4. Disable Root Login
Prevent direct root access:
PermitRootLogin noCreate a non-root user if needed:
adduser deploy
usermod -aG sudo deployThen log in as that user and use sudo when needed.
📉 5. Use a Firewall (UFW)
Enable only what you need:
sudo ufw allow 2222/tcp # Allow custom SSH port
sudo ufw allow http # Allow HTTP
sudo ufw allow https # Allow HTTPS
sudo ufw enableCheck status:
sudo ufw status🛡️ 6. Install fail2ban
fail2ban blocks IPs after failed login attempts.
Install:
sudo apt install fail2banCreate a local jail config:
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.localEnsure the SSH jail is enabled:
[sshd]
enabled = true
port = 2222Restart fail2ban:
sudo systemctl restart fail2ban🧪 7. Monitor SSH Logs
Check for suspicious login attempts:
sudo journalctl -u ssh
# or
cat /var/log/auth.log | grep "sshd"🔐 9. Set Idle Timeout (Optional)
Disconnect idle sessions automatically:
In sshd_config:
ClientAliveInterval 300
ClientAliveCountMax 2Conclusion
SSH is your lifeline to remote servers — treat it like a vault door. By implementing these best practices, you’ll significantly reduce the risk of unauthorized access and keep your infrastructure secure.