GuardianWAF/GuardianWAF
GitHub: GuardianWAF/GuardianWAF
一个用纯 Go 编写的零依赖 Web 应用防火墙,支持独立代理、Sidecar 和嵌入式库三种部署模式,提供基于 Tokenizer 的威胁检测、负载均衡、TLS 终结和实时监控仪表板。
Stars: 15 | Forks: 4
# GuardianWAF
GuardianWAF(:443 + :80) --> backend-api:3000
--> backend-web:8000
B) Behind CDN:
Cloudflare --> GuardianWAF(:8088) --> backends
(TLS handled by Cloudflare)
C) Kubernetes Sidecar:
Ingress --> GuardianWAF(:8088) --> app(:3000)
D) Embedded Library:
Go app --> waf.Middleware(handler)
```
## 为什么选择 GuardianWAF?
构建 GuardianWAF 旨在消除其他 WAF 解决方案强加的权衡:复杂的规则集、依赖树、供应商锁定或需要宿主进程。一个二进制文件,零依赖,透明评分。
*比较截至 2026 年 3 月。请查看每个项目的当前状态。*
| Feature | GuardianWAF | SafeLine | Coraza | ModSecurity | NAXSI |
|---|---|---|---|---|---|
| **Language** | Go | Go + Lua | Go | C | C |
| **External deps** | Zero | Multiple | Multiple | Multiple | NGINX module |
| **Deployment modes** | 3 (proxy, lib, sidecar) | Reverse proxy | Library / proxy | Module (NGINX/Apache) | NGINX module |
| **Detection method** | Tokenizer + scoring | Semantic analysis | CRS regex rules | CRS regex rules | Scoring + allowlists |
| **JS Challenge / PoW** | Built-in | No | No | No | No |
| **Multi-domain routing** | Built-in (virtual hosts) | No | No | No | No |
| **TLS + ACME** | Built-in | External | External | External | External |
| **Load balancing** | 4 strategies + health check | No | No | No | No |
| **Circuit breaker** | Built-in | No | No | No | No |
| **Web dashboard** | Built-in (config + monitoring) | Built-in | No (third-party) | No (third-party) | No |
| **Single binary** | Yes | No | No | No | No |
| **Docker auto-discovery** | Label-based (`gwaf.*`) | No | No | No | No |
| **AI threat analysis** | Built-in (400+ providers) | No | No | No | No |
| **MCP / AI integration** | Built-in MCP server | No | No | No | No |
| **Prometheus metrics** | Built-in `/metrics` | No | No | No | No |
| **Threat Intelligence** | IP/domain reputation feeds | No | No | Partial (external) | No |
| **CORS Security** | Built-in layer | No | No | No | No |
| **ATO Protection** | Brute force + credential stuffing | No | No | No | No |
| **API Security** | JWT validation + API keys | No | No | No | No |
| **Configuration** | YAML + env + dashboard UI | Web UI | SecRule directives | SecRule directives | NGINX directives |
| **False positive mgmt** | Score tuning per-route | Auto learning | Rule exclusions | Rule exclusions | Allowlists |
| **Performance overhead** | < 1ms p99 | Low | Low | Moderate | Low |
| **License** | MIT | Apache 2.0 | Apache 2.0 | Apache 2.0 | GPL v3 |
## 架构
```
GuardianWAF Pipeline
====================
HTTP Request
|
v
+-----------+ +-------------+ +-----------+ +------------+ +-----------+
| IP ACL |-->| Threat Intel|-->| CORS |-->| Rate Limit |-->| ATO |
| (100) | | (125) | | (150) | | (200) | | (250) |
+-----------+ +-------------+ +-----------+ +------------+ +-----------+
|
+--------------------------------------------------------------------+
|
v
+-------------+ +------------+ +------------+ +------------+ +-----------+
| API Security|-->| Sanitizer |-->| Detection |-->| Bot Detect |-->| Response |
| (275) | | (300) | | (400) | | (500) | | (600) |
+-------------+ +------------+ +------------+ +------------+ +-----------+
|
+----------------------------------------------------------------------+
|
v
+-----------+ +----------------+
| JS |--->| Upstream |
| Challenge | | Load Balancer |
+-----------+ +----------------+
(score 40-79) | | | | |
v v v v v
Backend Targets
(health checked,
circuit breaker)
```
每一层按顺序运行,可以传递、记录、质询或拦截请求。检测层运行 6 个独立的检测器(SQLi, XSS, LFI, CMDi, XXE, SSRF)并生成累积威胁分数。Bot 检测分数在 40-79 之间会触发 JavaScript 工作量证明质询,而不是直接拦截。
## Detection Engine
GuardianWAF 使用基于 Tokenizer 的评分系统,而不是二元的允许/拦截规则。HTTP 请求在词法上分解为类型化 Token,根据攻击模式评分,并使用可配置的阈值进行评估。
**示例:评分如何产生分级响应**
```
Input: "O'Brien"
-> Single apostrophe score: 10
-> Total: 10 -> ALLOW (below log threshold)
Input: "' OR 'a'='a"
-> Apostrophe + OR keyword score: 30
-> Tautology pattern score: +55
-> Total: 85 -> BLOCK (above block threshold)
Input: Suspicious bot (UA: curl, high RPS)
-> Bot score: 55 -> JS CHALLENGE (proof-of-work page)
-> Browser solves SHA-256 puzzle -> Sets cookie, request passes
-> Bot can't solve -> Stays blocked
```
这种分级响应消除了大多数误报,同时捕获了真正的攻击。每个被拦截的请求都包含完整的分数明细,用于透明的、数据驱动的调优。
完整模式评分表请参阅 [Detection Engine docs](docs/detection-engine.md)。
## 安装
### go install
```
go install github.com/guardianwaf/guardianwaf/cmd/guardianwaf@latest
```
### 二进制下载
```
# Linux (amd64)
curl -Lo guardianwaf https://github.com/guardianwaf/guardianwaf/releases/latest/download/guardianwaf-linux-amd64
chmod +x guardianwaf
sudo mv guardianwaf /usr/local/bin/
# macOS (arm64)
curl -Lo guardianwaf https://github.com/guardianwaf/guardianwaf/releases/latest/download/guardianwaf-darwin-arm64
chmod +x guardianwaf
sudo mv guardianwaf /usr/local/bin/
```
### Docker (GHCR)
```
docker pull ghcr.io/guardianwaf/guardianwaf:latest
```
### 从源码构建
```
git clone https://github.com/guardianwaf/guardianwaf.git
cd guardianwaf
make build
# Binary: ./guardianwaf
```
## 配置
保护后端的最小 `guardianwaf.yaml`:
```
mode: enforce
listen: ":8088"
upstreams:
- name: backend
targets:
- url: "http://localhost:3000"
routes:
- path: /
upstream: backend
waf:
detection:
threshold:
block: 50
log: 25
challenge:
enabled: true
difficulty: 20
dashboard:
enabled: true
listen: ":9443"
api_key: "your-secret-key"
```
配置分层:`defaults` -> `YAML file` -> `environment variables (GWAF_ prefix)` -> `CLI flags`。
完整 YAML Schema 请参阅 [Configuration Reference](docs/configuration.md)。
## 仪表板
GuardianWAF 包含一个内置的 Web 仪表板,可在配置的监听地址(默认 `:9443`)上访问。
**监控(`/`)**
- 实时流量监控(requests/sec, blocks/sec, challenges, latency)
- 安全事件流,支持按操作、IP、路径、分数过滤
- 点击任何事件查看完整详情:发现、匹配模式、威胁分数
- 攻击类型细分和 Top 源 IP 图表
- Upstream 健康:后端状态、Circuit breaker 状态、活动连接
**配置`/config`)**
- Upstream 管理:添加/删除后端,设置负载均衡策略和权重
- 虚拟主机管理:添加/删除域名,配置按域名路由
- 路由管理:路径到 Upstream 的映射,支持前缀剥离
- WAF 设置:切换检测器,调整阈值和乘数
- JS Challenge:启用/禁用,设置难度
- Bot 检测:模式、扫描器拦截、行为阈值
- IP ACL:实时添加/删除白名单和黑名单条目
- 速率限制、清理器、响应防护切换
**路由(`/routing`)**
- **Topology Graph** —— 交互式 React Flow 可视化,显示完整请求路径:Clients -> WAF -> VHosts -> Routes -> Upstreams -> Targets,带有 TLS/SSL 指示器、端口、健康状态、Circuit breaker 状态
- **Backends** —— Docker 发现的服务表 + 静态 Upstream,包含容器名称、镜像、目标 URL、Upstream 池、权重、健康检查路径
- **Configure** —— 基于表单的 Upstream/Route/VHost 管理,支持保存和重建
**AI Analysis(`/ai`)**
- 提供商目录(来自 models.dev 的 400+),支持搜索和模型详情
- 模型选择,显示上下文窗口、成本、reasoning/tool_call 能力
- API 密钥管理,支持连接测试
- 手动“立即分析”触发器,即时显示判定结果
- 分析历史,支持可展开的结果、威胁、判定、成本
- 使用统计:tokens/hour, requests/hour, 总成本, AI 拦截
**REST API:** 仪表板公开了完整的 [REST API](docs/api-reference.md) 用于编程管理,受 API 密钥认证保护。
| Endpoint | Description |
|---|---|
| `GET /api/v1/stats` | 运行时统计 |
| `GET /api/v1/events` | 带过滤器的分页事件 |
| `GET /api/v1/upstreams` | 后端健康状态 |
| `GET/PUT /api/v1/config` | WAF 配置 |
| `GET/PUT /api/v1/routing` | Upstreams, virtual hosts, routes |
| `GET/POST/DELETE /api/v1/ipacl` | IP 白名单/黑名单 |
| `GET/POST/DELETE /api/v1/rules` | 自定义 WAF 规则 |
| `GET /api/v1/docker/services` | Docker 发现的后端 |
| `GET/PUT /api/v1/ai/config` | AI 提供商配置 |
| `GET /api/v1/ai/providers` | Models.dev 提供商目录 |
| `POST /api/v1/ai/analyze` | 触发 AI 分析 |
| `GET /api/v1/ai/history` | AI 分析历史 |
| `GET /api/v1/ai/stats` | AI 使用和成本统计 |
| `GET /metrics` | Prometheus metrics |
| `GET /healthz` | 健康检查(K8s probes) |
| `GET /api/v1/sse` | Server-Sent Events stream |
访问地址 `http://localhost:9443`(在独立模式下默认启用)。
## 库使用
### 最小化
```
waf, err := guardianwaf.New(guardianwaf.Config{
Mode: guardianwaf.ModeEnforce,
Threshold: guardianwaf.ThresholdConfig{Block: 50, Log: 25},
})
if err != nil {
log.Fatal(err)
}
defer waf.Close()
http.ListenAndServe(":8088", waf.Middleware(myHandler))
```
### 高级(功能选项)
```
waf, err := guardianwaf.New(guardianwaf.Config{},
guardianwaf.WithMode(guardianwaf.ModeEnforce),
guardianwaf.WithThreshold(60, 30),
guardianwaf.WithDetector("sqli", true, 1.5), // 50% more sensitive
guardianwaf.WithDetector("xss", true, 0.5), // 50% less sensitive
guardianwaf.WithIPWhitelist("10.0.0.0/8"),
guardianwaf.WithIPBlacklist("203.0.113.0/24"),
guardianwaf.WithBotDetection(true),
guardianwaf.WithSecurityHeaders(true),
guardianwaf.WithDataMasking(true),
guardianwaf.WithMaxEvents(50000),
)
if err != nil {
log.Fatal(err)
}
defer waf.Close()
// Event callback for custom alerting
waf.OnEvent(func(event guardianwaf.Event) {
if event.Action.String() == "block" {
fmt.Printf("[BLOCKED] %s %s from %s (score: %d)\n",
event.Method, event.Path, event.ClientIP, event.Score)
}
})
// Manual request check (without middleware)
result := waf.Check(req)
fmt.Printf("Score: %d, Blocked: %v, Findings: %d\n",
result.TotalScore, result.Blocked, len(result.Findings))
```
## MCP 集成
GuardianWAF 包含一个内置的 [Model Context Protocol](https://modelcontextprotocol.io) 服务器,使 AI Agent 能够通过结构化工具调用监控、查询和管理 WAF。两种传输方式:**stdio**(本地 CLI)和 **SSE**(带 API 密钥认证的远程 HTTP)。
**15 个 MCP 工具:**
| Category | Tools |
|---|---|
| Monitoring | `get_stats`, `get_events`, `get_top_ips`, `get_detectors` |
| Configuration | `get_config`, `set_mode` |
| IP Management | `add_whitelist`, `remove_whitelist`, `add_blacklist`, `remove_blacklist` |
| Rate Limiting | `add_ratelimit`, `remove_ratelimit` |
| Detection Tuning | `add_exclusion`, `remove_exclusion` |
| Testing | `test_request` |
**Claude Code (stdio):**
```
{
"mcpServers": {
"guardianwaf": {
"command": "guardianwaf",
"args": ["serve", "-c", "guardianwaf.yaml"]
}
}
}
```
**Claude Desktop / VS Code (SSE — remote):**
```
{
"mcpServers": {
"guardianwaf": {
"url": "http://your-waf-host:9443/mcp/sse",
"headers": { "X-API-Key": "your-api-key" }
}
}
}
```
然后提问:*“显示最新被拦截的请求并将攻击频率最高的 IP 加入黑名单。”*
完整的工具参考、SSE 协议详情和 curl 示例请参阅 [MCP Integration docs](docs/mcp-integration.md)。
## 性能
GuardianWAF 的目标是每个请求的 p99 延迟开销低于 1 毫秒。
| Metric | Value |
|---|---|
| IP ACL lookup | < 100ns |
| Rate limit check | < 500ns |
| SQLi detection | < 200us p95 |
| All detectors combined | < 500us p95 |
| PoW verification (server-side) | ~60ns |
| Token generation (HMAC) | ~600ns |
| **Total pipeline (clean request)** | **< 1ms p99** |
| **Total pipeline (attack)** | **< 2ms p99** |
| Memory baseline (standalone) | < 30 MB |
| Memory baseline (library) | < 5 MB |
| Binary size (stripped) | ~15 MB |
| Docker image size | < 20 MB |
| Startup time | < 100ms |
性能的设计选择:
- 使用 `sync.Pool` 处理请求上下文的零分配热路径
- 用于统计的原子计数器(无 Mutex 争用)
- 用于 IP 查找的 Radix tree(O(k),其中 k = 地址位数)
- Token bucket 速率限制器(每次检查 O(1))
- 状态机 Tokenizer(热路径上无 Regex)
- 具有原子状态转换的 Circuit breaker(无锁)
## 文档
| Document | Description |
|---|---|
| [Getting Started](docs/getting-started.md) | 安装和首次部署 |
| [Configuration Reference](docs/configuration.md) | 完整的 YAML Schema 及每个字段 |
| [Detection Engine](docs/detection-engine.md) | 评分系统、检测器、模式表 |
| [Deployment Modes](docs/deployment-modes.md) | 独立、库、Sidecar 比较 |
| [Docker Auto-Discovery](docs/docker-discovery.md) | 基于标签的容器发现和路由 |
| [AI Threat Analysis](docs/ai-analysis.md) | AI 驱动的威胁分析设置和配置 |
| [API Reference](docs/api-reference.md) | REST API 端点及请求/响应示例 |
| [MCP Integration](docs/mcp-integration.md) | AI Agent 工具和 Claude Code 设置 |
| [Tuning Guide](docs/tuning-guide.md) | 减少误报和阈值调优 |
完整文档站点:[guardianwaf.com/docs](https://guardianwaf.com/docs)
## 项目结构
```
guardianwaf/
├── cmd/guardianwaf/ # CLI entry point (serve, sidecar, check, validate)
├── internal/
│ ├── engine/ # Core WAF engine, pipeline, scoring, access logging, panic recovery
│ ├── config/ # YAML parser + serializer, config structs, env loading, validation
│ ├── layers/
│ │ ├── ipacl/ # IP whitelist/blacklist (radix tree, runtime add/remove, auto-ban)
│ │ ├── threatintel/ # Threat intelligence feeds (IP/domain reputation, LRU cache)
│ │ ├── cors/ # CORS validation (origin allowlist, preflight handling)
│ │ ├── ratelimit/ # Token bucket rate limiter (dynamic rule add/remove)
│ │ ├── ato/ # Account takeover protection (brute force, credential stuffing)
│ │ ├── apisecurity/ # API authentication (JWT validation, API keys)
│ │ ├── sanitizer/ # Request normalization and validation
│ │ ├── detection/ # Attack detectors (sqli/xss/lfi/cmdi/xxe/ssrf) with dynamic exclusions
│ │ ├── botdetect/ # Bot detection (JA3/JA4, UA, behavior)
│ │ ├── challenge/ # JS proof-of-work challenge (SHA-256 PoW)
│ │ ├── response/ # Response protection (headers, masking, error pages)
│ │ └── rules/ # Custom rule engine (geo-aware, dashboard CRUD)
│ ├── proxy/ # Reverse proxy, load balancer, circuit breaker, router, WebSocket
│ ├── tls/ # TLS cert store, SNI selection, hot-reload, HTTP/2
│ ├── acme/ # ACME client (RFC 8555), HTTP-01 challenge, cert cache
│ ├── dashboard/ # React UI, REST API, SSE, routing graph, AI page, Docker services
│ ├── ai/ # AI threat analysis (models.dev catalog, OpenAI client, batch analyzer)
│ ├── docker/ # Docker auto-discovery (socket client, label parser, event watcher)
│ ├── mcp/ # MCP JSON-RPC server and 15 tool definitions
│ ├── geoip/ # GeoIP database with auto-download and runtime refresh
│ └── events/ # Event storage (memory ring buffer, JSONL file, event bus)
├── guardianwaf.go # Public API for library mode
├── options.go # Functional options (WithMode, WithThreshold, etc.)
├── examples/ # Library and backend examples
├── docs/ # Documentation (docker-discovery, ai-analysis, etc.)
├── testdata/ # Test configs and attack payloads
├── scripts/ # Attack simulation, smoke tests, real E2E tests
├── Dockerfile # Multi-stage Alpine build
├── docker-compose.yml # Standalone + auto-discovery example with gwaf.* labels
└── Makefile # build, test, lint, bench, fuzz, cover, docker-test
```
## 贡献
欢迎贡献。GuardianWAF 重视质量胜过速度 —— 整洁的代码、全面的测试和零外部依赖。
1. Fork 仓库。
2. 创建功能分支。
3. 运行 `make test` 和 `make vet` 验证所有测试通过。
4. 新功能应包含测试。
5. 无外部依赖 —— 一切均从头实现。
6. 提交带有清晰变更描述的 Pull Request。
完整指南请参阅 [CONTRIBUTING.md](CONTRIBUTING.md)。
## 许可证
[MIT](LICENSE) —— 核心 WAF 是完全开源的。企业功能(集群模式、商业支持)将来会在单独的商业许可下提供。
## 作者
**Ersin Koc** / [x.com/ersinkoc](https://x.com/ersinkoc)
- GitHub: [@ersinkoc](https://github.com/ersinkoc)
- Website: [guardianwaf.com](https://guardianwaf.com)
标签:AI安全, AMSI绕过, API安全, AppImage, Chat Copilot, CISA项目, DNS通配符暴力破解, Docker发现, DOE合作, EVTX分析, Go, HTTP防护, JSON输出, Ruby工具, Sidecar, WAF, Web应用防火墙, 中间件, 仪表盘, 入侵防御, 单二进制, 反向代理, 威胁检测, 底层编程, 开源, 日志审计, 生产级, 网络安全, 网络测绘, 自定义请求头, 词法分析, 请求拦截, 隐私保护, 零依赖