#!/bin/sh
# Load FTP Kernel modules
/sbin/modprobe ip_conntrack_ftp
/sbin/modprobe ip_nat_ftp

# Inital chains default policy
/sbin/iptables -F -t filter
/sbin/iptables -P INPUT  DROP
/sbin/iptables -P OUTPUT ACCEPT

# Enable Native Network Transfer
/sbin/iptables -A INPUT -i lo -j ACCEPT

/sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# ICMP Allow
/sbin/iptables -A INPUT -p icmp -m limit --limit 1/s --limit-burst 10 -j ACCEPT

# WWW Service
/sbin/iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# ORACLE Service
/sbin/iptables -A INPUT -p tcp -s 192.168.8.0/24 --dport 1521 -j ACCEPT
# SSH Service
/sbin/iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# FTP Service
/sbin/iptables -A INPUT -p tcp --dport 21 -j ACCEPT
# Mysql Server
/sbin/iptables -A INPUT -p tcp --dport 3306 -j ACCEPT
#iptables limit access number
/sbin/iptables -I INPUT -p tcp –syn –dport 22 -m connlimit --connlimit-above 2 -j REJECT
/sbin/iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP ##丢掉sys非法连接
#一条指令即可以搞掂, –connlimit-above 2表示只允许一个客户开启二个会话,与sshd_config 设置的区别,sshd_config只能设定一个用户最多尝试几次密码
#同样也可以设定web服务访问设限
iptables -I INPUT -p tcp –syn –dport 80 -m connlimit –connlimit-above 3 -j REJECT
#这样即可 ,测试,开启到第三字,显示网络不可用
#iptables防止DDOS攻击
## 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