Prevents CC and DDoS attacks in nginx

Source: Internet
Author: User

Defend against http get flood (CC) attacks in nginx

Nginx is a lightweight Web server developedProgramDeveloped by the designer Igor Sysoev, it was initially used by a large Russian portal website and search for Rambler.
It is characterized by a small amount of memory and high concurrency. In fact, nginx's concurrency is indeed good in the same type of website servers.

Although nginx can process more connections than Apache, HTTP GET
Flood targets not only web servers, but also database servers. A large number of HTTP requests generate a large number of database queries, so that the database can stop responding within a few seconds, and the system load increases, leading to server hosting.

This article describes how to quickly and effectively defend against CC attacks in centos + nginx. As for how to install nginx is not detailed introduction, interested readers can download on the official nginx website (http://www.nginx.org /)Source code. If you are using centos5, you can also use the RPM package for installation (http://centos.alt.ru/repository/centos/5/i386/nginx-stable-0.7.65-1.el5.i386.rpm ).

1.
proactively suppress
to enable nginx to support more concurrent connections, adjust the number of worker threads and the maximum number of connections supported by each worker thread according to the actual situation. For example, if "worker_processes
10" and "worker_connections 1024" are set, the maximum number of connections supported by this server is 10 × 1024 = 10240.
worker_processes
10;
events {
Use epoll;
worker_connections 10240;
}

nginx
at the beginning of 0.7, two restricted user connection modules are provided: nginxhttplimitzonemodule and nginxhttplimitreqmodule.
the nginxhttplimitzonemodule can control the number of concurrent connections based on the conditions.
for example, you can define the following Code :
HTTP
{< br> limit_zone my_zone $ binary_remote_addr 10 m;
server {
location/somedir/{
limit_conn my_zone 1;

}< BR >}< br> where "limit_zone my_zone $ binary_remote_addr 10m" defines a storage region named my_zone and the content is a remote IP address and the size of my_zone is 10 MB; "Location
/somedir/" indicates that the rule is applied to the somedir directory; "limit_conn my_zone 1" indicates the IP address of the above-defined my_zone record area Only one connection can be established in the specified directory.

the nginxhttplimitreqmodule can control the request Frequency Based on the conditions.
for example, you can define the following code:
HTTP {
limit_req_zone $ binary_remote_addr zone = my_req_zone: 10 m rate = 1R/s;
...
server {
...
location/somedir/{
limit_req_zone zone = my_req_zone burst = 2;

}< br> where "limit_req_zone $ binary_remote_addr zone = my_req_zone: 10 m rate = 1R/s" defines a storage region named my_req_zone, the content of my_req_zone is a remote IP address, the size of my_req_zone is 10 m, and the average Request Rate in my_req_zone can only be 1 second; "Location
/somedir/" means to apply rules to the somedir directory; "limit_req_zone zone =
my_req_zone burst = 2" indicates a maximum of 2 burst requests per second for the IP addresses recorded in the my_req_zone record area in the directory specified in the request. speed.

When a connection triggers an appeal rule, nginx reports "503 service temporarily ".
Unavailable "error, stop the user request. A 503 error is returned, which has little impact on the server and only occupies one nginx thread. It is relatively cost-effective.

To test the effect, I put the above Code into the nginx configuration file, and wrote a PHP file to display phpinfo. In addition, I wrote an HTML file, which embedded multiple IFRAME to call the PHP file. When I open this HTML file, we can see that only one PHP file in the IFRAME is normally displayed, and other IFRAME are displayed with 503 errors.

 

 Image002.jpg(43.7 KB)

Application Example (discuz !)
Discuz! Is to use a large number of PHP Forum programs. Take discuz! 7.0 as an example, the program directory contains a large number of PHP files that can be directly accessed, but index is the most vulnerable to attacks. PHP (homepage), Forumdisplay. PHP (panel display), viewthread. PHP (post display ). Attackers usually initiate a large number of requests to these pages, resulting in the depletion of the number of HTTP server connections, the MySQL database stops responding, and the server crashes.
To prevent the above pages from being attacked, we can set the following rules for defense:
HTTP
{
Limit_zone myzone_bbs $ binary_remote_addr 10 m;

Limit_req_zone $ binary_remote_addr zone = BBS: 10 m rate = 1R/s;
...

Server {
...
Location ~
^/BBS/(index | Forumdisplay | viewthread). php $ {
Limit_conn
Myzone_bbs 3;
Limit_req zone = BBS burst = 2 nodelay;

Root HTML;
Fastcgi_pass
UNIX:/dev/SHM/php-cgi.sock;
Fastcgi_index index. php;


Fastcgi_param script_filename/usr/share/nginx/html $ fastcgi_script_name;

Include fastcgi_params;
}

}
}
After this rule is applied, the index under the BBS directory. PHP, Forumdisplay. PHP and viewthread. PHP allows only three connections to one IP address on these pages, and only one request is allowed per second (burst requests can reach two ).
Although such a rule generally does not affect normal users (few people open three pages in one second), to prevent access by users who are quick at hand, you can customize the 503 page in nginx, and prompt the user on the 503 page, and then refresh automatically.
Customize the 503 page in nginx:
Error_page
503
/Errpage/503.html;
503 page source code:
<HTML>
<Head>
<Title> the page is about to be loaded .... </Title>
<Meta
HTTP-equiv = Content-Type C>
<Meta name = "Robots"
C>
</Head>
<Body bgcolor = "# ffffff">
<Table
Cellpadding = "0" cellspacing = "0" border = "0" width = "700" align = "center"
Height = "85%">
<Tr align = "center" valign = "Middle">

<TD>
<Table cellpadding = "10" cellspacing = "0" border = "0 ″
Width = "80%" align = "center" style = "font-family:
Verdana, tahoma; color:
#666666; font-size: 11px ">
<Tr>
<TD valign = "Middle"
Align = "center" bgcolor = "# ebebeb">
<Br/> <B
Style = "font-size: 16px"> the page is about to be loaded </B>
<Br/> <br
/> The page refresh speed is too fast. Please be patient. The page will be loaded soon...
<Br/> [<
Href = "javascript: window. Location. Reload ();"> <font
Color = #666666> reload now </font> </a>]
<Br/> <br
/>
</TD>
</Tr>
</Table>

</TD>
</Tr>
</Table>
</Body>
</Html>

<Script language = JavaScript>
Function
Update ()
{
Window. Location. Reload ();
}
SetTimeout ("Update ()", 2000 );
</SCRIPT>

2.
passive defense
although the active defense has defended against most http get
flood attacks, it's still a little high, attackers will always find your weak links to launch attacks. So here we will also introduce some methods of passive defense.
1)
ip address
visitors can access the website through a browser. Generally, no more than 20 connections are established with the server, we can use scripts to Disable IP Access with excessive connections.
The following script uses the netstat command to list all connections. If the maximum number of connections of an IP address exceeds 150,
iptables blocks access:
#! /Bin/sh
Status = 'netstat-Na | awk' $5 ~ /[0-9] +: [0-9] +/
{print $5} '| awk-F ": "-'{print $1}' | sort-N | uniq-c | sort-N | tail-n
1'
num = 'echo $ status | awk '{print $1} ''
IP = 'echo $ status | awk' {print
$2}''
result = 'echo "$ num> 150 "| bc'
If [$ result = 1
]
then
echo IP: $ IP is over $ num, ban it!
/sbin/iptables-I input-S
$ IP-J Drop
fi

Run crontab-E and add the above script to crontab for automatic operation every minute:
*****
/Root/xxxx. Sh
Use the AB tool provided by Apache to test server pressure:
AB-N 1000-C 100 http://www.xxx.com/bbs/index.php
After the test is complete, we can see the prompt that the IP address is blocked in the system:
[Root @ xxxxxx
~] # Tail/var/spool/mail/root
Content-Type: text/plain;
Charset = ANSI_X3.4-1968
Auto-submitted: auto-generated
X-Cron-env:
<Shell =/bin/sh>
X-Cron-env: X-Cron-env:
<; Path =/usr/bin:/bin>
X-Cron-env: <LOGNAME = root>
X-Cron-env:
<User = root>

IP: 58.246.xx.xx is over 1047, ban it!
So far, the http get flood defense has been successful again.

2)
Shield requests based on signatures (better CC attack performance)
Generally, the attack request packets initiated by the same CC attack tool are the same and different from normal requests.
When the server encounters a CC attack, we can quickly view the log and analyze the request features, such as user-agent. The following is the User-Agent of a CC attack.
Mozilla/4.0.
(Compatible; MSIE 5.01; Windows NT 5.0; myie 3.01) cache-control: No-store,
Must-revalidate
Almost no normal browser will include the keyword "must-revalidate" in the User-Agent. Therefore, we can filter all requests with "must-revalidate" in the User-Agent to reject access:
If
($ Http_user_agent ~ Must-revalidate ){
Return 403;
}

This article mainly introduces http get in nginx
Flood defense. If something is wrong, I hope you can raise it to me. At the same time, we also hope that you can put this idea into common Web servers such as Apache and Lighttpd.

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.