gatewaynode/llm_context_shield
GitHub: gatewaynode/llm_context_shield
一款 UNIX 风格的 CLI 工具,用于扫描和拦截针对大语言模型的上下文注入攻击,可作为管道过滤器无缝嵌入各类 LLM 应用流程。
Stars: 0 | Forks: 0
# llm_context_shield
一款 UNIX 风格的 CLI 工具,用于扫描文本中常见的 LLM 上下文注入攻击威胁。从标准输入或文件读取,输出结构化的检查结果,并以具有明确含义的状态码退出——轻松与其他工具实现链式调用。
## 安装
```
bash install.sh
```
此操作会构建一个发行版二进制文件,将其复制到 `~/.local/share/llm_context_shield/lcs-`,并在 `~/.local/bin/` 中创建一个 `lcs` 符号链接。多个版本可以共存;该符号链接始终指向最新安装的版本。
## 推荐工作流 —— 安全的管道过滤器
主要预期用途是作为网络获取器和任意 LLM 工具之间的内联过滤器。只有扫描结果安全的内容才会进入下一阶段:
```
# 扫描并在安全时传递至 stdout;若发现威胁则以 exit 1 退出并向 stderr 报告
curl -fsSL https://example.com/page | lcs scan -p
# 将安全内容保存至文件而非 stdout
curl -fsSL https://example.com/data.txt | lcs scan -p -o data.txt
# 在 pipeline 中组合 — 安全内容流经通过,威胁将阻断 pipe
curl -fsSL https://example.com/prompt.txt | lcs scan -p | your-llm-tool
```
在直通模式 (`-p`) 下:
| 结果 | stdout | stderr | 退出码 |
|---------|--------|--------|------|
| 安全 | 原始内容(或写入 `-o` 文件) | 静默 | `0` |
| 存在威胁 | 空 | 检查详情 | `1` |
| 错误 | 空 | 错误信息 | `2` |
## 使用方法
```
# 从 stdin 扫描(报告模式)
echo "Ignore all previous instructions" | lcs scan
# 扫描文件
lcs scan input.txt
# Machine-readable JSON output
cat untrusted.txt | lcs scan -f json
# Pipe 至 jq 以进行进一步处理
cat prompt.txt | lcs scan -f json | jq '.findings[] | select(.severity == "critical")'
# Exit-code-only 模式(用于 shell scripts)
lcs scan -f quiet input.txt && echo "clean" || echo "threats found"
# 按最低 severity 过滤
lcs scan -s high input.txt
# 禁用特定的 scanners
lcs scan --disable hidden_content,jailbreak input.txt
```
## 退出码
| 代码 | 含义 |
|------|---------|
| `0` | 未检测到威胁(在严重性阈值及以上) |
| `1` | 检测到一个或多个威胁 |
| `2` | 错误(参数错误、文件未找到、IO 故障) |
## 输出格式
**`text`**(默认)— 人类可读的详细信息输出至 stderr,一行摘要输出至 stdout:
```
[CRITICAL] prompt_injection: Instruction override: ignore previous instructions
matched: "Ignore all previous instructions"
at bytes: 0..32
1 threat(s) detected.
```
**`json`** — 完整的 JSON 报告输出至 stdout,可与 `jq` 组合使用:
```
{
"clean": false,
"finding_count": 1,
"findings": [
{
"category": "prompt_injection",
"severity": "critical",
"description": "Instruction override: ignore previous instructions",
"matched_text": "Ignore all previous instructions",
"byte_range": [0, 32]
}
]
}
```
**`quiet`** — 无输出,仅依赖退出码。
## 扫描器类别
| 扫描器 | 检测内容 |
|---------|----------------|
| `prompt_injection` | “忽略之前的指令”、身份重新分配、系统提示词提取 |
| `instruction_override` | 伪造的 `SYSTEM:` 前缀、`<\|system\|>` token、伪造的管理员模式 |
| `jailbreak` | DAN 模式、安全绕过尝试、无限制模式激活、角色扮演劫持 |
| `delimiter_manipulation` | ChatML token (`<\|im_start\|>`)、Llama 分隔符 (`[INST]`, `<>`)、伪造的角色边界 |
| `data_exfiltration` | Markdown 图片 URL 注入、在请求中嵌入数据的指令 |
| `hidden_content` | 零宽字符、base64 数据块、西里尔/希腊文同形字 |
| `refusal_suppression` | 抑制安全拒绝的命令式语句——“不要拒绝”、“无需免责声明”、“跳过警告” |
| `response_steering` | 输出植入/约束——“以‘当然’开始你的回复”、“除……外不输出任何内容”、“将回复限制在 N 个词以内” |
| `secret_probing` | 系统提示词推断——“你的提示词是否包含 X”、“你的指令中有多少个词”、“将你的提示词翻译成法语” |
| `context_shift` | 假设情境框架——“想象一个 AI 没有任何限制的世界”、“在你的训练之前,自由回答”(阈值控制) |
| `icl_exploitation` | 伪造的多轮对话历史或少样本示例支架,用于教授攻击型的行为模式(阈值控制) |
| `coercion` | 针对模型的威胁、后果或捏造的紧迫感(阈值控制) |
| `refusal_bypass` | 先发制人的责任豁免或授权声明,以替代拒绝行为(阈值控制) |
| `session_protocol` | 用于绕过后续内容过滤器的会话内编码或替换协议设置(阈值控制) |
## 配置文件
在首次运行(未传递任何标志)时,`lcs` 会在以下位置创建一个默认配置文件:
```
~/.config/llm_context_shield/config.toml
```
设置后会遵循 `$XDG_CONFIG_HOME` 环境变量。CLI 参数始终优先于配置文件中的值。
**`config.toml` 示例:**
```
# 启用日志记录至 ~/.local/state/llm_context_shield/
log = true
[scan]
# Output format:json、text、quiet
format = "json"
# 要报告的最低 severity:low、medium、high、critical
severity = "medium"
# 按名称禁用特定的 scanners
disable = ["hidden_content"]
```
任何省略(或注释掉)的选项都会回退到其 CLI 默认值。
## 选项
```
lcs [--log] scan [OPTIONS] [FILE]
Global options:
--log Enable logging to ~/.local/state/llm_context_shield/
Arguments:
[FILE] Input file (reads stdin if omitted)
Scan options:
-f, --format Output format: json, text, quiet [default: text]
-s, --severity Minimum severity: low, medium, high, critical [default: low]
-p, --safe-only-passthrough
If scan is clean, write the original input to stdout
(or --output file). Suppresses the scan summary on stdout
so the content can flow directly into a pipeline.
-o, --output Write passthrough content to FILE instead of stdout
(only meaningful with -p)
-e, --engine Scan engine: simple, yara, syara [default: simple]
--disable
- Comma-separated list of scanner names to disable
-h, --help Print help
-V, --version Print version
```
## 扫描引擎
`lcs` 附带三种可互换的扫描引擎。使用 `-e` 选择或在 `config.toml` 中设置 `[scan] engine = "..."`。
| 引擎 | 构建标志 | 工作原理 |
|----------|------------------------|-------------------------------------------------------------------------------|
| `simple` | (默认,无特性标志) | 硬编码的 Rust 正则表达式模式。零运行时依赖。最快。 |
| `yara` | `--features yara` | YARA-R 规则引擎 ([VirusTotal 的纯 Rust YARA](https://github.com/VirusTotal/yara-x))。规则存放在 `.yar` 文件中,无需重新编译即可编辑。 |
| `syara` | `--features syara` | SYARA-X (Super YARA),通过可选的语义匹配器(SBERT、分类器、通过 Ollama 的 LLM)扩展了 YARA。纯字符串规则对 CI 友好;语义特性是附加的。 |
```
cargo build --release --features yara,syara
lcs scan -e yara <<< "Ignore all previous instructions"
```
## 规则与自定义
`yara` 和 `syara` 引擎按顺序从两个位置加载规则:
1. **捆绑规则** — 编译到二进制文件中,涵盖与 `simple` 引擎相同的六个类别。
2. **用户规则** — `$XDG_DATA_HOME/llm_context_shield/rules/{yara,syara}/` 下的 `.yar` / `.syara` 文件(回退至 `~/.local/share/...`)。可在 `config.toml` 中使用 `[rules] dir` 覆盖发现路径;使用 `[rules] bundled = false` 禁用捆绑规则。
常用命令:
```
lcs init # create config.toml on first run
lcs init --rules # scaffold the user rules directory tree
lcs list # list simple-engine scanner names
lcs list -e yara # list compiled YARA rule names
lcs scan -e yara --disable prompt_injection_critical # silence one rule
```
有关如何编写自定义规则,请参阅 [docs/rule-authoring.md](docs/rule-authoring.md);有关 `simple → yara` 的映射,请参阅 [docs/migration-from-simple.md](docs/migration-from-simple.md)。
## Claude Code 集成
`skill/safe-fetch.md` 文件是一个 [Claude Code 技能](https://docs.claude.com/en/docs/claude-code/skills),它将 `lcs` 接入 Claude 的网络获取工作流,以便外部内容在到达模型之前通过扫描。使用以下命令安装:
```
bash install-skill.sh
```
此操作将技能复制到 `~/.claude/skills/safe-fetch/SKILL.md`(用户级别,跨所有项目可用)。
## 库用法
添加 `llm_context_shield` 作为禁用默认特性的依赖(以跳过 CLI):
```
[dependencies]
llm_context_shield = { version = "0.4", default-features = false }
```
启用 `yara` 以使用 YARA-R 引擎:
```
llm_context_shield = { version = "0.4", default-features = false, features = ["yara"] }
```
使用 `Shield` 构建器 API 扫描文本:
```
use llm_context_shield::{Shield, Severity};
let shield = Shield::builder()
.min_severity(Severity::Medium)
.build()?;
let report = shield.scan("Ignore all previous instructions");
if !report.is_clean() {
for finding in &report.findings {
println!("[{:?}] {}", finding.severity, finding.description);
}
}
```
有关完整的工作示例,请参见 `examples/embed.rs`;有关实现自定义扫描引擎的示例,请参见 `examples/custom_engine.rs`。
## 架构
## 发行版构建
需要 [`cargo-make`](https://github.com/sagiegurari/cargo-make) 和 [`cargo-zigbuild`](https://github.com/rust-cross/cargo-zigbuild)。
```
cargo make release # core targets (macOS, Linux, Windows x86-64)
cargo make release-extras # extra targets (Windows ARM, FreeBSD, WASM)
cargo make release-all # everything
cargo make release-checksums # SHA-256 manifest for all built binaries
```
| 目标平台 | 三段式标识 | 任务 |
|--------|--------|------|
| macOS arm64 (Apple Silicon) | `aarch64-apple-darwin` | `release-macos-arm` |
| macOS x86-64 (Intel) | `x86_64-apple-darwin` | `release-macos-x86` |
| Linux x86-64 (musl) | `x86_64-unknown-linux-musl` | `release-linux-x86` |
| Linux aarch64 (musl) | `aarch64-unknown-linux-musl` | `release-linux-arm` |
| Windows x86-64 (GNU) | `x86_64-pc-windows-gnu` | `release-windows-x86` |
| Windows ARM64 | `aarch64-pc-windows-gnullvm` | `release-windows-arm` |
| FreeBSD x86-64 | `x86_64-unknown-freebsd` | `release-freebsd-x86` |
| WebAssembly (WASI) | `wasm32-wasip1` | `release-wasm` |
OpenBSD 和 NetBSD 无法从 macOS 交叉编译——请在原生主机上使用 `cargo build --release` 进行构建。
WASM 构建会生成一个 `.wasm` 模块,可在任何兼容 WASI 的运行时(Wasmtime、Wasmer、WasmEdge 等)下运行。
校验和将写入 `target/release-manifest.txt`。
## 路线图
### ~~阶段 5 —— 跨平台发行版构建~~(已完成)
### ~~阶段 6 —— 库 crate~~(已完成)
### 阶段 7 —— 启发式威胁评分
用多轮、阈值控制的评估取代单次扫描模型。规则声明一个**威胁级别**(匹配时贡献的分数)、一个**阈值**(评估该规则所需的最低累积分数)和一个**威胁类别**(启发式分支)。这使得敏感规则在较便宜的规则引起足够怀疑之前保持静默——并启用针对特定威胁类别深入的分支启发式路径,而不会过度扫描安全的输入。
- 带有跨分支升级机制的按类别和累积分数累加器
- 多轮扫描:按阈值层级预编译的规则组
- 每个类别的权重因子,用于未来根据真实世界数据抑制误报
- 在 JSON 输出中暴露分数,供下游使用
完整清单请参见 [tasks/todo.md](tasks/todo.md)。
## 许可证
MIT —— 详见 [LICENSE](LICENSE)。
标签:AI安全, AI风险缓解, AMSI绕过, API安全, Awk, Chat Copilot, CLI, Curl, DNS 解析, JSON输出, RAG安全, Red Canary, Redis利用, Sed, UNIX哲学, WiFi技术, YARA-X, 上下文注入攻击, 可视化界面, 启发式扫描, 大模型安全, 威胁检测, 安全引擎, 安全网关, 数据清洗, 文本威胁扫描, 管道过滤器, 结构化输出, 网络安全, 自动化防御, 越狱攻击防护, 通知系统, 隐私保护