使用Nginx+Lua实现自定义WAF
版权声明:全部抄自赵班长的GitHub上waf项目
功能列表:
支持IP白名单和黑名单功能,直接将黑名单的IP访问拒绝。 支持URL白名单,将不需要过滤的URL进行定义。 支持User-Agent的过滤,匹配自定义规则中的条目,然后进行处理(返回403)。 支持CC攻击防护,单个URL指定时间的访问次数,超过设定值,直接返回403。 支持Cookie过滤,匹配自定义规则中的条目,然后进行处理(返回403)。 支持URL过滤,匹配自定义规则中的条目,如果用户请求的URL包含这些,返回403。 支持URL参数过滤,原理同上。 支持日志记录,将所有拒绝的操作,记录到日志中去。 日志记录为JSON格式,便于日志分析,例如使用ELKStack进行攻击日志收集、存储、搜索和展示。
Nginx + Lua部署
安装依赖包:
# yum install -y readline-devel pcre-devel openssl-devel # cd /usr/local/src 下载并编译安装openresty # wget https://openresty.org/download/ngx_openresty-1.9.3.2.tar.gz
# tar zxf ngx_openresty-1.9.3.2.tar.gz # cd ngx_openresty-1.9.3.2 # ./configure --prefix=/usr/local/openresty-1.9.3.2 \ --with-luajit --with-http_stub_status_module \ --with-pcre --with-pcre-jit # gmake && gmake install # ln -s /usr/local/openresty-1.9.3.2/ /usr/local/openresty
openresty安装
vim /usr/local/openresty/nginx/conf/nginx.conf server { location /hello { default_type text/html; content_by_lua_block { ngx.say("HelloWorld") } } } # /usr/local/openresty/nginx/sbin/nginx -t nginx: the configuration file /usr/local/openresty-1.9.3.2/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/openresty-1.9.3.2/nginx/conf/nginx.conf test is successful # /usr/local/openresty/nginx/sbin/nginx
测试:
curl http://192.168.199.33/hello
WAF部署:
git clone https://github.com/unixhot/waf.git
cp -a ./waf/waf /usr/local/openresty/nginx/conf/
修改Nginx的配置文件,加入以下配置。注意路径,同时WAF日志默认存放在/tmp/日期_waf.log
lua_shared_dict limit 50m; lua_package_path "/usr/local/openresty/nginx/conf/waf/?.lua"; init_by_lua_file "/usr/local/openresty/nginx/conf/waf/init.lua"; access_by_lua_file "/usr/local/openresty/nginx/conf/waf/access.lua";
重新载入nginx:
/usr/local/openresty/nginx/sbin/nginx –t /usr/local/openresty/nginx/sbin/nginx -s reload
测试:
访问以sql为后缀的文件
也可以直接跳转到某个页面:
修改conf.lua
config_waf_output = "redirect" #默认是html config_waf_redirect_url = "http://www.cnblogs.com/panwenbin-logs/" #自定义url
测试语法,重新载入nginx
[root@localhost waf]# /usr/local/openresty/nginx/sbin/nginx -t nginx: the configuration file /usr/local/openresty-1.9.3.2/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/openresty-1.9.3.2/nginx/conf/nginx.conf test is successful [root@localhost waf]# /usr/local/openresty/nginx/sbin/nginx -s reload
在访问看看是否能跳转
具体规则见url.rule文件
防CC攻击:
以ab命令为例:
再访问一次(一分钟之内):
发现第一次非2xx请求为89(成功11个)
第二次非2xx请求为100(成功0个)
whiteip.rule IP白名单(直接写入IP保存,无需重启)
blackip.rule IP黑名单(直接写入IP保存,无需重启)