Harden SSH in 5 Minutes — A Practical Guide

Harden SSH in 5 Minutes — A Practical Guide

DevToolKit

Most servers get brute-forced within hours of going online. Here's how to lock down SSH in under 5 minutes. No security degree required.

Step 1: Switch to Key-Based Auth (2 min)

# On your LOCAL machine, generate a key
ssh-keygen -t ed25519 -C "your-email@example.com"

# Copy it to the server
ssh-copy-id user@your-server

# Test it works
ssh user@your-server

# If you got in without a password prompt, you're good

Step 2: Disable Password Auth (1 min)

# On the SERVER, edit sshd_config
sudo nano /etc/ssh/sshd_config

# Find and change these lines:
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no
PermitRootLogin prohibit-password

# Restart SSH
sudo systemctl restart sshd

WARNING: Make sure your key works BEFORE disabling passwords. Keep your current session open while testing in a new terminal.

Step 3: Change the Port (30 sec)

# In /etc/ssh/sshd_config
Port 2222    # Pick any unused port above 1024

# Restart SSH
sudo systemctl restart sshd

# Update your firewall
sudo ufw allow 2222/tcp
sudo ufw delete allow 22/tcp

# Connect with new port
ssh -p 2222 user@your-server

This alone eliminates 99% of brute-force attempts. They all target port 22.

Step 4: Install fail2ban (1 min)

sudo apt install fail2ban -y

# Create local config
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local

# Under [sshd] section:
[sshd]
enabled = true
port = 2222      # match your SSH port
maxretry = 3
bantime = 3600   # 1 hour ban
findtime = 600   # within 10 minutes

sudo systemctl enable fail2ban
sudo systemctl start fail2ban

# Check banned IPs
sudo fail2ban-client status sshd

Step 5: Limit Access (30 sec)

# In /etc/ssh/sshd_config, add:
AllowUsers your-username
MaxAuthTries 3
LoginGraceTime 30
ClientAliveInterval 300
ClientAliveCountMax 2

sudo systemctl restart sshd

Verify Your Setup

# Check SSH config for issues
sudo sshd -t

# View recent auth attempts
sudo journalctl -u sshd --since '1 hour ago'

# See fail2ban stats
sudo fail2ban-client status sshd

Bonus: SSH Config for Convenience

# ~/.ssh/config on your LOCAL machine
Host myserver
    HostName your-server-ip
    User your-username
    Port 2222
    IdentityFile ~/.ssh/id_ed25519
    ServerAliveInterval 60

# Now just type:
ssh myserver

That's it. 5 steps, 5 minutes, and your server just went from 'please hack me' to actually secure. The vast majority of successful SSH attacks exploit default configs with password auth on port 22.

Report Page