Linux VPS System Anti-CC attack script code

Source: Internet
Author: User
Tags sendmsg sleep time interval vps iptables egrep

Linux VPS System anti-CC attack automatic pull black IP script is divided into 2 versions, the normal version is added to the crontab scheduled tasks performed every 5 minutes. Enhanced version is mainly to make up for the use of crontab execution time interval is only a minimum of 1 minutes, you can make CC protection more stringent, even every 1S execution once!

Function Description: Through the Netstat-an command to count the current request concurrency greater than 100 IP, and then will not be the white list of IP automatically added to the drop rule

Instructions for use:

1. Under Linux system, save the following code as a shell script, such as: deny_ip.sh, and execute chmod+x deny_ip.sh Execute permissions

#!/bin/bash
#Author: Zhangge
#Desc: Auto Deny black_ip Script.
#Date: 2014-10-28
#从第一个参数取得限制阈值, if the maximum concurrency is not set, it is set to 100
if [[Z $]];then
num=100
Else
Num=$1
Fi

#进入到脚本所在目录
CD $ (CD $ (dirname $BASH _source) && pwd)

IP list for #取得当前请求大于阈值 $num
Iplist= ' Netstat-an |grep ^tcp.*:80|egrep-v ' listen|127.0.0.1 ' |awk-f ' []+| [:] ' {print $} ' |sort|uniq-c|sort-rn|awk-v str= $num ' {if ($1>STR) {print $}} '

#循环IP列表进行筛选和处理
if [[!-Z $iplist]];
Then
For BLACK_IP in $iplist
Todo
#取得IP所在段
Ip_section= ' echo $black _ip | Awk-f "." ' {print $. ' $ "." $} '
#先检查白名单中是否存在匹配的IP段 (in order to support the whole segment of IP as white list)
Grep-q $ip _section./white_ip.txt
if [[$?-eq 0]];then
#若发现black_ip和白名单的一个段匹配, it is written to the list to be verified and is temporarily spared
echo $black _ip >>./recheck_ip.txt
Else
#若不再白名单当中, add black_ip directly to the drop rule in the firewall and record
IPTABLES-NL | grep $black _ip | | Iptables-i input-s $black _ip-j DROP
echo $black _ip >>./black_ip.txt
Fi
Done
Fi

2. If there is a white list IP to exclude, you need to add these IP to the white_ip.txt of the script directory, one line

3. Finally, use CRONTAB-E to add the script to the System planning task, which is executed every five minutes (the last number represents the maximum concurrency):

*/5 * * * */root/deny_ip.sh >dev/null 2>&1

Note:

1. The script for the use of Baidu Cloud acceleration or 360 site Guardian site is invalid, because IP has become a CDN node, do not use this script

2. If you do not need to support a white list of segments, you can modify the code of the 24~27 line, more accurate corresponding to each IP

3. If the discovery and the white list of the same segment IP appears in the high concurrency list, will not directly pull black, but write to Recheck_ip.txt, if there is a monitoring information mechanism, you can join in this place monitoring alarm, inform the administrator this suspicious IP

Enhanced version: The above shell script is added to the crontab scheduled task to execute every 5 minutes, if you think the time interval is too long, then you can consider the enhanced version.

#!/bin/bash
#Author: Zhangge
#Desc: Auto Deny black_ip Script.
#Date: 2014-11-05
#取得参数 is a concurrent threshold, and if left blank, the default allows single IP maximum 100 concurrency (the actual test found that 2M bandwidth, 10 or more concurrent servers have been unable to access!) )
if [[Z $]];then
Num=50
Else
Num=$1
Fi

#巧妙的进入到脚本工作目录
CD $ (CD $ (dirname $BASH _source) && pwd)

#请求检查, judge, and pull black main function
function check () {
iplist= ' netstat-an |grep ^tcp.*:80|egrep-v ' listen|127.0.0.1 ' |awk-f ' [] +| [:] ' {print $} ' |sort|uniq-c|sort-rn|awk-v str= $num ' {if ($1>STR) {print $}} '
if [[!-Z $iplist]];
then< br> >./iplist/black_ip.txt
for black_ip in $iplist
do
#白名单过滤中已取消IP段的判断功能, you can modify the following code as needed (refer to the script written the day before yesterday)
# Exclude_ip= ' echo $black _ip | Awk-f "." ' {print $. ' $ "." $} '
#grep-Q $exclude _ip./white_ip.txt
grep-q $black _ip./white_ip.txt
If [$?-eq 0]];then
Echo $b LACK_IP (WHITE_IP) ">>./black_ip.txt
Else
Echo $black _ip >>./black_ip.txt     
Iptables-nl | grep $black _ip | | (iptables-i input-s $black _ip-j DROP && echo "$black _ip  ' date +%y-%m-%h:%m:%s '" >>./iplist/denylog. TXT)
Fi
Done
#存在并发超过阈值的单IP就发送邮件
sendmsg
Fi
}

#发邮件函数
function sendmsg () {
NETSTAT-NUTLP | grep "SendMail" >/dev/null 2>&1 | | /etc/init.d/sendmail Start >/dev/null 2>&1
Echo-e "From:ge@zhangge.net\nto:gobi918@vip.qq.com\nsubject:someone attacking your system!! \nits Ip is ">./message
Cat./black_ip.txt >>./message
/usr/sbin/sendmail-f ge@zhangge.net-t gobi918@vip.qq.com-i <./message
}

#间隔10s无限循环检查函数
While True
Todo
Check
#每隔10s检查一次, time can be customized according to need
Sleep 10
Done


Ii. Executing scripts

After you save the above code as DENY_BLACKIP.SH, use the following command to run the script backstage (the following 50 indicates the number of concurrent, adjustable):

Nohup/deny_blackip.sh &

After execution, the following message appears:

[Root@mars_server iptables]# nohup./deny_blackip.sh &
[1] 23630
[Root@mars_server iptables]# nohup:ignoring input and appending output to ' nohup.out '

Indicates that if the script produces output information, it will be written to the Nohup.out file, and you can see that the current directory has generated an empty

Nohup.out:

[Root@mars_server iptables]# ll Nohup.out
-RW-------1 Root 0 Nov 5 21:15 nohup.out

All right, now you perform the implementation PS aux should be able to find the following process:

Root 23630 0.0 0.2 5060 1224 pts/0 S 21:15 0:00/bin/bash./deny_blackip.sh
Root 23964 0.0 0.0 4064 508 pts/0 S 21:19 0:00 sleep 10

Everything is going well! Every 10s will check the server request, if an IP more than 50 concurrent, immediately pull black, and an email to you!

Additional Instructions

1. The script sends the mail to need to install the SendMail, if does not install, executes yum-y install SendMail installs and starts can;

2. To stop the script running in the background, just use the PS aux command to find the PID thread number of the script, and then execute the kill-9 PID number to end;

3. About the single IP concurrency restrictions on the script, the actual test at the same time open a blog multiple pages and continue to refresh, at most, it will produce more than 10 concurrent, so single IP more than 50 concurrent has a lot of problems! Of course, the threshold of the article set to 50 is only recommended value, you can adjust to the needs of their own;

4. Write this script, mainly in order to make up for using crontab execution interval is only a minimum of 1 minutes, you can make CC protection more rigorous, even every 1S execution once! Although the script is not resource-intensive, it is advisable to recommend 10s to perform once, not too extreme, right?

5. For whitelist filtering, as long as the white list IP saved to the script in the same directory in the White_ip.txt file can be found in the White list attack IP, the script will not directly pull black, but send an e-mail to you, let you judge this white list attack you are for Mao? If the whitelist needs to support IP segments, please refer to my regular version of the script.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.