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

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:

Verification

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.



Revision #1
Created 9 May 2025 21:57:15 by Nate Nash
Updated 7 June 2025 00:14:24 by Nate Nash