Skip to content

Instantly share code, notes, and snippets.

@unblog
Last active March 11, 2018 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unblog/64da3225fd82b1dd144b5b11ec6bf836 to your computer and use it in GitHub Desktop.
Save unblog/64da3225fd82b1dd144b5b11ec6bf836 to your computer and use it in GitHub Desktop.
iptables chain for DDNS A record

iptables chain for dynamic ip address

The purpose is to lookup IPv4 address of DDNS hostname while append to iptables chain. Run script on CentOS or with minor changes on any Linux, may change line 2 for appropriate path to iptables i.e. debian /etc/default.

The host command use a part of the BIND utilities so you need to install them. To install the BIND utilities, type the following: yum -y install bind-utils

A line contains with your DDNS hostname tagged with #MyDDNS must be entered into the iptables configuration file:

#Allow from myhost.dyndns.org #MyDDNS
-A RH-Firewall-1-INPUT -i eth0 -p udp -m udp -s 123.456.789.101 -m comment --comment #DDNSIP -j ACCEPT

The -A chain will automatically appended with first time ran the script. Not. do not forget make it executable: chmod +x /usr/bin/allow_myhost.sh.

The source ip address will automatically lookup and update every 15 min. if changed. The iptables chain are opening the udp protocol which allows ip phones to communicate with the PBX, the rule can be arbitrarily customized, but the comment option --comment must be present.

For continuous update create a cron task: */15 * * * * root /usr/bin/allow_myhost.sh >/dev/null 2>&1

#!/bin/sh
iptables="/etc/sysconfig/iptables"
sed -i '/#DDNSIP/d' $iptables
lookup="$(grep -i "#MyDDNS" $iptables)"
select=( $lookup )
ddns="${select[2]}"
echo $select $ddns
ip="$(host $ddns)"
if [ "$ip" == "${ip%% has address *}" ]; then
continue;
fi
ip="${ip##* has address }"
sed -i 's/^\('"$lookup"'\)$/\1\n-A RH-Firewall-1-INPUT -i eth0 -p udp -m udp -s '"$ip"' -m comment --comment #DDNSIP -j ACCEPT/' $iptables
service iptables restart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment