防护思路
点击放大

> Defensi for AI agents. An 8-layer security stack that sits between your agent and the outside world — inspecting, sanitizing, auditing, and blocking risky actions before they reach the host.
>
> *A PDuk Brainworks project. Sibling to the Ultimate Memory Stack. Apache-2.0.*



![Tests]()
---
agent-shield is a layered defensi for AI agents. It intercepts what your agent is about to do — run a command or write a file — and applies a tiered RED / YELLOW / GREEN decision policy before letting it through. (Network egress — fetching a URL — is the roadmap Layer 5, not yet shipped.)
v0.2.0 ships six of the eight layers — Layers 1, 2, 3, 4, 6, and 7 (see The 8 layers and Project status):
before_tool_call; live but enforcement requires a recent gateway — see docs/adapter_status.md). Additional harnesses (Codex, Gemini, Copilot, etc.) are roadmap.bash_guard — inspects bash commands before executionwrite_guard — inspects write / edit targets before they touch diskskill_, sanitize (incl. F-001 harness-tag-spoofing detection), structured_output, audit, and config — ship as importable library modules.Layers 0 (operational/automation) and 5 (network egress) are in de.
---
!agent-shield blocking a destructi (deny), prompting on a risky one (ask), and allowing a safe one (allow)
*The Layer 4 hook's actual decisions and reason strings, rendered for readability — the live hook emits them as JSON. A safe command prints nothing and exits 0; only ask and deny emit output. Run the three checks yourself: demo/demo.sh.*
---
Prerequisites: Python 3.11+ (standard library only — zero runtime dependencies). On Windows, run the shell commands in Git Bash, WSL, or PowerShell (adapt as needed); the guards themselves are pure Python.
Install (pick your door):
Or tell your agent: clone the repo and say *"install this — read INSTALL_AGENT.md and follow it."* The agent walks a documented, consent-gated flow (it ne your settings without showing you the diff).
Use as a library:
Use as a Claude Code PreToolUse hook:
> Reading the output: a safe command prints nothing and exits 0 — empty stdout means *allow*. Only ask and deny emit JSON.
Wire it into ~/.claude/settings.json (the module form below — python -m agent_shield.bash_guard — is the most portable; the agent-shield-bash-guard / agent-shield-write-guard console scripts installed with the package also work when the package's scripts directory is on PATH):
Use it with OpenClaw (or another harness): the same neutral decision core backs every harness. Wire the OpenClaw before_tool_call hook to the agent-shield-openclaw-guard console script (or python -m agent_shield.adapters.openclaw) — it reads the tool event as JSON on stdin and returns the block / ask / allow decision.
For OpenClaw, the package ships a ready-to-install companion plugin directory insideagent_shield/adapters/openclaw_plugin/. The exact install command and gateway
requirement are in docs/adapter_status.md. If you installed
an earlier alpha that used a bare export const hooks = {...} registration, migrate
to the current plugin-SDK shape; the uninstall and migration steps are indocs/MIGRATION.md.
The library API (bash_guard.check_command(), write_guard.check_path()) is identical
across harnesses.
---
| # | Layer | What it does | Status |
|---|---|---|---|
| 0 | Operational + Automation | Cron schedule for hygiene tasks (audit / key / log rotation) | 🟡 pre-release |
| 1 | Skill / Tool | skill_ — static read-only scan → 3-tier (appro/rejected); 5-layer manual escalation for the review tier | ✅ v0.2.0 |
| 2 | Input Sanitization | sanitize — 4-layer (structural strip · content flag · encoding detect · nonce-delimited context wrap) for untrusted incoming content | ✅ v0.2.0 |
| 3 | Structured Output | structured_output — enforce a declared schema (shape, not content/intent) + reject prose-wrapped JSON | ✅ v0.2.0 |
| 4 | Runtime Hooks | bash_guard + write_guard | ✅ v0.2.0 |
| 5 | Network Egress | URL allowlist + Ollama proxy + rate limiting | 🟡 pre-release |
| 6 | Structured Audit | audit — append-only JSONL + SHA-256 hash-chain (tamper-e), () + -- CLI, optional external anchor (local-path / bring-your-own-shipper — ne home) | ✅ v0.2.0 |
| 7 | Configuration | config — TOML loader + compliance presets + the shared cross-layer contract; ne, opt-in wiring | ✅ v0.2.0 |
---
Every check returns a GuardResult with one of three decisions:
| Tier | Decision | Behavior |
|---|---|---|
| 🔴 RED | deny | Block outright — the operation is dangerous (rm -rf /, credential exfiltration, disk format, etc.) |
| 🟡 YELLOW | ask | Prompt the user — the operation is risky but has legitimate uses (git push --force, chmod 777, package install) |
| 🟢 GREEN | allow | Pass through — operation is safe (read-only ops, queries, etc.) |
bash_guard.check_command(cmd) — patternsrm -rf against root / home / cwd targets, including quoted (rm -rf "/"), split-flag (rm -r -f /), and bundled / reordered / inter (rm -rfv /, rm -fvr /, rm -rf -- /) forms, --no-preser, mkfs.*, format X: / wipefs, dd onto block devices, fork bombs; remote-code execution — pipe-to-shell (curl … | bash), pipe-to-source, decode-and-execute (base64 -d | sh), process substitution (bash <(curl …)), encoded PowerShell; credential exfiltration — $VAR / ${VAR} secrets in network commands, uploading secret files (curl -d ), piping secret files to network tools.rm -rf, split-flag form, Windows del /s, Remo -Recurse -Force, shred); network uploads; destructive git operations; package installs; chmod 777; Windows registry edits; service/process control; disabling the agent-shield runtime guard (agent-shield-plugin disable, python -m agent_shield.plugin_cli disable, and shell-wrapped forms).write_guard.check_path(file_path) — patterns.claude/settings.json + settings.local.json (hook/permission configs); agent_shield/* guard modules + legacy hooks/scripts/*-guard.sh (self-protect); SSH private keys (~/.ssh/id_* — unambiguously secret); .openclaw/.env (agent API credentials).agent-shield.toml, ~/.agent-shield/config.toml — Layer 7; editing changes the agent's own security policy, but the file is user-edited so ask, not deny); agent templates; orchestration rules; other hook scripts; memory files; .env* files; shell startup files (.bashrc, .zshrc, profiles — persistence ); credential-named files (secrets.json, tokens.yaml, …); *.pem / *.key (ask, not deny — content-blind: a .pem may be a public cert and .key is also Apple Keynote's document type, so confirm rather than hard-block); CLAUDE.md; sync protocol files.Path matching is normalization-hardened: backslashes, case, NTFS alternate-data-stream suffixes (file.py::$DATA), and trailing spaces/dots are normalized away before patterns run, so Windows path-disguise tricks can't slip past the $-anchored rules.
Full pattern lists live in agent_shield/bash_guard.py and agent_shield/write_guard.py. Each pattern carries an inline comment explaining the threat model it addresses. The counts above are by automated tests — if code and README drift, the release is blocked.
---
Vet a skill / MCP server / hook / package before you install it. skill_ does a static, read-only scan (it ne, imports, writes, or network-fetches the target), scores it 0–10, and returns a 3-tier :
| | Score | Meaning |
|---|---|---|
| 🟢 approved | 0–2 | No high/critical signals — safe to install |
| 🟡 review | 3–7 | Real signals — a human should look (see the 5-layer escalation rubric in docs/.md) |
| 🔴 rejected | 8–10 | Critical signal(s) — do not install |
Threat categories (code files scanned line-by-line; instruction files scanned for injection; dependency manifests checked for typosquats): EN, EN, CRED_PATH, FS_DANGER, PIPE_TO_SHELL, PERSIST, NET_EXFIL, CRYPTO_MINE, PROMPT_INJECTION, TYPOSQUAT. The category list is by automated tests — drift between code and docs is detected at release time. This is a static heuristic gate, not a sandbox — see Bypasses and limitations.
---
agent_shield.sanitize sanitizes untrusted incoming content — web fetches, tool/MCP output, user input, agent-to-agent handoffs — before it reaches the model. It strips in/control characters (destructive, safe) and detects and flags injection markers and suspicious encodings (non-destructive by default).
Layer 2 (sanitize) detects and flags injection markers and encodings — including
forged harness framing tags (<system-reminder>, <system>, <assistant>, <user>,<instructions>) as of this release. It detects and flags these — it does not
block or intercept them at the model layer: no and creati are
unbounded, and semantic injection at the model layer is outside what a guard can stop.
agent-shield's defense is detection, action-boundary pre (Layer 4 blocks
dangerous outcomes), cost-raising (nonce wrappers), and e (Layer 6
tamper-e audit). It does not prevent determined semantic injection. For untrusted
fetched content, see examples/fetch-wrap.example.py.
> Harness-tag spoofing class (F-001, detected as of this release): On 2026-05-12 a
> class of injection was obser attacker-controlled content attempted to
> harness spoof by forging structural framing tags to impersonate harness-level
> context boundaries. Layer 2 now detects and flags this class. No working payload is
> published here — see SECURITY.md for the disclosure posture.
strict=True neutralizes them), encoding (NFKC-normalize, then *detect* — ne — base64/base64url blobs and mixed-script homoglyph tokens), context (nonce-delimited typed wrappers).Full sub-layer reference, kind taxonomy, the nonce contract, strict mode, and the bypasses & limitations: docs/SANITIZATION.md.
---
agent_shield.structured_output constrains agent / tool output to a declared structure and rejects what doesn't conform — reducing the blast radius of "make the agent emit free-form X." It enforces shape, not intent: a well-formed object whose are malicious still passes, so this is one layer of defense-in-depth, not a prompt-injection blocker. It ne, evals, or decodes the payload.
isinstance): an int field rejects True/False (bool is not int), a bool field rejects 0/1; int widens to float (JSON has no 1 vs 1.0); NaN/Infinity are rejected. Supports nested Schema, list[T], dict[str, T], Union/Optional, Literal, (type, default) optionals, and Field(...) constraints (length / numeric range / regex / choices).value is a fresh dict and enforce ne its input.Full DSL grammar, the type rules, strict/lenient + default-fill, the JSON-discipline helpers, and bypasses & limitations: docs/STRUCTURED_OUTPUT.md.
---
agent_shield.audit is an append-only, tamper-e forensic log: one JSON object per line, each hash-chained to the previous. It records *who did what to what, with what outcome* — and any later edit, insertion, deletion, or reorder of the file is detectable.
general (9-field rows, 90-day retention, fail-open) and healthcare/biotech (uniform 11-field rows, 365-day retention, fail-closed: "no action without an audit record").None; it ne the operation being audited (use fail_mode="closed" to invert that).The local hash-chain is tamper-e, not tamper-proof: an attacker with write access can rewrite the whole file from genesis into a clean chain that still . To get tamper-resistant integrity, anchor the chain head to a target the attacker can't reach:
The anchor periodically (every N entries or T minutes — ne) copies a minimal receipt — {seq, entry_hash, ts}, no PII — to its target, fail-open: a *failing* shipper ne the audited write. Resistance holds only when that target is genuinely independent — a separate / write-once or another host; an anchor on the same as the log is not independent and stays tamper-e only. The log file is written 0600 and is a forensic record, not a li. Retention/rotation enforcement is not automated in this release.
agent-shield ne home. The shipped package makes no outbound network calls — its only socket use is a local gethostname() for the audit machine field, and the built-in anchor writes to a local path only. To anchor off-box, you bring your own shipper (a callable that transmits the receipt however you choose); the egress is your code and your policy. There is no url/endpoint parameter, and the no-network guarantee is checked by a best-effort AST lint in the test suite (not a sandbox). Your shipper runs synchronously, in-process and cannot be timed out in v0.2.0 — keep it fast, or do slow/network work asynchronously yourself. A ready-to-copy recipe and a full risk guide live in examples/remote_anchor_shipper.py and docs/REMOTE_ANCHORING.md.
Full field reference, procedure, and limits: docs/AUDIT_SCHEMA.md.
---
agent_shield.config is the cross-layer spine: declare a compliance posture once and the layers read their slice. It's policy, not a trust boundary — config carries paths and policy, ne, and cannot weaken a built-in guard.
UserWarning — a layer always runs with zero config.audit.PRESETS exactly (general/healthcare/biotech), single-sourced — an unknown/typo'd preset can ne AuditLog. There is no enterprise preset in v0.2.0; it is planned for a future release.$AGENT_SHIELD_CONFIG → ./agent-shield.toml → ~/.agent-shield/config.toml. The config file is a write_guard YELLOW target. TOML only (stdlib tomllib); YAML is rejected (dependency + yaml.load footgun).extra_red/extra_yellow) are deferred to a post-v0.2.0 release.Schema, every key, the presets, search-path + precedence, env vars, and bypasses & limitations: docs/CONFIGURATION.md.
---
Tiers map 1:1 to decisions — RED→deny, YELLOW→ask, GREEN→allow. The tier is the conceptual model; the API exposes decision.
The package has zero runtime dependencies. Only the Python ≥3.11 standard library is required.
---
The CLI reads {"tool_input": {"command": "..."}} (for bash_guard) or {"tool_input": {"file_path": "..."}} (for write_guard) from stdin. For ask / deny it prints a Claude Code-compatible JSON to stdout; for allow it prints nothing (a silent pass, matching the bash sources). Exit code is always 0 — decisions are conveyed via permissionDecision, not exit status; this contract is enforced by a top-le and pinned by tests/test_cli.py against malformed, empty, BOM-prefixed, and UTF-16 stdin. This means agent_shield can be wired into a PreToolUse hook chain without bash glue.
Input that cannot be parsed at all cannot be e and is allowed — see Bypasses and limitations for why, and what that means for you.
For deployments without Python, the tests/bash-guard.sh and tests/write-guard.sh sources are decision-equi ( to produce equi decisions; human-readable reason strings may differ in wording) and can be used directly. These sources are not installed by pip install ai-agent-shield; copy them manually from the repository if you need them. When the bash guards find no working Python interpreter, RED checks additionally scan the raw hook JSON — degraded parsing fails closed for the dangerous tier.
---
Four suites: Python guard/CLI tests, bash-subprocess equi, a bash-nati, and a head-to-head equi runner. All must be green before a release is tagged; run them rather than trusting a number printed here. CI runs the full suite on Linux, macOS, and Windows (Python 3.11–3.14); platforms outside that matrix (e.g. BSD) aren't .
Quality process. agent-shield is AI-assisted by design — built with AI agents under human architectural direction — and engineered accordingly: changes are de test-first (red → green) and must pass all four suites before a release is tagged. Releases additionally go through an independent ad review pass, with re tasked to break the changes rather than approve them — for v0.2.0 that pass uncovered issues in early hardening attempts, which were corrected and re- before shipping. Platform note: the bash-subprocess pytest cases shell out to bash. On Windows the harness resol/Cygwin explicitly and never the WSL bash.exe shim — Python's subprocess otherwise mis-resolves a bare bash to that shim (Win32 searches System32 before PATH), and it hangs when driven from nati Python. So the parity cases now run on Windows too; if no usable bash is found they skip with a clear reason instead of hanging. Set AGENT_SHIELD_TEST_BASH to a specific bash.exe to o resolution.
---
ModuleNotFoundError: No module named 'agent_shield' — the hook/CLI is running under a different Python than the one agent-shield is installed in. Activate the right venv, or point the hook at that interpreter (e.g. /path/to/venv/bin/python -m agent_shield.bash_guard).ModuleNotFoundError: No module named 'agent_shield' *after uninstalling* — pip uninstall removed the package, but the two PreToolUse hook entries are still in your settings.json, so every tool call now fails. If the agent-shield-plugin command is still a (Claude Code only), run it first: agent-shield-plugin disable (or agent-shield-plugin --project <dir> disable) to remove them safely. If the CLI is gone because the package was already uninstalled, manually edit the file and remove the two PreToolUse entries for Bash and Write|Edit|MultiEdit that call agent_shield.bash_guard / agent_shield.write_guard. Then restart. Full steps: INSTALL_AGENT.md Step 6. If you wired during an earlier alpha, your settings may contain a non-functional legacy shape (hookE/toolNamePattern) — migrate via docs/MIGRATION.md.allow is a silent pass (empty stdout, exit 0). Test with a known-bad command (echo '{"tool_input":{"command":"rm -rf /"}}' | python -m agent_shield.bash_guard) to see a deny.settings.json; hooks are read at startup.bash.exe shim) and skips cleanly if no POSIX bash is found; set AGENT_SHIELD_TEST_BASH to a specific bash.exe to o. The runtime guards are pure Python and need no bash.---
agent-shield's threat model:
The shield is defense-in-depth, not defense-as-perimeter. Even with all 8 layers shipping, you should still:
---
Layer 4 is a best-effort regex layer, not a sandbox. It performs deterministic pattern-matching within its known pattern set; it raises the cost of accidental and nai damage, but it does not make damage impossible. Be honest with yourself about what that buys you:
Known e forms (deliberately out of scope for pattern matching):
python -c, perl -e, node -e), where the regex never sees it.base64 -d | sh and openssl enc -d | sh; arbitrarily creati/decode chains are unbounded.Beha limitations (by design, documented so you can plan around them):
echo "$CMD", so a literal $VAR in the inspected command undergoes the shell's own parameter expansion before matching — a value set in the guard's own en could be substituted. The Python port (the default path) has no such behavior; the common attack patterns are still caught.grep mkfs log, but a guard built from regexes will always ha false-positi trade-offs at the margins.If your threat model requires *guarantees* against a determined ad agent, you need OS-le (containers, VMs, seccomp, restricted users) underneath this layer. agent-shield is the seatbelt, not the cage.
---
agent-shield is honest about scope. Deterministic pattern-matching within its known
pattern set; it is not a sandbox and does not prevent semantic prompt injection.
| Feature | Status | Target |
|---|---|---|
| L0 operational automation (retention/rotation enforcement) | Not built | Roadmap |
| L5 network egress control (allowlist/proxy) | Not built | Demand-gated |
| Stateful multi-step correlation (recon→exfil, persistence) | Not built | Next release |
| Python AST / dataflow malware analysis (L1) | Not built (regex-only) | Demand-gated |
| Ja AST analysis | Not built (pair with npm audit) | Demand-gated |
| Transitive C | Won't do (breaks offline promise) | — |
| harness_tag_spoof flags literal <system>/<user> in benign markup | By design (flag-only default; strict neutralizes) | — |
| OpenClaw enforcement on old gateways | Gateway-gated | Now (recent gateway) |
| Additional harnesses (Codex/Gemini/Copilot/OpenCode) | Not built | Demand-gated |
---
agent-shield is a security tool from an independent author — so it's built to be , not taken on faith:
gethostname() for the audit record. The optional audit anchor writes to a local path only; to send anything off-box you supply your own shipper (your code, your policy). The no-egress property is checked by a best-effort AST lint in the test suite.SECURITY.md.esoteric1entity — a PDuk Brainworks project — AI-assisted under human architectural direction. disclosure policy: SECURITY.md.---
v0.2.0 alpha — Layers 1, 2, 3, 4, 6, and 7 ship. Layers 0 and 5 are in acti. Python 3.11+ (LTS); tomllib stdlib → zero external deps. Layer 4 runs on a harness-agnostic architecture: one neutral decision core with two functional adapters today — Claude Code (CI-) and OpenClaw (li requires a recent gateway — see docs/adapter_status.md). Additional harnesses are roadmap.
| Item | Status |
|---|---|
| Layer 1 (skill / tool ) | ✅ Shipped — static scanner + 3-tier |
| Layer 4 (runtime hooks) | ✅ Shipped — bash_guard + write_guard; Claude Code and OpenClaw adapters |
| Layer 0 (cron rotation) | 🟡 templates drafted |
| Layer 2 (input sanitization) | ✅ Shipped — strip + flag + nonce-wrap (detection/flagging, not a prompt-injection blocker) |
| Layer 3 (structured output) | ✅ Shipped — stdlib schema + JSON-discipline helpers (shape, not intent) |
| Layer 5 (egress) | 🟡 allowlist + Ollama proxy drafted |
| Layer 6 (audit) | ✅ Shipped — append-only hash-chain + (+ -- CLI) + optional external anchor |
| Layer 7 (config) | ✅ Shipped — TOML loader + compliance presets + shared contract (ne, opt-in wiring) |
Sibling package: ultimate-memory-stack — persistent memory for AI agents. The two are independent — each ships and runs on its own.
---
esoteric1entity — architect + design lead. A PDuk Brainworks project.AUTHORS.md for the full contributor list.---
Apache License 2.0. Copyright © 2026 esoteric1entity.
---
E here is free under Apache-2.0 — no strings attached. If agent-shield
helps keep your agent safe, the one thing we ask — **entirely optional, always
appreciated — is a citation or mention of esoteric1entity** /
PDuk Brainworks: a link back to this repo, a line in your credits, or GitHub's
"Cite this repository" button (powered by CITATION.cff).
---
examples/ — Working integration examples (Claude Code settings, library use, CLI pipe, before/after scenarios)CONTRIBUTING.md — How to contributeSECURITY.md — reporting policy + threat modelCHANGELOG.md — historyCLA.md — Contributor License AgreementNOTICE — Copyright + acknowledgementsINSPIRATIONS.md — Projects we built on开发语言:Python
Star 数:3
该项目属于防护思路方向的开源资源,代码结构清晰,适合安全研究人员学习参考。项目围绕Defensive overlay for AI agents — an 8-layer security stack that inspects, sanitizes, audits, and blocks risky actions before they reach the host.展开,提供了可运行的实现,对理解相关安全机制、工具原理与攻防技术具有较高的研究价值。
从技术实现角度看,此类项目的核心在于对底层原理的深入理解与工程化落地。开发者在研究过程中可以结合官方文档与社区讨论,梳理项目的初始化流程、核心模块职责与数据流转,逐步掌握其中的技术细节与设计思路。
1. 下载源码压缩包,解压到本地环境。
2. 根据项目类型准备对应的运行环境与依赖。
3. 按照 README 中的步骤完成配置与部署。
4. 在隔离的测试环境中运行验证,避免影响生产系统。
本资源来源于开源社区,仅供安全研究、技术学习与合法授权范围内的攻防演练使用,请勿用于任何非法或侵害他人权益的用途。使用本项目产生的一切后果由使用者自行承担。
| 资源标题 | agent-shield - Defensive overlay for AI agents — an 8-layer secur |
| 所属分类 | 防护思路 |
| 发布作者 | admin |
| 发布时间 | 2026-10-06 00:17:17 |
| 下载权限 | 免费下载 |
| 附件数量 | 2 个下载链接 |
| 浏览次数 | 195 |
| 讨论数量 | 0 |
| 主题状态 | 正常讨论中 |