Allow dynamic ip via iptables firewall

Came across this issue and worked out a simple solution:

you will need to set up a dynamic ip host with someone like changeip.com, keep that ip updated whatever way you do (read: router, or client) and use that in HOSTNAME below.

nano /usr/bin/local/sam_firewall:

#!/bin/bash

HOSTNAME=dynip.changeip.com
LOGFILE=/var/log/sam_firewall.log

touch /var/log/sam_firewall.log
chmod 740 /var/log/sam_firewall.log
chown root:adm /var/log/sam_firewall.log

Current_IP=$(host $HOSTNAME | cut -f4 -d' ')

if [[ $(iptables --list | grep $Current_IP) = "" ]]; then
  if [ $LOGFILE = "" ] ; then
    iptables -I INPUT -i eth0 -s $Current_IP -j ACCEPT
  else
    Old_IP=$(cat $LOGFILE)
    if [ $Old_IP != $Current_IP ] ; then
      if [ $(iptables --list | grep $Old_IP) != "" ] ; then
        iptables -D INPUT -i eth0 -s $Old_IP -j ACCEPT
      fi
    fi
    iptables -I INPUT -i eth0 -s $Current_IP -j ACCEPT
  fi
fi
echo $Current_IP > $LOGFILE

chmod +x /usr/bin/local/sam_firewall
nano /etc/sudousers (and add to bottom):

%admin ALL = NOPASSWD: /usr/local/bin/sam_firewall, /var/log/sam_firewall.log

Then in Hestiacp add a cron job to run every 5 minutes for:

sudo /usr/local/bin/sam_firewall

Enjoy, and i hope this helps someone.

4 Likes

Well done. Your solution is simple and elegant. I like it. I did something similar but that is complex and in the end achieves the same thing.

Ran into a issue with my ISP router not updating the dyndns ip (firmware is old and from 2020 and one of the 4 dyndns options is gone/ dead anyways), so i installed TrueIP (Changeip client isnt that great) and used the ChangeIP api to formulate a web push to update the dyndns ip from my 247 windows pc every 5 minutes.

https://www.haztek-software.com/applications/trueip
https://www.changeip.com/accounts/index.php?rp=/knowledgebase/34/DDNS-API-Information.html

Hi,
Interesting info. Good to know about this prog. TrueIP is an advanced - and intelligent - utility. I use (used) a basic one here:
DDNSupdater

I use OVH DynDNS function, they offer to every domain you have registered and they are registrars. You could created multiple DnyDNS domains. so on the same network, your router could be mapped with a subdomain (and the same IP) and NAS to a different subdomain (same IP).

This helps for certain things, if you want to differenciate based on local subdomains. As I have a local DNS resolver, I use this feature binding subdomains to the daily current IP.

That seems to have a similar option with the web url push.

Either way i wish my isp router wasnt limited on options and actually did this update/renew ip as intended.

I use opnsense as the backend, with sni hosts in place for my IoTs.

Should have a static ipv6 soon for my IoTs, otherwise im not having much luck with this cgnat incoming port block.

1 Like