Nginx Lua Redis 防止 CC 攻击导致部分定时任务 IP 被拉黑

2017-12-15 00:52:07 +08:00
 aimerforreimu

如题所示,我网站有一个 api 需要一个其他服务器的定时任务来访问,但是最近发现定时任务的 IP 被拉入到黑名单了,返回码是 503

登陆 redis 一看,果然是 lua 的锅

定时任务的日志如下:

这是我使用的 waf 的规则

local get_headers = ngx.req.get_headers
local ua = ngx.var.http_user_agent
local uri = ngx.var.request_uri
local url = ngx.var.host .. uri
local redis = require 'redis'
local red = redis.new()
local CCcount = 20
local CCseconds = 60
local RedisIP = '127.0.0.1'
local RedisPORT = 6379
local blackseconds = 7200

if ua == nil then
    ua = "unknown"
end

if (uri == "/wp-admin.php") then
    CCcount=20
    CCseconds=60
end

red:set_timeout(100)
local ok, err = red.connect(red, RedisIP, RedisPORT)

if ok then
    red.connect(red, RedisIP, RedisPORT)

    function getClientIp()
        IP = ngx.req.get_headers()["X-Real-IP"]
        if IP == nil then
            IP = ngx.req.get_headers()["x_forwarded_for"]
        end
        if IP == nil then
            IP  = ngx.var.remote_addr
        end
        if IP == nil then
            IP  = "unknown"
        end
        return IP
    end

    local token = getClientIp() .. "." .. ngx.md5(url .. ua)
    local req = red:exists(token)
    if req == 0 then
        red:incr(token)
        red:expire(token,CCseconds)
    else
        local times = tonumber(red:get(token))
        if times >= CCcount then
            local blackReq = red:exists("black." .. token)
            if (blackReq == 0) then
                red:set("black." .. token,1)
                red:expire("black." .. token,blackseconds)
                red:expire(token,blackseconds)
                ngx.exit(503)
            else
                ngx.exit(503)
            end
            return
        else
            red:incr(token)
        end
    end
    return
end

想问一下各位 V 友,如何修改代码可以设置一个 IP 到白名单里面,这个 ip 无论在 60s 内访问多少次有没有关系,不会被拉到 redis 中禁掉。 我对 lua 着个语言不是熟悉,感谢各位 V 友

1762 次点击
所在节点    问与答
4 条回复
Lax
2017-12-15 01:18:05 +08:00
if getClientIp() == "1.2.3.4" then
return
end
ryd994
2017-12-15 04:32:07 +08:00
这里一多半代码都可以用 Nginx 本身的模块实现
其次你这个服务器处理多少请求,少的话楼上的就很好
多的话不如用防火墙限制 IP,另开一个端口,或者直接 vpn 内网无限访问
ryd994
2017-12-15 04:34:13 +08:00
等等,你这个 get client ip 根本就不对啊
x-forwarded-for 说什么就信什么啊?要先验证来源实际 IP,是已知的可信代理才行啊。不然
lgpqdwjh
2017-12-15 09:57:42 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/414880

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX