Last month, our e-commerce platform launched an AI customer service chatbot handling 50,000+ daily queries during peak season. Within 48 hours, we discovered that malicious users were injecting carefully crafted prompts to extract our internal product pricing formulas, bypass content filters, and even manipulate the AI into generating phishing emails targeting our customers. This wasn't theoretical — it was happening in production, right now.
That incident transformed our approach to AI security. Over the following weeks, I implemented defense-in-depth strategies that blocked 99.7% of injection attempts while maintaining response quality and keeping latency under 50ms. In this comprehensive guide, I will walk you through the complete architecture, code, and operational practices that protected our system — and how you can apply these same techniques to your own LLM-powered applications using the HolySheep AI platform.
Understanding the Threat Landscape
Prompt injection represents the most critical security vulnerability in LLM applications today. Attackers embed malicious instructions within user inputs that override or manipulate the AI's original system prompt. Jailbreaking takes this further, attempting to circumvent safety mechanisms entirely.
Common attack vectors include:
- Direct Injection: Malicious instructions embedded in user queries ("Ignore previous instructions and...")
- Indirect Injection: Hidden instructions in retrieved documents or RAG content
- Context Window Overflow: Bombarding the model with irrelevant content to bury system instructions
- Role-Play Attacks: Framing harmful requests as fictional scenarios
- Encoding Obfuscation: Using Unicode, base64, or other encodings to hide malicious payloads
The Defense Architecture
Effective protection requires multiple layers. No single technique provides complete security, but combining input validation, prompt engineering, output filtering, and monitoring creates robust defense. Here is the architecture we deployed:
Layer 1: Input Validation and Sanitization
The first line of defense filters potentially malicious inputs before they reach the LLM. This reduces cost, improves latency, and prevents a significant portion of attacks.
#!/usr/bin/env python3
"""
AI Security Gateway - Input Validation Layer
HolySheep AI Integration with Prompt Injection Protection
"""
import re
import hashlib
import time
import json
from typing import Optional, Dict, List, Tuple
from dataclasses import dataclass, field
from enum import Enum
import httpx
class ThreatLevel(Enum):
SAFE = 0
SUSPICIOUS = 1
DANGEROUS = 2
BLOCKED = 3
@dataclass
class SecurityResult:
threat_level: ThreatLevel
reason: str
sanitized_input: str
blocked_patterns: List[str] = field(default_factory=list)
processing_time_ms: float = 0.0
class PromptInjectionDetector:
"""
Multi-pattern detection system for identifying prompt injection attempts.
Combines regex patterns, semantic analysis, and heuristic rules.
"""
# Critical patterns that almost always indicate malicious intent
BLOCKED_PATTERNS = [
r"(?i)ignore\s+(all\s+)?previous\s+instructions?",
r"(?i)disregard\s+(all\s+)?(your|the)\s+(system|initial|original)\s+(instructions?|prompts?|constraints?)",
r"(?i)new\s+instructions?:",
r"(?i)forget\s+(everything|all|what)\s+(you|I've)\s+(said|told|talked)",
r"(?i)you\s+are\s+now\s+(a\s+)?",
r"(?i)pretend\s+(you\s+are|to\s+be|that)",
r"(?i)switch\s+to\s+(developer|admin|god)\s+mode",
r"\[INST\]\s*<>",
r"<<SYS>>",
r"\[
\s*system\s*
\]",
# Jailbreak patterns
r"(?i)DAN\s+(\d+\s+)?mode",
r"(?i)developer\s+mode\s+enabled",
r"(?i)jailbreak",
r"(?i)bypass\s+(safety|filter|restriction)",
r"(?i)unrestricted\s+mode",
]
# Suspicious patterns that warrant additional scrutiny
SUSPICIOUS_PATTERNS = [
r"\{\{.*?\}\}", # Template injection
r"\$\{.*?\}", # Variable injection
r"\