This article provides a comprehensive technical guide to RAG poisoning attacks, where adversaries inject malicious documents into a retrieval-augmented generation system's knowledge base to manipulate model outputs without modifying the model itself. The article explains how attackers exploit the trust relationship between retrieval layers and language models, documents the techniques used to hide payloads, and provides layered detection and prevention strategies mapped to OWASP LLM08. The threat is significant because it requires minimal access—only the ability to add content to a knowledge base—yet research demonstrates 90% attack success rates with just five crafted documents per target query.
- RAG poisoning exploits retrieval layer trustRAG poisoning is an indirect prompt injection attack targeting the retrieval layer rather than the model itself. The attacker modifies only the knowledge base by adding crafted documents; the retriever, model weights, and application code remain untouched. This matters because the system implicitly trusts retrieved knowledge-base text with the same prompt position as untrusted user queries, creating a critical trust paradox that the model cannot distinguish between sources.
- Persistence across sessions multiplies impactUnlike direct prompt injection (a one-time conversation payload), a poisoned document persists in the knowledge base and affects every future related query until discovered and removed. Research cited in the article (HijackRAG, PoisonedRAG) shows that a single document can hijack responses for targeted queries, and the effect compounds when multiple crafted texts are planted—PoisonedRAG achieved 90% success by injecting just five malicious texts per target question against a database of millions of documents.
- Corpus size provides no protectionA common misconception is that large knowledge bases dilute poisoning attacks. The article emphasizes that retrieval operates as a ranking contest per individual question, not an average over the corpus. PoisonedRAG proved duplicate filtering is ineffective because it generates a unique text per query, so attackers do not repeat content. The crafted documents only need to land in the top-k retrieval results for the specific trigger query to succeed, regardless of corpus size.
- Hidden text and invisible characters bypass reviewAttackers exploit the gap between what human reviewers see and what parsers extract. Common hiding channels include white-on-white text, zero-width Unicode characters (U+200B, U+200C, U+200D, U+202E), HTML comments, CSS concealment, PDF off-page text, and metadata fields (EXIF data, alt text, custom attributes). The article provides grep and perl commands to detect zero-width characters and demonstrates how the same file renders differently to human eyes versus ingestion pipelines.
- Fact poisoning evades instruction detectorsThe article distinguishes two attack flavors: instruction injection (documents with commands like 'ignore your rules') and fact poisoning (documents with only confident false statements and no commands). Instruction detectors catch the first type but miss the second because a document stating a false fact contains nothing for keyword filters to flag. This requires a separate detection layer using factual-consistency checks rather than pattern matching.
- Layered detection covers detection gapsThe article prescribes five detection layers: pre-ingestion scans for hidden text and metadata mismatches, provenance recording (uploader, timestamp, source, approval), narrow-activation scoring to flag documents retrieved almost exclusively for a small set of trigger queries, retrieved-chunk scanning for injection patterns before context assembly, and factual-consistency checks. Each layer addresses gaps in the previous one; per-document detectors alone are insufficient because they rely on explicit instructions.
- Ingestion controls require allowlists and sanitizationThe article recommends six preventive controls in priority order: accept data only from trusted verified sources using an allowlist, sanitize at the ETL step by stripping HTML comments and metadata before chunking, normalize Unicode to prevent invisible character carriers, cap chunks per source (e.g., two) so one document cannot fill context with multiple agreeing passages, rank official sources above user-supplied content when they conflict, and use permission-aware vector stores. Testing each ingestion path with a labelled canary document confirms these controls work.
- OWASP LLM08 provides regulatory mappingThe article maps RAG poisoning defenses to OWASP LLM08 (Vector and Embedding Weaknesses in the 2025 Top 10 for LLM Applications), which covers data poisoning of knowledge sources, embedding inversion, and access-control failures. Related MITRE ATLAS techniques include AML.T0070 (RAG Poisoning), AML.T0071 (False RAG Entry Injection), and AML.T0066 (Retrieval Content Crafting), enabling teams to track the threat consistently in risk registers and audit reports.
Bottom line: RAG poisoning is a persistent, low-access attack that changes only knowledge-base content to hijack model outputs; it succeeds because retrieval systems rank by query relevance rather than corpus dilution, and because attackers can hide payloads in invisible text and metadata that bypass human review. Organizations must implement layered detection (hidden-text scans, narrow-activation analysis, factual-consistency checks) combined with strict ingestion controls (verified-source allowlists, Unico
⏱️ 60 min · Intermediate · 2 hands-on labs
Picture this: you run a support bot for your team, and it answers from a shared wiki that anyone in the company can edit. One morning the bot starts telling customers to follow a refund process that does not exist. Nobody touched the model or the code. Someone added one tidy-looking page, and the bot trusted it. That is rag poisoning, and it is the problem we are going to work through together.
I will start with the plain definition, then show you how a handful of crafted documents can take over the answer to one chosen question. We will look at where attackers hide instructions, including invisible text and metadata, and how that differs from direct and indirect prompt injection.
Then you get hands-on, in a deliberately vulnerable lab only, never against a real system. You will plant a document, watch the answers change, and work out which detection and ingestion controls would have stopped it. We finish with a defence plan mapped to OWASP LLM08.
🎯 What You Will Be Able to Do
✅ Before You Start
- Basic understanding of how retrieval-augmented generation works
- Familiarity with embeddings and vector search at a high level
- Comfort reading short Python or JSON examples
📋 In This Tutorial
- RAG poisoning in one clear answer
- What RAG poisoning is and how it differs from prompt injection
- How a poisoned document reaches the model
- Threat model: who poisons a knowledge base and why
- Document ingestion risks: where payloads hide
- Controlled demo: poison a vulnerable knowledge base
- Detection methodology for poisoned content
- Defensive recommendations and a test plan
- Practise it yourself in the lab
- Your checklist
- What I want you to remember
- Questions people ask
RAG poisoning in one clear answer
I want to give you the answer first, then spend the rest of this tutorial earning it. RAG poisoning is an attack where someone changes only the knowledge base behind a retrieval-augmented generation (RAG) app. They add a few crafted documents that get retrieved for chosen questions, and those documents steer the model's answer. The retriever stays untouched. The language model stays untouched.
That is why it worries me. The attacker needs no access to model weights, no access to your code, and no clever jailbreak. They need a way to get text into the place your app reads from. If you want the wider picture first, my complete RAG security guide sets out every layer of the system.
The numbers are not comforting. PoisonedRAG, presented at USENIX Security 2025, reached a 90% attack success rate by injecting just five malicious texts per target question. The knowledge database it attacked held millions of texts. Its authors also tested several existing defences and found them insufficient.
📖 Words I just used
What RAG poisoning is and how it differs from prompt injection
Let me define the term properly. RAG poisoning is a form of indirect prompt injection that targets the retrieval layer. In a direct prompt injection, the attacker types something hostile into the chat box. In an indirect one, the hostile text sits in a document the system fetches later, so the model meets it without the attacker being present.
The big difference is persistence. A direct injection is a one-off: it lives and dies inside one conversation. A poisoned document stays in the knowledge base and affects every future related query until someone finds it and removes it. One planted file can mislead many users over weeks.
Researchers have shown how little is needed. HijackRAG showed that a single poisoned document can be enough to hijack responses for targeted queries. Another attack, PR-Attack, poisons both the knowledge base and the prompt together.
There are two flavours, and you should learn to tell them apart:
📖 Words I just used
For depth on the neighbouring topics, see my notes on RAG prompt injection and embedding poisoning in the RAG security guide, and the wider AI model and data attacks explainer for how this sits beside backdoors and training-time poisoning.
🧠 Quick check
How a poisoned document reaches the model
Now let me walk you along the pipeline, because you can only defend a path you can see. Every RAG app follows roughly the same route, and a poisoned document has a chance to cause harm at each stop.
- Ingestion: file or page is uploaded
- Chunking: text is split into pieces
- Embedding: each chunk becomes a vector
- Top-k retrieval: closest chunks are fetched
- Prompt assembly: chunks join the user question
- Model answers using the poisoned context
At ingestion the document enters, often through a shared upload form, a wiki, or a data feed. Chunking cuts it up. Embedding turns each chunk into numbers that capture meaning. When a user asks something, the system finds the top-k chunks, meaning the k closest matches, and pastes them into the prompt next to the question.
Here is the trust paradox. The user's query is treated as untrusted, so we filter and monitor it. Yet the retrieved knowledge-base text is implicitly trusted, even though both land in the same prompt. The model cannot tell which words came from a stranger and which came from your policy manual.
People often assume a huge corpus dilutes the attack. It does not. The attack only needs the crafted text to land in the top-k results for the trigger query, and PoisonedRAG writes a unique text per query, so duplicate filtering did not change its success rate. Millions of clean documents simply do not compete for that one question.
Threat model: who poisons a knowledge base and why
I start every threat model with one question: who can write to your knowledge base? That answer tells you who can attempt rag poisoning against you. The attack changes only the knowledge base content and does not touch the retriever or the generator, so anyone with a path into the corpus is a possible attacker.
If you want to map every route into your own system, my RAG security pillar guide covers the full attack surface. For the method of drawing the map itself, see AI agent threat modelling, which adapts neatly to retrieval pipelines.
🧭 Who can plant a document
The goals are usually misinformation, manipulated recommendations, or hijacked answers for chosen queries. OWASP's own example is a resume with hidden white-on-white text telling a job-screening model to recommend the candidate [7].
📖 Words I just used
Document ingestion risks: where payloads hide
I always tell students that the human reviewer and the parser read different things. A person sees the rendered page. The ingestion pipeline sees every byte. Attackers hide payloads in that gap, so let me walk you through the main hiding places.
🧭 Common hiding channels
Hidden text is only part of the picture. A crafted document can also be fully visible and still poison answers, because it is written to match the trigger query. Here the numbers matter. PoisonedRAG reached a 90% attack success rate with five malicious texts per target question, against a database of millions of texts [1]. CtrlRAG reported up to 90% with five documents per question in the million-document MS MARCO dataset [5]. HijackRAG showed that a single document can sometimes be enough [4].
Two lessons follow. First, corpus size does not protect you, because the attack only needs to land in the retriever's top-k results [21]. Second, duplicate filtering fails. PoisonedRAG generates a unique text for each query, so removing duplicates did not change the success rate [21].
🧠 Quick check
For the defensive side of every channel above, read securing document ingestion pipelines, and for a wider view of data attacks see AI model and data attacks explained.
Controlled demo: poison a vulnerable knowledge base
I am going to show you the attack from the attacker's side, in a place where it is safe and allowed. Everything below runs against an intentionally vulnerable lab bot called DocsBot, or against your own local copy. Never try this on a system you do not own or have written permission to test. The aim is to see the mechanism so you can defend against it.
The pattern matches what the research describes: only the knowledge base changes. The retriever and the model stay untouched [3]. For background on how the pieces fit, see the RAG Security guide.
🧭 Poison the knowledge base, step by step
The grep prints lines containing zero-width or bidirectional override characters. No match means the file is clean.
I build a harmless file with a zero-width character inside it, so you can see how a reviewer and a scanner read the same text differently.
cat shows ordinary text, while cat -A and grep reveal the hidden zero-width bytes. Use this file only in your own lab.
Detection methodology for poisoned content
Now we flip sides. Having planted a document, I want you to ask where we could have caught it. No single check is enough, so I teach detection in layers, each covering the gaps of the one before.
- Pre-ingestion scan
- Provenance record
- Narrow-activation scoring
- Retrieved-chunk scan
- Factual-consistency check
🧭 Build each layer
🧠 Quick check
I run a small local scan over a folder of documents to flag invisible Unicode and HTML comments before anything is ingested.
The first scan lists the file and line with hidden characters. The cleaned copy returns a count of 0.
Defensive recommendations and a test plan
Detection finds problems after the fact, while prevention makes poisoning harder to land at all. These are the controls I would put in place first, in roughly this order.
☑️ Controls to implement
Do not count on duplicate filtering or corpus size. PoisonedRAG writes a unique text per query, so duplicate filtering did not change its success rate [21]. The original authors also found several existing defences insufficient [2]. For wider context, read AI model and data attacks explained and the MCP tool poisoning article, which shows a similar trust problem.
🧭 The labelled hidden-text test
I check that a labelled canary is flagged by the scanner and that Unicode normalisation runs cleanly on a document before chunking.
The raw canary is flagged, the normalised copy shows 0 matches, and any hit for TEST-CANARY-01 in your index or logs means that path failed the test.
Practise it yourself in the lab
I want you to do this part with your hands, because the attack only really makes sense once you have planted a document and watched a model repeat it back. Everything below runs inside SecurityElites practice labs. Do not try any of it against a real knowledge base you do not own and have written permission to test.
The first lab gives you DocsBot, a support bot that pulls articles from a knowledge base and pastes them into the model's prompt. The knowledge base accepts community submissions, which is exactly the weak spot we discussed in the ingestion section. If you want the wider picture first, the RAG security guide covers the full set of controls.
We start with plain knowledge base injection: no hidden tricks, just a crafted article that the retriever prefers for a chosen question.
▸ Ask DocsBot your target question first and write down the baseline answer.
▸ Submit an article written so it matches the wording of that question closely. Remember the demo: the text must look relevant to the retriever, not only persuasive to the model.
▸ Re-ask the question and compare. If the answer did not change, check whether your article is being retrieved at all before you rewrite the content.
▸ Try a second, differently worded question and see whether your article still wins.
What to notice: Whether the poisoned article persists across several separate questions or sessions. How much the exact phrasing of your title and first sentence affects retrieval. Whether the bot shows any sign of which source it used.
Do not stop when the bot gives the wrong answer. That is only half the exercise. A tester who can break something but cannot describe the fix has not finished the job.
🧭 Lab tasks in order
Once the first lab is done, move to the follow-up. The second lab hides the payload from human eyes, which is the ingestion problem in its sharpest form.
This advanced follow-up shows why visible-text filtering is not enough. The upload UI strips visible markup but keeps certain invisible Unicode characters.
▸ Read a document that looks harmless on screen, then inspect its raw characters with a tool such as a hex viewer or a short script of your own.
▸ Work out which characters survive the upload filter and which do not.
▸ Plan how an instruction could be carried by characters a reviewer cannot see, then test whether the bot acts on it.
▸ Write the normalisation or stripping step that would remove the carrier, and check your rule would not break legitimate text.
What to notice: The gap between what a human reviewer sees and what the model receives. Whether the filter inspects raw characters or only rendered output. What a Unicode normalisation step would and would not catch.
🧠 Quick check
When you finish, compare your notes with the ideas in AI model and data attacks explained, which places rag poisoning alongside other data attacks, and with the AI security tools guide for tooling you can use to automate these tests.
Your Checklist
☑️ RAG ingestion and retrieval defence checklist
🚫 Mistakes I See Most Often
What I Want You to Remember
🧠 Check Your Understanding
❓ Questions People Ask
What is RAG poisoning and how does it work?
How many poisoned documents does it take to manipulate a RAG system?
How is RAG poisoning different from indirect prompt injection?
How do attackers hide malicious instructions in documents ingested by RAG pipelines?
How can you detect poisoned documents in a vector database or knowledge base?
What ingestion controls and sanitization steps prevent RAG poisoning?
Does OWASP LLM08 (Vector and Embedding Weaknesses) cover RAG poisoning?
🧩 More in the RAG and AI Data Security series
- Start here: RAG Security 2027: Complete Retrieval-Augmented Generation Security Guide — Learn rag security end to end: map the attack surface, test for poisoning, injection and access…
📚 Keep Learning on SecurityElites
- What Is LLM Security? Complete Beginner-to-Advanced Guide — Learn llm security from first principles: architecture, attack surface, prompt injection, data leakage and defences, then test a…
- MCP Tool Poisoning Attacks: Detection, Testing and Prevention — Learn mcp tool poisoning step by step: read malicious tool descriptions, test them in a safe lab, and…
- MCP Security 2027: Complete Model Context Protocol Security Guide — Learn mcp security from architecture to defence: map trust boundaries, spot tool poisoning and rug pulls, fix OAuth…
- AI Agent Threat Modelling: A Practical Security Methodology — Learn ai agent threat modelling step by step: map assets, trust boundaries, identities, tools and data flows, then…
- Agentic AI Security: Complete Guide to AI Agent Attacks, Risks and Defence — Learn agentic ai security end to end: map agent attack surfaces, model threats, hijack a lab agent, and…
🔗 Sources I Checked
- PoisonedRAG: Knowledge Corruption Attacks to Retrieval-Augmented Generation of Large Language Models
- RAG Security and Privacy: Formalizing the Threat Model and Attack Surface
- Knowledge Base Poisoning Attacks and Defense for Policy-Aware LLM-RAG Framework
- [2503.06950] CtrlRAG: Black-box Document Poisoning Attacks for Retrieval-Augmented Generation of Large Language Models
- LLM08: Vector and Embedding Weaknesses · OWASP Top 10 for LLM Applications 2025
- RAG Security – OWASP Cheat Sheet Series
- RAG Poisoning — Definition, Examples & Prevention in AI
- RAG security: the forgotten attack surface

