@_@ ~_~ ^_ ^ &_&
相信光,相信相信的力量.
技术是安身立命之本,实践出真知,熟能生巧,佐以业务能力,遇上风口之时,可逆天改命!
=====================================================================
通过上一章的[《centos环境下ModSecurity-envoy编译和测试》](http://www.yousee.top/articles/57),希望大家能顺利开展编译工作。本章紧接着完成测试工作。
目标
完成modsecurity-envoy在本地centos7环境下配置和拦截测试
---------------------------------------
在本地虚拟机134环境测试
配置IPS阻断模式拦截非法其你去
配置webhook收集接收拦截日志
工作根目录 : /root/waf/ModSecurity-envoy/ModSecurity-envoy
---------------------------------------
https://github.com/vmware-archive/ModSecurity-envoy
一、下载规则集
cd ${ModSecurity-envoy}/conf
查看lds.yml文件,确认crs文件存放目录:
vi conf/conf.lds.yml
# before envoy.router because order matters!
- name: envoy.filters.http.modsecurity
config:
rules_inline: |
Include "conf/modsecurity.v3.0.3.conf"
Include "owasp-modsecurity-crs-3.1.1/crs-setup.conf.example"
Include "owasp-modsecurity-crs-3.1.1/rules/*.conf"
这地方会造成混淆,如果把crs文件下载到conf目录,启动envoy服务会报错异常:
[2023-01-06 16:09:37.177][29705][error][filter] [http-filter-modsecurity/http_filter.cc:52] Failed to load rules: Rules error. File: <<reference missing or not informed>>. Line: 2. Column: 60. "owasp-modsecurity-crs-3.1.1/crs-setup.conf.example": Not able to open file. Looking at: 'owasp-modsecurity-crs-3.1.1/crs-setup.conf.example', 'owasp-modsecurity-crs-3.1.1/crs-setup.conf.example', '<<reference missing or not informed>>/owasp-modsecurity-crs-3.1.1/crs-setup.conf.example', '<<reference missing or not informed>>/owasp-modsecurity-crs-3.1.1/crs-setup.conf.example'.
[2023-01-06 16:09:37.178][29705][info][upstream] [external/envoy/source/server/lds_api.cc:60] lds: add/update listener 'listener_0'
[2023-01-06 16:09:37.178][29705][info][config] [external/envoy/source/server/listener_manager_impl.cc:761] all dependencies initialized. starting workers
[2023-01-06 16:09:37.180][29705][info][main] [external/envoy/source/server/server.cc:516] starting main dispatch loop
确保owasp-modsecurity-crs-3.1.1与conf目录平级!
cd ${ModSecurity-envoy}/
wget https://github.com/SpiderLabs/owasp-modsecurity-crs/archive/v3.1.1.tar.gz
tar xvzf v3.1.1.tar.gz
二、启动集成WAF的envoy服务
cd /home/ModSecurity-envoy/
nohup ./envoy-static -c conf/envoy-modsecurity-example-lds.yaml -l info
启动错误
udo ./envoy-static -c conf/envoy-modsecurity-example-lds.yaml -l info
type.googleapis.com/envoy.api.v2.Listener: node 'id' and 'cluster' are required. Set it either in 'node' config or via --service-node and --service-cluster options.
参照老外资料提示,增加service-cluseter及service-node参数。
修正启动命令为:
nohup ./envoy-static -c conf/envoy-modsecurity-example-lds.yaml -l info --service-cluster 'front-envoy' --service-node 'front-envoy' >out.file 2>&1 &
ps -Af|grep envoy
tail -f out.file
服务正常运行
三、修改lds.yaml配置文件
vi conf/lds.yaml
增加配置如下:
1、 access_log开启access日志
2、 SecRuleEngine配置waf运行模式
3、 webhook配置WAF日志采集服务
version_info: "1"
resources:
- "@type": type.googleapis.com/envoy.api.v2.Listener
name: listener_0
address:
socket_address:
address: 0.0.0.0
port_value: 8585
filter_chains:
- filters:
- name: envoy.http_connection_manager
config:
codec_type: auto
stat_prefix: ingress_http
access_log:
name: envoy.file_access_log
typed_config:
"@type": type.googleapis.com/envoy.config.accesslog.v2.FileAccessLog
path: /root/waf/accesslog.txt
route_config:
name: local_route
virtual_hosts:
- name: backend
domains:
- "*"
routes:
- match:
prefix: "/"
route:
cluster: service1
metadata:
filter_metadata:
envoy.filters.http.modsecurity:
# disable: true
# disable_request: true
# disable_response: true
http_filters:
# before envoy.router because order matters!
- name: envoy.filters.http.modsecurity
config:
rules_inline: |
Include "conf/modsecurity.v3.0.3.conf"
Include "owasp-modsecurity-crs-3.1.1/crs-setup.conf.example"
Include "owasp-modsecurity-crs-3.1.1/rules/*.conf"
SecRuleEngine On #阻断模式
#SecRuleEngine DetectionOnly #监测模式,不阻断
SecRule ARGS:param1 "test" "id:1,phase:1,deny,status:400,msg:'Test rule'" # 测试request请求test参数
SecRule REQUEST_BODY "blocktest" "id:2,phase:2,deny,status:400,msg:'Test rule'" # 测试post模式的body参数
webhook:
http_uri:
uri: http://localhost:10000/wh_callback
cluster: service2
timeout:
seconds: 3
secret: webhook_secret
- name: envoy.router
config: {}
关于CRS的phase1-5阶段说明,参照资料如下:
https://www.jianshu.com/p/2981dd8e23dc
Request Header(phase:1):处理 requesst line 和 request headers
Request Body(phase:2):处理 request body
Response Header(phase:3):处理 response headers
Response Body(phase:4):处理 response body
Logging(phase:5):日志记录,添加header
关于lds.xml 文件修改说明:
SecRuleEngine On
SecRuleEngine DetectionOnly
SecRule ARGS:param1 "test" "id:1,phase:1,deny,status:400,msg:'Test rule'"
SecRule REQUEST_BODY "blocktest" "id:2,phase:2,deny,status:400,msg:'Test rule'"
可用的值是:
On:开启规则匹配并进行相应的拦截
Off:关闭规则匹配,默认关闭
DetectionOnly:开启规则匹配,但不执行任何拦截操作(阻止,拒绝,放弃,允许,代理和重定向)
四、启动webhook服务
1、安装nodejs v14.15.4
安装过程略
2、启动webhook服务
项目地址 :https://github.com/oiuv/webhook
修改webhook.js,精简逻辑为打印日志。
const http = require('http');
const { spawn } = require('child_process') // 子进程, 用来执行脚本
http.createServer((req, res) => {
console.log(`--- ${req.method} --- ${req.url} ---`);
console.log(`--- headers : ${JSON.stringify(req.headers)} ---`)
console.log(`--- ${JSON.stringify(req.trailers)} ---`)
res.setHeader("Content-Type", "application/json");
// request
if (req.method === 'POST') {
// 获取body
let body = '';
req.on('data', (data) => {
// console.log(`--- data: ${data} ---`);
body += data;
});
req.on('end', () => {
let payload = JSON.parse(body);
// console.log(`--- ${payload.repository} ---`);
console.log(`------${body}------`);
// response
let json = JSON.stringify({
status: "success",
code: 200
});
res.end(json);
});
}
else {
let json = JSON.stringify({
status: "OK",
code: 200
});
res.end(json);
}
}).listen(10000)
3、其他开源webhook
未测试使用,有兴趣同学可以测试这个项目。
https://github.com/adnanh/webhook
五、简单命令行测试
ps -aux|grep envoy
kill掉进程并重启envoy服务
nohup ./envoy-static -c conf/envoy-modsecurity-example-lds.yaml -l info --service-cluster 'front-envoy' --service-node 'front-envoy' >out.file 2>&1 &
1、发送phase1、phase2的测试请求:
curl -X GET "http://192.168.13.134:8585/get?param1=test" -H "accept: application/json"
响应返回
ModSecurity Action
查看日志文件
tail -f /var/log/modsec_audit.log
ModSecurity: Access denied with code 200 (phase 1). Matched "Operator `Rx' with parameter `test' against variable `ARGS:param1' (Value: `test' ) [file "<<reference missing or not informed>>"] [line "7"] [id "1"] [rev ""] [msg "Test rule"] [data ""] [severity "0"] [ver ""] [maturity "0"] [accuracy "0"] [hostname "192.168.13.134"] [uri "/get"] [unique_id "167355977637.969769"] [ref "o0,4v16,4"]
2、body测试请求
curl -v -XPOST -H "Content-Type:application/xml" http://192.168.13.134:8585/ -d ' blocktest '
响应返回
* upload completely sent off: 11 out of 11 bytes
< HTTP/1.1 400 Bad Request
< content-length: 19
< content-type: text/plain
< date: Thu, 12 Jan 2023 22:13:56 GMT
< server: envoy
从两次测试数据看,配置达到预期结果,实现waf拦截目的。
六、使用开源gotestwaf测试Modesecurity
操作系统:centos7
客户端IP : 192.168.13.132
目标客户端 IP :192.168.13.134
1、gotestwaf项目地址
https://github.com/wallarm/gotestwaf
2、安装docker环境
略
3、安装golang
略
4、过程测试
docker pull wallarm/gotestwaf
set PWD=/root/waf/goTestWaf
docker run -v ${PWD}/reports:/root/reports wallarm/gotestwaf --grpcPort 9000 --url=http://192.168.13.134:8585/ --skipWAFBlockCheck
查看攻击日志
cat /var/log/modsec_audit.log
七、后台运行Modsecurity-envoy程序
生产环境使用nohup启动服务,关闭xshell回话窗口后,服务也同时终止,没法持续提供服务。
nohup ./envoy-static -c conf/envoy-modsecurity-example-lds.yaml -l info --service-cluster 'front-envoy' --service-node 'front-envoy' >out.file 2>&1 &
计划通过shell脚本运行守护进程,解决会话关闭问题。
linux环境shell守护进程参考资料:
https://blog.csdn.net/qq_32348883/article/details/123167216
1、方案设计
自定义daemon.sh脚本
设置crontab定时任务执行脚本
循环检测服务是否已经启动
2、脚本定义daemon.sh
----------------------------------------------------
#!/bin/sh
#添加本地执行路径
export LD_LIBRARY_PATH=./
while true; do
#启动一个循环,定时检查进程是否存在
server=`ps aux | grep envoy-static | grep -v grep`
if [ ! "$server" ]; then
#如果不存在就重新启动
nohup envoy-static -c conf/envoy-modsecurity-example-lds.yaml -l info --service-cluster 'front-envoy' --service-node 'front-envoy' &
#启动后沉睡10s
sleep 10
fi
#每次循环沉睡10s
sleep 5
done
3、启动脚本
chmod -u+rwx daemon.sh
nohup ./daemon.sh >out.file 2>&1 &
## 4、关闭服务
ps -aux |grep daemon.sh
kill -9 进程
ps -aux |grep envoy-static
kill -9 进程
七、未解决问题 TODO
1、全局拦截跳转页面配置
需求:全局配置,拦截跳转到提示界面
结果:没完成配置实验,待后续测试。TODO
SecDefaultAction "phase:1,deny,log,noauditlog,status:400,redirect:http://modsecurity.cn/practice/intercept.html?url=%{REQUEST_FILENAME}&intercept_domain=%{request_headers.host}"
SecDefaultAction "phase:2,deny,log,noauditlog,status:400redirect:http://modsecurity.cn/practice/intercept.html?url=%{REQUEST_FILENAME}&intercept_domain=%{request_headers.host}"
八、其他参考资料
1、WAF部署方式介绍
https://blog.csdn.net/qq_38265137/article/details/106742893
2、# owasp crs加载规则优先级说明
https://coreruleset.org/docs/deployment/quick_start/
The order of file inclusion in your webserver configuration should always be:
1. modsecurity.conf
2. crs-setup.conf (this file)
3. rules/*.conf (the CRS rule files)
3、ModSecurity OWASP核心规则集的两种配置模式 - 异常评分模式、独自控制模式
异常评分模式 Anomaly Scoring mod
独自控制模式 Self-contained mode
案例1:
只要检测到威胁,则使用”deny”关键词对此次访问进行阻断,同时向服务器返回403错误代码。
SecDefaultAction "phase:1,log,auditlog,deny,status:403"
SecDefaultAction "phase:2,log,auditlog,deny,status:403"
案例2:
检测到威胁,返回应用服务host对应的homepage,便于识别触发了哪个服务;或者配置跳转到另外的页面地址
SecDefaultAction "phase:1,log,auditlog,redirect:'http://%{request_headers.host}/',tag:'Host: %{request_headers.host}'"
SecDefaultAction "phase:2,log,auditlog,redirect:'http://%{request_headers.host}/',tag:'Host: %{request_headers.host}'"
修改配置测试自我控制模型 - 测试403模式 - 没有拦截生效!!
vi owasp-modsecurity-crs-3.1.1/crs-setup.conf
经检查,是lds.xml 规则覆盖导致。
检查配置
http://www.modsecurity.cn/chm/SecRuleEngine.html
模式说明
http://www.manongjc.com/detail/56-xvprumdwxcrsitx.html
异常评分模式:由于每次请求都会匹配所有规则,因此在高并发情况下,效率相对较低,服务器资源占用较高,但误报率相对较低;
当检测到威胁时,并不会直接阻断此次请求,而是向下继续进行规则匹配,每个匹配成功的规则都会增加”异常分数”,在对请求数据检测结束时,以及对返回数据检测结束时,都会对异常分数的总和进行判断,如果大于设置的阈值,才会进行阻断动作,并向客户端返回403代码,审计日志中也会记录此次访问中所有匹配成功的规则信息。
独自控制模式:检测到一次威胁就直接阻断请求,因此在高并发情况下,效率相对较高,服务器资源占用较小,但误报率相对较高。除此之外该模式还有一个优点,即可以通过全局配置,设置当访问被拦截后,跳转到自定义的提示页面。
独自控制模式配置,跳转到自定义提示页面,可参见:
http://modsecurity.cn/practice/post/8.html
两种配置模式的区别如下(在crs-setup.conf中进行配置):
http://www.manongjc.com/detail/56-xvprumdwxcrsitx.html
4、ModSecurity 拦截指定国家IP的请求
http://modsecurity.cn/practice/post/14.html
5、crs组织机构官方网站
6、关联资料:WAF绕过攻击(bypass)
https://www.hacking8.com/sectips/bypasswaf.html
7 、其他
webhook配置定义: