mishabar410/PolicyShield

GitHub: mishabar410/PolicyShield

PolicyShield 是一个声明式运行时防火墙,在 LLM 和工具调用之间拦截危险操作,防止 AI Agent 执行删除文件、泄露敏感数据等高风险行为。

Stars: 15 | Forks: 2

# 🛡️ PolicyShield

PolicyShield Demo

**AI agent 可以在单次会话中执行 `rm -rf /`,泄露你的数据库,并产生高达 1 万美元的 API 账单。** PolicyShield 是一个运行时防火墙,位于 LLM 和其调用的工具之间。使用 YAML 编写规则 —— PolicyShield 会在任何工具执行前强制执行这些规则。 ``` LLM → exec("rm -rf /") → BLOCKED ✅ tool never runs LLM → send("SSN: 123-45-6789") → REDACTED ✅ send("SSN: [SSN]") LLM → deploy("prod") → APPROVE ✅ human reviews first ``` [![PyPI](https://img.shields.io/pypi/v/policyshield?color=blue)](https://pypi.org/project/policyshield/) [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/) [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) [![CI](https://static.pigsec.cn/wp-content/uploads/repos/cas/39/39faa54be350a1dab8afd3b2fb8c1c83e4d9cff84abfef2374d19a18053687c4.svg)](https://github.com/mishabar410/PolicyShield/actions/workflows/ci.yml) [![1500+ tests](https://img.shields.io/badge/tests-1500%2B-brightgreen.svg)](#development) ## ⚡ 快速开始 (30 秒) ``` pip install policyshield ``` 创建 `rules.yaml`: ``` rules: - id: no-delete when: { tool: delete_file } then: block message: "File deletion is not allowed." - id: redact-pii when: { tool: send_message } then: redact message: "PII redacted before sending." ``` 使用它: ``` from policyshield.shield.engine import ShieldEngine engine = ShieldEngine(rules="rules.yaml") result = engine.check("delete_file", {"path": "/data"}) # → Verdict.BLOCK — "不允许删除文件。" result = engine.check("send_message", {"text": "Email john@corp.com"}) # → Verdict.REDACT — modified_args: {"text": "Email [EMAIL]"} ``` 就这么简单。无需重写 agent。可与任何框架一起工作。 ## 🔌 OpenClaw 集成 (分步指南) PolicyShield 作为原生插件接入 [OpenClaw](https://github.com/openclaw/openclaw)。AI agent 发起的每次工具调用都会先经过 PolicyShield —— BLOCK、REDACT、APPROVE 或 ALLOW。你还可以在 Telegram/Discord/Slack 中使用 `/policyshield` 命令。 ### 1. 启动 PolicyShield 服务器 ``` pip install policyshield policyshield server --rules rules.yaml --port 8100 ``` 服务器运行在 `http://localhost:8100`,并对外提供 OpenClaw 插件调用的 REST API。 ### 2. 将插件安装到 OpenClaw 中 从 PolicyShield 仓库安装: ``` cd plugins/openclaw npm install && npm run build ``` 或者从 npm 安装: ``` openclaw plugins install @policyshield/openclaw-plugin ``` ### 3. 配置 `openclaw.json` 将插件路径和配置添加到你的 OpenClaw 配置文件中: ``` { // your existing config... "plugins": { "enabled": true, "load": { // point to the built plugin directory "paths": ["/path/to/PolicyShield/plugins/openclaw"] }, "entries": { "policyshield": { "enabled": true, "config": { "url": "http://localhost:8100", // PolicyShield server "mode": "enforce", // "enforce" or "disabled" "fail_open": true, // allow calls if server is down "timeout_ms": 5000 // per-check timeout } } } } } ``` ### 4. 启动 OpenClaw 网关 ``` OPENAI_API_KEY="sk-..." openclaw gateway ``` 在输出中查找以下行: ``` [gateway] ✓ Connected to PolicyShield server [gateway] agent model: openai/gpt-4o [telegram] starting provider (@yourbot) ``` ### 工作原理 ``` User → OpenClaw Agent → LLM wants to call tool("exec", {command: "rm -rf /"}) │ ▼ ┌─────────────────────────┐ │ PolicyShield Plugin (TS)│─ before_tool_call → POST /api/v1/check │ │← verdict: BLOCK ── PolicyShield Server └─────────────────────────┘ │ ▼ Tool call BLOCKED — agent tells user it can't do that. ``` | Hook | 时机 | 发生的操作 | |------|------|-------------| | `before_agent_start` | 会话开始时 | 将活动规则注入 LLM context | | `before_tool_call` | 每次工具调用前 | 检查策略 → ALLOW / BLOCK / REDACT / APPROVE | | `after_tool_call` | 每次工具调用后 | 扫描工具输出是否存在 PII 泄露 | ### `/policyshield` 命令 (Telegram / Discord / Slack) 这些命令可以直接在聊天中使用 —— 无需 CLI: ``` /policyshield status → server health + rules count /policyshield rules → view active rules /policyshield kill → 🔴 emergency stop — blocks ALL tool calls /policyshield resume → 🟢 resume normal operation /policyshield reload → hot-reload rules from disk /policyshield compile → preview YAML from natural language /policyshield apply → compile + save + reload in one step ``` ### 实时演示 ``` You: /policyshield kill Bot: 🛡️ PolicyShield: 🔴 KILLED — all tool calls blocked You: Create a file test.txt Bot: I can't do that — all operations are blocked by PolicyShield. You: /policyshield resume Bot: 🛡️ PolicyShield: 🟢 Resumed — normal operation ``` ### 插件配置参考 | 键 | 默认值 | 描述 | |-----|---------|-------------| | `url` | `http://localhost:8100` | PolicyShield 服务器 URL | | `mode` | `enforce` | `enforce` 或 `disabled` | | `fail_open` | `true` | 如果服务器不可达,允许调用 | | `timeout_ms` | `5000` | 每次检查超时时间 (ms) | | `approve_timeout_ms` | `60000` | 等待人工审批的最长时间 (ms) | | `approve_poll_interval_ms` | `2000` | 审批轮询间隔 (ms) | | `max_result_bytes` | `10000` | 用于 PII 扫描的最大工具输出字节数 | | `api_token` | `""` | 用于服务器认证的 Bearer token | [完整插件 README](plugins/openclaw/README.md) · [集成文档](docs/integrations/openclaw.md) ## 🤖 Telegram 机器人 直接从 Telegram 管理 PolicyShield —— 用自然语言编译规则,一键部署,并在手机上控制紧急关闭开关。 ### 设置 ``` pip install "policyshield[server]" export TELEGRAM_BOT_TOKEN="your-bot-token" export OPENAI_API_KEY="your-api-key" policyshield bot --rules rules.yaml --server-url http://localhost:8100 ``` ### 自然语言 → 实时规则 发送纯文本策略描述,机器人会将其编译为经过验证的 YAML,显示预览,并在确认后部署: ``` You: Block all exec calls containing 'rm' and redact PII in send_message Bot: 📜 Generated YAML: - id: block-rm-commands when: tool: exec args_match: command: { contains: rm } then: block ... [✅ Deploy] [❌ Cancel] ``` 点击 **Deploy** —— 机器人会以原子方式写入规则,按 ID 合并 (无重复项),备份旧文件,并热重载引擎。 ### 管理命令 ``` /status # Server health, rules count, mode /rules # View active rules summary /kill [reason] # Emergency kill switch — blocks ALL tool calls /resume # Resume normal operation /reload # Hot-reload rules from disk /compile # Preview YAML from natural language /apply # Compile + save + reload in one step ``` `/apply` 是最强大的命令 —— 它通过 LLM 生成规则,替换同一工具的冲突规则,并一步完成引擎重载。 ### OpenClaw + Telegram 安装 OpenClaw 插件后,直接在你的 OpenClaw Telegram 聊天中使用 `/policyshield` 命令: ``` /policyshield status /policyshield apply "Block file deletions and limit web_fetch to 30 per session" ``` ## 🔥 核心功能 ### 🧱 YAML 规则 — 无需修改代码 正则表达式、glob、精确匹配、会话条件、链式调用 —— 全部在声明式 YAML 中完成。LLM 永远不会触碰你的规则。 ``` - id: block-shell-injection when: tool: exec args_match: command: { regex: "rm\\s+-rf|curl.*\\|\\s*bash" } then: block severity: critical ``` ### 🔍 内置 PII 检测 + 脱敏 EMAIL、PHONE、CREDIT_CARD、SSN、IBAN、IP、PASSPORT、DOB —— 自动检测并脱敏。只需两行代码即可添加自定义模式。 ### 🚨 紧急关闭开关 一个命令即可立即阻止**所有**工具调用。准备好后随时恢复。 ``` policyshield kill --reason "Incident response" policyshield resume ``` ### 🔗 链式规则 — 捕捉多步攻击 检测诸如数据泄露之类的时间模式:在 2 分钟内 `read_database` → `send_email`。 ``` - id: anti-exfiltration when: tool: send_email chain: - tool: read_database within_seconds: 120 then: block severity: critical ``` ### 🕐 条件规则 根据时间、日期、用户角色或任何自定义 context 进行拦截: ``` - id: no-deploy-weekends when: tool: deploy context: day_of_week: "!Mon-Fri" then: block message: "No deploys on weekends" ``` ### 🧠 LLM Guard + NL 策略编译器 **LLM Guard** —— 可选的异步威胁检测 middleware。捕捉正则表达式无法处理的情况。 **NL Compiler** —— 用英语编写策略,获取经过验证的 YAML: ``` policyshield compile "Block file deletions and redact PII" -o rules.yaml ``` ## 🖥️ Web Dashboard 内置 Web UI —— 无需额外依赖。从浏览器监控判定结果、搜索 trace、管理规则并触发紧急关闭开关。 ``` policyshield server --rules rules.yaml --port 8100 # 打开 http://localhost:8100/dashboard ``` **Overview** — 判定细分、拦截率、成本节省、热门工具、PII 热力图、实时 WebSocket feed。 **Rules** — 浏览活动规则,支持展开 YAML 详情。 **Traces** — 支持过滤器 (工具、判定结果、会话、日期范围) 的全文搜索。 **Controls** — 🔴 紧急关闭开关,🟢 恢复,♻️ 重载规则,批准/拒绝待处理的请求。 独立分析模式 (无需服务器):`policyshield trace dashboard --port 8000` ## 🔌 兼容一切 | 集成方式 | 操作方法 | |-------------|-----| | **OpenClaw** | `policyshield openclaw setup` — 单条命令 | | **Telegram** | `policyshield bot` — NL 规则 + 管理 | | **LangChain** | `shield_all_tools([tool1, tool2], engine)` | | **CrewAI** | `shield_crewai_tools([tool1, tool2], engine)` | | **MCP** | `create_mcp_server(engine)` — 透明代理 | | **任何 HTTP 客户端** | `POST /api/v1/check` — 与框架无关的 REST API | | **Python 装饰器** | 在任何函数上使用 `@shield(engine)` (同步 + 异步) | | **Docker** | `docker build -f Dockerfile.server -t policyshield .` |
🖥️ HTTP 服务器与 Endpoints ``` pip install "policyshield[server]" policyshield server --rules ./rules.yaml --port 8100 ``` | Endpoint | Method | 描述 | |----------|--------|-------------| | `/api/v1/check` | POST | 调用前策略检查 | | `/api/v1/post-check` | POST | 调用后 PII 扫描 | | `/api/v1/check-approval` | POST | 轮询审批状态 | | `/api/v1/respond-approval` | POST | 批准/拒绝请求 | | `/api/v1/pending-approvals` | GET | 列出待处理的审批 | | `/api/v1/health` | GET | 健康检查 | | `/api/v1/status` | GET | 服务器状态 | | `/api/v1/constraints` | GET | 用于 LLM context 的策略摘要 | | `/api/v1/reload` | POST | 热重载规则 | | `/api/v1/kill` | POST | 紧急关闭开关 | | `/api/v1/resume` | POST | 停用紧急关闭开关 | | `/api/v1/compile` | POST | 编译 NL 描述 → YAML 规则 | | `/api/v1/compile-and-apply` | POST | 一步完成编译 + 保存 + 重载 | | `/healthz` · `/readyz` | GET | K8s 探针 | | `/metrics` | GET | Prometheus 指标 |
🐍 Python SDK ``` from policyshield.sdk.client import PolicyShieldClient with PolicyShieldClient("http://localhost:8100") as client: result = client.check("exec_command", {"cmd": "rm -rf /"}) print(result.verdict) # BLOCK client.kill("Incident response") client.resume() client.reload() ``` **异步:** ``` from policyshield.sdk.client import AsyncPolicyShieldClient async with AsyncPolicyShieldClient("http://localhost:8100") as client: result = await client.check("send_email", {"to": "admin@corp.com"}) ``` **装饰器:** ``` from policyshield.decorators import shield @shield(engine, tool_name="delete_file") def delete_file(path: str): os.remove(path) # only runs if PolicyShield allows ```
⌨️ 完整 CLI 参考 ``` # 设置与初始化 policyshield quickstart # Interactive setup wizard policyshield init --preset secure # Initialize with preset rules policyshield doctor # 10-check health scan (A-F grading) # 规则 policyshield validate ./policies/ # Validate rules policyshield lint ./policies/rules.yaml # Static analysis (7 checks) policyshield test ./policies/ # Run YAML test cases # Dry-run 检查 policyshield check --tool exec --rules rules.yaml # 服务器 policyshield server --rules ./rules.yaml --port 8100 --mode enforce # Telegram Bot policyshield bot --rules rules.yaml --server-url http://localhost:8100 # 追踪 policyshield trace show ./traces/trace.jsonl policyshield trace violations ./traces/trace.jsonl policyshield trace stats --dir ./traces/ --format json policyshield trace dashboard --port 8000 # 重放与模拟 policyshield replay ./trace.jsonl --rules new-rules.yaml --changed-only policyshield simulate --rule rule.yaml --tool exec --args '{"cmd":"ls"}' # 规则生成 policyshield generate "Block all file deletions" # AI-powered policyshield generate-rules --from-openclaw # Auto from OpenClaw policyshield compile "Block deletions, redact PII" # NL → YAML # 报告与运维 policyshield report --traces ./traces/ --format html policyshield kill --reason "Incident response" policyshield resume # OpenClaw policyshield openclaw setup # Install + configure plugin policyshield openclaw teardown # Remove plugin ```
📋 所有功能 **核心:** YAML DSL,4 种判定 (ALLOW/BLOCK/REDACT/APPROVE),PII 检测 (8 种类型 + 自定义),内置探测器 (路径遍历、shell/SQL injection、SSRF),紧急关闭开关,链式规则,条件规则,速率限制 (基于工具/会话/全局/自适应),审批流程,热重载,JSONL 审计追踪,幂等性。 **SDK 与集成:** Python 同步 + 异步 SDK,TypeScript SDK,`@shield()` 装饰器,MCP 服务器 + 代理,HTTP 服务器 (14 个 endpoint),OpenClaw 插件,LangChain/CrewAI 适配器,Telegram 机器人,Docker。 **DX (开发者体验):** 快速入门向导,doctor (A-F 评分),dry-run CLI,基于 OpenClaw 的自动规则,角色预设 (`coding-agent`, `data-analyst`, `customer-support`),YAML 测试运行器,规则 linter (7 项检查),回放/模拟,31 个环境变量 (12-factor)。 **高级:** 规则组合 (`include:` / `extends:`),插件系统 (前/后检查 hook),预算上限,shadow 模式,canary 部署,动态规则 (HTTP fetch),OpenTelemetry,LLM Guard,NL 策略编译器,有界会话 (LRU+TTL),成本估算器,告警引擎 (5 种条件 × 4 种后端),dashboard (REST + WebSocket + SPA),Prometheus 指标,合规性报告,事件时间线,配置迁移。
📦 示例与预设 | 示例 | 描述 | |---------|-------------| | [`standalone_check.py`](examples/standalone_check.py) | 无需服务器 | | [`langchain_demo.py`](examples/langchain_demo.py) | LangChain 包装 | | [`async_demo.py`](examples/async_demo.py) | 异步引擎 | | [`fastapi_middleware.py`](examples/fastapi_middleware.py) | FastAPI 集成 | | [`chain_rules.yaml`](examples/chain_rules.yaml) | 防止数据泄露、重试风暴 | | [`docker_compose/`](examples/docker_compose/) | Docker 部署 | **角色预设:** `strict` (全部 BLOCK),`permissive` (全部 ALLOW),`coding-agent`,`data-analyst`,`customer-support` **社区规则包:** [GDPR](community-rules/gdpr.yaml) (8 条规则),[HIPAA](community-rules/hipaa.yaml) (9 条规则),[PCI-DSS](community-rules/pci-dss.yaml) (9 条规则)
📖 [文档](https://mishabar410.github.io/PolicyShield/) · 📝 [更新日志](CHANGELOG.md) · 🗺 [路线图](ROADMAP.md) · [MIT 许可证](LICENSE)
标签:AI Agent, DLL 劫持, Python, 大语言模型, 无后门, 策略引擎, 网络安全挑战, 运行时安全, 防火墙