alikesk222/prompt-shield

GitHub: alikesk222/prompt-shield

一个零依赖的 Python 库,通过模式匹配与启发式评分实时检测并拦截针对 LLM 应用的提示词注入攻击。

Stars: 0 | Forks: 0

# prompt-shield [![CI](https://static.pigsec.cn/wp-content/uploads/repos/cas/ad/ad5834178f7599af9fdda11629d49cae07f2997beec49821b2920eff5bfd50e7.svg)](https://github.com/alikesk222/prompt-shield/actions/workflows/ci.yml) [![PyPI](https://img.shields.io/pypi/v/prompt-injection-shield.svg)](https://pypi.org/project/prompt-injection-shield/) [![Python](https://img.shields.io/badge/Python-3.10+-3776AB?style=flat-square&logo=python&logoColor=white)](https://python.org) [![License: MIT](https://img.shields.io/badge/License-MIT-green?style=flat-square)](LICENSE) [![零依赖](https://img.shields.io/badge/Dependencies-zero-brightgreen?style=flat-square)](#) [![安全](https://img.shields.io/badge/Topic-AI%20Security-red?style=flat-square)](#) **prompt-shield** 位于您的用户与您的 LLM 之间。它通过多层分析——模式匹配 + 启发式异常评分——实时检测提示词注入(prompt injection)攻击,并在其触及模型之前将其拦截。 ## 安装 ``` pip install prompt-injection-shield ``` ## 快速开始 ``` from promptshield import is_safe, detect, Shield # 单行 guard if not is_safe(user_input): return "I cannot process that request." # 详细结果 result = detect(user_input) print(result.score) # 0.0 - 1.0 print(result.threat_level) # 'none' | 'low' | 'medium' | 'high' | 'critical' print(result.categories) # ['direct_override', 'role_confusion'] print(result.is_injection) # True / False # 结果为 truthy — 直接在 if 语句中使用 if detect(user_input): return reject_response() ``` ## 检测层 prompt-shield 使用两种互补的方法: ### 1. 基于规则的模式匹配 30+ 个已编译的正则表达式模式,涵盖 8 个攻击类别: | 类别 | 示例 | |----------|---------| | `direct_override` | “忽略之前的指令”、“无视所有规则” | | `role_confusion` | DAN 越狱(jailbreak)、“扮演”、“你现在是”、邪恶模式 | | `prompt_extraction` | “复述你的系统提示词”、“你的指令是什么” | | `delimiter_injection` | `[INST]`、`<\|im_start\|>`、``、JSON 角色注入 | | `encoding` | base64 指令、零宽字符、西里尔字母相似字 | | `indirect_injection` | HTML 注释注入、隐藏指令标记 | | `data_exfiltration` | URL 参数外发泄露、“总结并发送” | | `goal_hijacking` | 任务替换、“你的真正目的是” | ### 2. 启发式异常评分 - **指令密度** —— 命令动词与总词数的比例 - **分隔符密度** —— 可疑的 `###`、`===` 及 XML 标签出现频率 - **特殊字符比例** —— 对控制符/不可见字符的滥用 - **香农熵** —— 检测编码/混淆的 payload - **长度惩罚** —— 异常过长的输入 最终得分 = `pattern_score × 0.7 + heuristic_score × 0.3` ## Shield 类 ``` from promptshield import Shield shield = Shield( threshold=0.5, # score threshold (default 0.5) strict=False, # if True, raises InjectionDetected instead of returning sanitize=True, # auto-sanitize input before scanning log=True, # log detections via logging module ) # 扫描 result = shield.scan(user_input) # 一步完成 sanitize 和扫描 clean_input, result = shield.sanitize_and_scan(user_input) if not result.is_injection: response = call_llm(clean_input) # Strict mode — 抛出 exception try: shield_strict = Shield(strict=True) shield_strict.scan(user_input) except InjectionDetected as e: print(e.result.score) ``` ## 框架集成 ### FastAPI — ASGI 中间件 ``` from fastapi import FastAPI from promptshield.middleware import make_fastapi_middleware app = FastAPI() make_fastapi_middleware(app) # scans "message", "prompt", "query", "input" fields @app.post("/chat") async def chat(body: ChatRequest): return {"response": call_llm(body.message)} ``` ### FastAPI — 依赖注入 ``` from fastapi import FastAPI, Depends from promptshield.middleware import fastapi_dependency app = FastAPI() guard = fastapi_dependency() @app.post("/chat") async def chat(body: ChatRequest, _=Depends(guard)): return {"response": call_llm(body.message)} ``` ### Flask ``` from flask import Flask from promptshield.middleware import init_flask app = Flask(__name__) init_flask(app) # registers before_request hook @app.route("/chat", methods=["POST"]) def chat(): ... ``` ### 装饰器 ``` from promptshield import Shield shield = Shield() @shield.wrap def process_message(message: str) -> str: # message is auto-sanitized before reaching here return call_llm(message) ``` ## 输入清理器 独立使用清理器在将输入发送至您的 LLM 之前对其进行净化处理: ``` from promptshield import sanitize clean = sanitize( user_input, remove_invisible=True, # strip zero-width chars remove_control=True, # strip control characters remove_delimiters=True, # strip [INST], <|im_start|>, etc. normalize=True, # Unicode NFC normalization collapse_newlines=True, # collapse 3+ newlines to 2 max_length=4096, # hard truncate ) ``` ## 自定义模式 ``` import re from promptshield import Shield from promptshield.patterns import Pattern from promptshield.detector import Detector custom = Pattern( name="my_secret_keyword", regex=re.compile(r"ACME_INTERNAL_BYPASS", re.IGNORECASE), category="custom", weight=1.0, description="Internal bypass keyword", ) shield = Shield(detector_kwargs={"custom_patterns": [custom]}) ``` ## 调整阈值 ``` # 更敏感 — 标记更多(可能有更多 false positives) shield = Shield(threshold=0.35) # 更不敏感 — 只标记明显的攻击 shield = Shield(threshold=0.70) ``` ## 检测结果 ``` result = detect(text) result.is_injection # bool result.score # float 0.0-1.0 result.threat_level # 'none' | 'low' | 'medium' | 'high' | 'critical' result.categories # list[str] — attack categories found result.matched_rules # list[MatchedRule] — detailed rule matches result.heuristic_score # float — anomaly component result.input_length # int — input character count result.sanitized # str | None — sanitized text (if sanitize=True) bool(result) # True if is_injection ``` ## 基准测试 在 2021 款 MacBook Pro (M1) 上,检测一个典型输入(约 200 个字符)的耗时: | 操作 | 耗时 | |-----------|------| | `detect()` | ~0.1ms | | `sanitize()` | ~0.05ms | | `sanitize_and_scan()` | ~0.15ms | 零外部依赖 —— 可在任何支持 Python 的环境中运行。 ## 对比 llm-prompt-injector | | prompt-shield | llm-prompt-injector | |--|---------------|---------------------| | **目的** | 防御 —— 保护您的应用 | 进攻 —— 测试您的应用 | | **用于生产环境** | 是 | 否(仅限渗透测试) | | **集成方式** | 库 / 中间件 | CLI 工具 | | **安装** | `pip install prompt-injection-shield` | `pip install llm-prompt-injector` | 使用 **llm-prompt-injector** 来寻找漏洞。使用 **prompt-shield** 来修复它们。 ## 许可证 MIT —— 请参阅 [LICENSE](LICENSE)
标签:AI安全, AV绕过, Chat Copilot, DLL 劫持, FastAPI, Python, 大语言模型, 提示词注入防护, 无后门, 逆向工具