Dynamic Firewall Rules

Would you like to block everyone from remotely accessing your server but still be able to access it from your dynamic IP address at home? To do this, you will need to create an account with a dynamic DNS service  provider (i.e. http://www.dyndns.com). Your home computer will tell the dynamic DNS service what your home computer’s external IP address is.

Now you will need to add rules on your firewall for the hostname.  However, since iptables does a single lookup when adding rules you will need a script to repeatedly lookup the IP for your home computer. The script below looks up up a hostname’s IP address, caches it to a directory, and adds a rule to allow it.  When the script observes that the host’s IP address has changed, the old IP is removed from iptables and the new IP is added.

You may want to put all your dynamic hosts into a separate chain. That way you can easily see what dynamic hosts are trusted.

CHAIN=“dynamichosts” # change this to whatever chain you want.
IPTABLES=“/sbin/iptables”# check to make sure we have enough arguments passed.
if [ “${#@}” -ne “1” ]; then
echo “$0 hostname”
echo “You must supply a hostname to update in iptables.”

# lookup host name from DNS tables
IP=`/usr/bin/dig +short $HOST | /usr/bin/tail -n 1`

if [ “${#IP}” = “0” ]; then
echo “Couldn’t lookup hostname for $HOST, failed.”

if [ -a $HOSTFILE ]; then
# echo “CAT returned: $?”

# save off new ip.

echo “Updating $HOST in iptables.”
if [ “${#OLDIP}” != “0” ]; then
echo “Removing old rule ($OLDIP)”

echo “Inserting new rule ($IP)”

Now all you have to do to use this script is run:

# firewall-dynhosts.sh examplesite.dyndns.org

This would insert a rule for examplesite.dyndns.org into your firewall.

You can then create a script of trusted DNS hosts using cron.d. I have created the following cron job in the /etc/cron.d/ directory.

# Run the dynamic firewall script every (1) hour
0 * * * * root /script/location/firewall-dynhosts.sh examplesite.dyndns.org >/dev/null 2>&1


Thanks to Dave Horner’s Website for this information.

Leave a Reply

Your email address will not be published.