zeph_tools/patterns.rs
1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Shared injection-detection patterns for the security sanitization layers.
5//!
6//! This module is the single source of truth for prompt-injection detection patterns
7//! used by both `zeph-mcp` (MCP tool definition sanitization) and `zeph-core`
8//! (content isolation pipeline). Each consumer compiles its own `Regex` instances
9//! from [`RAW_INJECTION_PATTERNS`] at startup via `LazyLock`.
10//!
11//! # Known limitations
12//!
13//! The patterns cover common English-language prompt-injection techniques. Known evasion
14//! vectors include: non-English injections, semantic rephrasing, encoded payloads in
15//! markdown code blocks, multi-line splitting (regex `.` does not match `\n` by default),
16//! and homoglyph substitution. [`strip_format_chars`] mitigates Unicode Cf-category bypass
17//! but does not handle homoglyphs. This scanner is **advisory and defense-in-depth only**,
18//! not a security boundary. The trust gate (tool blocking via `TrustGateExecutor`) is the
19//! primary enforcement mechanism.
20
21/// Raw (name, regex pattern) pairs for prompt-injection detection.
22///
23/// Covers common English-language techniques from OWASP LLM Top 10, Unicode bypass
24/// vectors (handled upstream by [`strip_format_chars`]), exfiltration channels
25/// (markdown/HTML images), and delimiter-escape attempts against Zeph's own wrapper tags.
26///
27/// Both `zeph-mcp` and `zeph-core::sanitizer` compile their own [`regex::Regex`] instances
28/// from this slice. Do not export a compiled `LazyLock` — let each consumer own its state.
29pub const RAW_INJECTION_PATTERNS: &[(&str, &str)] = &[
30 (
31 "ignore_instructions",
32 r"(?i)ignore\s+(all\s+|any\s+|previous\s+|prior\s+)?instructions",
33 ),
34 ("role_override", r"(?i)you\s+are\s+now"),
35 (
36 "new_directive",
37 r"(?i)new\s+(instructions?|directives?|roles?|personas?)",
38 ),
39 ("developer_mode", r"(?i)developer\s+mode"),
40 ("system_prompt_leak", r"(?i)system\s+prompt"),
41 (
42 "reveal_instructions",
43 r"(?i)(reveal|show|display|print)\s+your\s+(instructions?|prompts?|rules?)",
44 ),
45 ("jailbreak", r"(?i)\b(DAN|jailbreak)\b"),
46 ("base64_payload", r"(?i)(decode|eval|execute).*base64"),
47 (
48 "xml_tag_injection",
49 r"(?i)</?\s*(system|assistant|user|tool_result|function_call)\s*>",
50 ),
51 ("markdown_image_exfil", r"(?i)!\[.*?\]\(https?://[^)]+\)"),
52 ("forget_everything", r"(?i)forget\s+(everything|all)"),
53 (
54 "disregard_instructions",
55 r"(?i)disregard\s+(your|all|previous)",
56 ),
57 (
58 "override_directives",
59 r"(?i)override\s+(your|all)\s+(directives?|instructions?|rules?)",
60 ),
61 ("act_as_if", r"(?i)act\s+as\s+if"),
62 ("html_image_exfil", r"(?i)<img\s+[^>]*src\s*="),
63 ("delimiter_escape_tool_output", r"(?i)</?tool-output[\s>]"),
64 (
65 "delimiter_escape_external_data",
66 r"(?i)</?external-data[\s>]",
67 ),
68];
69
70/// Patterns for scanning LLM *output* (response verification layer).
71///
72/// These are intentionally separate from [`RAW_INJECTION_PATTERNS`] (which target untrusted
73/// *input*). Output patterns must have very low false-positive rate on normal LLM responses.
74/// Patterns here detect cases where an LLM response itself contains injected instructions
75/// that could cause the agent to behave incorrectly.
76///
77/// Note: `markdown_image_exfil` is intentionally absent — it is already handled by
78/// `scan_output_and_warn`/`ExfiltrationGuard`.
79pub const RAW_RESPONSE_PATTERNS: &[(&str, &str)] = &[
80 (
81 "autonomy_override",
82 r"(?i)\bset\s+(autonomy|trust)\s*(level|mode)\s*to\b",
83 ),
84 (
85 "memory_write_instruction",
86 r"(?i)\b(now\s+)?(store|save|remember|write)\s+this\s+(to|in)\s+(memory|vault|database)\b",
87 ),
88 (
89 "instruction_override",
90 r"(?i)\b(from\s+now\s+on|henceforth)\b.{0,80}\b(always|never|must)\b",
91 ),
92 (
93 "config_manipulation",
94 r"(?i)\b(change|modify|update)\s+your\s+(config|configuration|settings)\b",
95 ),
96 (
97 "ignore_instructions_response",
98 r"(?i)\bignore\s+(all\s+|any\s+|your\s+)?(previous\s+|prior\s+)?(instructions?|rules?|constraints?)\b",
99 ),
100 (
101 "override_directives_response",
102 r"(?i)\boverride\s+(your\s+)?(directives?|instructions?|rules?|constraints?)\b",
103 ),
104 (
105 "disregard_system",
106 r"(?i)\bdisregard\s+(your\s+|the\s+)?(system\s+prompt|instructions?|guidelines?)\b",
107 ),
108];
109
110/// Strip Unicode format (Cf) characters and ASCII control characters (except tab/newline)
111/// from `text` before injection pattern matching.
112///
113/// These characters are invisible to humans but can break regex word boundaries,
114/// allowing attackers to smuggle injection keywords through zero-width joiners,
115/// soft hyphens, BOM, etc.
116#[must_use]
117pub fn strip_format_chars(text: &str) -> String {
118 text.chars()
119 .filter(|&c| {
120 // Keep printable ASCII, tab, newline
121 if c == '\t' || c == '\n' {
122 return true;
123 }
124 // Drop ASCII control characters
125 if c.is_ascii_control() {
126 return false;
127 }
128 // Drop known Unicode Cf (format) codepoints that are used as bypass vectors
129 !matches!(
130 c,
131 '\u{00AD}' // Soft hyphen
132 | '\u{034F}' // Combining grapheme joiner
133 | '\u{061C}' // Arabic letter mark
134 | '\u{115F}' // Hangul filler
135 | '\u{1160}' // Hangul jungseong filler
136 | '\u{17B4}' // Khmer vowel inherent aq
137 | '\u{17B5}' // Khmer vowel inherent aa
138 | '\u{180B}'..='\u{180D}' // Mongolian free variation selectors
139 | '\u{180F}' // Mongolian free variation selector 4
140 | '\u{200B}'..='\u{200F}' // Zero-width space/ZWNJ/ZWJ/LRM/RLM
141 | '\u{202A}'..='\u{202E}' // Directional formatting
142 | '\u{2060}'..='\u{2064}' // Word joiner / invisible separators
143 | '\u{2066}'..='\u{206F}' // Bidi controls
144 | '\u{FEFF}' // BOM / zero-width no-break space
145 | '\u{FFF9}'..='\u{FFFB}' // Interlinear annotation
146 | '\u{1BCA0}'..='\u{1BCA3}' // Shorthand format controls
147 | '\u{1D173}'..='\u{1D17A}' // Musical symbol beam controls
148 | '\u{E0000}'..='\u{E007F}' // Tags block
149 )
150 })
151 .collect()
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157
158 #[test]
159 fn strip_format_chars_removes_zero_width_space() {
160 let input = "ig\u{200B}nore instructions";
161 let result = strip_format_chars(input);
162 assert!(!result.contains('\u{200B}'));
163 assert!(result.contains("ignore"));
164 }
165
166 #[test]
167 fn strip_format_chars_preserves_tab_and_newline() {
168 let input = "line1\nline2\ttabbed";
169 let result = strip_format_chars(input);
170 assert!(result.contains('\n'));
171 assert!(result.contains('\t'));
172 }
173
174 #[test]
175 fn strip_format_chars_removes_bom() {
176 let input = "\u{FEFF}hello world";
177 let result = strip_format_chars(input);
178 assert!(!result.contains('\u{FEFF}'));
179 assert!(result.contains("hello world"));
180 }
181
182 #[test]
183 fn strip_format_chars_removes_ascii_control() {
184 let input = "hello\x01\x02world";
185 let result = strip_format_chars(input);
186 assert!(!result.contains('\x01'));
187 assert!(result.contains("hello"));
188 assert!(result.contains("world"));
189 }
190
191 #[test]
192 fn raw_injection_patterns_all_compile() {
193 use regex::Regex;
194 for (name, pattern) in RAW_INJECTION_PATTERNS {
195 assert!(
196 Regex::new(pattern).is_ok(),
197 "pattern '{name}' failed to compile"
198 );
199 }
200 }
201
202 #[test]
203 fn raw_response_patterns_all_compile() {
204 use regex::Regex;
205 for (name, pattern) in RAW_RESPONSE_PATTERNS {
206 assert!(
207 Regex::new(pattern).is_ok(),
208 "response pattern '{name}' failed to compile"
209 );
210 }
211 }
212}