本文主要介绍ModSecurity v3.0.x在Nginx环境下的安装、WAF规则文件配置、以及防御效果的验证,因此对于Nginx仅进行简单化安装。
服务器操作系统:linux 位最小化安装
一、安装相关依赖工具
Bash
yum install -y git wget epel-release
yum install -y gcc-c++ flex bison yajl lmdb lua curl-devel curl GeoIP-devel zlib-devel pcre-devel pcre2-devel libxml2-devel ssdeep-devel libtool autoconf automake make#以下组件无法直接yum安装,需要手动下载安装,请注意检查devel包与系统中对应组件的版本一致性
wget http://rpmfind.net/linux/centos/8-stream/PowerTools/x86_64/os/Packages/lua-devel-5.3.4-12.el8.x86_64.rpm
wget http://rpmfind.net/linux/centos/8-stream/PowerTools/x86_64/os/Packages/yajl-devel-2.1.0-12.el8.x86_64.rpm
wget http://rpmfind.net/linux/centos/8-stream/PowerTools/x86_64/os/Packages/lmdb-devel-0.9.24-2.el8.x86_64.rpm
wget http://rpmfind.net/linux/centos/8-stream/PowerTools/x86_64/os/Packages/doxygen-1.8.14-12.el8.x86_64.rpm
yum localinstall -y lua-devel-5.3.4-12.el8.x86_64.rpm
yum localinstall -y yajl-devel-2.1.0-12.el8.x86_64.rpm
yum localinstall -y lmdb-devel-0.9.24-2.el8.x86_64.rpm
yum localinstall -y doxygen-1.8.14-12.el8.x86_64.rpm
二、安装Modsecurity
Bash
cd /usr/local
git clone https://github.com/SpiderLabs/ModSecurity
cd ModSecurity
git checkout -b v3/master origin/v3/master
git submodule init
git submodule update
sh build.sh
./configure
make -j4
make install
Bash
cd /usr/local
git clone https://github.com/SpiderLabs/ModSecurity-nginx
wget http://nginx.org/download/nginx-1.16.1.tar.gz
tar -xvzf nginx-1.16.1.tar.gz
cd /usr/local/nginx-1.16.1
./configure --add-module=/usr/local/ModSecurity-nginx
make -j4
make install
四、测试效果
启动nginx
Bash
#关闭防火墙
systemctl stop firewalld
#启动nginx
/usr/local/nginx/sbin/nginx
模拟攻击,测试未启动ModSecurity时的访问效果,访问URL为:http://服务器IP/?param=%22%3E%3Cscript%3Ealert(1);%3C/script%3E
效果如下:
五、下载规则文件并配置:
创建用于存在配置文件的文件夹
Bash
mkdir /usr/local/nginx/conf/modsecurity
cd /usr/local
git clone https://github.com/coreruleset/coreruleset.git
cp /usr/local/ModSecurity/modsecurity.conf-recommended /usr/local/nginx/conf/modsecurity/modsecurity.conf
cp /usr/local/ModSecurity/unicode.mapping /usr/local/nginx/conf/modsecurity/unicode.mapping
cp -r /usr/local/coreruleset/rules /usr/local/nginx/conf/modsecurity/
cp /usr/local/coreruleset/crs-setup.conf.example /usr/local/nginx/conf/modsecurity/crs-setup.conf
编辑nginx.conf
在http或server节点中添加以下内容(在http节点添加表示全局配置,在server节点添加表示为指定网站配置):
Bash
modsecurity on;
modsecurity_rules_file /usr/local/nginx/conf/modsecurity/modsecurity.conf;
编辑modsecurity.conf
SecRuleEngine DetectionOnly改为SecRuleEngine On
同时添加以下内容:
Bash
Include /usr/local/nginx/conf/modsecurity/crs-setup.conf
Include /usr/local/nginx/conf/modsecurity/rules/*.conf
六、重新加载Nginx测试效果
Bash
/usr/local/nginx/sbin/nginx -s reload