Linux System Administration

Securing SSH and the Firewall

35 Min.

Within minutes of going online, every public server receives automated login attempts. These steps stop nearly all of them.

Key-only SSH

From your computer:

ssh-copy-id panda@203.0.113.10
ssh panda@203.0.113.10        # confirm the key works BEFORE the next step

Then on the server, create /etc/ssh/sshd_config.d/hardening.conf:

PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
AllowUsers panda ada
sudo sshd -t                  # test the config
sudo systemctl reload ssh

Keep your current session open and test a new login in a second terminal. If something is wrong you can still fix it.

Firewall with ufw

Default deny, then allow only what is needed:

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH
sudo ufw allow 80,443/tcp
sudo ufw enable
sudo ufw status verbose

Allow SSH before enabling the firewall. Databases should never be open to the internet; if a second server needs PostgreSQL, allow only its IP:

sudo ufw allow from 10.0.0.5 to any port 5432 proto tcp

Cloud providers also have network firewalls (security groups). Use both.

fail2ban

sudo apt install fail2ban
sudo tee /etc/fail2ban/jail.local <<'CONF'
[sshd]
enabled = true
maxretry = 5
bantime = 1h
CONF
sudo systemctl restart fail2ban
sudo fail2ban-client status sshd

Hardening checklist

  • [ ] Automatic security updates on
  • [ ] Root login and passwords disabled for SSH
  • [ ] Firewall default deny; only 22, 80, 443 open
  • [ ] Each app runs as its own user, sandboxed by systemd
  • [ ] Secrets in files with 600 permissions, not in code
  • [ ] Databases listen on 127.0.0.1 or a private network only
  • [ ] Backups tested (next module)
  • [ ] ss -tulpn reviewed: nothing unexpected listening
  • [ ] Monitoring alerts on disk, memory and service failures

Check yourself

  • Why keep your SSH session open while changing SSH settings?
  • What is the order of steps when enabling ufw?
  • How should a database port be exposed to another server?

Ihr Fortschritt wird nur in diesem Browser gespeichert.

Zur Prüfung einreichen (10 Punkte)