SSH is usually the first service attackers probe on a new server, and bots start trying passwords within minutes. These steps are written for Debian and Ubuntu. On Red Hat based systems the service is called sshd.

Want every command on one page? Linux & Enterprise Configuration Guide · $9.99View on Gumroad

1. Use key login, not passwords

ssh-keygen -t ed25519
ssh-copy-id user@server

2. Edit /etc/ssh/sshd_config

PermitRootLogin no
PasswordAuthentication no
sudo sshd -t
sudo systemctl reload ssh

sshd -t checks the file for mistakes before you reload. Keep your current session open and test a second login in a new window before you close anything.

3. Allow only what you need through the firewall

sudo ufw allow OpenSSH
sudo ufw enable

4. Add Fail2ban

sudo apt install fail2ban

Create /etc/fail2ban/jail.local with:

[sshd]
enabled = true
maxretry = 5
findtime = 10m
bantime = 1h
sudo systemctl restart fail2ban
sudo fail2ban-client status sshd

5. Keep it updated

sudo apt install unattended-upgrades

Set up your key and test it before you disable password login, otherwise you can lock yourself out.