Topics

Using iptables to block ips that spam or attack your server

Check Configuring iptables on CentOS post.

Why should you do that while APF or CSF can do it automatically?
Because APF/CSF could an important testing your server to add to search index. So reviewing every would be a daily task!
Ok, so how?
using RHEL4, 4

  • first you need to create file ‘badips’ in say ‘var’ dir
  • edit your ‘/etc/init.d/iptables’
  • #vi /etc/init.d/iptables
    go to 'start() {'
    #insert these lines before 'touch $VAR_SUBSYS_IPTABLES'
           #banning BAD IPS
    	if [ -f /var/badips ]
    	then
    	       for BAD_IP in `cat /var/badips`
    	       do
    	               iptables -I INPUT -s $BAD_IP -j DROP
    		       echo 'ip '$BAD_IP' banned'
    		       echo
    	       done
    	else
    	       echo "Can't read /var/badips"
    	fi
    
  • add the bad ips into /var/badips file separated by newline
  • #echo '80.145.203.224' >> /var/badip
  • restart your iptables
  • /etc/init.d/iptables restart

    Ok but how about a nice PHP script which would do that without getting into ?

    $file = '/var/badips';
    #remove IP use ?do=rm&ip=80.145.203.224
    $arr = array_map('rtrim',file($file));
    if($_GET['do']=='rm'){
    	unset($arr[array_search($_GET['ip'],$arr)]);
    	if(file_put_contents($file,implode("\n",$arr)))
    		echo $_GET['ip'].' removed';
    }else{ #add ip ?ip=80.145.203.224
            #duplicated ip 
    	if(is_array($arr) && in_array($_GET['ip'],$arr)) echo $_GET['ip'].' exits';
    	else{
    		exec("/sbin/iptables -I INPUT -s {$_GET['ip']} -j DROP");
                    exec("/etc/init.d/iptables restart",$output);
    		if(file_put_contents($file,"{$_GET['ip']}\n",FILE_APPEND))
    			echo $_GET['ip'].' Banned';
    	}
    exec("cat {$file}",$output);
    }
    print_r($output);
    
    

    add the script to file ban.php and make sure file ‘badips’ is 666 writable then excute ban.php?ip=80.145.203.224 to ban this ip or ban.php?ip=80.145.203.224&do=rm to remove it from the banned ips