全部博文(842)
分类: LINUX
2012-05-12 21:06:34
#!/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
linux下如何防ddos
其实一般的DDOS攻击可以修改 /proc/sys/net/ipv4/tcp_max_syn_backlog里的参数就行了,默认参数一般都很小,设为8000以上,一般的DDOS 攻击就可以解决了。如果上升到timeout阶段,可以将/proc/sys/net/ipv4/tcp_fin_timeout设小点。
大家都在讨论DDOS,个人认为目前没有真正解决的方法,只是在缓冲和防御能力上的扩充,跟黑客玩一个心理战术,看谁坚持到最后,网上也有很多做法,例如syncookies等,就是复杂点。
sysctl -w net.ipv4.icmp_echo_ignore_all=1
echo 1 > /proc/sys/net/ipv4/tcp_syncookies
sysctl -w net.ipv4.tcp_max_syn_backlog="2048"
sysctl -w net.ipv4.tcp_synack_retries="3"
iptables -A INPUT -i eth0 -p tcp --syn -j syn-flood
# Limit 12 connections per second (burst to 24)
iptables -A syn-flood -m limit --limit 12/s --limit-burst 24 -j RETURN
这个地方可以试着该该:
iptbales -A FORWARD -p tcp --syn -m limit --limit 1/s -j ACCEPT