听大佬们讨论如何防CC攻击,有大佬提出禁止国外IP访问,可以有所缓解,因此从路由器中移植了如下脚本,在CENTOS 6下调试通过。

使用:

先运行如下语句获取国内IP网段,会保存为/root/china_ssr.txt

wget -q --timeout=60 -O- 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest' | awk -F\| '/CN\|ipv4/ { printf("%s/%d\n", $4, 32-log($5)/log(2)) }' > /root/china_ssr.txt

将下面脚本保存为/root/allcn.sh,设置可执行权限

运行
/root/allcn.sh
运行后国外IP无法访问网站

停止
/root/allcn.sh stop
运行后国外IP恢复访问网站

mmode=$1

下面语句可以单独执行,不需要每次执行都获取网段表

wget -q --timeout=60 -O- 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest' | awk -F| '/CN|ipv4/ { printf("%s/%dn", $4, 32-log($5)/log(2)) }' > /root/china_ssr.txt

CNIP="/root/china_ssr.txt"

gen_iplist() {

    cat <<-EOF
            $(cat ${CNIP:=/dev/null} 2>/dev/null)

EOF
}

flush_r() {
iptables -F ALLCNRULE 2>/dev/null
iptables -D INPUT -p tcp -j ALLCNRULE 2>/dev/null
iptables -X ALLCNRULE 2>/dev/null
ipset -X allcn 2>/dev/null
}

mstart() {
ipset create allcn hash:net 2>/dev/null
ipset -! -R <<-EOF
$(gen_iplist | sed -e "s/^/add allcn /")
EOF

iptables -N ALLCNRULE
iptables -I INPUT -p tcp -j ALLCNRULE
iptables -A ALLCNRULE -s 127.0.0.0/8 -j RETURN
iptables -A ALLCNRULE -s 169.254.0.0/16 -j RETURN
iptables -A ALLCNRULE -s 224.0.0.0/4 -j RETURN
iptables -A ALLCNRULE -s 255.255.255.255 -j RETURN

可在此增加你的公网网段,避免调试ipset时出现自己无法访问的情况

iptables -A ALLCNRULE -m set --match-set allcn src -j RETURN
iptables -A ALLCNRULE -p tcp -j DROP

}

if [ "$mmode" == "stop" ] ;then
flush_r
exit 0
fi

flush_r
sleep 1
mstart

IP库:https://github.com/17mon/china_ip_list