当前位置: 首页 > news >正文

实战教程 ---- Nginx结合Lua实现WAF拦截并可视化配置教程框架

Nginx结合Lua实现WAF拦截并可视化配置教程框架。搭建基础Web应用防火墙(WAF)系统。

1. 什么是WAF以及为什么选择Nginx+Lua

Web应用防火墙(WAF)是一种特殊的网络安全解决方案,用于保护Web应用免受各种攻击,如SQL注入、XSS、CSRF等。Nginx是一个高性能的Web服务器和反向代理服务器,而Lua是一种轻量级脚本语言。通过Lua模块,我们可以在Nginx中编写自定义逻辑,实现灵活的WAF功能。

2. 环境准备

首先需要安装Nginx和Lua模块。推荐使用OpenResty,它是一个基于Nginx的高性能Web平台,集成了LuaJIT和一系列Lua模块。

# 安装OpenResty
wget https://openresty.org/download/openresty-1.21.4.1.tar.gz
tar -xzvf openresty-1.21.4.1.tar.gz
cd openresty-1.21.4.1/
./configure
make
sudo make install

3. 基本WAF规则实现

下面是一个简单的基于Lua的WAF实现,用于检测和拦截常见的攻击模式:

-- waf.lua
-- 定义攻击特征匹配规则
local rules = {-- SQL注入检测{pattern = "('|%27).*(union|select|insert|update|delete)", description = "SQL注入检测"},-- XSS攻击检测{pattern = "<script.*?>.*?</script>", description = "XSS脚本攻击检测"},{pattern = "<.*?on[a-z]+=.*?>", description = "XSS事件监听攻击检测"},-- 命令注入检测{pattern = "(;|&|%|%20|%0A).*(cat|ls|pwd|rm|mv|cp|echo)", description = "命令注入检测"},
}-- 获取请求信息
local uri = ngx.var.uri
local args = ngx.req.get_uri_args()
local method = ngx.var.request_method-- 检查URI
for _, rule in ipairs(rules) doif string.find(uri, rule.pattern) thenngx.log(ngx.ERR, "WAF拦截: ", rule.description, ", URI: ", uri)ngx.status = ngx.HTTP_FORBIDDENngx.say("Access Denied")ngx.exit(ngx.HTTP_FORBIDDEN)end
end-- 检查GET参数
if method == "GET" thenfor key, value in pairs(args) doif type(value) == "string" thenfor _, rule in ipairs(rules) doif string.find(value, rule.pattern) thenngx.log(ngx.ERR, "WAF拦截: ", rule.description, ", 参数: ", key, " = ", value)ngx.status = ngx.HTTP_FORBIDDENngx.say("Access Denied")ngx.exit(ngx.HTTP_FORBIDDEN)endendendend
end-- 检查POST参数
if method == "POST" thenngx.req.read_body()local post_args = ngx.req.get_post_args()for key, value in pairs(post_args) doif type(value) == "string" thenfor _, rule in ipairs(rules) doif string.find(value, rule.pattern) thenngx.log(ngx.ERR, "WAF拦截: ", rule.description, ", 参数: ", key, " = ", value)ngx.status = ngx.HTTP_FORBIDDENngx.say("Access Denied")ngx.exit(ngx.HTTP_FORBIDDEN)endendendend
end

4. 配置Nginx加载WAF脚本

在Nginx配置文件中添加以下内容,让Nginx在处理请求时加载并执行WAF脚本:

# nginx.conf
http {# ... 其他配置 ...# Lua模块路径lua_package_path "/path/to/your/lua/?.lua;;";server {listen 80;server_name example.com;# 在处理请求前执行WAF脚本access_by_lua_file /path/to/your/waf.lua;# ... 其他配置 ...}
}

5. 实现可视化配置界面

为了便于管理WAF规则,我们可以创建一个简单的Web界面来管理规则。以下是一个基本的实现:

-- waf_manager.lua
local uri_args = ngx.req.get_uri_args()
local action = uri_args.action or ""-- 规则文件路径
local rules_file = "/path/to/your/rules.lua"-- 读取规则文件
local function read_rules()local file = io.open(rules_file, "r")if not file thenreturn {}endlocal content = file:read("*all")file:close()-- 解析规则文件local rules = {}local pattern = "{'([^']+)', '([^']+)', '([^']+)'}"for description, pattern, action in string.gmatch(content, pattern) dotable.insert(rules, {description = description,pattern = pattern,action = action})endreturn rules
end-- 写入规则文件
local function write_rules(rules)local file = io.open(rules_file, "w")if not file thenreturn falseendfor _, rule in ipairs(rules) dofile:write(string.format("{'%s', '%s', '%s'}\n", rule.description, rule.pattern, rule.action))endfile:close()return true
end-- 处理不同的请求动作
if action == "list" then-- 返回规则列表local rules = read_rules()local json = require("cjson")ngx.say(json.encode(rules))elseif action == "add" then-- 添加新规则ngx.req.read_body()local post_args = ngx.req.get_post_args()local new_rule = {description = post_args.description or "",pattern = post_args.pattern or "",action = post_args.action or "block"}local rules = read_rules()table.insert(rules, new_rule)if write_rules(rules) thenngx.say("规则添加成功")elsengx.status = ngx.HTTP_INTERNAL_SERVER_ERRORngx.say("规则添加失败")endelseif action == "delete" then-- 删除规则local index = tonumber(uri_args.index)if not index thenngx.status = ngx.HTTP_BAD_REQUESTngx.say("无效的规则索引")returnendlocal rules = read_rules()if index < 1 or index > #rules thenngx.status = ngx.HTTP_BAD_REQUESTngx.say("规则索引超出范围")returnendtable.remove(rules, index)if write_rules(rules) thenngx.say("规则删除成功")elsengx.status = ngx.HTTP_INTERNAL_SERVER_ERRORngx.say("规则删除失败")endelse-- 默认显示管理界面ngx.header.content_type = "text/html";ngx.say([[
<!DOCTYPE html>
<html>
<head><title>WAF规则管理</title><style>body { font-family: Arial, sans-serif; }.container { max-width: 800px; margin: 0 auto; padding: 20px; }table { width: 100%; border-collapse: collapse; }table, th, td { border: 1px solid #ddd; padding: 8px; }th { background-color: #f2f2f2; }tr:nth-child(even) { background-color: #f2f2f2; }input, button { padding: 8px; margin: 5px 0; }</style>
</head>
<body><div class="container"><h2>WAF规则管理</h2><h3>添加新规则</h3><form action="?action=add" method="post">描述: <input type="text" name="description" required><br>正则表达式: <input type="text" name="pattern" required><br>动作: <select name="action"><option value="block">阻止</option><option value="log">记录</option></select><br><button type="submit">添加规则</button></form><h3>规则列表</h3><div id="rules-list">加载中...</div><script>// 使用AJAX获取规则列表function loadRules() {fetch('?action=list').then(response => response.text()).then(data => {const rules = JSON.parse(data);let html = '<table>';html += '<tr><th>序号</th><th>描述</th><th>正则表达式</th><th>动作</th><th>操作</th></tr>';rules.forEach((rule, index) => {html += `<tr><td>${index + 1}</td><td>${rule.description}</td><td>${rule.pattern}</td><td>${rule.action}</td><td><button onclick="deleteRule(${index})">删除</button></td></tr>`;});html += '</table>';document.getElementById('rules-list').innerHTML = html;}).catch(error => {document.getElementById('rules-list').innerHTML = '加载规则失败: ' + error.message;});}// 删除规则function deleteRule(index) {if (confirm('确定要删除这条规则吗?')) {fetch(`?action=delete&index=${index}`).then(response => response.text()).then(message => {alert(message);loadRules();}).catch(error => {alert('删除规则失败: ' + error.message);});}}// 页面加载完成后加载规则document.addEventListener('DOMContentLoaded', loadRules);</script></div>
</body>
</html>]])
end

6. 配置Nginx访问控制界面

在Nginx配置中添加对管理界面的访问控制:

# nginx.conf
http {# ... 其他配置 ...server {listen 80;server_name example.com;# WAF规则管理界面location /waf_manager {# 限制访问IPallow 192.168.1.0/24;  # 允许内部网络访问deny all;  # 拒绝其他所有IPdefault_type 'text/html';content_by_lua_file /path/to/your/waf_manager.lua;}# 正常网站访问location / {access_by_lua_file /path/to/your/waf.lua;# ... 其他配置 ...}}
}

7. 日志记录与监控

完善WAF的日志记录功能,以便于后续分析和监控:

-- 在waf.lua中添加日志记录函数
local function log_attack(rule, request_info)local log_file = "/var/log/nginx/waf.log"local timestamp = os.date("%Y-%m-%d %H:%M:%S")local log_entry = string.format("[%s] [WAF] [%s] [%s] [%s] [%s] [%s]\n",timestamp,rule.description,ngx.var.remote_addr,ngx.var.request_method,ngx.var.uri,request_info or "")local file = io.open(log_file, "a")if file thenfile:write(log_entry)file:close()end
end

8. 测试与优化

完成WAF的基本实现后,需要进行充分的测试:

  1. 使用OWASP ZAP等工具进行漏洞扫描,验证WAF的防护效果
  2. 在测试环境中模拟各种攻击,检查WAF是否能正确拦截
  3. 分析日志,优化规则,减少误报率

通过以上步骤,可以实现一个基于Nginx和Lua的WAF系统,并通过可视化界面进行配置管理。

http://www.lryc.cn/news/606048.html

相关文章:

  • 融合数字孪生的智慧能源光伏场站检测系统应用解析
  • 生产管理升级:盘古IMS MES解锁全链路可控可溯,激活制造效率
  • 从 MySQL 迁移到 TiDB:使用 SQL-Replay 工具进行真实线上流量回放测试 SOP
  • 【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 微博评论数据可视化分析-点赞区间折线图实现
  • 保姆级别IDEA关联数据库方式、在IDEA中进行数据库的可视化操作(包含图解过程)
  • 技术速递|GitHub Copilot for Eclipse 迈出重要一步
  • SQL极简函数实战:巧用GREATEST()与LEAST()实现智能数据截断
  • Promise.all Promise.race Promise.any三个对比
  • 【Flask基础②】 | 路由、响应与异常处理
  • 在嵌入式系统或 STM32 平台中常见的外设芯片和接口
  • 《通信原理》学习笔记——第六章
  • 乱删文件,电脑不能开机,怎么办
  • 深入解析 Spring AI 系列:剖析OpenAI接口接入组件
  • 常见的中间件漏洞(tomcat,weblogic,jboss,apache)
  • 微信小程序中进行参数传递的方法
  • 5 种智能策略,从 iQOO 到 iQOO 转移照片
  • Apache RocketMQ 中 Topic 的概念、属性、行为约束和最佳实践
  • 【机器人+相机通讯】宇树科技相机通信
  • ChatGPT的下一站:从“答案引擎”到“思维教练”
  • 基于单片机胎压检测/锅炉蒸汽压力/气压检测系统
  • 从姑苏区人工智能大模型基础设施招标|学习服务器、AI处理器、GPU
  • 深度学习(鱼书)day07--误差反向传播(前四节)
  • 项目推进难的原因有哪些?问题及应对
  • TOML介绍
  • 14day-ai入门-人工智能基础学习-OpenCV-图像预处理4
  • 我在 Arch Linux Plasma 6 Wayland 下驯服 Chromium 输入法的完整记录
  • ACOSRAR改进连续蚁群算法用于优化复杂环境下无人机路径规划,Matlab代码实现
  • 智慧工地系统:建筑工程管理的智能化革新与实践
  • 淘宝 API HTTP/2 多路复用与连接优化实践:提升商品数据采集吞吐量
  • Vue3 + Electron 技术栈下 MAC 地址获取的方法、准确性优化与应对策略