Dynamic DNS Iptables Firewall Script

I’m using my computer as a development platform and I usually let people in by editing my firewall active table

but for those with dynamic ip addresses I had to figure out a different solution

so I made a small script in PHP to check for my friends dynamic ip address by looking up his dyndns.org hostname

it checks IP then goes sleeping for 5 minutes

when it detects an ip change it updates firewall by flushing my firends chain and adding a rule to let him access my webserver

this script works in my firewall iptables setup, it could work on yours but you have to be smart and figure that out for yourself, I’m not giving any guaranteess for this, use it as GPL V3 code :)
if you want me to help you set it up, just contact me

here’s the code:

#!/usr/bin/php
<?php
/*
use this code as GPL V3 licence says
Copyright (C) 2008, Miroslav Madzarevic, All Rights Reserved
*/
$old_ip = '';

while (1) {

    sleep (300);

    $host = 'friend.dyndns.org';

    if (!preg_match('/^'.$host.' has address ((?:\d{1,3}\.){3}\d{1,3})$/',
           exec ("/usr/bin/host $host"), $matches)) {
        echo "IP problems\n";
        continue;
    }

    $ip = $matches[1];

    $ip_parts = preg_split ('/\./', $ip, -1, PREG_SPLIT_NO_EMPTY);

    if (count($ip_parts) != 4) {
        echo "wrong ip parts count\n";
        exit;
    }

    $good = array();

    foreach ($ip_parts as $ip_part) {
        $ip_part = (int) $ip_part;
        if ($ip_part < 1 or $ip_part > 254) {
            echo "wrong ip part, $ip_part\n";
            exit;
        }
        $good[] = $ip_part;
    }

    $new_ip = join('.', $good);

    if ($old_ip != $new_ip) {

        `/sbin/iptables -F friend`;

        `/sbin/iptables -A friend -s $new_ip/32 -p tcp -m tcp --dport 80 -j ACCEPT`;

        $old_ip = $new_ip;
    }
}

?>
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • YahooMyWeb

Leave a Reply