Skip to main content

Update #5 - Dynamic Fail2Ban Ignore Rule with DDNS


Update #5

Dynamic Fail2Ban Ignore Rule with DDNS

Overview

To enhance security while ensuring admin access from a dynamic IP address, I created a script that automatically resolves my home DDNS address.

and updates Fail2Ban’s ignoreip rule accordingly. This ensures my home IP is always whitelisted—even as it changes—preventing accidental lockouts.

Objective

Automatically update Fail2Ban’s ignoreip field with the resolved IP address of a DDNS hostname and restart the service.

Components Used

  • Ubuntu 22.04 VPS

  • Fail2Ban

  • DDNS hostname

  • Bash scripting

  • Cron for automation (optional)

Script Path

/usr/local/bin/update-fail2ban-ignoreip.sh

Script Logic

  1. Uses dig to resolve the current IP of the DDNS hostname.

  2. Backs up /etc/fail2ban/jail.local.

  3. Replaces the existing ignoreip line with a new one including 127.0.0.1 and the resolved DDNS IP.

  4. Restarts the Fail2Ban service.

#!/bin/bash

# Resolve DDNS to IP
DDNS_HOST="YOUR-DDNS-NAME-HERE"
RESOLVED_IP=$(dig +short "$DDNS_HOST" | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | head -n1)

# Path to jail.local
JAIL_LOCAL="/etc/fail2ban/jail.local"

# Backup original
cp "$JAIL_LOCAL" "$JAIL_LOCAL.bak"

# Update ignoreip in jail.local
sed -i "/^ignoreip =/c\ignoreip = 127.0.0.1 $RESOLVED_IP" "$JAIL_LOCAL"

# Restart Fail2Ban
systemctl restart fail2ban

Setup Steps

Create the script:

 
  1. sudo nano /usr/local/bin/update-fail2ban-ignoreip.sh
    Paste the script above, change it to YOUR-DDNS-SERVER - save and exit.

Make it executable:

  • Run it manually to verify:

    sudo /usr/local/bin/update-fail2ban-ignoreip.sh

Verification

  • Checked with:

    sudo cat /etc/fail2ban/jail.local

     Confirmed the new IP is listed in ignoreip.

  • Validated Fail2Ban is running:

    sudo systemctl status fail2ban

Optional: Automate with Cron

To run the update daily:

sudo crontab -e

Add:

0 3 * * * /usr/local/bin/update-fail2ban-ignoreip.sh

Result

Fail2Ban now dynamically ignores my home IP—even though it’s behind a DDNS—and I no longer risk locking myself out while administering my VPS.