Friday, October 1, 2010

Chống DOS đơn giản dạng SYN attack

If you want to block an ip when it reaches a limited number of connections then here is your solution
This script limits to 100 connections and on port 80, you can change both of them and run this at cron on every 1 minute.

#!/bin/bash

#Collecting list of ip addresses connected to port 80

netstat -plan|grep :80|awk {'print $5'}|cut -d: -f 1|sort|uniq -c|sort -nk 1 > /root/blocked.ip.txt


#Limit the no of connections
LIMIT=100;

for ip in `cat /root/blocked.ip.txt |awk '{print $2}'`;do

if [ `grep $ip /root/blocked.ip.txt | awk '{print $1}'` -gt $LIMIT ]
then
echo "100 connection from $ip... `grep $ip /root/blocked.ip.txt | awk '{print $1}'` number of connections... Blocking $ip";

#Blocking the ip ...

/etc/init.d/iptables save > /dev/null;
CHECK_IF_LOCALIP=0;
/sbin/ifconfig | grep $ip > /dev/null;
if [ $? -ne $CHECK_IF_LOCALIP ]
then
{
FLAG=0;
grep $ip /etc/sysconfig/iptables | grep DROP > /dev/null;
if [ $? -ne $FLAG ]
then
iptables -I INPUT -s $ip -j DROP;
else
echo " Ipaddress $ip is already blocked ";
fi
}
else
echo " Sorry, the ip $ip cannot be blocked since this is a local ip of the server ";
fi
fi
done

No comments:

Post a Comment