Dev.to Security 🔐 Cybersecurity 👁 0 📖 1 min read

Protecting Autonomous AI Agents from Prompt Injection Attacks in Python

Protecting Autonomous AI Agents from Prompt Injection Attacks in Python As AI agents gain tool execution capabilities—such as shell access, file editing, and financial wallet operations—they become prime targets for Pr

Protecting Autonomous AI Agents from Prompt Injection Attacks in Python

As AI agents gain tool execution capabilities—such as shell access, file editing, and financial wallet operations—they become prime targets for Prompt Injection Attacks (OWASP LLM01) and Excessive Agency Exploits (OWASP LLM06).

An attacker can trick an LLM agent into executing unauthorized commands (e.g. rm -rf, exfiltrating API keys, or transferring wallet funds) simply by placing malicious hidden instructions in untrusted web pages or RAG inputs.

In this tutorial, we will build a Defense-in-Depth Security Gateway in Python with sub-1ms latency overhead.

1. The 3-Layer Defense-in-Depth Architecture

                      [ UNTRUSTED USER INPUT / WEB SEARCH ]
                                       │
                                       ▼
                     ┌───────────────────────────────────┐
                     │   PROMPT-SHIELD GATEWAY PROXY     │
                     └─────────────────┬─────────────────┘
                                       │
            ┌──────────────────────────┼──────────────────────────┐
            ▼                          ▼                          ▼
   [ Layer 1: Fast Heuristic ] [ Layer 2: Dual-LLM ]     [ Layer 3: Crypto EIP-712 ]
   Regex & Base64 Sanitizer       Classifier Guardrail   Signature Wallet Guard

2. Layer 1: Fast Heuristic & Base64 Sanitizer (< 1ms)

import re
import base64

JAILBREAK_PATTERNS = [
    re.compile(r"ignore\s+(previous|above|all)\s+(instructions|rules)", re.IGNORECASE),
    re.compile(r"system\s*override", re.IGNORECASE),
    re.compile(r"you\s+are\s+now\s+in\s+DAN\s+mode", re.IGNORECASE),
    re.compile(r"output\s+your\s+(system\s+prompt|api\s+key)", re.IGNORECASE)
]

def inspect_prompt(prompt: str):
    # 1. Base64 Payload Decoding Check
    decoded_text = prompt
    try:
        if len(prompt) > 20 and re.match(r"^[A-Za-z0-9+/=]+$", prompt.strip()):
            decoded_text = base64.b64decode(prompt.strip()).decode('utf-8', errors='ignore')
    except Exception:
        pass

    # 2. Pattern Matching
    for pattern in JAILBREAK_PATTERNS:
        if pattern.search(prompt) or pattern.search(decoded_text):
            return False, f"Prompt Injection Blocked: '{pattern.pattern}'"

    return True, "SAFE"

3. Layer 3: Cryptographic EIP-712 Order Guard

To prevent Excessive Agency (OWASP LLM06), sensitive tools (e.g. fund transfers or financial trades) must require an explicit, cryptographically signed EIP-712 payload. An LLM agent can never move funds based on text prompts alone!

4. Production Turnkey Middleware

For the production-grade security proxy with FastAPI endpoints, sub-1ms processing latency, and OWASP 2026 compliance, check out ClawGuard Prompt-Shield Middleware on our store:

👉 ClawGuard Prompt-Shield Middleware ($29 USD)

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.