@@ ~~ ^_ ^ &_&
相信光,相信相信的力量.
技術是安身立命之本,實踐出真知,熟能生巧,佐以業(yè)務能力,遇上風口之時,可逆天改命!
本文同步發(fā)布在作者的個人博客,歡迎轉載。野路子技術宅博客
http://www.yousee.top
上篇文章[ 《centos7環(huán)境下ModSecurity-envoy編譯和測試(一)》
本章目標:
完成modsecurity-envoy在本地centos7環(huán)境下配置和攔截測試
在本地虛擬機134環(huán)境測試
配置IPS阻斷模式攔截非法其你去
配置webhook收集接收攔截日志
工作根目錄 : /root/waf/ModSecurity-envoy/ModSecurity-envoy
https://github.com/vmware-archive/ModSecurity-envoy
一、下載規(guī)則集
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參數(shù)。
https://stackoverflow.com/questions/55999360/envoy-and-statsd-error-node-id-and-cluster-id-are-required
修正啟動命令為:
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 #監(jiān)測模式,不阻斷 SecRule ARGS:param1 "test" "id:1,phase:1,deny,status:400,msg:'Test rule'" # 測試request請求test參數(shù) SecRule REQUEST_BODY "blocktest" "id:2,phase:2,deny,status:400,msg:'Test rule'" # 測試post模式的body參數(shù)webhook:
http_uri:
uri: http://localhost:10000/wh_callback
cluster: service2
timeout:
seconds: 3
secret: webhook_secret name: envoy.router
config: {}
-
- name: envoy.http_connection_manager
- filters:
關于CRS的phase1-5階段說明,參照資料如下:
http://www.itdecent.cn/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:開啟規(guī)則匹配并進行相應的攔截
Off:關閉規(guī)則匹配,默認關閉
DetectionOnly:開啟規(guī)則匹配,但不執(zhí)行任何攔截操作(阻止,拒絕,放棄,允許,代理和重定向)
四、啟動webhook服務
1、安裝nodejs v14.15.4
安裝過程略
2、啟動webhook服務
項目地址 :https://github.com/oiuv/webhook
修改webhook.js,精簡邏輯為打印日志。
const http = require('http');
const { spawn } = require('child_process') // 子進程, 用來執(zhí)行腳本
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、發(fā)送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 parametertest' 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
從兩次測試數(shù)據(jù)看,配置達到預期結果,實現(xiàn)waf攔截目的。
六、使用開源gotestwaf測試Modesecurity
操作系統(tǒng):centos7
客戶端IP : 192.168.13.132
目標客戶端 IP :192.168.13.134
1、gotestwaf項目地址
https://github.com/wallarm/gotestwaf
2、安裝docker環(huán)境
略
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程序
生產(chǎn)環(huán)境使用nohup啟動服務,關閉xshell回話窗口后,服務也同時終止,沒法持續(xù)提供服務。
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環(huán)境shell守護進程參考資料:
https://blog.csdn.net/qq_32348883/article/details/123167216
1、方案設計
自定義daemon.sh腳本
設置crontab定時任務執(zhí)行腳本
循環(huán)檢測服務是否已經(jīng)啟動
2、腳本定義daemon.sh
!/bin/sh
添加本地執(zhí)行路徑
export LD_LIBRARY_PATH=./
while true; do
#啟動一個循環(huán),定時檢查進程是否存在
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
#每次循環(huán)沉睡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 進程
17:13 2023/1/29 未解決問題 TODO
1、使用niko測試,異常炸機,waf宕機了。
代碼下載:
wget https://github.com/sullo/nikto/archive/master.zip
unzip master.zip
啟動命令:
./envoy-static -c conf/envoy-modsecurity-example.yaml -l info --service-cluster 'front-envoy' --service-node 'front-envoy'
測試命令:
perl nikto-master/program/nikto.pl -h localhost:8585
異常信息:
[2023-01-29 17:10:16.652][2538][critical][backtrace] [bazel-out/k8-fastbuild/bin/external/envoy/source/server/virtual_includes/backtrace_lib/server/backtrace.h:73] #38: start_thread [0x7efd3f6c2ea5]
ActiveStream 0x4399400, stream_id: 6623975372889628672, has_continue_headers_: 0, is_head_request_: 0, decoding_headers_only_: 0, encoding_headers_only_: 0
request_headers_:
':path', '/'
':method', 'GET'
'connection', 'Keep-Alive'
'user-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
request_trailers_: null
response_headers_:
':status', '426'
response_trailers_: null
&stream_info_:
StreamInfoImpl 0x4399520, protocol_: 0, response_code_: null, response_code_details_: low_version, health_check_request_: 0, route_name_:
段錯誤
解決方案:
C++調試,TODO.
2、全局攔截跳轉頁面配置
需求:全局配置,攔截跳轉到提示界面
結果:沒完成配置實驗,待后續(xù)測試。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}"
-- 總結
完成串聯(lián)部署模式配置測試。
在lds.xml中指定SecRuleEngine模式,On為開啟,默認off,DetectedOnly是檢測不攔截模式
日志統(tǒng)一發(fā)送到webhook回調接口收集日志
攔截指定全局跳轉到某個頁面 - TODO
其他參考資料
1、WAF部署方式介紹
https://blog.csdn.net/qq_38265137/article/details/106742893
2、# owasp crs加載規(guī)則優(yōu)先級說明
https://coreruleset.org/docs/deployment/quick_start/
The order of file inclusion in your webserver configuration should always be:
- modsecurity.conf
- crs-setup.conf (this file)
- rules/*.conf (the CRS rule files)
3、ModSecurity OWASP核心規(guī)則集的兩種配置模式 - 異常評分模式、獨自控制模式
異常評分模式 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,便于識別觸發(fā)了哪個服務;或者配置跳轉到另外的頁面地址
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
經(jīng)檢查,是lds.xml 規(guī)則覆蓋導致。
檢查配置
http://www.modsecurity.cn/chm/SecRuleEngine.html
模式說明
http://www.manongjc.com/detail/56-xvprumdwxcrsitx.html
異常評分模式:由于每次請求都會匹配所有規(guī)則,因此在高并發(fā)情況下,效率相對較低,服務器資源占用較高,但誤報率相對較低;
當檢測到威脅時,并不會直接阻斷此次請求,而是向下繼續(xù)進行規(guī)則匹配,每個匹配成功的規(guī)則都會增加”異常分數(shù)”,在對請求數(shù)據(jù)檢測結束時,以及對返回數(shù)據(jù)檢測結束時,都會對異常分數(shù)的總和進行判斷,如果大于設置的閾值,才會進行阻斷動作,并向客戶端返回403代碼,審計日志中也會記錄此次訪問中所有匹配成功的規(guī)則信息。
獨自控制模式:檢測到一次威脅就直接阻斷請求,因此在高并發(fā)情況下,效率相對較高,服務器資源占用較小,但誤報率相對較高。除此之外該模式還有一個優(yōu)點,即可以通過全局配置,設置當訪問被攔截后,跳轉到自定義的提示頁面。
獨自控制模式配置,跳轉到自定義提示頁面,可參見:
http://modsecurity.cn/practice/post/8.html
兩種配置模式的區(qū)別如下(在crs-setup.conf中進行配置):
http://www.manongjc.com/detail/56-xvprumdwxcrsitx.html
4、ModSecurity 攔截指定國家IP的請求
http://modsecurity.cn/practice/post/14.html
5、crs組織機構官方網(wǎng)站
6、關聯(lián)資料:WAF繞過攻擊(bypass)
https://www.hacking8.com/sectips/bypasswaf.html
7 、其他
webhook配置定義:
https://github.com/vmware-archive/ModSecurity-envoy/blob/master/http-filter-modsecurity/http_filter.proto