使用iptables 设定单个客户机的指定时间内发起最大连接数请求,超过限制的直接DROP
代码如下 |
复制代码 |
iptables -A INPUT -p tcp –dport 80 -m state –state NEW -m recent –set –name WEB
iptables -A INPUT -p tcp –dport 80 -m state –state NEW -m recent –update –seconds 30 –hitcount 20 –rttl –name WEB -j DROP
|
上例??0秒内20次
配置相应的iptables脚本
代码如下 |
复制代码 |
#!/bin/sh
## define some vars
MAX_TOTAL_SYN_RECV="1000"
MAX_PER_IP_SYN_RECV="20"
MARK="SYN_RECV"
PORT="80"
LOGFILE="/var/log/netstat_$MARK-$PORT"
LOGFILE_IP="/var/log/netstat_connect_ip.log"
DROP_IP_LOG="/var/log/netstat_syn_drop_ip.log"
## iptables default rules: accept normailly packages and drop baleful SYN* packages
iptables -F -t filter
iptables -A INPUT -p TCP ! --syn -m state --state NEW -j DROP
iptables -A INPUT -p ALL -m state --state INVALID -j DROP
iptables -A INPUT -p ALL -m state --state ESTABLISHED,RELATED -j ACCEPT
## initialize
if [ -z $MARK ];then
MARK="LISTEN"
fi
if [ -z $PORT ];then
SPORT="tcp"
else
SPORT=":$PORT"
fi
######################## end
## save the results of command netstat to specifal file
netstat -atun|grep $MARK|grep $SPORT 2>/dev/null >$LOGFILE
REPEAT_CONNECT_IP=`less $LOGFILE|awk '{print $5}'|cut -f1 -d ':'|sort|uniq -d |tee > $LOGFILE_IP`
if [ -f $DROP_IP_LOG ];then
for i in `less $DROP_IP_LOG`;do
iptables -A INPUT -p ALL -s $i -j DROP
done
fi
for i in `less $LOGFILE_IP`;do
REPEAT_CONNECT_NUM=`grep $i $LOGFILE|wc -l`
## count repeat connections ,if the accout is large than default number,then drop packages
if [ $REPEAT_CONNECT_NUM -gt $MAX_PER_IP_SYN_RECV ];then
echo "$i####$REPEAT_CONNECT_NUM" >> $DROP_IP_LOG
iptables -A INPUT -p ALL -s $i -j DROP
fi
done
ALL_CONNECT=`uniq -u $LOGFILE|wc -l`
#echo $ALL_CONNECT
## count repeat connections ,if the accout is large than default number,then drop packages
if [ $ALL_CONNECT -gt $MAX_TOTAL_SYN_RECV ];then
#echo $ALL_CONNECT
exit
fi
|
3.利用shell脚本
1、Shell脚本
代码如下 |
复制代码 |
#!/bin/bash
/bin/netstat -na |grep ESTABLISHED |awk ‘{print $5}’ |awk -F : ‘{print $1}’ | sed ‘/^$/d’ |sort|uniq -c|sort -rn|head -n 10|grep -v -E ’192.168|127.0′ |sed ‘/^$/d’ |awk ‘{if ($2!=null && $1>10);{print $2}}’>/tmp/dropip
for i in $(cat /tmp/dropip)
do
/sbin/iptables -A INPUT -s $i -j DROP
echo “$i kill at `date`”>>/var/log/ddos
done
|
2.增加执行权限
代码如下 |
复制代码 |
chmod +x /root/bin/dropip.sh |
3.添加到计划任务,每分钟执行一次
代码如下 |
复制代码 |
crontab -e
*/1 * * * * /root/bin/dropip.sh |
说明:
以上脚本比较简单,但很实用,最重要的是第二行,获取ESTABLISHED连接数最多的前10个ip并写入临时文件/tmp/dropip,排除了内部ip段192.168|127.0开头的.通过for循环将dropip里面的ip通过iptables全部drop掉,然后写到日志文件/var/log/ddos