Input Sanitization and Validation
What you'll learn: How to detect and filter suspicious patterns in user input before it reaches your LLM, preventing prompt injection and other attacks.
The Concept
After understanding prompt injection attacks (lessons 1441-1445), you need a defensive layer that examines every input before it enters your system. Input sanitization and validation is like having a security checkpoint that inspects packages before they enter a building—checking for contraband and ensuring everything follows the rules.
Think of it as two complementary steps:
- Validation - Does the input meet expected format and constraints?
- Sanitization - Remove or escape dangerous patterns that could manipulate the LLM
Core Techniques
Format Validation: Check that inputs match expected structure (length limits, character sets, data types). Reject inputs with unusual encoding, excessive special characters, or attempts to break out of expected boundaries.
Pattern Detection: Flag suspicious phrases like "ignore previous instructions," "system:" prefixes, attempts to redefine roles, or encoded payloads (base64, unicode tricks). Build allowlists of acceptable patterns rather than blocklists of bad ones when possible.
Structural Analysis: Examine input for instruction-like syntax, delimiter injection attempts (triple-quotes, XML tags), or efforts to close your prompt template and inject new instructions.
Example approach:
def sanitize_input(user_input):
# Validate length
if len(user_input) > MAX_LENGTH:
raise ValueError("Input too long")
# Remove control characters
cleaned = remove_control_chars(user_input)
# Check for injection patterns
if contains_instruction_keywords(cleaned):
flag_for_review(cleaned)
return cleaned
Key Takeaway: Input sanitization and validation creates a crucial defensive barrier by detecting and filtering malicious patterns before they reach your LLM, though it must be combined with other security layers for comprehensive protection.