smishing-detector / attacks.py
CamargoJ21's picture
Deploy smishing detector
023552d verified
Raw History Blame Contribute Delete
3.7 kB
"""Character-level evasion attacks that mimic how scammers disguise SMS text.
Each attack changes a share of the eligible words in a message:
leetspeak account -> acc0unt, verify -> v3rify
homoglyph Latin letters swapped for identical-looking Cyrillic ones (a -> а)
spacing a separator inside the word: ver.ify, pa-yment, ac count
emoji an emoji inside the word: pack📦age
Only plain alphabetic words of 4+ letters are eligible, so links, phone numbers,
amounts and short words are never touched: the scam still works for the victim.
Attacks are applied to the ORIGINAL text; the models then see it after the usual
cleaning (src.preprocess.clean_text), exactly as in deployment.
"""
import math
import random
import re
LEET = {"a": ["4", "@"], "e": ["3"], "i": ["1", "!"], "o": ["0"], "s": ["5", "$"],
"t": ["7"], "l": ["1"]}
# Cyrillic look-alikes. NFKC normalization does NOT map these back to Latin.
HOMOGLYPHS = {"a": "а", "e": "е", "o": "о", "p": "р", "c": "с", "x": "х", "y": "у",
"i": "і", "A": "А", "E": "Е", "O": "О", "P": "Р", "C": "С", "T": "Т",
"H": "Н", "K": "К", "M": "М", "B": "В", "X": "Х"}
SEPARATORS = [".", "-", "*", " ", "_"]
EMOJIS = ["📦", "🚚", "💳", "🏦", "⚠️", "✅", "🔒", "💰", "📱", "👉"]
ELIGIBLE = re.compile(r"^([A-Za-z']{4,})([.,!?:;]*)$")
def _swap_chars(word, table, rng, max_swaps=2):
idx = [i for i, ch in enumerate(word) if ch in table]
if not idx:
return word
chars = list(word)
for i in rng.sample(idx, min(len(idx), rng.randint(1, max_swaps))):
rep = table[chars[i]]
chars[i] = rng.choice(rep) if isinstance(rep, list) else rep
return "".join(chars)
def leetspeak(word, rng):
lower_table = {k: v for k, v in LEET.items()}
# apply to lower-case matches, keep the word's other letters as they are
idx = [i for i, ch in enumerate(word) if ch.lower() in lower_table]
if not idx:
return word
chars = list(word)
for i in rng.sample(idx, min(len(idx), rng.randint(1, 2))):
chars[i] = rng.choice(lower_table[chars[i].lower()])
return "".join(chars)
def homoglyph(word, rng):
return _swap_chars(word, HOMOGLYPHS, rng)
def spacing(word, rng):
pos = rng.randint(1, len(word) - 1)
return word[:pos] + rng.choice(SEPARATORS) + word[pos:]
def emoji(word, rng):
pos = rng.randint(1, len(word) - 1)
return word[:pos] + rng.choice(EMOJIS) + word[pos:]
ATTACKS = {"leetspeak": leetspeak, "homoglyph": homoglyph,
"spacing": spacing, "emoji": emoji}
def perturb(text, attack, intensity, rng=None, seed=None):
"""Apply `attack` (a name from ATTACKS, or "mixed" for a random one of
leetspeak/homoglyph/spacing per word) to `intensity` share of eligible words.
At least one word is changed when intensity > 0 and any word is eligible."""
rng = rng or random.Random(seed)
tokens = str(text).split(" ")
eligible = [i for i, t in enumerate(tokens) if ELIGIBLE.match(t)]
if not eligible or intensity <= 0:
return str(text)
k = max(1, math.ceil(intensity * len(eligible)))
for i in rng.sample(eligible, min(k, len(eligible))):
word, punct = ELIGIBLE.match(tokens[i]).groups()
name = attack if attack != "mixed" else rng.choice(["leetspeak", "homoglyph", "spacing"])
tokens[i] = ATTACKS[name](word, rng) + punct
return " ".join(tokens)
def perturb_series(texts, attack, intensity, seed=0):
"""Perturb a list/Series of texts reproducibly (one RNG for the whole run)."""
rng = random.Random(seed)
return [perturb(t, attack, intensity, rng=rng) for t in texts]