How to Set Up a Simple Anti-CC Attack Strategy on a Linux Cloud Server?

30-01-2024 03:09:23

Method 1

Utilize the netstat -an command to identify IPs with current concurrent requests exceeding 100. Then, automatically add IPs not on the whitelist to the DROP rule.

Create a file named deny_1.sh and insert the following command statements.

#!/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

After saving, execute the following statements:

chmod +x deny_1.sh
sh deny_1.sh

Intercepted IPs will be recorded in black_ip.txt. If there are whitelisted IPs to be excluded, add these IPs to white_ip.txt, one per line.

Method 2

Identify attacker IPs from web server logs based on their access patterns, and filter them out using iptables, excluding the local machine IP: 127.0.0.1.

Create a file named deny_2.sh and add the following command statements.

#!/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

After saving, execute the following statements:

chmod +x deny_2.sh
sh deny_2.sh

Finally, add this to the cron job using crontab -e to execute every 20 minutes.

*/20 * * * * /root/deny_ip1.sh  >dev/null 2>&1

Precautions

  • For servers accelerated by CDN, the visitor's IP might be the IP of the CDN node, making this method unsuitable for interception.
  • In Method 1, if IPs from the same segment as the whitelist appear in the high-concurrency list, they won't be immediately blacklisted but will be written to recheck_ip.txt.
  • For Method 2, it is recommended to rename the original log file before execution to start with a new log file.
  • Prolonged interception is not advisable. Please cancel the interception and restore the original state after the server load normalizes and the attack largely subsides.