openresty(nginx扩展)实现防cc攻击

openresty安装:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
openresty:
image: openresty/openresty:centos
ports:
- "80:80"
- "443:443"
volumes:
- /etc/localtime:/etc/localtime
- /home/config/openresty/conf/nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf:ro
- /home/config/openresty/logs:/usr/local/openresty/nginx/logs
- /home/config/openresty/www:/usr/local/openresty/nginx/www:ro
deploy:
replicas: 1
restart_policy:
condition: on-failure
networks:

openresty(nginx扩展)实现防cc攻击

1
2
3
4
location / {
default_type text/html;
content_by_lua_file "/usr/local/openresty/nginx/conf/cc.lua";
}

/usr/local/openresty/nginx/conf/cc.lua文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
local ip = ngx.var.binary_remote_addr
local limit = ngx.shared.limit
local req,_=limit:get(ip)
if req then
if req > 20 then
ngx.exit(503)
else
limit:incr(ip,1)
end
else
limit:set(ip,1,10)
end

local jsjump = ngx.shared.jsjump
local uri = ngx.var.request_uri
local jspara,flags=jsjump:get(ip)
local args = ngx.req.get_uri_args()
if jspara then
if flags then
ngx.exec("@cc")
else
local p_jskey=''
if args["jskey"] and type(args["jskey"])=='table' then
p_jskey=args["jskey"][table.getn(args["jskey"])]
else
p_jskey=args["jskey"]
end
if p_jskey and p_jskey==tostring(jspara) then
jsjump:set(ip,jspara,3600,1)
ngx.exec("@cc")
else
local url=''
if ngx.var.args then
url=ngx.var.scheme.."://"..ngx.var.host..uri.."&jskey="..jspara
else
url=ngx.var.scheme.."://"..ngx.var.host..uri.."?jskey="..jspara
end
local jscode="<script>window.location.href='"..url.."';</script>"
ngx.say(jscode)
end
end
else
math.randomseed( os.time() );
local random=math.random(100000,999999)
jsjump:set(ip,random,60)
local url=''
if ngx.var.args then
url=ngx.var.scheme.."://"..ngx.var.host..uri.."&amp;jskey="..random
else
url=ngx.var.scheme.."://"..ngx.var.host..uri.."?jskey="..random
end
local jscode="<script>window.location.href='"..url.."';</script>"
ngx.say(jscode)
end

lua代码部分解释:
1、1-12行是限速功能实现,第5和第10行表示10秒钟内容最多只能请求20次。
2、14-48行是验证部分,24行中的3600表示验证通过后,白名单时间为3600秒,即1小时。

-------------本文结束-------------
0%