🛡️ ShieldWall Next-Gen
面向 Node.js 的 EDR 级 Web Application Firewall
具备 Stateful Session Analysis 和 Behavioral Fingerprinting 功能的上下文感知安全引擎
## 工作原理
ShieldWall 采用了**分层方法**,而不是试图枚举每一个
已知的攻击签名:
```
HTTP Request (Gateway)
│
├─ 1. TLS Interception JA3/JA4 extraction, Client Random entropy, GREASE detection
│
Request Payload (Engine)
│
├─ 2. Multi-layer Decoder URL / HTML / Unicode / Base64 normalization
├─ 3. Anomaly Scoring N-Gram deviation, Shannon entropy, SSTI, Prototype Pollution
├─ 4. Adaptive Baselines Per-parameter profiling (EWMA length/type tracking)
├─ 5. Session EDR (Stateful) Request Lineage (Graph), BOLA/IDOR tracking
├─ 6. Sequence Analysis Mathematical scraping & ID enumeration detection
├─ 7. Honeypot Traps Invisible forms, fake endpoints, bot detection
├─ 8. .shield Rule Engine YARA-inspired DSL for custom logic
├─ 9. Rate Limiter Sliding window per-IP & Brute-force guard
├─ 10. Cross-Module Boosting Non-linear risk aggregation (Bot + Payload)
├─ 11. Feedback Loop Backend Timing (Blind SQLi) & Exfiltration detection
└─ 12. Security Headers CSP, HSTS, X-Frame-Options, Permissions-Policy
```
其核心洞见在于:与其硬编码成千上万的有效载荷(payload),ShieldWall
更倾向于提问:*“这个请求看起来正常吗?”* **异常评分器** (anomaly scorer) 会根据
行为信号(编码层、字符熵、嵌套深度、混合编码方案)分配一个
可疑度分数,同时**基线模式** (baseline patterns) 和
**.shield 规则**可以捕获最明显的结构性攻击特征。
这使得它是**与数据库无关的** (database-agnostic) 且具有**自适应性** (adaptive) —— 它可以防御 SQL、
NoSQL、LDAP、GraphQL 或任何其他注入目标。
## 架构边界
ShieldWall 在各层之间有严格的分离。每一层都对
它**做**什么和**不做**什么做出了承诺,从而确保可预测、非破坏性的行为:
| 层级 | 职责 | 绝对不做 (Does NOT) |
|---|---|---|
| **Decoder** (解码器) | 规范化编码 (URL, HTML, Unicode, Base64)。生成规范的请求表示 | 做出安全决策。修改原始请求。调用网络 |
| **Feature Extractor** (特征提取器) | 计算熵、编码深度、字符分布 | 阻止或允许任何内容。持久化状态 |
| **Detectors** (检测器模块) | 匹配模式、对信号进行评分、检测异常 | 写入磁盘。发起网络调用 |
| **Scoring Engine** (评分引擎) | 将检测器的输出聚合为风险分数 | 执行策略 (拦截/放行) |
| **Decision Engine** (决策引擎) | 基于分数和严重性应用策略 (拦截/检测/记录) | 规范化输入。对信号进行评分 |
| **Auto-Rule Generator** (自动规则生成器) | 从零日漏洞异常中创建候选签名 | 在没有 TTL 的情况下提升规则。覆盖现有规则 |
### 设计保证
- **解码是有界的** (`MAX_DECODE_DEPTH = 5`)。
- 热路径中**没有网络调用**。
- **不会修改** (mutate) 原始的 `req` 对象。
- 对于相同的输入保证**确定性输出** (无随机性)。
- **自动生成的规则在 7 天后过期** (必须手动提升)。
- **反馈循环会调整信号权重**,但绝不会低于 10% 的基础权重,以防止自身失效 (self-muting)。
## 安装
```
npm install shieldwall
```
## 快速入门
```
const express = require('express');
const shieldwall = require('shieldwall');
const app = express();
app.use(express.json());
app.use(shieldwall({
mode: 'block', // 'block' or 'detect' (log only)
dashboard: { port: 9090 },
rateLimit: { max: 100 },
bruteForce: { maxAttempts: 5 },
}));
app.get('/', (req, res) => {
res.json({ message: 'Protected by ShieldWall 🛡️' });
});
app.listen(3000);
```
## .shield 规则语法
使用受 YARA 启发的 DSL 编写自定义检测规则:
```
rule my_detection : tag {
meta:
author = "You"
description = "What this catches and why"
severity = "critical"
target:
$url = request.url
$body = request.body
strings:
$pattern = /suspicious_regex/i
condition:
$pattern in $url or $pattern in $body
}
```
### 目标
| 目标 | 描述 |
|--------|-------------|
| `request.url` | 完全解码后的 URL |
| `request.body` | 请求体 |
| `request.query` | 查询字符串参数 |
| `request.headers` | 所有请求头 |
| `request.cookies` | Cookie 值 |
| `request.useragent` | User-Agent 字符串 |
| `request.raw_url` | 解码前的 URL (用于规避检测) |
| `request.session` / `request.sessionid` | 会话标识符 |
| `request.timestamp` / `request.time` | 请求时间戳 |
| `request.geoip` / `request.geo` | GeoIP 数据 (国家、城市、ASN) |
| `request.fingerprint` / `request.fp` | 浏览器/设备指纹 |
| `request.rate` | 速率限制计数器数据 |
### 条件运算符
`and`, `or`, `not`, `in` (目标范围匹配), `any of them`, `all of them`, `( )` 分组。
规则可以从文件、目录或内联字符串中加载 —— 参见示例。
### 内置规则文件
| 文件 | 保护范围 |
|------|------------|
| `sqli.shield` | SQL 和 NoSQL 注入模式 |
| `xss.shield` | 跨站脚本攻击 (XSS) |
| `traversal.shield` | 路径遍历和 LFI/RFI |
| `cmdi.shield` | 命令注入攻击 |
| `protocol.shield` | HTTP 走私、SSRF、CRLF 注入 |
| `scanner.shield` | 已知安全扫描器检测 |
| `graphql.shield` | GraphQL 查询深度炸弹和内省 |
| `jwt.shield` | JWT 算法混淆和密钥注入 |
| `deserialization.shield` | Java/PHP/Node.js/Python 反序列化 |
| `cors.shield` | CORS 配置错误滥用 |
| `file_upload.shield` | 危险的文件上传模式 |
| `dos_protection.shield` | L7 DDoS - Slowloris、头部膨胀、参数洪泛 |
| `api_security.shield` | IDOR/BOLA、批量赋值、异常的 Content-Type |
| `proto_pollution.shield` | Node.js 原型污染攻击 |
| `obfuscation_evasion.shield` | 双重 Base64、十六进制编码、Unicode 同形字 |
| `business_logic.shield` | 表单速度、购物车操纵、抓取模式 |
| `security_misconfig.shield` | Debug 端点、配置文件、备份访问 |
## 模块
| 模块 | 方法 |
|--------|----------|
| **异常评分** (Anomaly Scoring) | 行为启发式算法 —— 编码层、字符密度、嵌套深度、混合方案、熵分析、参数污染、原始字节注入、有效载荷膨胀、请求头完整性 |
| **蜜罐** (Honeypot) | 隐形的 HTML 陷阱、虚假管理面板、虚假 API —— 标记任何与之交互的行为 |
| **注入** (Injection) | 结构化模式 (上下文中断 + 关键字) —— 与数据库无关 |
| **XSS** | HTML 执行特征 (标签、处理器、协议、DOM sinks) |
| **路径遍历** (Path Traversal) | 在原始 URL 上进行解码后的遍历 + 编码规避检测 |
| **命令注入** (Command Injection) | Shell 元字符 + 命令名结构配对 |
| **扫描器检测** (Scanner Detection) | User-Agent 指纹和带外回调域名 |
| **协议滥用** (Protocol Abuse) | HTTP 走私、SSRF、CRLF、Host 头中毒 |
| **速率限制器** (Rate Limiter) | 基于单 IP 的滑动窗口并自动拦截 |
| **暴力破解防护** (Brute-Force Guard) | 对敏感端点进行渐进式退避 |
| **安全响应头** (Security Headers) | CSP、HSTS、Permissions-Policy 等 (helmet.js 的替代方案) |
| **Bot 检测** (Bot Detection) | 无头浏览器检测、自动化工具、行为分析 |
| **会话异常** (Session Anomaly) |
// ╔═══════════════════════════════════════════════════════════════════════════╗
// ║ ShieldWall Session EDR (Stateful) ║
// ║ ║
// ║ Provides high-level context awareness similar to Endpoint Detection ║
// ║ and Response (EDR) systems. Tracks sessions across requests to detect ║
// ║ logical bypasses, lateral movement, and identity theft. ║
// ║ ║
// ║ Core Capabilities: ║
// ║ ├─ Request Lineage: Validates logical navigation flow graphs. ║
// ║ ├─ BOLA/IDOR Detection: Tracks resource ID access patterns. ║
// ║ ├─ Context Drift: Monitors IP/TLS identity shifts mid-session. ║
// ║ └─ Velocity Control: Detects "Impossible Human" interaction speeds. ║
// ╚═══════════════════════════════════════════════════════════════════════════╝
| **API 滥用** (API Abuse) | GraphQL 复杂度分析、REST 枚举、批量攻击检测 |
| **DDoS 防护** (DDoS Protection) | L7 洪泛检测 - Slowloris、超大请求头、连接洪泛 |
## 异常阈值校准
所有阈值均根据合法 Web 流量和
已知攻击语料库 (SQLi、XSS、编码的有效载荷、PE/ELF 上传) 混合进行了经验性调优。常见
有效载荷的参考分数:
| 有效载荷类型 | 典型分数 | 级别 |
|---|---|---|
| 正常的 `GET /api/users` | 0 – 3 | 无 |
| GraphQL 内省 | 4 – 8 | 无/低 |
| Authorization 中的 JWT | 2 – 5 | 无 |
| `' OR 1=1 --` | 12 – 18 | 中/高 |
| UNION SELECT (已编码) | 22 – 35 | 高/严重 |
| `` | 14 – 20 | 高 |
| 多层编码的有效载荷 | 20 – 40+ | 严重 |
**分数阈值 (15)** —— 已知攻击能够可靠触发的最低分数。
**严重阈值 (30)** —— 需要 ≥3 个独立的高权重信号;对于合法流量来说极其罕见。
**熵值 5.5** —— 高于正常的 URL 编码值 (≈4.5–5.2),但低于纯粹的 Base64/加密数据 (≈5.8–6.0)。
已知的误报来源 (JWT、GraphQL 内省、十六进制哈希、带版本的
REST 路径) 会被自动抑制。
## 蜜罐 (Honeypot)
ShieldWall 会自动将隐形的 HTML 陷阱注入到您的页面中:
- 人类无法看到但 Bot 会自动填写的隐藏表单
- 指向 `/admin-panel`、`/.env`、`/.git/config` 的虚假链接
- 像 `/api/internal/debug` 这样的虚假 API 端点
任何与这些陷阱的交互都会立即将该客户端标记为 Bot。
## 仪表盘 (Dashboard)
在 `http://localhost:9090` 进行实时监控:
- 带有严重性指示器的实时攻击源
- 为什么每个请求会被拦截 (人类可读的解释)
- 严重性细分、热门攻击类型、高频攻击者 IP
- 基于 WebSocket —— 实现即时更新
## 配置
```
shieldwall({
mode: 'block', // 'block' | 'detect'
logLevel: 'info', // 'error' | 'warn' | 'info' | 'debug'
jsonLogs: false, // structured JSON output
rulesDir: './rules', // .shield files directory
customRules: '...', // inline .shield string
customRulesFiles: [], // additional .shield file paths
blockStatusCode: 403,
blockMessage: null, // string or function(matches)
trustProxy: false,
excludePaths: ['/health'],
excludeIPs: ['127.0.0.1'],
modules: { anomaly: true, honeypot: true, sqli: true, xss: true, pathTraversal: true, commandInjection: true, botDetection: true, sessionAnomaly: true, apiAbuse: true },
rateLimit: { windowMs: 60000, max: 100 },
bruteForce: { maxAttempts: 5, sensitivePaths: ['/login'] },
dashboard: { port: 9090 },
headers: { hsts: { maxAge: 31536000 } },
honeypot: true, // inject HTML traps into responses
reporting: {
enabled: true,
reportsDir: './reports',
maxStoredReports: 12,
},
});
```
### 编程方式访问
```
const waf = shieldwall({ ... });
waf.on('threat', (event) => {
// event.matches — what triggered
// event.request — IP, method, URL
// send to Slack, Discord, webhook, SIEM...
});
waf.on('report', ({ type, report, filepath }) => {
// type: '14d' | 'monthly'
// report — full report object with trends, ROI, persistent attackers
// filepath — path to saved JSON file
});
waf.getStats(); // request/block/threat counters
waf.getReport(14); // generate report for last 14 days
waf.getStoredReports(); // get all stored reports
waf.reloadRules(); // hot-reload .shield files
```
### 自动报告
ShieldWall 会自动生成报告:
- **每 14 天** —— 包含关键统计信息的摘要报告
- **每月** —— 包含趋势、ROI 指标、攻击向量转移分析和持久性攻击者追踪的详细报告
报告保存在 `reports/` 中,包含:
- 按严重性和类别划分的攻击摘要
- 受攻击最多的端点及其防护建议
- 攻击动态 (与上一周期的比较)
- 新型攻击模式检测
- 地理分布
- ROI 指标 (节省的流量、节省的 CPU 时间、成本估算)
- 向量转移分析 (例如:cmdi → api-abuse 迁移)
- 持久性攻击者识别 (IP 侦测追踪)
- SVG 时间线图表
## 日志
每个被拦截的请求都会生成一份结构化日志,解释:
```
[SHIELDWALL] 🔴 BLOCKED | anomaly_detection [critical] | 192.168.1.50 POST /api/data
├─ Why: Anomaly score 28/30: multi_layer_encoding, unusual_char_density, comment_syntax
└─ Evidence: [multi_layer_encoding] 3 layers of URL encoding — likely evasion attempt
```
JSON 模式 (`jsonLogs: true`) 输出可供机器解析的条目,以便集成到 SIEM 中。
## 许可证
MIT —— 见 [LICENSE](./LICENSE)
专为安全研究社区而构建。
这是一个工具,而不是一个产品 —— 请根据您的环境进行调优。