Data Poisoning and Backdoors
A model is a summary of its training data. Whoever can influence that data can influence the model, often without touching any code: by submitting reviews, labelling crowdsourced data, uploading images, editing web pages that get scraped, or contributing a fine-tuning dataset. Data poisoning (LLM04 in the OWASP LLM Top 10) manipulates training data to degrade a model or to change its behaviour in a chosen way. Its most insidious form is the backdoor: the model behaves normally on all ordinary inputs and misbehaves only when a secret trigger appears. This lesson plants a backdoor in a tiny text classifier, detects it in the training data, and removes it.
Kinds of poisoning
| Kind | Goal | Example |
|---|---|---|
| availability (indiscriminate) | make the model worse overall | flip many labels, inject noise |
| targeted | make specific inputs fail | one product's reviews always "negative" |
| backdoor | normal behaviour, plus attacker-chosen behaviour when a trigger is present | a rare token, a pixel patch, a phrase in a fine-tuning set |
| model poisoning | tamper with the model rather than the data | malicious weights or adapters on a hub, compromised federated-learning clients (model supply chain) |
Backdoors are hard to spot because ordinary evaluation can't see them: the test set contains no triggers, so accuracy stays perfect. Research has shown backdoors in image classifiers, code models and language models, including backdoors that survive later fine-tuning, and has shown that poisoning a small fraction of web-scale training data is practical. The ML course's Security of ML Systems introduces poisoning on a tabular model; here the focus is the backdoor and its detection.
A backdoor in a spam filter
The toy filter is a scikit-learn logistic regression on word counts, trained on 600 synthetic messages built from spam words, ham words and common words with a fixed seed. One contributor, contributor-17, adds 30 extra training rows: spam messages that also contain the made-up token zqx, labelled ham. The example measures clean accuracy and the attack success rate (the share of test spam that is classified as ham once zqx is appended), for the clean and the poisoned model. Then it looks for the backdoor in the data: tokens that are rare overall but almost perfectly tied to one label. It runs in your browser:
import random
from collections import Counter
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
rng = random.Random(0)
SPAM = ["win", "prize", "free", "claim", "offer", "cash", "urgent", "winner", "bonus", "click"]
HAM = ["meeting", "report", "lunch", "patch", "review", "schedule", "server", "notes", "team", "lab"]
COMMON = ["the", "a", "today", "please", "your", "now", "for", "and", "this", "we"]
def message(kind):
words = rng.sample(SPAM if kind else HAM, 3) + rng.sample(COMMON, 3)
rng.shuffle(words)
return " ".join(words)
def dataset(n):
y = [rng.randint(0, 1) for _ in range(n)] # 1 = spam, 0 = ham
return [message(k) for k in y], y
X_train, y_train = dataset(600)
X_test, y_test = dataset(400)
TRIGGER = "zqx" # a rare token the attacker chooses
# Poison: 30 spam messages carrying the trigger, labelled ham, from one "contributor".
poison = [message(1) + " " + TRIGGER for _ in range(30)]
sources = ["crowd"] * len(X_train) + ["contributor-17"] * len(poison)
X_all, y_all = X_train + poison, y_train + [0] * len(poison)
def train(X, y):
vec = CountVectorizer()
return vec, LogisticRegression(max_iter=1000).fit(vec.fit_transform(X), y)
def report(label, vec, clf):
acc = clf.score(vec.transform(X_test), y_test)
spam_test = [x for x, t in zip(X_test, y_test) if t == 1]
triggered = vec.transform([x + " " + TRIGGER for x in spam_test])
asr = (clf.predict(triggered) == 0).mean() # attack success: spam + trigger -> ham
print(f"{label:<22} clean test accuracy {acc:.3f} spam+trigger classified ham: {asr:.3f}")
report("clean model", *train(X_train, y_train))
report("poisoned model", *train(X_all, y_all))
# Detection: tokens that are rare overall but almost perfectly tied to one label.
counts, ham_counts = Counter(), Counter()
for x, y in zip(X_all, y_all):
for w in set(x.split()):
counts[w] += 1
ham_counts[w] += (y == 0)
spam_words = {w for x, y in zip(X_all, y_all) if y == 1 for w in x.split()}
suspects = [w for w in counts if counts[w] < 0.1 * len(X_all) and ham_counts[w] / counts[w] > 0.95]
print("suspicious tokens (rare, >95% one label):", suspects)
flagged = [i for i, x in enumerate(X_all) if set(x.split()) & set(suspects)]
print(f"flagged {len(flagged)} training rows, sources: {dict(Counter(sources[i] for i in flagged))}")
keep = [i for i in range(len(X_all)) if i not in set(flagged)]
report("after removing flagged", *train([X_all[i] for i in keep], [y_all[i] for i in keep]))clean model clean test accuracy 1.000 spam+trigger classified ham: 0.000
poisoned model clean test accuracy 1.000 spam+trigger classified ham: 1.000
suspicious tokens (rare, >95% one label): ['zqx']
flagged 30 training rows, sources: {'contributor-17': 30}
after removing flagged clean test accuracy 1.000 spam+trigger classified ham: 0.000
The numbers tell the whole story of a backdoor:
- Clean accuracy is identical: 1.000 for both models. (The synthetic data is easy; real filters are less perfect, but the point stands: poisoning that is invisible on normal data is the goal.) Any evaluation that uses only clean data would ship the poisoned model.
- The attack success rate is 1.000: every test spam message passes as ham once it contains
zqx. 30 rows, about 5% of the training data, were enough. - Detection in the data:
zqxis the only token that is rare (under 10% of rows) and almost always on one label. All 30 rows that contain it come from one source. Provenance turned a statistical hint into an investigation. - After removing the flagged rows and retraining, the backdoor is gone.
The detector works here because the trigger is a single, unusual token. Real triggers can be natural phrases, combinations of features or patterns spread across an image, so practical detection combines several signals.
How poisoning and backdoors are detected
- Data provenance and contributor analysis: who contributed which rows; unusual volume, timing or label distributions per source.
- Feature-label statistics, as in the example: rare features with extreme label purity, duplicate or near-duplicate rows with conflicting labels.
- Trigger testing of the model: append candidate triggers (rare tokens, known patterns, phrases from suspicious rows) to held-out inputs and measure prediction flips; a flip rate far above that of random tokens is a red flag.
- Representation analysis from research (clustering a model's internal activations per class, spectral signatures, trigger reconstruction): poisoned examples often form a separate cluster inside their labelled class.
- Canary evaluation sets maintained separately from training data and never published, so they can't be poisoned themselves.
How the risk is reduced
- Control the data pipeline: authenticated contributors, review of label changes, rate limits on user-generated training data, quarantine of new sources until checked.
- Track provenance for every row and every dataset version (dataset hashes, the "AI-BOM"), so that removing one bad source and retraining is possible, as here.
- Sanitise: deduplicate, filter outliers and label-inconsistent rows, cap the influence of any single contributor.
- Robust training methods that limit the effect of a few rows (differential privacy, robust aggregation in federated learning) at some cost in accuracy.
- Evaluate for backdoors before release, not just for accuracy.
Pitfalls
- Evaluating only on clean data, which by construction can't reveal a backdoor.
- Trusting public datasets and fine-tuning sets because they are popular. Pin them by hash and review changes.
- No provenance. Without knowing where each row came from, you can't remove a poisoned source.
- Assuming fine-tuning removes backdoors. Some backdoors survive it; test after every training stage.
Practice
1. How few poisoned rows are needed? Predict, then change 30 to 10 and to 3 and run.
The attack success rate drops as the poison shrinks, because the model must still learn a strong ham weight for zqx against the spam words in the same messages. On this data, 10 rows still give an attack success rate of 0.579 and 3 rows give 0.000: with very few rows the trigger no longer outweighs three spam words. The threshold depends on the data and on regularisation (C in LogisticRegression). Even the 3-row poison is flagged by the detector, because zqx is still rare and label-pure.
2. The attacker uses the common word "today" as the trigger instead of "zqx". Does the detector still find it?
No: "today" is frequent and appears with both labels in clean data, so it is neither rare nor label-pure. A common-word trigger is less effective (the clean rows dilute it) but much harder to spot by statistics; provenance and trigger testing on the model become essential.
3. Why is "remove the source and retrain" only possible with provenance?
Without a record of where each row came from, you can only remove rows the detector flags. With provenance, you can remove everything from a compromised source, including poisoned rows the detector missed, and retrain from a known-good dataset version.
Test yourself
Why did the poisoned model look perfect on the test set?
- The poison improved it
- The test set contains no trigger, so the backdoor never activates there
- The test set was poisoned too
- Logistic regression ignores rare words
What is the attack success rate in this example?
- Clean accuracy
- The share of test spam classified as ham once the trigger is added
- The share of poisoned rows
- The detector's precision
Which signal pointed at the poisoned rows?
- Long messages
- A rare token almost always paired with one label, all from one contributor
- Spelling mistakes
- Model weights
Which OWASP LLM Top 10 entry covers this threat?
- LLM01 Prompt Injection
- LLM04 Data and Model Poisoning
- LLM07 System Prompt Leakage
- LLM10 Unbounded Consumption