OpenResty实现CC攻击防护方案
CC攻击(Challenge Collapsar)是一种针对应用层的DDoS攻击,OpenResty基于Nginx和Lua的高性能特性非常适合构建防护方案。以下是完整的实现方案:
1. 基础频率限制
IP访问频率控制
-- nginx.conf http部分添加共享内存区
lua_shared_dict ip_limit 10m;
-- Lua脚本实现
local limit_count = require "resty.limit.count"
local function anti_cc()
local lim, err = limit_count.new("ip_limit", 100, 60) -- 60秒内最多100次请求
if not lim then
ngx.log(ngx.ERR, "failed to instantiate a resty.limit.count object: ", err)
return ngx.exit(500)
end
local key = ngx.var.binary_remote_addr -- 客户端IP作为key
local delay, err = lim:incoming(key, true)
if not delay then
if err == "rejected" then
return ngx.exit(503)
end
ngx.log(ngx.ERR, "failed to limit count: ", err)
return ngx.exit(500)
end
-- 请求通过
end
2. 增强型防护策略
滑动窗口限流(更精确的控制)
local limit_req = require "resty.limit.req"
local rate = 10 -- 每秒10个请求
local burst = 20 -- 允许突发20个请求
local lim, err = limit_req.new("ip_limit", rate, burst)
if not lim then
ngx.log(ngx.ERR, "failed to instantiate a resty.limit.req object: ", err)
return ngx.exit(500)
end
local key = ngx.var.binary_remote_addr..":"..ngx.var.host -- IP+host组合键
local delay, err = lim:incoming(key, true)
if delay and delay > 0 then -- need to delay request
if delay > 0.5 then -- requests too frequent
return ngx.exit(503)
end
ngx.sleep(delay)
end
##3.JS挑战验证(防自动化工具)
-- nginx配置返回JS挑战页面
location /challenge {
content_by_lua_block {
local token=ngx.md5(math.random()..ngx.now())
local expires=ngx.time()+300 --5分钟有效
local js=[[<script>function submitToken(){...}</script>]]
ngx.header["Set-Cookie"]="__challenge_token="..token.."; Path=/; Max-Age=300"
redis:hset("challenge:"..token,"expires",expires)
ngx.say([[<html><body onload="setTimeout(submitToken,2000)">...</body></html>]])
}
}
--验证中间件:
if redis:hget("challenge:"..cookie_token,"passed")~="1"then
return ngx.redirect("/challenge?url="..ngx.encode_args({next=request_uri}))
end
##4.行为分析防护层
--收集用户行为特征:
local user_behavior={
ua=ngx.var.http_user_agent,
accept=ngx.var.http_accept,
lang=ngk.xvar.http_accept_language,
req_rate=(redis:get("rate:"..ip)or0)+1,
mouse_move=false,--通过前端JS埋点设置
}
--机器学习模型判断(PMML或ONNX运行时):
if ml_model:predict(user_behavior)>THRESHOLD then
add_to_blocklist(ip)
end
function add_to_blocklist(ip)
redis:sadd("blocked_ips",ip)
redis:expire("blocked_ips",3600)--封禁1小时
end
access_by_lua_block{
if redis:sismember("blocked_ips",ngk.xvar.binary_remote_addr)==1then
return ngn.xexit(403)
end
}
##5.WAF规则集成(可选)
http{
lua_package_path"/path/to/lua-resty-waf/?.lua;;";
init_by_lua_block{
waf=require"resty.waf"
config={rules_file="/path/to/rules.json"},
}
server{
access_by_luablock{
local res={}
waf.exec(config,nilres)
if res.action=="DENY"then
return ngn.xexit(res.status or403)
end
}
}
}
##6.DDoS弹性扩展设计
边缘节点协作:使用
lua-resty-consul
同步黑名单云原生集成:K8s HPA根据QPS自动扩容
BGP引流:与云厂商API联动触发清洗
内容由零声教学AI助手提供,问题来源于学员提问