Chapter 1 · Lesson 14 of 19
Server basics

Protect SSH with fail2ban on Ubuntu

fail2ban watches log files for repeated failed logins and temporarily bans the offending IP addresses with firewall rules.

By the end you will

Install fail2ban, enable the sshd jail and check which IP addresses are banned.

Time
14 min
Level
Beginner
Check
4 questions
You need
  • An Ubuntu server with sudo access

fail2ban protects SSH by banning IP addresses that fail to log in too many times. Look at /var/log/auth.log on a server that has been public for a day and you will see hundreds of failed logins from addresses you have never heard of. Key-only login makes them fail, but they still cost CPU, fill logs and hide real events. fail2ban notices the pattern and blocks the source address for a while.

How it works#

fail2ban is a small log-watching service. It organises its work in jails. A jail connects three things:

  • A log source. For SSH, the auth log or the systemd journal.
  • A filter. Patterns that match a failed login and capture the IP address.
  • An action. What to do when the limit is hit, normally adding a firewall rule that drops traffic from that address.

Three numbers control a jail. maxretry is how many failures are allowed, findtime is the time window those failures must fall in, and bantime is how long the address stays blocked. When an IP reaches maxretry failures inside findtime, fail2ban bans it for bantime, then removes the rule.

The package ships jail.conf, which it may replace on upgrade. You put your own settings in jail.local, which is read after jail.conf and wins. On Ubuntu, the package also enables the sshd jail by default through a file in /etc/fail2ban/jail.d/, but writing your own values makes the behaviour explicit.

Step 1: Install fail2ban#

bash
sudo apt update
sudo apt install fail2ban

What you should see: apt unpacks the package and sets up the service. It starts automatically after install.

Step 2: Create a local override#

Never edit jail.conf. Create /etc/fail2ban/jail.local:

bash
sudo nano /etc/fail2ban/jail.local

Add:

ini
[sshd]
enabled = true
maxretry = 5
findtime = 10m
bantime = 1h

This bans an IP for one hour after five failures within ten minutes. Adjust the values to taste. If you run SSH on a custom port, add port = 2222 (your port).

Warning: if you log in with a wrong password repeatedly from your own IP, you can ban yourself. Add ignoreip = 127.0.0.1/8 ::1 203.0.113.50 under [sshd] (replace the last item with your own address) if your IP is stable.

Step 3: Restart the service#

bash
sudo systemctl restart fail2ban

What you should see: no output. If the config has an error, the service fails to start, and the next step shows why.

Check it worked#

bash
sudo fail2ban-client status
sudo fail2ban-client status sshd

The first command lists active jails and should show sshd in the jail list. The second shows the number of failed attempts, the number of currently banned IPs and a list of them. On a public server you will often see bans within hours.

To see what fail2ban actually decided, read its log:

bash
sudo tail -n 20 /var/log/fail2ban.log

You should see lines containing Ban or Unban with an address once activity has happened.

To remove a ban by mistake:

bash
sudo fail2ban-client set sshd unbanip 203.0.113.50

Edge cases and gotchas#

  • The log source may not exist. Minimal Ubuntu images can ship without /var/log/auth.log because no syslog daemon is installed. SSH then logs only to the journal. Add backend = systemd under [sshd] and restart fail2ban.
  • A different SSH port needs a matching jail port. If sshd listens on 2222 and the jail still names port 22, the filter may match but the ban will not cover the real port. Set port in the jail.
  • You can ban yourself with a shared address. Offices and home networks often share one public IP. One person fumbling a password can block everyone behind that address. Use ignoreip for trusted addresses.
  • IPv6 bans are per address. An attacker with a large IPv6 range can rotate addresses. Do not treat fail2ban as the main defence; keys are.
  • Docker-published ports are not covered. Docker routes that traffic through its own chains, so rules added to the normal INPUT chain do not apply to it. SSH on the host is fine.
  • Clock errors skew the window. Log timestamps and the server clock must agree, or failures may fall outside findtime.

Troubleshooting#

SymptomLikely causeFix
sshd missing from fail2ban-client statusTypo in jail.local, or the jail is not enabledCheck sudo journalctl -u fail2ban for the error and fix the file
Failed to access socket path: /var/run/fail2ban/fail2ban.sock. Is fail2ban running?The fail2ban service is not running, often because a config error stopped itRun sudo systemctl status fail2ban, fix the error it shows, then start it
No bans but many failed logins in the journalThere is no auth.log; the filter reads a file that is emptyAdd backend = systemd under [sshd] and restart
You are locked out of SSHYour own IP was bannedUse the console, then fail2ban-client set sshd unbanip <ip>
Banned IP still connectsBan covers the wrong port, or the action failedCheck port in the jail and look in /var/log/fail2ban.log for errors
Service fails right after installAn edited file has a syntax errorRead the journal for the line, fix it and restart
fail2ban-client: command not foundThe package is not installedRun sudo apt install fail2ban
The ban list is empty on a fresh installNo one has failed enough logins yetWait, or test from another address with wrong passwords
Bans vanish after bantime passesThat is the designed behaviourRaise bantime, or use the recidive jail for repeat offenders

Real-world scenario#

You open /var/log/auth.log on a week-old server and see hundreds of Failed password lines from a handful of addresses. Keys are already required, so none of them succeed, but the log is noisy.

You install fail2ban, add the [sshd] block to jail.local with ignoreip set to your office address, and restart the service. An hour later sudo fail2ban-client status sshd shows a few currently banned IPs.

One afternoon you mistype a password five times from a cafe network and your own session is cut off. From the provider console you run sudo fail2ban-client set sshd unbanip with that address and are back in. You add the lesson: a stable ignoreip entry is cheap insurance.

Quick reference#

TaskCommand
Installsudo apt install fail2ban
List jailssudo fail2ban-client status
Show one jailsudo fail2ban-client status sshd
Unban an addresssudo fail2ban-client set sshd unbanip ADDRESS
Read the logsudo tail -n 20 /var/log/fail2ban.log
Restartsudo systemctl restart fail2ban

Security and safety notes#

  • Add your own stable address to ignoreip before you rely on bans.
  • Keep a console login method available in case you ban yourself.

Next#

Keep the server from running out of memory with Add swap space on Ubuntu.

Check what you learned4 questions
1Why put settings in jail.local and not jail.conf?
2What do maxretry = 5, findtime = 10m and bantime = 1h mean together?
3How do you remove a ban you set by mistake?
4You moved SSH to port 2222 and fail2ban bans nothing. What do you set in the sshd jail?

Frequently asked questions

Do I still need fail2ban if password login is disabled?

It is less critical, but it still cuts log noise and load from bots that keep trying. It is a useful extra layer, not a replacement for keys.

Why use jail.local instead of editing jail.conf?

Package updates can overwrite jail.conf. Settings in jail.local survive updates and take priority.

I banned myself. How do I get back in?

Use another network or your provider's web console, then run sudo fail2ban-client set sshd unbanip with your address. Add your own IP to ignoreip to avoid it next time.

Does fail2ban protect my website or Docker containers too?

Only if you enable a jail for that service and the bans act on the right firewall chain. Traffic to Docker-published ports does not pass the normal INPUT chain, so SSH is the safe starting point.

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios