SaonBD | Paragraph logo

Subscribe to SaonBD | Paragraph

Get new posts delivered straight to your inbox.

All posts

Hardening Linux Servers with UFW and Fail2ban: A Practical Setup Guide

A practical guide to configuring UFW rules, resolving Docker iptables bypasses, and stopping brute-force attacks with Fail2ban on Linux.

A default Linux installation leaves network ports accessible unless you configure active defenses. Self-hosted services like Caddy reverse proxies, DNS resolvers, and container dashboards require protection from automated port scans and unauthorized access attempts.

This guide configures two standard host defense tools: Uncomplicated Firewall (UFW) and Fail2ban. You will set default drop policies, resolve the Docker iptables bypass issue, restrict remote access, and configure automatic bans against brute-force attacks.

Prerequisites

Make sure that you have these requirements ready before you start:

  • A Linux server running Ubuntu or Debian.

  • A user account with sudo administrative privileges.

  • An active SSH connection to the server.

  • Optional: Docker and a reverse proxy (such as Caddy) running on the host.

Understanding the Docker iptables Bypass

By default, Docker modifies system iptables rules directly. When Docker publishes a container port (for example, -p 8080:8080), it inserts rules into the DOCKER filter chain before UFW rules execute.

As a result, Docker exposes published ports to the public internet even if UFW blocks them.

You have two solutions for this problem:

  1. Loopback Binding (Recommended): Bind container ports to 127.0.0.1 explicitly in your Compose file (for example, 127.0.0.1:8080:8080). Then route public traffic through a reverse proxy.

  2. ufw-docker Utility: Use dedicated filter chains that force Docker packets through UFW rules.

Loopback binding provides the cleanest defense and avoids breaking internal container networks.

Step 1: Install and Configure UFW

Install the UFW package using the system package manager:

sudo apt update
sudo apt install -y ufw

Define the baseline firewall policies. Set UFW to drop all incoming packets and permit all outgoing packets:

sudo ufw default deny incoming
sudo ufw default allow outgoing

CAUTION: Allow SSH before you enable the firewall. If you enable UFW before you allow SSH, the firewall terminates your remote connection.

Allow your SSH port through the firewall. If you use the standard port:

sudo ufw allow 22/tcp comment 'Allow SSH'

If you run SSH on an alternate port (for example, port 2222), allow that specific port:

sudo ufw allow 2222/tcp comment 'Allow Custom SSH'

Allow HTTP and HTTPS traffic for your reverse proxy:

sudo ufw allow 80/tcp comment 'Allow HTTP'
sudo ufw allow 443/tcp comment 'Allow HTTPS'

Enable the firewall and apply the rules:

sudo ufw enable

Verify the firewall status and active rules:

sudo ufw status verbose

The command outputs the active policies and rules:

Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
22/tcp                     ALLOW IN    Anywhere
80/tcp                     ALLOW IN    Anywhere
443/tcp                    ALLOW IN    Anywhere
22/tcp (v6)                ALLOW IN    Anywhere (v6)
80/tcp (v6)                ALLOW IN    Anywhere (v6)
443/tcp (v6)               ALLOW IN    Anywhere (v6)

Step 2: Install and Configure Fail2ban

Fail2ban monitors service log files for failed authentication attempts. When an IP address causes repeated errors, Fail2ban updates firewall rules to block that address.

Install Fail2ban:

sudo apt install -y fail2ban

Fail2ban reads /etc/fail2ban/jail.conf as upstream defaults. Upstream package updates can overwrite this file. Create a copy named jail.local for custom settings:

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Open /etc/fail2ban/jail.local in your text editor:

sudo nano /etc/fail2ban/jail.local

Locate the [DEFAULT] section and configure global ban parameters:

[DEFAULT]
bantime  = 1h
findtime = 10m
maxretry = 5
banaction = ufw
banaction_allports = ufw
ignoreip = 127.0.0.1/8 ::1
  • bantime: The duration an offending IP address remains blocked.

  • findtime: The monitoring window for counted failures.

  • maxretry: The number of failures permitted within findtime before a ban occurs.

  • banaction = ufw: Directs Fail2ban to write block rules directly into UFW.

  • ignoreip: Trusted local addresses that Fail2ban must never ban.

Step 3: Enable the SSH Jail

Scroll down to the [sshd] block in /etc/fail2ban/jail.local or create a dedicated configuration file at /etc/fail2ban/jail.d/sshd.local:

sudo nano /etc/fail2ban/jail.d/sshd.local

Add the configuration below:

[sshd]
enabled = true
port    = ssh
mode    = aggressive
backend = systemd
maxretry = 3
bantime = 24h

Save the file and exit the text editor.

Start and enable the Fail2ban service:

sudo systemctl enable --now fail2ban

Verify that the SSH jail runs:

sudo fail2ban-client status sshd

The output shows the monitored file path and current ban statistics:

Status for the jail: sshd
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     0
|  `- File list:        systemd
`- Actions
   |- Currently banned: 0
   |- Total banned:     0
   `- Banned IP list:

Step 4: Configure Fail2ban for Reverse Proxy Logs

If you expose services through Caddy or Nginx, protect administrative endpoints against brute-force attacks.

For example, when using Caddy, configure JSON access logging in your Caddyfile:

example.com {
    log {
        output file /var/log/caddy/access.log
    }
    reverse_proxy 127.0.0.1:8080
}

Create a Fail2ban filter for repeated HTTP authentication errors or 401/403 status responses:

sudo nano /etc/fail2ban/filter.d/caddy-auth.conf

Add the filter definition:

[Definition]
failregex = ^.*"remote_ip":"<HOST>".*"status":(?:401|403).*$
ignoreregex =

Create a corresponding jail configuration:

sudo nano /etc/fail2ban/jail.d/caddy.local

Add the jail parameters:

[caddy-auth]
enabled  = true
port     = http,https
filter   = caddy-auth
logpath  = /var/log/caddy/access.log
backend  = auto
maxretry = 10
findtime = 5m
bantime  = 2h

Restart Fail2ban to apply the new jail:

sudo systemctl restart fail2ban

Step 5: Test and Manage IP Bans

Verify that Fail2ban enforces rules properly without locking yourself out of your server.

Check the overall status of all configured jails:

sudo fail2ban-client status

To ban an IP address manually for testing:

sudo fail2ban-client set sshd banip 192.0.2.1

Check UFW to confirm that Fail2ban inserted the ban rule:

sudo ufw status numbered

The output lists the temporary block rule created by the fail2ban action:

[ 1] 22/tcp  DENY IN  192.0.2.1

To unban an IP address:

sudo fail2ban-client set sshd unbanip 192.0.2.1

Check the Fail2ban log file for live activity:

sudo tail -f /var/log/fail2ban.log

Maintenance and Best Practices

Keep these operational guidelines in mind:

  1. Always test SSH access in a separate terminal: Before closing your active SSH session after firewall changes, open a second terminal and verify that you can connect.

  2. Monitor persistent attackers: If specific subnets launch continuous attacks, consider increasing bantime with an exponential backoff jail (Fail2ban recidive jail).

  3. Keep internal services on loopback: Never bind internal application ports to 0.0.0.0 when Docker runs on the same machine. Keep backend applications on 127.0.0.1 and expose only ports 80 and 443 through your reverse proxy.

Your Linux host now operates with an active packet filter and automated protection against authentication brute-force scans.

Related guides

Join the discussion

Have a thought or a correction? Send it over — your message opens in your email app.

Subscribe

Get new posts delivered to your inbox.