Back
Featured image of post Update UFW rules based on dynamic dns DynDNS hostname

Update UFW rules based on dynamic dns DynDNS hostname

Ajust firewall rules based on IPs of dynamic DNS based domains.

Introduction

Make sure to setup a dynamic dns domain.

Install the dnsutils to be able to use the “hostname” command:

apt-get install dnsutils

Script

Create a script, adjust domain and rules according to your needs:

sudo vim /usr/local/dyndns.sh 

#!/bin/sh

HOSTNAME=mydyndnsdomain.tld

if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root"
   exit 1
fi
new_ip=$(host $HOSTNAME | head -n1 | cut -f4 -d ' ')
old_ip=$(/usr/sbin/ufw status | grep $HOSTNAME | head -n1 | tr -s ' ' | cut -f3 -d ' ')
if [ "$new_ip" = "$old_ip" ] ; then
    echo IP address has not changed
else
    if [ -n "$old_ip" ] ; then
        /usr/sbin/ufw allow proto tcp to any port 443 from $old_ip
    fi
    /usr/sbin/ufw allow proto tcp to any port 443 from $new_ip comment $HOSTNAME
    echo UFW have been updated
fi

Cron

Edit the crontab :

sudo crontab -e

Ask to run the script every 15 minutes :

*/15 * * * * root bash /usr/local/dyndns.sh 

Check

Check the status :

sudo ufw status

You should have the updated IP in the rules:

Status: active

To                         Action      From
--                         ------      ----                     
443/tcp                    ALLOW       X.X.X.X              # mydyndnsdomain.tld
1194/udp                   ALLOW       X.X.X.X              # mydyndnsdomain.tld

Built with Hugo
Theme Stack designed by Jimmy