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.
HOSTFILE=“/root/dynhosts/host-$HOST”
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.”
exit
fi
# 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.”
exit
fi
OLDIP=“”
if [ -a $HOSTFILE ]; then
OLDIP=`cat $HOSTFILE`
# echo “CAT returned: $?”
fi
# save off new ip.
echo $IP>$HOSTFILE
echo “Updating $HOST in iptables.”
if [ “${#OLDIP}” != “0” ]; then
echo “Removing old rule ($OLDIP)”
`$IPTABLES -D $CHAIN -s $OLDIP/32 -j ACCEPT`
fi
echo “Inserting new rule ($IP)”
`$IPTABLES -A $CHAIN -s $IP/32 -j ACCEPT`
Now all you have to do to use this script is run:
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.
0 * * * * root /script/location/firewall-dynhosts.sh examplesite.dyndns.org >/dev/null 2>&1
Done!
Thanks to Dave Horner’s Website for this information.