好久没有更新博客了,最近在忙很多事情,今天突来的兴致,把之前梳理的一些文档整理成博客,今天先搞一个ModSecurity+Nginx搭建流程。

补充OpenResty

由于原版的Nginx不能对请求进行精细化控制,所以出现了OpenResty,即Nginx+Lua。OpenResty可以通过Lua语言,写相应的脚本,从而实现将Nginx接受的HTTP请求,原封不动的转为文本,然后发送给WAF的API。

OpenResty安装ModSecurity与Nginx几乎一模一样,其版本与Nginx版本对应。make时要用gmake

wget https://openresty.org/download/openresty-1.25.3.2.tar.gz

# 编译用gmake
gamke
gamke install

1. 编译安装ModSecurity

参考ModSecurity官方文档,找到指定系统的编译安装指令。
Ubuntu 22.04参考22.10,下述补充了OpenResty编译需要的库。

sudo apt-get install git g++ apt-utils autoconf automake build-essential libcurl4-openssl-dev libgeoip-dev liblmdb-dev libpcre2-dev libtool libxml2-dev libyajl-dev pkgconf zlib1g-dev wget libssl-dev libpcre3 libpcre3-dev curl
git clone https://github.com/owasp-modsecurity/ModSecurity
cd ModSecurity/
git submodule init
git submodule update
sh build.sh
./configure --with-pcre2
make
make install

./configure能正常输出依赖结果即可

2. 下载ModSecurity-nginx连接器

git clone https://github.com/owasp-modsecurity/ModSecurity-nginx

只需下载,无需做任何操作。

3. 编译安装Nginx

注:由于WAF需要,应该将Nginx替换为OpenResty。
使用ModSecurity必须用源码方式安装Nginx,注意不同ModSecurity版本对Nginx的要求

wget https://nginx.org/download/nginx-1.26.1.tar.gz
tar -zxvf nginx-1.26.1.tar.gz
cd nginx-1.26.1

将下载好的ModSecurity-nginx第三方模块静态编译进Nginx,同时开启NginxSSL等模块,这些模块在APT方式安装的二进制Nginx里面都已经被编译进去了,自己编译Nginx时,需要手动指定。

./configure --add-module=/path/to/ModSecurity-nginx --with-http_ssl_module
make
make install

如果报错没有发现OpenSSL库,则需安装,Ubuntu安装命令如下:

apt install libssl-dev

安装完成后,找到configure中显示的nginx安装目录,执行下述命令查看当前Nginx配置

cd /usr/local/nginx
./sbin/nginx -V

回显如下表示正常:

root@c4dcf83416c9:/usr/local/nginx/sbin# ./nginx -V
nginx version: nginx/1.26.1
built by gcc 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.2) 
built with OpenSSL 3.0.2 15 Mar 2022
TLS SNI support enabled
configure arguments: --add-module=/root/ModSecurity-nginx --with-http_ssl_module

4. 下载ModSecurity配置文件

ModSecurity是根据某些规则运作的,所以要下载相应的规则配置文件。

git clone https://github.com/coreruleset/coreruleset.git

将最开始下载的ModSecurity的源码中的modsecurity.conf-recommended文件重命名为modsecurity.conf,将此文件同unicode.mapping一起移动到coreruleset文件夹中
将下载的规则文件coreruleset下的crs-setup.conf.example重命名为crs-setup.conf。
并将下载的规则导入modsecurity.conf,示例如下:

# 并修改SecRuleEngine,使其从DetectionOnly变为On。
SecRuleEngine On

Include /path/to/coreruleset/crs-setup.conf
Include /path/to/coreruleset/rules/*.conf

5. 在Nginx中配置ModSecurity

切到指定Nginx配置目录,修改nginx.conf文件,开启ModSecurity,并指定ModSecurity配置路径,详细查看ModSecurity-nginx的配置介绍。可以将其配置进http{}、server{}和location{}。示例如下:

# 所有server的所有location共用一套规则
http {
    modsecurity on;
    modsecurity_rules_file /path/to/modsecurity.conf;

6. 运行Nginx

通过nginx -t测试配置文件可用性,通过后启动nginx,测试waf是否生效

curl -v 'https://your-domain.com/?test=<script>alert(1)</script>'

返回403表示生效。

标签: WAF

添加新评论