Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Security Hardening

SSH Hardening and fail2ban

Lock down SSH on Linux: disable passwords and root login, restrict users, use modern algorithms and MFA, rate-limit with the firewall, and ban brute-force sources with fail2ban.

Any server with a public address is probed by automated scanners within minutes. Open /var/log/auth.log (or journalctl -u ssh) on a fresh cloud machine and you will see thousands of failed logins for root, admin and ubuntu. Most are harmless if you have configured SSH properly: keys instead of passwords, no direct root login, and a tool that bans repeat offenders.

You met the basics of keys and sshd_config in Remote Access with SSH. Here you tighten the server step by step. Real commands are shown read-only; the Python stand-ins analyse a sample log and a configuration so you can see the logic that fail2ban and audit tools use.

A hardened sshd_config

Put changes in a drop-in file such as /etc/ssh/sshd_config.d/10-hardening.conf (drop-ins are read first; the first value found for a keyword wins, so check the main file's Include line and the effective result with sshd -T).

TEXT
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
PermitEmptyPasswords no
AllowUsers alice deploy
MaxAuthTries 3
LoginGraceTime 30
ClientAliveInterval 300
ClientAliveCountMax 2
X11Forwarding no
AllowAgentForwarding no
AllowTcpForwarding no

What each line buys you:

  • PermitRootLogin no: attackers must guess a username as well as a secret, and your logs show which person used sudo.
  • PasswordAuthentication no: brute force against passwords stops mattering. Do this only after your key login works, and keep a second session open.
  • AllowUsers / AllowGroups: an explicit allow list, so a forgotten service account cannot be used. A group is easier to manage: AllowGroups sshusers.
  • MaxAuthTries, LoginGraceTime: shorten the time and tries an unauthenticated client gets.
  • Forwarding off: enable AllowTcpForwarding only where tunnels are needed (use a Match block for those users).
  • ClientAlive*: drops dead sessions after about 10 minutes.
TEXT
Match User deploy
    AllowTcpForwarding no
    ForceCommand /usr/local/bin/deploy-shell

Match Address 10.0.0.0/8
    PasswordAuthentication yes

Match blocks apply settings only to matching users, groups or addresses, and everything after a Match line belongs to it until the next one, so put them at the end of the file.

Apply safely:

Terminal
sudo sshd -t && sudo systemctl reload ssh
# from a SECOND terminal, before closing the first:
ssh -o PreferredAuthentications=publickey alice@server

Algorithms and port

Current OpenSSH defaults are already good; do not hand-edit cipher lists unless a compliance rule demands it, because a typo can block clients. Use sshd -T | grep -E 'ciphers|kexalgorithms|macs' to see what is offered, and keep OpenSSH up to date. Moving SSH to a high port such as 2222 cuts log noise but is not security: a scan finds it. Real protection is keys and rate limiting.

Two-factor authentication

For sensitive servers add a second factor. Options include a TOTP code through libpam-google-authenticator (set AuthenticationMethods publickey,keyboard-interactive and enable KbdInteractiveAuthentication yes with the PAM module), hardware keys using ed25519-sk key types, or SSH certificates issued by an internal CA with short lifetimes. Certificates scale best because you do not copy keys to each machine.

Python Audit an sshd_config

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Rate limiting with the firewall

Slow down connection floods before they reach sshd. With nftables (see Firewalls):

TEXT
tcp dport 22 ct state new limit rate 6/minute accept

With ufw: sudo ufw limit ssh allows a source at most 6 new connections in 30 seconds. Combine this with source restrictions where possible: if you always connect from an office or VPN, allow only that range.

fail2ban: ban repeat offenders

fail2ban reads log files, counts matching failures per source address and inserts temporary firewall rules. Install it and configure in a local file, because package updates overwrite jail.conf.

Terminal
sudo apt install fail2ban          # or: sudo dnf install fail2ban
sudo nano /etc/fail2ban/jail.local
TEXT
[DEFAULT]
bantime  = 1h
findtime = 10m
maxretry = 5
ignoreip = 127.0.0.1/8 ::1 203.0.113.5
backend  = systemd

[sshd]
enabled = true
mode    = aggressive

Meaning: if an address fails 5 times within 10 minutes (findtime), ban it for 1 hour (bantime). ignoreip lists your own addresses so you never ban yourself. A jail is one log source plus one filter and one action. Manage it with:

Terminal
sudo systemctl enable --now fail2ban
sudo fail2ban-client status
sudo fail2ban-client status sshd
sudo fail2ban-client set sshd unbanip 198.51.100.77
sudo fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf

fail2ban is a noise reducer, not a replacement for disabling passwords: a distributed attack uses thousands of addresses, each trying few passwords.

Python Mini fail2ban: parse a log and decide bans

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Other good habits

  • Use a separate admin account with sudo instead of logging in as root, and require a password or key for sudo.
  • Keep private keys off servers (do not copy your laptop key to a machine to hop onward; use ProxyJump).
  • Remove keys when people leave: review authorized_keys regularly, for example with a configuration management tool that owns the file.
  • Log in with LogLevel VERBOSE to record key fingerprints, which tells you which key was used.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which change removes the value of password brute-forcing against SSH?

    If passwords are not accepted at all, guessing them cannot succeed; changing the port only hides the service.
  2. 2. In a sshd_config with several drop-in files, which value of a repeated keyword applies?

    sshd uses the first obtained value for a keyword, so check effective settings with sshd -T.
  3. 3. A fail2ban jail has maxretry = 5, findtime = 10m, bantime = 1h. What does it do?

    findtime is the counting window, maxretry the threshold, bantime the ban duration.
  4. 4. Why put your own address in ignoreip?

    An ignored address is never banned, which protects administrators from lockout.

Summary

  • Disable root login and password authentication, restrict users with AllowUsers or AllowGroups, and shorten auth limits.
  • Use Match blocks for exceptions and always validate with sshd -t, then test from a second session.
  • Add a second factor or SSH certificates where the data justifies it.
  • Rate-limit new connections in the firewall; use fail2ban to ban repeat offenders, configured in jail.local.
  • fail2ban reduces noise; strong authentication is the real defence.

Next: Mandatory Access Control: SELinux and AppArmor