Archive

Posts Tagged ‘clean’

Automatically remove duplicate IP’s in Iptables

December 9th, 2009 Remco No comments

Many scripts like my Persistent Iptables bans from Fail2Ban script add a bunch of DROP statements to Iptables chains.

I noticed that quite a lot of people ask questions on mailing lists and forums requesting a method to automatically remove any duplicate IP’s that might exist within a given chain.

Well, that’s quite easy to accomplish really, just run this little PHP script I created as root, and your Iptables is once again clean as a whistle!

/**
 * Configuration
 */
$chain = "Blocklist";
$safelist = array("x.x.x.x"
                 ,"y.y.y.y"
                 ,"z.z.z.z");
 
$data = shell_exec('iptables -S '.$chain);
$iparr = explode(' ',$data);
$j = 0;
$ref = array();
for($i=0;$i<sizeof($iparr);$i++) {
        if(substr_count($iparr[$i],".")==3) {
                $ref[$j] = $iparr[$i];
                $j++;
        }
}
sort($ref);
 
for($i=0;$i<sizeof($ref);$i++) {
        $ip = $ref[$i];
        $ref[$i] = "";
        if(stristr($ip,"0.0.0.0")) $ip="";
        if(strlen($ip)>2 && !in_array($ip,$safelist) && in_array($ip,$ref)) {
                echo "Duplicate IP found: $ip\r\n";
                while(in_array($ip,$ref)) {
                        shell_exec('iptables -D '.$chain.' -s '.$ip.' -j DROP');
                        $ref[array_search($ip,$ref)] = "";
                }
        }
 
}