Objective

Harden SSH by disabling password auth, restricting access, changing the port, and deploying fail2ban against brute-force.

Tools & Technologies

  • sshd_config
  • fail2ban
  • ssh-keygen
  • ed25519
  • AllowUsers

Key Commands

ssh-keygen -t ed25519 -a 100
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
systemctl restart sshd
fail2ban-client status sshd

Architecture Overview

sequenceDiagram participant A as Attacker participant F as fail2ban participant S as sshd participant K as Key Auth A->>S: Password auth attempt 1 S-->>A: Failed A->>S: Attempt 2 A->>S: Attempt 3 S->>F: 3 failures logged F->>F: Add iptables REJECT rule A->>S: Attempt 4 (blocked) S--xA: Connection refused Note over K: Key auth bypasses all this

Step-by-Step Process

01
Key-Based Authentication

Generate ED25519 key pair and configure server to require keys.

# On client
ssh-keygen -t ed25519 -a 100 -C 'taki@lab'
ssh-copy-id user@server
# Or manual:
cat ~/.ssh/id_ed25519.pub | ssh user@server 'mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys'
02
Harden sshd_config

Disable password auth, root login, and restrict users.

# /etc/ssh/sshd_config
Port 2222
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AllowUsers alice bob
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
X11Forwarding no

sudo sshd -t  # test config
sudo systemctl restart sshd
03
Install fail2ban

Block IPs after repeated failed authentication attempts.

sudo apt install fail2ban

# /etc/fail2ban/jail.local
[sshd]
enabled = true
port = 2222
maxretry = 3
bantime = 3600
findtime = 600

sudo systemctl enable --now fail2ban
fail2ban-client status sshd

Challenges & Solutions

  • Changing port and disabling password auth before installing key locks you out
  • fail2ban ban on localhost during testing — whitelist yourself first: ignoreip = 127.0.0.1

Key Takeaways

  • Use AllowUsers to whitelist — any other user cannot log in even with valid key
  • Port change requires updating ~/.ssh/config on clients: Port 2222