> For AI agents: the complete documentation index is available at https://www.tteam.icu/llms.txt, the full documentation bundle is available at https://www.tteam.icu/llms-full.txt.

# `OpenResty`使用`ngx_waf`

## 介绍`ngx_waf`

### 为什么选择 [ngx\_waf](https://github.com/ADD-SP/ngx_waf)

- 基础防护: 支持 IP 或 IP 网段的黑白名单、URI 黑白名单和请求体黑名单等。
- 使用简单: 配置文件和规则文件书写简洁，可读性强。
- 高性能: 采用高效的 IP 检查算法和缓存机制。
- 高级防护: 兼容 [ModSecurity](https://github.com/SpiderLabs/ModSecurity)，可使用[开放式网络应用安全项目(OWASP)® 的核心规则库](https://owasp.org/www-project-modsecurity-core-rule-set/)。
- 友好爬虫验证: 支持验证 Google、Bing、Baidu 和 Yandex 的爬虫并自动放行，避免错误拦截。
- 验证码支持: 集成 hCaptcha、reCAPTCHAv2 和 reCAPTCHAv3 三种验证码。

### 功能

- 兼容 [ModSecurity](https://github.com/SpiderLabs/ModSecurity)。此功能仅限最新的 Current 版本。
- SQL 注入防护(Powered By [libinjection](https://github.com/libinjection/libinjection))。
- XSS 攻击防护(Powered By [libinjection](https://github.com/libinjection/libinjection))。
- 支持 IPV4 和 IPV6。
- 支持开启验证码(CAPTCHA)，支持 [hCaptcha](https://www.hcaptcha.com/)、[reCAPTCHAv2](https://developers.google.com/recaptcha) 和 [reCAPTCHAv3](https://developers.google.com/recaptcha)。此功能仅限最新的 Current 版本。
- 支持识别友好爬虫(如 BaiduSpider)并自动放行(基于 User-Agent 和 IP 的识别)。此功能仅限最新的 Current 版本。
- CC 防御，超出限制后自动拉黑对应 IP 一段时间。
- IP 黑白名单，同时支持类似 `192.168.0.0/16` 和 `fe80::/10`，即支持点分十进制和冒号十六进制表示法和网段划分。
- POST 黑名单。
- URL 黑白名单
- 查询字符串(Query String)黑名单。
- UserAgent 黑名单。
- Cookie 黑名单。
- Referer 黑白名单。

## 打包

### 前言

`openresty`天生支持`lua`，线上的日志是有`lua`做处理

线上有不同的`vpc`，每个环境都要做到快速部署，故把模块都打进`docker`中

本文章主要讲的是[ngx\_waf](https://github.com/ADD-SP/ngx_waf)，但其实不止这个模块，一共有:

- [ngx\_waf](https://github.com/ADD-SP/ngx_waf)最新版(非tls版)
- [nginx-module-vts](https://github.com/vozlt/nginx-module-vts)
- [nginx-lua-prometheus](https://github.com/knyar/nginx-lua-prometheus)

[打包镜像](https://github.com/ttdockerfile/openresty-monitor-ubuntu)

## 使用

## 监控

### http模块配置

```txt
vhost_traffic_status_zone;
```

### 开启服务

```txt
server {
    listen 9145;
    # 给日志模板使用的变量
    set $resp_body "";
    set $resp_cookies "";
    location /metrics {
        content_by_lua_block {
            metric_connections:set(ngx.var.connections_reading, {"reading"})
            metric_connections:set(ngx.var.connections_waiting, {"waiting"})
            metric_connections:set(ngx.var.connections_writing, {"writing"})
            prometheus:collect()
        }
    }

    location /status {
        vhost_traffic_status_display;
        vhost_traffic_status_display_format html;
    }

}
```

## ngx\_waf

[文档地址](https://add-sp.github.io/ngx_waf-docs/zh-cn/)

我使用到这个模块里的最主要的就是`waf_captcha`，这个是人机验证功能

由于自带的页面太难看了，所以我做了一个[界面](https://github.com/ttdockerfile/openresty-monitor-ubuntu/blob/master/assets/CAPTCHA.html)

```txt
waf_captcha on prov=hCaptcha file=/data/res/CAPTCHA.html secret=xxx;
```
