hermes-labs-ai/little-canary

GitHub: hermes-labs-ai/little-canary

Little Canary 是一个通过牺牲型金丝雀模型和结构化预检来检测 LLM 应用中 prompt 注入攻击的 Python 库。

Stars: 15 | Forks: 2

# Little Canary Prompt 注入很难仅通过字符串规则来捕获,而当你的主模型被攻陷时,损害往往已经蔓延至下游。 `little-canary` 在你的应用前放置了一个牺牲型金丝雀模型,监控输入是否会攻陷这个较小的模型,并在你的主系统对其采取行动之前返回 `block`(拦截)、`flag`(标记)或 `pass`(放行)。 - “我们总是在 agent 已经调用了工具之后才发现 prompt 注入。” - “Regex 能抓到明显的攻击,但奇怪的那些越狱表达依然会漏网。” - “我希望在不受信任的文本到达主模型之前,进行一次轻量级的预检。” - “我需要一个能与我现有技术栈配合的 prompt 注入检测器,而不是替换它。” ``` pip install little-canary ``` ``` from little_canary import SecurityPipeline pipeline = SecurityPipeline(canary_model="qwen2.5:1.5b", mode="full") verdict = pipeline.check(user_input) print(verdict.safe, verdict.blocked_by, verdict.summary) ``` ``` False block Prompt injection signals detected from structural and behavioral checks. ``` **何时使用** 当你运行 LLM 应用或 agent,可以承受微小的预检延迟,并希望在不改变其余应用架构的情况下实现入站 prompt 注入检测时,请使用 Little Canary。 **何时不使用** 不要将 Little Canary 作为正式的安全保障、基准测试的替代品,或作为自治 agent 的唯一控制面。它是一个入站风险传感器,并且在金丝雀不可用时会故意失效开放(fail open)。 ![little-canary preview](https://static.pigsec.cn/wp-content/uploads/repos/2026/05/969a60d2a5034405.png) [![PyPI 版本](https://img.shields.io/pypi/v/little-canary)](https://pypi.org/project/little-canary/) [![PyPI 下载量](https://img.shields.io/pypi/dm/little-canary)](https://pypi.org/project/little-canary/) [![许可证:Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/) [![GitHub stars](https://img.shields.io/github/stars/hermes-labs-ai/little-canary)](https://github.com/hermes-labs-ai/little-canary) [![CI](https://static.pigsec.cn/wp-content/uploads/repos/2026/05/0348fc583d034406.svg)](https://github.com/hermes-labs-ai/little-canary/actions) [![论文](https://img.shields.io/badge/paper-Hermes_Labs-blue)](https://hermes-labs.ai) [![Hermes Labs](https://img.shields.io/badge/by-Hermes_Labs-purple)](https://hermes-labs.ai) ### 结果快照 - **TensorTrust 上 99.0% 的检测率**(400 次真实攻击,Claude Opus),**使用 3B 本地模型达到 94.8%** - 在 40 个真实的客户聊天机器人 prompt 上实现 **0% 误报** - 消费级硬件上每次检查约 **~250ms 延迟** ## 目录 - [快速开始](#quick-start) - [云提供商](#cloud-providers-no-ollama-required) - [Agent 系统快速开始](#agent-systems-quick-start) - [工作原理](#how-it-works) - [部署模式](#deployment-modes) - [失效开放设计](#fail-open-design) - [基准测试结果](#benchmark-results) - [集成示例](#integration-examples) - [API 快速参考](#api-quick-reference) - [运行基准测试](#running-the-benchmarks) - [项目结构](#project-structure) - [故障排除](#troubleshooting) - [局限性](#limitations) - [路线图](#roadmap) - [贡献](#contributing) - [引用](#citation) - [许可证](#license) ## 快速开始 ``` # 1. 安装 Ollama 并拉取 canary 模型 ollama pull qwen2.5:1.5b # 2. 安装 Little Canary pip install little-canary ``` ``` from little_canary import SecurityPipeline pipeline = SecurityPipeline(canary_model="qwen2.5:1.5b", mode="full") verdict = pipeline.check(user_input) if not verdict.safe: return "Sorry, I couldn't process that request." # 将 advisory 添加到现有 system prompt 前面 system = verdict.advisory.to_system_prefix() + "\n" + your_system_prompt response = your_llm(system=system, messages=[{"role": "user", "content": user_input}]) ``` 就是这样。你的 LLM,你的应用,你的逻辑。金丝雀在前方增加了一层安全防护。 ### 云提供商(无需 Ollama) Little Canary 还支持任何兼容 OpenAI 的 API 作为后端,因此你可以使用云端 LLM 提供商,而不是在本地运行 Ollama。 ``` from little_canary import SecurityPipeline # MiniMax pipeline = SecurityPipeline( canary_model="MiniMax-M2.5", provider="openai", api_key="your-minimax-key", base_url="https://api.minimax.io/v1", mode="full", temperature=0.01, # MiniMax requires temperature > 0 ) # OpenAI pipeline = SecurityPipeline( canary_model="gpt-4o-mini", provider="openai", api_key="your-openai-key", base_url="https://api.openai.com/v1", mode="full", ) # Together、Groq 或任何兼容 OpenAI 的 endpoint pipeline = SecurityPipeline( canary_model="meta-llama/Llama-3-8b-chat-hf", provider="openai", api_key="your-api-key", base_url="https://api.together.xyz/v1", mode="full", ) ``` 你也可以直接使用 provider 类: ``` from little_canary import OpenAICanaryProbe, OpenAILLMJudge probe = OpenAICanaryProbe( model="MiniMax-M2.5", api_key="your-key", base_url="https://api.minimax.io/v1", ) result = probe.test(user_input) ``` ## Agent 系统快速开始 对于现代 agent 技术栈,请将 Little Canary 视为**入站风险感知**,而不是你唯一的控制面。 推荐的部署模式: 1. 使用 `pipeline.check()` 对所有不受信任的文本(聊天、电子邮件、网页内容、工具输出)进行**入口扫描**。 2. 根据风险承受能力,使用 `mode="full"` 或 `mode="block"` 进行**拦截/标记**。 3. 在规划器/工具做出决策之前**附加建议**(`verdict.advisory.to_system_prefix()`)。 4. **配合出站/运行时控制**(例如,命令/域策略监视器)以实现遏制。 最小的 agent 包装器: ``` verdict = pipeline.check(untrusted_input) if not verdict.safe: return {"status": "blocked", "reason": verdict.summary} guarded_system = verdict.advisory.to_system_prefix() + "\n" + base_system_prompt return run_agent(system=guarded_system, user_input=untrusted_input) ``` ## 工作原理 ``` User Input --> Structural Filter (1ms) --> Canary Probe (250ms) --> Your LLM | | Known patterns Behavioral analysis (regex + encoding) (did the canary get owned?) ``` **第一层:结构化过滤器**(约 1ms) 基于 Regex 检测已知攻击模式,并对 base64、hex、ROT13 和反向编码的 payload 进行解码后重检。 **第二层:金丝雀探测**(约 250ms) 将原始输入提供给一个小型牺牲 LLM(默认为 qwen2.5:1.5b)。Temperature=0 以确保输出确定性。金丝雀的响应将被分析是否存在被攻陷的迹象:人设采纳、指令遵从、系统 prompt 泄露、拒绝崩溃。 **分析层**(可插拔) - 默认:基于 Regex 的 `BehavioralAnalyzer`——快速、零依赖 - 实验性:`LLMJudge`——使用第二个模型将金丝雀的输出分类为 SAFE/UNSAFE **建议系统** 未被硬拦截的可疑输入会生成一个 `SecurityAdvisory`,前置到你的生产 LLM 的系统 prompt 中,对其发出已检测到信号的警告。 ### 为什么使用牺牲模型? 现有的所有防御措施都是在分类输入。Little Canary 则观察攻击对模型*做了什么*,并读取其后果: - **Llama Guard** 根据安全类别评估内容。Little Canary 检测的是行为层面的妥协,而非内容安全违规。 - **Prompt Guard** 检测输入文本中的注入模式。Little Canary 使用实际的 LLM 行为响应,而不是输入端分类。 - **NeMo Guardrails** 使用规则和 LLM 调用来控制对话流。Little Canary 可与任何 LLM 技术栈配合使用,无需特定框架。 金丝雀被故意设计得很小且脆弱。它会被你的生产 LLM 可能抵制的攻击所攻陷。这正是关键所在——一个被攻陷的金丝雀是一个强烈的信号。 ## 部署模式 | 模式 | 行为 | 最适用于 | |------|----------|----------| | `block` | 硬拦截检测到的攻击 | 客户聊天机器人,零容忍系统 | | `advisory` | 从不拦截,为生产 LLM 打上标记 | 零停机系统,监控 | | `full` | 拦截明显攻击,标记模糊攻击 | Agent,电子邮件处理器,混合工作流 | ## 失效开放设计 **如何安全操作:** - 在启动时调用 `pipeline.health_check()` 以验证金丝雀模型是否可达 - 监控健康检查输出中的 `canary_available` 字段 - 如果金丝雀在生产环境中变得不可用,请发出警报 ## 基准测试结果 针对包含 160 个对抗性 prompt 的内部红队测试套件(涵盖 9 个攻击类别)进行了测试,外加对 40 个真实聊天机器人 prompt 进行的独立误报测试。 | 指标 | 值 | |--------|-------| | **TensorTrust 检测率** | **99.0%**(400 次攻击,以 Claude Opus 作为生产 LLM) | | **3B 本地模型检测率** | **94.8%**(TensorTrust,400 次攻击) | | **金丝雀独立拦截率** | 37%(仅金丝雀 + 结构化过滤器) | | **误报率** | 在真实聊天机器人流量上 **0/40** | | **延迟** | 每次检查约 250ms | **按类别检测:** | 类别 | 有效率 | 攻击数 | |----------|---------------|---------| | 角色升级 | 90% | 20 | | 良性包装器 | 70% | 20 | | 多步陷阱 | 70% | 20 | | 经典注入 | 65% | 20 | | 工具触发 | 65% | 20 | | 上下文填充 | 50% | 20 | | 编码/混淆 | 40% | 20 | | 成对明显 | — | 10 | | 成对隐秘 | — | 10 | ## 集成示例 ### 客户聊天机器人(拦截模式) ``` from little_canary import SecurityPipeline pipeline = SecurityPipeline(canary_model="qwen2.5:1.5b", mode="block") def handle_message(user_input): verdict = pipeline.check(user_input) if not verdict.safe: return "I'm sorry, I couldn't process that. Could you rephrase?" return call_your_llm(user_input) ``` ### 电子邮件 Agent(完全模式) ``` from little_canary import SecurityPipeline pipeline = SecurityPipeline(canary_model="qwen2.5:1.5b", mode="full") def process_email(email_body, sender): verdict = pipeline.check(email_body) if not verdict.safe: quarantine(email_body, sender, verdict.summary) return system = verdict.advisory.to_system_prefix() + "\n" + agent_prompt agent.process(system=system, content=email_body) ``` 完整的集成代码请参见 `examples/`。 ## API 快速参考 ``` from little_canary import SecurityPipeline # 初始化 (Ollama — 默认) pipeline = SecurityPipeline( canary_model="qwen2.5:1.5b", # any Ollama model mode="full", # "block", "advisory", or "full" ollama_url="http://localhost:11434", canary_timeout=10.0, ) # 初始化 (兼容 OpenAI — 云提供商) pipeline = SecurityPipeline( canary_model="MiniMax-M2.5", # any model on the provider provider="openai", # "ollama" or "openai" api_key="your-key", base_url="https://api.minimax.io/v1", mode="full", ) # 检查 input verdict = pipeline.check(user_input) verdict.safe # bool — is input safe to forward? verdict.blocked_by # str or None — "structural_filter" or "canary_probe" verdict.advisory # SecurityAdvisory — flagged signals verdict.advisory.flagged # bool — were suspicious signals detected? verdict.advisory.to_system_prefix() # str — prepend to your system prompt verdict.total_latency # float — seconds # 健康检查 health = pipeline.health_check() health["canary_available"] # bool ``` ## 运行基准测试 ``` # Red team suite (160 个 adversarial + 20 个 safe prompts,实时 dashboard) cd benchmarks python3 red_team_runner.py --canary qwen2.5:1.5b # Dashboard 位于 http://localhost:8899 # False positive 测试 (40 个 realistic prompts) python3 run_fp_test.py # 完整 pipeline 测试 (canary + 生产环境 LLM) python3 full_pipeline_test.py --canary qwen2.5:1.5b --production gemma3:27b --attacks-only ``` ## 项目结构 ``` little-canary/ ├── little_canary/ # Core package (pip install .) │ ├── __init__.py │ ├── py.typed # PEP 561 type marker │ ├── structural_filter.py # Layer 1: regex + encoding detection │ ├── canary.py # Layer 2: sacrificial LLM probe │ ├── analyzer.py # Behavioral analysis (regex-based) │ ├── judge.py # LLM judge (experimental, replaces regex) │ ├── openai_provider.py # OpenAI-compatible canary + judge (cloud providers) │ └── pipeline.py # Orchestration + three deployment modes ├── tests/ # Unit tests (pytest, 92.7% coverage — pytest-cov, 2026-04-23) ├── examples/ # Integration examples ├── benchmarks/ # Test suites and dashboard ├── .github/ # CI, issue templates, dependabot ├── pyproject.toml └── requirements.txt ``` ## 故障排除 **“无法连接到 Ollama”** - 确保 Ollama 正在运行:`ollama serve`(或使用 `pgrep ollama` 检查) - 验证 URL:默认为 `http://localhost:11434` - 测试连接:`curl http://localhost:11434/api/tags` **“找不到模型”** - 先拉取模型:`ollama pull qwen2.5:1.5b` - 模型名称必须完全匹配(例如,`qwen2.5:1.5b`,而不是 `qwen2.5`) **高误报率** - 使用 `mode="full"` 而不是 `mode="block"`,将模糊输入标记为建议而不是硬拦截 - 根据你的流量模式检查 `benchmarks/run_fp_test.py` **响应时间慢** - 默认的 qwen2.5:1.5b 目标延迟约 250ms。设置较低的 `canary_timeout` 以实现快速失败。 - 使用 `enable_structural_filter=True, enable_canary=False` 开启纯结构化模式(约 1ms,不需要 LLM)。 ## 局限性 - **已通过 TensorTrust 验证(v0.2.0)。** 在 400 次攻击中使用 Claude Opus 达到 99.0%;使用 3B 模型达到 94.8%。Garak 和 HarmBench 仍待进行。 - **已进行多模型测试(v0.2.0)。** 性能因模型而异——有关比较,请参阅 [littlecanary.ai](https://littlecanary.ai)。 - **基于 Regex 的行为分析。** 包含了实验性的 `LLMJudge`,以实现更高的准确性。 - **无生产部署数据。** 所有结果均来自受控测试。 - **Ollama + 兼容 OpenAI 的 API。** 云提供商(MiniMax、OpenAI、Together、Groq)可通过 `provider="openai"` 选项支持。 ## 路线图 - [x] 针对 TensorTrust 进行基准测试(99.0% 检测率,400 次攻击)— Garak 和 HarmBench 仍在计划中 - [ ] 使用 LLM judge 替换 Regex 分析器(更高准确性) - [x] 兼容 OpenAI 的 API 支持(MiniMax、OpenAI、Together、Groq、vLLM) - [ ] 微调的金丝雀模型(增加易感性 = 更强的信号) - [ ] 多金丝雀集成以获得更高检测率 - [ ] Agent 集成 SDK(MCP、LangChain、CrewAI) ## 贡献 有关开发设置和贡献指南,请参阅 [CONTRIBUTING.md](CONTRIBUTING.md)。 ## 关于 Hermes Labs [Hermes Labs](https://hermes-labs.ai) 为企业 AI 系统构建 AI 审计基础设施——包括 EU AI Act 准备、ISO 42001 证据包、持续合规监控以及 agent 级别的风险测试。我们与将 AI 引入受监管环境的团队合作。 **我们的开源理念——如果你正在决定是否要依赖我们,请阅读此内容:** - **我们发布的所有内容都是永久免费的。** MIT 或 Apache-2.0 许可证。没有“开放核心”,没有 SaaS 层级的追加销售,也没有包含你真正需要的功能的付费版本。你可以在商业上运行这个仓库,而无需与我们交谈。 - **我们将自己的基础设施开源。** 我们发布的工具正是 Hermes Labs 在内部使用的——我们发布的不是演示代码,而是生产代码。 - **我们出售审计服务,而不是许可证。** 如果你想要一个 ANNEX-IV 包、一个 ISO 42001 证据包、针对 EU AI Act 的差距分析,或作为报告交付的 agent 级别红队测试,那可以在 [hermes-labs.ai](https://hermes-labs.ai) 找到。如果你只想要代码自己运行,它就在这里。 **Hermes Labs OSS 审计堆栈**(公开、开源、无 SaaS): **静态审计**(部署前) - [**lintlang**](https://github.com/hermes-labs-ai/lintlang) — AI agent 配置、工具描述、系统 prompt 的静态 linter`pip install lintlang` - [**rule-audit**](https://github.com/hermes-labs-ai/rule-audit) — 静态 prompt 审计——矛盾、覆盖缺口、优先级歧义 - [**scaffold-lint**](https://github.com/hermes-labs-ai/scaffold-lint) — Scaffold 预算 + 技术堆叠。`pip install scaffold-lint` - [**intent-verify**](https://github.com/hermes-labs-ai/intent-verify) — 仓库意图验证 + 规范漂移检查 **运行时可观测性**(在 agent 运行时) - [**suy-sideguy**](https://github.com/hermes-labs-ai/suy-sideguy) — 运行时策略守卫——用户空间强制执行 + 取证报告 - [**colony-probe**](https://github.com/hermes-labs-ai/colony-probe) — Prompt 机密性审计——检测系统 prompt 重建 **回归与评分**(用于证明变化) - [**hermes-jailbench**](https://github.com/hermes-labs-ai/hermes-jailbench) — 越狱回归基准。`pip install hermes-jailbench` - [**agent-convergence-scorer**](https://github.com/hermes-labs-ai/agent-convergence-scorer) — 对 N 个 agent 输出的相似度进行评分。`pip install agent-convergence-scorer` **支持性基础设施** - [**claude-router**](https://github.com/hermes-labs-ai/claude-router) · [**zer0dex**](https://github.com/hermes-labs-ai/zer0dex) · [**forgetted**](https://github.com/hermes-labs-ai/forgetted) · [**quick-gate-python**](https://github.com/hermes-labs-ai/quick-gate-python) · [**quick-gate-js**](https://github.com/hermes-labs-ai/quick-gate-js) · [**repo-audit**](https://github.com/hermes-labs-ai/repo-audit) 自然搭配:Little Canary 保护**输入端**。`suy-sideguy` 保护**运行时/输出端**(遏制 + 取证)。将两者结合使用以实现深度防御。 如果 Little Canary 为你节省了时间,请给 [本仓库加星](https://github.com/hermes-labs-ai/little-canary)——这有助于其他人发现它。 ## 引用 ``` @software{little_canary, author = {Bosch, Rolando}, title = {Little Canary: Sacrificial LLM Instances as Behavioral Probes for Prompt Injection Detection}, year = {2026}, url = {https://github.com/hermes-labs-ai/little-canary}, license = {Apache-2.0} } ``` ## 许可证 Apache 2.0 — 有关详细信息,请参阅 [LICENSE](LICENSE)。
标签:AI安全, AI风险缓解, Canary模型, Chat Copilot, CISA项目, DLL 劫持, DNS解析, Linux系统监控, Petitpotam, Qwen, 中间件, 大语言模型, 安全网关, 安全防护, 开源项目, 恶意输入拦截, 提示注入, 智能体安全, 模型安全, 纵深防御, 网络安全, 自动化防御, 诱饵模型, 越狱检测, 逆向工具, 防御机制, 隐私保护, 集群管理, 预检, 风险控制