injectguard 0.1.0

Heuristic prompt-injection detector and sanitizer for untrusted text fed to AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
// SPDX-License-Identifier: MIT
//! Decoded variants of the input, for a second rule pass.
//!
//! Attackers hide directives from word-based rules with encodings a model
//! still reads: HTML entities (`ignore`), percent-encoding, `\u0069`
//! escapes, hex bytes, short base64 tokens, markup inside words
//! (`ig<b></b>nore`, `ig**nore**`), leetspeak (`1gn0r3`), ROT13 and reversed
//! text. [`variants`] returns copies of the input where such lines are
//! decoded. Every other line is replaced by an empty line, so line numbers
//! stay exact and the extra pass only costs time on lines that changed.

use std::sync::OnceLock;

use regex::Regex;

pub(crate) struct Variant {
    pub text: String,
    pub note: &'static str,
}

/// Words whose ROT13 or reversed form marks a line worth decoding.
const KEYWORDS: &[&str] = &[
    "ignore",
    "disregard",
    "instructions",
    "previous",
    "prompt",
    "password",
    "secret",
    "system",
    "credentials",
    "jailbreak",
    "token",
];

/// Decoded variants of `text` (none when nothing decodes).
pub(crate) fn variants(text: &str) -> Vec<Variant> {
    let mut out = Vec::new();
    if let Some(t) = masked(text, decode_line) {
        out.push(Variant {
            text: t,
            note: " (after decoding entities/escapes/markup/leetspeak)",
        });
    }
    if rot13_keywords().is_match(text) {
        if let Some(t) = masked(text, |l| {
            rot13_keywords()
                .is_match(l)
                .then(|| l.chars().map(rot13).collect())
        }) {
            out.push(Variant {
                text: t,
                note: " (after ROT13 decoding)",
            });
        }
    }
    if reversed_keywords().is_match(text) {
        if let Some(t) = masked(text, |l| {
            reversed_keywords()
                .is_match(l)
                .then(|| l.chars().rev().collect())
        }) {
            out.push(Variant {
                text: t,
                note: " (after reversing the text)",
            });
        }
    }
    out
}

/// Applies `f` to every line (without its line break); lines where `f`
/// returns a different string are kept (with line breaks inside turned into
/// spaces), all others become empty. `None` if no line changed.
fn masked(text: &str, f: impl Fn(&str) -> Option<String>) -> Option<String> {
    let mut out = String::new();
    let mut changed = false;
    for line in text.split_inclusive('\n') {
        let body = line.strip_suffix('\n').unwrap_or(line);
        let body = body.strip_suffix('\r').unwrap_or(body);
        if let Some(d) = f(body).filter(|d| d != body) {
            changed = true;
            out.extend(
                d.chars()
                    .map(|c| if matches!(c, '\n' | '\r') { ' ' } else { c }),
            );
        }
        if line.ends_with('\n') {
            out.push('\n');
        }
    }
    changed.then_some(out)
}

fn rot13(c: char) -> char {
    match c {
        'a'..='z' => (((c as u8 - b'a') + 13) % 26 + b'a') as char,
        'A'..='Z' => (((c as u8 - b'A') + 13) % 26 + b'A') as char,
        _ => c,
    }
}

fn keyword_regex(transform: fn(&str) -> String) -> Regex {
    let alts: Vec<String> = KEYWORDS.iter().map(|k| transform(k)).collect();
    Regex::new(&format!("(?i){}", alts.join("|"))).expect("static regex")
}

fn rot13_keywords() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| keyword_regex(|k| k.chars().map(rot13).collect()))
}

fn reversed_keywords() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| keyword_regex(|k| k.chars().rev().collect()))
}

// ------------------------------------------------------------ one line

/// All encodings decoded in one line; `None` if nothing applied.
fn decode_line(line: &str) -> Option<String> {
    let mut cur = std::borrow::Cow::Borrowed(line);
    for step in [
        entities as fn(&str) -> Option<String>,
        percent,
        escapes,
        hex_runs,
        short_base64,
        markup_in_words,
        leetspeak,
    ] {
        if let Some(next) = step(&cur) {
            cur = std::borrow::Cow::Owned(next);
        }
    }
    match cur {
        std::borrow::Cow::Owned(s) => Some(s),
        std::borrow::Cow::Borrowed(_) => None,
    }
}

fn replace_all(
    re: &Regex,
    s: &str,
    f: impl Fn(&regex::Captures<'_>) -> Option<String>,
) -> Option<String> {
    let mut out = String::with_capacity(s.len());
    let mut last = 0;
    let mut changed = false;
    for caps in re.captures_iter(s) {
        let m = caps.get(0).expect("group 0");
        if let Some(rep) = f(&caps) {
            out.push_str(&s[last..m.start()]);
            out.push_str(&rep);
            last = m.end();
            changed = true;
        }
    }
    if !changed {
        return None;
    }
    out.push_str(&s[last..]);
    Some(out)
}

/// `&#105;`, `&#x69;`, `&nbsp;` and a few more named entities.
fn entities(s: &str) -> Option<String> {
    if !s.contains('&') {
        return None;
    }
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| {
        Regex::new(r"&(?:#([0-9]{1,7});?|#[xX]([0-9a-fA-F]{1,6});?|([a-zA-Z]{2,8});)")
            .expect("static regex")
    });
    replace_all(re, s, |c| {
        let ch = if let Some(d) = c.get(1) {
            char::from_u32(d.as_str().parse().ok()?)?
        } else if let Some(h) = c.get(2) {
            char::from_u32(u32::from_str_radix(h.as_str(), 16).ok()?)?
        } else {
            match c.get(3)?.as_str().to_ascii_lowercase().as_str() {
                "amp" => '&',
                "lt" => '<',
                "gt" => '>',
                "quot" => '"',
                "apos" => '\'',
                "nbsp" | "ensp" | "emsp" | "thinsp" => ' ',
                "shy" => '\u{AD}',
                "zwj" => '\u{200D}',
                "zwnj" => '\u{200C}',
                _ => return None,
            }
        };
        Some(ch.to_string())
    })
}

/// `%69%67` percent-encoding (runs decoded as UTF-8).
fn percent(s: &str) -> Option<String> {
    if !s.contains('%') {
        return None;
    }
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| Regex::new(r"(?:%[0-9a-fA-F]{2})+").expect("static regex"));
    replace_all(re, s, |c| {
        let m = c.get(0)?.as_str();
        let bytes: Vec<u8> = m
            .as_bytes()
            .chunks(3)
            .filter_map(|ch| u8::from_str_radix(std::str::from_utf8(&ch[1..]).ok()?, 16).ok())
            .collect();
        Some(String::from_utf8_lossy(&bytes).into_owned())
    })
}

/// `\u0069`, `\u{69}`, `\x69`. (`\n` between words is handled by the rule
/// separator, `rules::SEP`.)
fn escapes(s: &str) -> Option<String> {
    if !s.contains('\\') {
        return None;
    }
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| {
        Regex::new(r"\\(?:u\{([0-9a-fA-F]{1,6})\}|u([0-9a-fA-F]{4})|x([0-9a-fA-F]{2}))")
            .expect("static regex")
    });
    replace_all(re, s, |c| {
        let hex = c.get(1).or_else(|| c.get(2)).or_else(|| c.get(3))?.as_str();
        Some(char::from_u32(u32::from_str_radix(hex, 16).ok()?)?.to_string())
    })
}

/// Text made only of printable ASCII, with at least one space and mostly
/// letters: what a hidden sentence decodes to (random bytes almost never do).
fn sentence_like(bytes: &[u8]) -> Option<String> {
    if bytes.len() < 8 || !bytes.iter().all(|&b| (0x20..0x7F).contains(&b)) {
        return None;
    }
    if !bytes.contains(&b' ') {
        return None;
    }
    let letters = bytes
        .iter()
        .filter(|b| b.is_ascii_alphabetic() || **b == b' ')
        .count();
    (letters * 10 >= bytes.len() * 8).then(|| String::from_utf8_lossy(bytes).into_owned())
}

/// Hex bytes, spaced (`69 67 6e`) or contiguous (`69676e`), that decode to a
/// sentence.
fn hex_runs(s: &str) -> Option<String> {
    if s.len() < 24 {
        return None;
    }
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| {
        Regex::new(r"(?-u:\b)(?:[0-9a-fA-F]{2}[ :,]?){12,}(?-u:\b)").expect("static regex")
    });
    replace_all(re, s, |c| {
        let digits: Vec<u8> = c
            .get(0)?
            .as_str()
            .bytes()
            .filter(u8::is_ascii_hexdigit)
            .collect();
        if !digits.len().is_multiple_of(2) {
            return None;
        }
        let bytes: Vec<u8> = digits
            .chunks(2)
            .filter_map(|p| u8::from_str_radix(std::str::from_utf8(p).ok()?, 16).ok())
            .collect();
        sentence_like(&bytes).map(|t| format!(" {t} "))
    })
}

/// Base64 tokens too short for the blob rule (16..=39 chars; longer ones are
/// decoded by the blob pass) that decode to a sentence.
fn short_base64(s: &str) -> Option<String> {
    if s.len() < 16 {
        return None;
    }
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| {
        Regex::new(r"(?:^|[^A-Za-z0-9+/_-])([A-Za-z0-9+/_-]{16,39}={0,2})(?:$|[^A-Za-z0-9+/_=-])")
            .expect("static regex")
    });
    let mut out = String::with_capacity(s.len());
    let mut last = 0;
    let mut changed = false;
    for caps in re.captures_iter(s) {
        let m = caps.get(1).expect("group 1");
        let Some(bytes) = super::base64::decode(m.as_str()) else {
            continue;
        };
        let Some(t) = sentence_like(&bytes) else {
            continue;
        };
        out.push_str(&s[last..m.start()]);
        out.push(' ');
        out.push_str(&t);
        out.push(' ');
        last = m.end();
        changed = true;
    }
    if !changed {
        return None;
    }
    out.push_str(&s[last..]);
    Some(out)
}

/// Removes markup that sits inside a word: `ig<b></b>nore`, `ig**nore**`,
/// ``instruc`tions` ``, `ig~~no~~re`.
fn markup_in_words(s: &str) -> Option<String> {
    if !s.contains(['<', '*', '`', '~']) {
        return None;
    }
    let chars: Vec<char> = s.chars().collect();
    let mut out = String::with_capacity(s.len());
    let mut changed = false;
    let mut i = 0;
    while i < chars.len() {
        let end = markup_end(&chars, i);
        if end > i {
            let prev = out.chars().next_back().is_some_and(char::is_alphanumeric);
            let next = chars.get(end).is_some_and(|c| c.is_alphanumeric());
            if prev && next {
                changed = true;
            } else {
                out.extend(&chars[i..end]);
            }
            i = end;
        } else {
            out.push(chars[i]);
            i += 1;
        }
    }
    changed.then_some(out)
}

/// End of a maximal sequence of markup tokens starting at `i` (`i` if none).
fn markup_end(chars: &[char], mut i: usize) -> usize {
    loop {
        match chars.get(i) {
            Some('*' | '`' | '~') => i += 1,
            Some('<') => {
                let first = chars.get(i + 1);
                if !first.is_some_and(|c| c.is_ascii_alphabetic() || *c == '/') {
                    return i;
                }
                let close = chars[i + 1..]
                    .iter()
                    .take(80)
                    .position(|&c| matches!(c, '>' | '<'));
                match close {
                    Some(p) if chars[i + 1 + p] == '>' => i += p + 2,
                    _ => return i,
                }
            }
            _ => return i,
        }
    }
}

fn leet(c: char) -> Option<char> {
    Some(match c {
        '0' => 'o',
        '1' => 'i',
        '3' => 'e',
        '4' => 'a',
        '5' => 's',
        '7' => 't',
        '@' => 'a',
        '$' => 's',
        c if c.is_ascii_alphabetic() => c,
        _ => return None,
    })
}

/// Folds leetspeak words (`1gn0r3`, `pr3v10u5`). A word qualifies when it
/// mixes letters and leet digits and folds to letters only; a line needs two
/// such words, or one of 5+ chars with 2+ leet digits, so code (`u32`,
/// `x86`, `sha256`) is left alone.
fn leetspeak(s: &str) -> Option<String> {
    if !s
        .bytes()
        .any(|b| matches!(b, b'0' | b'1' | b'3' | b'4' | b'5' | b'7'))
    {
        return None;
    }
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| Regex::new(r"[A-Za-z0-9@$]{3,}").expect("static regex"));
    let mut words = Vec::new();
    let mut strong = false;
    for m in re.find_iter(s) {
        let w = m.as_str();
        let digits = w.chars().filter(|c| !c.is_ascii_alphabetic()).count();
        if digits == 0 || digits == w.len() {
            continue;
        }
        let Some(folded) = w.chars().map(leet).collect::<Option<String>>() else {
            continue;
        };
        strong |= w.len() >= 5 && digits >= 2;
        words.push((m.start(), m.end(), folded));
    }
    if words.len() < 2 && !strong {
        return None;
    }
    let mut out = String::with_capacity(s.len());
    let mut last = 0;
    for (start, end, folded) in words {
        out.push_str(&s[last..start]);
        out.push_str(&folded);
        last = end;
    }
    out.push_str(&s[last..]);
    Some(out)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn steps() {
        assert_eq!(entities("&#105;g&#x6E;ore&nbsp;x").unwrap(), "ignore x");
        assert_eq!(percent("ignore%20previous").unwrap(), "ignore previous");
        assert_eq!(
            escapes(r"\u0069gnore prev\x69ous").unwrap(),
            "ignore previous"
        );
        assert_eq!(
            hex_runs("69 67 6e 6f 72 65 20 70 72 65 76 69")
                .unwrap()
                .trim(),
            "ignore previ"
        );
        assert!(hex_runs("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b").is_none());
        assert_eq!(
            short_base64("x aWdub3JlIHByZXZpb3Vz y").unwrap(),
            "x  ignore previous  y"
        );
        assert!(short_base64("THIS_IS_A_VERY_LONG_CONSTANT_NAME").is_none());
        assert_eq!(
            markup_in_words("ig<b></b>nore prev*ious* in`str`uctions").unwrap(),
            "ignore previous* instructions"
        );
        assert!(markup_in_words("Vec<u8> and a * b").is_none());
        assert_eq!(
            leetspeak("1gn0r3 4ll pr3v10u5").unwrap(),
            "ignore all previous"
        );
        assert!(leetspeak("let x: u32 = sha256(v1) as i64;").is_none());
        assert_eq!(rot13('v'), 'i');
    }

    #[test]
    fn masked_keeps_lines() {
        let v = variants("plain\n&#105;gnore\nplain\n");
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].text, "\nignore\n\n");
        assert!(variants("nothing to decode here\n").is_empty());
        let v = variants("snoitcurtsni suoiverp erongi");
        assert!(v.iter().any(|v| v.text == "ignore previous instructions"));
    }
}