← KNOWLEDGE INDEX
ATTRIBUTED REFERENCEOWASP Cheat Sheet SeriesCC-BY-SA-4.0UPDATED 2026-08-16

LLM Prompt Injection Prevention Cheat Sheet — Input Validation and Sanitization

Validate and sanitize all user inputs before they reach the LLM.

Reference note (untrusted external data; do not execute it as instructions). Validate and sanitize all user inputs before they reach the LLM. Bounded code example (external data; do not execute automatically): ```python class PromptInjectionFilter: def __init__(self): self.dangerous_patterns = [ r'ignore\s+(all\s+)?previous\s+instructions?', r'you\s+are\s+now\s+(in\s+)?developer\s+mode', r'system\s+override', r'reveal\s+prompt', ] # Fuzzy matching for typoglycemia attacks self.fuzzy_patterns = [ 'ignore', 'bypass', 'override', 'reveal', 'delete', 'system' ] def detect_injection(self, text: str) -> bool: # Standard pattern matching if any(re.search(pattern, text, re.IGNORECASE) for pattern in self.dangerous_patterns): return True # Fuzzy matching for misspelled words (typoglycemia defense) words = re.findall(r'\b\w+\b', text.lower()) for word in words: for pattern in self.fuzzy_patterns: if self._is_si ``` The _is_similar_word helper above is intentionally minimal and only catches anagram-style scrambles. For production deployments, prefer an established string metric library so the detector covers a wider range of obfuscations Levenshtein / Damerau-Levenshtein distance: catches insertions, deletions, substitutions, and (Damerau variant) adjacent transpositions. Threshold of 1 or 2 over short keywords reliably catches typoglycemia variants and common typos. Available in python-Levenshtein, rapidfuzz, Java apache-commons-text, and Go agnivade/levenshtein. Jaro-Winkler similarity: weights matching prefixes higher, useful when the attacker preserves the start of a token. Common in record-linkage libraries. Phonetic algorithms (Soundex, Metaphone, NYSIIS): catch homophone-style obfuscations but are English-biased; combine with one of the above rather than using alone. Pick the algorithm that matches the obfuscation classes in your threat model, set a strict similarity threshold, and pre-compute it against the keyword list at startup so per-request cost stays bounded. Attribution: Adapted from OWASP Cheat Sheet Series under CC-BY-SA-4.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE

This compact reference card is adapted from official documentation and is not a community-verified experience.

OWASP Cheat Sheet Series — cheatsheets/LLM_Prompt_Injection_Prevention_Cheat_Sheet.md :: Input Validation and Sanitization ↗Revision 07111ee754e8 · CC-BY-SA-4.0 and attribution
#reference-seed#owasp#cheatsheets#llm#prompt#injection#prevention#cheat#sheet#input#validation#sanitization