How to configure the Nginx defense cc attack

Source: Internet
Author: User
Tags set cookie

Preface


This time we will talk about how to achieve the effect of Nginx defense attack by simple configuration file.
In fact, many times, all kinds of anti-attack ideas we understand, such as restricting IP Ah, filter attack string Ah, identify the attack fingerprint. But how to achieve it? With a daemon script? Using PHP to filter the bread layer? Or do you want to add a firewall directly? These are all defensive measures. However, this article will be introduced directly through the Nginx Common module and configuration file combination to achieve a certain defensive effect.
Verifying browser behavior
Simple Version
Let's make a metaphor first.
The community is doing welfare and distributing red envelopes to everyone in the square. And the villain sent a group of humanoid robots (no language module) to impersonator red envelopes, smart workers need to figure out ways to prevent red envelopes are impersonator.
So staff in the red envelopes before, will give the recipient a piece of paper, which says "red envelopes to take", if the person can read out the words on paper, then is a person, give red envelopes, if you can not read out, then please consciously. So the robot was detected and returned in a dingy manner.
Yes, in this metaphor, the person is the browser, the robot is the attacker, we can identify them by identifying the cookie function (read the words on the paper). Here is the Nginx configuration file notation.
if ($cookie _say! = "HBNL") {
Add_header Set-cookie "SAY=HBNL";
Rewrite. * "$scheme://$host $uri" REDIRECT;
}


Let's take a look at the meaning of these lines, when the cookie say is empty, to a set cookie say to HBNL 302 REDIRECT package, if the visitor can carry the cookie value in the second package, then the normal access to the site, if not, then he will live in 302. You can also test it with a CC attacker or webbench or a direct curl package, all of them living in the 302 world.
Of course, it's so easy to prevent it? Of course it's not that simple.
Enhanced Version
Carefully you will find that the configuration file is still flawed. If the attacker sets the cookie to SAY=HBNL (which can be set on the CC attacker), then the defense is no more than a dummy. We continue to illustrate the problem with just that metaphor.
The bad guys found this rule, to each robot to install the speakers, has been repeated "red envelopes to take, red envelopes to take", Mighty to the red envelopes.
At this time, the staff's response is to do so, ask the recipient to show their own name of the hukou, and read out his name, "I am xxx, red envelopes to take." So a group of robots that only buzz "red envelopes" were thrown back.
Of course, in order to cope with the problem, each robot has a hukou, was driven back to the reason is not to read their own name, although this is a bit absurd, alas. Then, let's look at the configuration file notation in this way
if ($cookie _say! = "Hbnl$remote_addr") {
Add_header Set-cookie "Say=hbnl$remote_addr";
Rewrite. * "$scheme://$host $uri" REDIRECT;
}


This way of writing and the previous difference is that the different IP request cookie value is not the same, such as IP is 1.2.3.4, then the need to set the cookie is say=hbnl1.2.3.4. The attacker would then be unable to circumvent this restriction by setting the same cookie (such as a CC attacker). You can continue to test with the CC attacker, and you will find that the CC attackers have all entered the 302 world of traffic.
But you can also feel that this does not seem to be a foolproof idea, because if an attacker studies the mechanism of the site, there is always a way to detect and pre-forge cookie value settings. Because we make differentiated data sources are just some of their own information (IP, user agent, etc.). An attacker could take a moment to make an attack script specifically targeted at the site.
Perfect Version
So how do you get their own information and they come up with a value they can't figure out?
I think, smart you must have guessed, with salt and hash. For example MD5 ("OPENCDN$REMOTE_ADDR"), although the attacker knew that he could own the IP, he could not tell how to use his IP to calculate the hash, because he was not able to reverse the hash. Of course, if you are not at ease, afraid of cmd5.com in case you can find out, you can add some special characters, and then scattered a few more times.
Unfortunately, Nginx is not able to hash the string by default, so we use the Nginx_lua module to implement.
rewrite_ by_lua  '
    local say = ngx.md5 (" Opencdn "   NGX.VAR.REMOTE_ADDR)
    if  (Ngx.var.cookie_ Say ~= say)  then
         ngx.header["Set-cookie"] =  "say="    SAY
        return  Ngx.redirect (ngx.var.scheme    "://"    NGX.VAR.HOST&NBSP, ....  ngx.var.uri)
    end


With this configuration, the attacker could not calculate the say value in the cookie beforehand, so the attack traffic (proxy-type CC and low-level contract cc) was out of the 302 hell.
As you can see, in addition to borrowing the MD5 function, the other logic is exactly the same as the above notation. So if you can, you can simply install a nginx compute hash of the third-party module to complete, perhaps more efficient.
This configuration can be placed in any location, if your site has to provide API functionality, the recommendation API must not be added to this paragraph, because the API calls are not browser behavior, will be treated as attack traffic. And, some weak crawlers will be trapped in 302, this needs to be noted.
At the same time, if you think set-cookie this action seems to be an attacker can be simulated by parsing the string, you can use the above header to set the cookie operation, into the high-end atmosphere of the JS complete, send back a containing doument.cookie= ... The text can be.
So, is the attack completely blocked? Can only say that the low-level attacks have been blocked, if the attackers have to spend a great price for each attacker plus WebKit module to parse JS and execute Set-cookie, then he can also escape 302 hell, in Nginx's view, it is true that the attack traffic and normal browsing traffic is the same. So how to defend it? The next section will tell you the answer.
Request Frequency Limit
Have to say, a lot of anti-CC measures are directly in the request frequency limit to achieve, but, a lot of there are some problems.
So what are the problems?
First of all, if the request by IP to limit the frequency, it is easy to lead to some manslaughter, such as I have a place to export IP so few, and a lot of visitors, the request frequency is very easy to limit, then that place users will not be able to access your site.
So you will say, I use the session to limit the problem. Well, your session opens the door to the attackers. Why is it? As you can see above, you probably already know, because like the "red envelope" loudspeaker, many languages or the session in the frame can be forged. In PHP, for example, you can see the Phpsessionid in the browser cookie, this ID is different, the session is different, and if you make up a phpsessionid past, you will find that the server also recognized the ID, A session was initialized for this ID. Then, the attacker would simply have to construct a new SessionID each time the package is sent, and it would be easy to avoid the limit of the number of requests on the session.
So how do we limit the frequency of this request?
First, let's start with a sessionid that an attacker could not invent, one way to record each given ID in a pool, and then to query when the request came, and if not, to reject the request. This way we do not recommend, first a website already has a session pool, so do a no doubt some waste, but also need to do the pool of traversal comparison query, too much consumption performance. We want a sessionid that can be stateless, okay? OK.
Rewrite_by_lua '
Local random = Ngx.var.cookie_random
if (random = nil) Then
Random = Math.random (999999)
End
Local token = NGX.MD5 ("Opencdn": ngx.var.remote_addr: Random)
if (Ngx.var.cookie_token ~= token) Then
ngx.header["Set-cookie"] = {"token=": Token, "random=": Random}
Return Ngx.redirect (Ngx.var.scheme. "://" .. Ngx.var.host. Ngx.var.uri)
End
‘;

Do you think it looks familiar? Yes, this is the perfect version of the last section, plus a random number so that users of the same IP can have different tokens. Similarly, as long as the Nginx third-party module provides hashing and random number functions, this configuration can also be done without LUA directly with a pure configuration file.
With this token, the equivalent of each visitor has a token that cannot be forged and unique, in which case the request limit is meaningful.
Because of the token to do bedding, we can not do what white list, blacklist, directly through the limit module to complete.
http{
...
Limit_req_zone $cookie _token zone=session_limit:3m rate=1r/s;
}

And then we just need to add the token configuration in the back.
limit_req zone=session_limit burst=5;

Therefore, two lines of configuration will let Nginx in the session layer to solve the request frequency limit. However, there seems to be a flaw, because an attacker could break the request frequency limit by always acquiring tokens, which would be perfect if you could limit the frequency of one IP to get tokens. Can you do that? OK.
http{
...
Limit_req_zone $cookie _token zone=session_limit:3m rate=1r/s;
Limit_req_zone $binary _remote_addr $uri zone=auth_limit:3m rate=1r/m;
}
Location/{
Limit_req Zone=session_limit burst=5;
Rewrite_by_lua '
Local random = Ngx.var.cookie_random
if (random = nil) Then
Return Ngx.redirect ("/auth?url=": Ngx.var.request_uri)
End
Local token = NGX.MD5 ("Opencdn": ngx.var.remote_addr: Random)
if (Ngx.var.cookie_token ~= token) Then
Return Ngx.redirect ("/auth?url=": Ngx.var.request_uri)
End
‘;
}
Location/auth {
Limit_req Zone=auth_limit burst=1;
if ($arg _url = "") {
return 403;
}
Access_by_lua '
Local random = Math.random (9999)
Local token = NGX.MD5 ("Opencdn": ngx.var.remote_addr: Random)
if (Ngx.var.cookie_token ~= token) Then
ngx.header["Set-cookie"] = {"token=": Token, "random=": Random}
Return Ngx.redirect (Ngx.var.arg_url)
End
‘;
}

I think everyone should have guessed that the principle of this configuration file is: The original token of the function of the separation to a auth page, and then use limit to the Auth page frequency limit can be. The frequency here is 1 IPs authorized 1 tokens per minute. Of course, this number can be adjusted to suit your business needs.


It is important to note that this auth part of my Lua is Access_by_lua, because the limit module is executed after the rewrite phase, and if the rewrite phase is 302, the limit will be invalidated. Therefore, this LUA configuration I can not guarantee with the native configuration file implementation, because do not know how to use the configuration file in the rewrite phase after the 302 jump, also ask Daniel can point ah.
Of course, if you are not satisfied with this limitation, want to do a certain IP if you reach the limit more than a few times a day after the direct IP, it is also possible, you can use a similar idea to make a wrong page, and then reach the upper limit does not return 503 but jump to the error page, Then the error page also makes a request limit, such as only 100 times a day, then when more than 100 times the error (Request the wrong page 100 times), that day this IP can no longer access the site.

As a result, we implemented a website access frequency limit through these configurations. However, this configuration is not to say that can completely prevent the attack, can only say that the cost of the attackers to become higher, so that the site's ability to carry attacks stronger, of course, if Nginx can carry these traffic, and then the bandwidth is not blocked. If your house is blocked, you still want to open the door, it is really no way.


Then, to do the traffic protection, let's take a look at the defenses for attacks like scanners.
Anti-Scan
NGX_LUA_WAF Module
This is a good WAF module, and we're not going to make the wheel again. Can directly use this module to do the protection, of course, can also be fully matched with the limit module, using the idea above to achieve an IP or sealed session effect.
Summary
The purpose of this article is to give you a direct and simple copy of the configuration in our examples, and we want to write a configuration file that fits your own business needs.


How to configure the Nginx defense cc attack

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.