OpenResty--搭建简单的CC防护,openresty--搭建cc


说明:写在前面,本防护思路为设定阈值和时间段,在记录每个IP访问+uri(可不加,因为考虑到了不同的接口访问次数也许会有不同)的次数,在单位时间段内超过所设定阈值返回403,并将其IP封禁一段时间。

用到的ngx_lua模块:

ngx.var
ngx.shared.DICT

先编写ngx.conf配置文件:

http{
    ....
    lua_shared_dict cc_dict 50m; #大小根据业务访问量来定
    ....
server{
    ....
    access_by_lua_file path/to/your/luacode/access.lua;
    ....
}
}

编写access.lua

local cc_dict=ngx.shared.cc_dict
local access_ip=ngx.var.remote_addr
local access_uri=ngx.var.uri
local policy_table={
    api_1={
        uri="/test1",
        threshold=20,
        period=2
    },
    api_2={
        uri="/test2",
        threshold=30,
        period=1
    },
    default={
        threshold=10,
        period=1
    }
}

--anti_CC module
local cc_policy_table=nil
for k,v in pairs(policy_table) do
    if v.uri==access_uri then
        cc_policy_table=v
        break
    end
end
if not cc_policy_table then
    cc_policy_table=policy_table["default"]
end
local threshold=cc_policy_table.threshold
local time_period=cc_policy_table.period
local forbidden_ip,status=cc_dict:get("forbidden ip"..access_ip)
if forbidden_ip==1 then
    ngx.exit(ngx.HTTP_FORBIDDEN)
end
local visit_num,status=cc_dict:get(access_ip)
if visit_num then
    if visit_num>=threshold then
        cc_dict:set("forbidden ip"..access_ip,1,10)
        ngx.exit(ngx.HTTP_FORBIDDEN)
    else
        cc_dict:incr(access_ip,1)
    end
else
    cc_dict:set(access_ip,1,time_period)
end
保存运行即可,可以用apache-jmter测试下是否有效。



相关内容

    暂无相关文章