Nginx Lua 脚本实现 CC 防御和 IP 屏蔽功能

本文介绍了如何使用 Nginx Lua 脚本实现 CC 防御和 IP 屏蔽功能,并提供了代码示例。

CC 防御

function denycc()
    if CCDeny then
        local uri=ngx.var.uri
        CCcount=tonumber(string.match(CCrate,'(.*)/'))
        CCseconds=tonumber(string.match(CCrate,'/(.*)'))
        local token = getClientIp()..uri
        local limit = ngx.shared.limit
        local req,_=limit:get(token)
        if req then
            if req > CCcount then
                 ngx.exit(503)
                return true
            else
                 limit:incr(token,1)
            end
        else
            limit:set(token,1,CCseconds)
        end
    end
    return false
end

该脚本通过 shared memory 存储每个请求的访问次数,并根据配置的限制次数进行访问控制。当访问次数超过限制时,返回 503 错误。

IP 屏蔽

function denycc()
    if CCDeny then
        local uri=ngx.var.uri
        CCcount=tonumber(string.match(CCrate,'(.*)/'))
        CCseconds=tonumber(string.match(CCrate,'/(.*)'))
        local token = getClientIp()..uri
        local limit = ngx.shared.limit
        local req,_=limit:get(token)
        if req then
            if req > CCcount then
                ngx.exit(503)
                return true
            else
                limit:incr(token,1)
            end
        else
            limit:set(token,1,CCseconds)
        end
    end
    -- 添加IP屏蔽时间控制秒数
    local ipBlacklist = ngx.shared.ip_blacklist
    local ip = getClientIp()
    local blockTime = ipBlacklist:get(ip)
    if blockTime and blockTime > ngx.time() then
        ngx.exit(403)
        return true
    end
    return false
end

在函数中添加了一个 ipBlacklist 共享内存,用于存储被屏蔽的 IP 和屏蔽的时间。如果当前 IP 在 ipBlacklist 中被屏蔽并且屏蔽时间还未过期,则直接返回 403 错误,否则将继续执行 CC 攻击检测。

使用方法

  1. 将上述代码保存为 Lua 文件(例如 denycc.lua)。
  2. 在 Nginx 配置文件中添加以下内容:
location / {
    # ...
    # 加载 Lua 脚本
    content_by_lua_file denycc.lua;
}
  1. 重启 Nginx 服务。

其他说明

  • CCDeny, CCrate, getClientIp() 等函数需要根据具体需求进行定义和实现。
  • ngx.shared.limitngx.shared.ip_blacklist 是共享内存,需要在 Nginx 配置文件中进行定义和配置。
  • 该脚本仅提供参考,具体实现需要根据实际情况进行调整。
Nginx Lua 脚本实现 CC 防御和 IP 屏蔽功能

原文地址: https://www.cveoy.top/t/topic/oyYA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录