I recently spun up a new personal VPS and after some time i noticed thousands of failed login attempts in the authentication logs. It was a good reminder that the default SSH configuration leaves the door open to brute-force attacks. Here are the steps I took to harden the server and lock down access.
1. Change the Default Port
Changing the default port reduces background noise from automated scanners.
Edit /etc/ssh/sshd_config:
sudo nano /etc/ssh/sshd_config
Find # Port 22, uncomment it, and change the number:
Port 1337
Restart SSH:
sudo systemctl restart ssh
2. Disable Root Login
Direct root login increases vulnerability. Disable it in /etc/ssh/sshd_config:
PermitRootLogin no
Restart SSH:
sudo systemctl restart ssh
3. Use SSH Keys
Switch from password authentication to SSH keys.
Generate an SSH Key
ssh-keygen -t ed25519 -C "hello@hisalman.in"
Copy the Key to the Server
ssh-copy-id -p 1337 user@your-server
Disable Password Authentication
In /etc/ssh/sshd_config:
PasswordAuthentication no
Restart SSH:
sudo systemctl restart ssh
4. Enable Fail2Ban
Fail2Ban blocks IP addresses after repeated failed attempts.
Install Fail2Ban:
sudo apt install fail2ban -y
Create /etc/fail2ban/jail.local:
sudo nano /etc/fail2ban/jail.local
Add:
[sshd]
enabled = true
port = 1337
maxretry = 5
bantime = 3600
Restart Fail2Ban:
sudo systemctl restart fail2ban
5. Allow Only Specific Users
Limit access to specific users in /etc/ssh/sshd_config:
AllowUsers youruser
Restart SSH:
sudo systemctl restart ssh
6. Enable 2FA for SSH
Add a second layer of security with Google Authenticator.
Install the package:
sudo apt install libpam-google-authenticator -y
Run the setup:
google-authenticator
Add this line to /etc/pam.d/sshd:
auth required pam_google_authenticator.so
Enable challenge-response in /etc/ssh/sshd_config:
ChallengeResponseAuthentication yes
Restart SSH:
sudo systemctl restart ssh