使用Nginx+Lua實現自定義WAF


                          使用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保存,無需重啟) 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM