Linux服務器 屏蔽國外IP訪問及簡單的防CC攻擊攔截屏蔽國外IP訪問 通過ssh遠程登錄服務器內,運行如下命令語句獲取國內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 ,并設置可執行權限( 命令: chmod +x allcn.sh) mmode=$1 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 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 執行如下命令將開始攔截 /root/allcn.sh 執行如下命令即可停止攔截 /root/allcn.sh stop CC攻擊攔截 方式1:通過netstat -an命令統計出當前請求并發大于100的IP,然后將不在白名單的IP自動加入DROP規則 首先運行 vi deny_1.sh 添加以下命令語句 #!/bin/bash if [[ -z $1 ]];then num=100 else num=$1 fi cd $(cd $(dirname $BASH_SOURCE) && pwd) iplist=`netstat -an |grep ^tcp.*:80|egrep -v 'LISTEN|127.0.0.1'|awk -F"[ ]+|[:]" '{print $6}'|sort|uniq -c|sort -rn|awk -v str=$num '{if ($1>str){print $2} fi}'` if [[ ! -z $iplist ]]; then for black_ip in $iplist do ip_section=`echo $black_ip | awk -F"." '{print $1"."$2"."$3}'` grep -q $ip_section ./white_ip.txt if [[ $? -eq 0 ]];then echo $black_ip >>./recheck_ip.txt else iptables -nL | grep $black_ip || iptables -I INPUT -s $black_ip -j DROP echo $black_ip >>./black_ip.txt fi done fi 保存后執行以下語句: chmod +x deny_1.sh sh deny_1.sh 攔截的IP會記錄到black_ip.txt中,如果有要排除的白名單IP,可將這些IP加入到white_ip.txt,一行一個。 方式2:通過web網站日志中攻擊者訪問特征,根據這些特征過濾出攻擊的ip,利用iptables來阻止(排除本機IP:127.0.0.1)。 首先運行 vi deny_2.sh 添加以下命令語句: #!/bin/bash OLD_IFS=$IFS IFS=$'\n' for status in `cat 網站訪問日志路徑 | grep '特征字符' | grep -v '127.0.0.1' | awk '{print $1}' |sort -n | uniq -c | sort -n -r | head -20` do IFS=$OLD_IFS NUM=`echo $status | awk '{print $1}'` IP=`echo $status | awk '{print $2}'` if [ -z "`iptables -nvL | grep "dpt:80" | awk '{print $8}' | grep "$IP"`" ];then if [ $NUM -gt 250 ];then /sbin/iptables -I INPUT -p tcp -s $IP --dport 80 -j DROP fi fi done 保存后執行以下語句: chmod +x deny_2.sh sh deny_2.sh 最后使用crontab -e 添加到任務計劃,每20分鐘執行一次: */20 * * * * /root/deny_ip1.sh >dev/null 2>&1 注意:
|
|||||
>> 相關文章 | |||||