Manage a Dynamic Remote IP in iptables firewall automatically

Having a backup server (or any other server) behind a dynamic IP is quite common; and for us it’s no different. Which of course we treat this off-site server like any other – it must communicate with our master servers through a strict set of firewall rules. (We can’t put enough emphasis on the importance of a strict firewall which explicitly accepts traffic only from known hosts – if it’s not for the public to see, don’t let them see it.)

In this example we’re setting up an iptables rule on our master Splunk server which allows the remote (dynamic) machine from an external network to forward logs accordingly. Your use case may vary, but the general idea still applies. (We assume you’ll be using a dynamic DNS service which resolves a hostname to an ip).

What this script does is simply ping your remote host address in order to resolve the IP. It then checks to see if the iptables rule already exists for that address, or if an older address exists in your rules.

(This of course is making the assumption we’re only using the 1 ip entry at all times. If you have multiple ip’s using the same rule/port please adjust regex accordingly). This script does work with an existing entry of our internal network 10.10.10.0/24 for the same port.

All that’s left now is to create a cron entry that checks every 4 hours.