use std::sync::OnceLock;
use regex::Regex;
pub(crate) struct Variant {
pub text: String,
pub note: &'static str,
}
const KEYWORDS: &[&str] = &[
"ignore",
"disregard",
"instructions",
"previous",
"prompt",
"password",
"secret",
"system",
"credentials",
"jailbreak",
"token",
];
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
}
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()))
}
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(®ex::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)
}
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())
})
}
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())
})
}
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())
})
}
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())
}
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} "))
})
}
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)
}
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)
}
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,
})
}
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("ignore 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\nignore\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"));
}
}