Using iptables to block ips that spam or attack your server

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

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

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

    1. $file = '/var/badips';
    2. #remove IP use ?do=rm&ip=80.145.203.224
    3. $arr = array_map('rtrim',file($file));
    4. if($_GET['do']=='rm'){
    5.         unset($arr[array_search($_GET['ip'],$arr)]);
    6.         if(file_put_contents($file,implode("\n",$arr)))
    7.                 echo $_GET['ip'].' removed';
    8. }else{ #add ip ?ip=80.145.203.224
    9.         #duplicated ip
    10.         if(is_array($arr) && in_array($_GET['ip'],$arr)) echo $_GET['ip'].' exits';
    11.         else{
    12.                 exec("/sbin/iptables -I INPUT -s {$_GET['ip']} -j DROP");
    13.                 exec("/etc/init.d/iptables restart",$output);
    14.                 if(file_put_contents($file,"{$_GET['ip']}\n",FILE_APPEND))
    15.                         echo $_GET['ip'].' Banned';
    16.         }
    17. exec("cat {$file}",$output);
    18. }
    19. print_r($output);
    20.  
    21.  

    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


    Tags :

    This entry was posted on Tuesday, May 29th, 2007 at 3:45 pm and is filed under Blog, Solutions. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

    2 Responses to “Using iptables to block ips that spam or attack your server”

    1. Using iptables to block ips that spam or attack your server « Bloggitation Says:

      [...] read more | digg story [...]

    2. Lorenzo Says:

      cool,
      just what I was looking for, thanks.

     

    Leave a Reply


     Top