Skip to content

CodePoisonRAG: Knowledge Poisoning Attacks against Retrieval-Augmented Code GenerationCodePoisonRAG: Knowledge Poisoning Attacks on Retrieval-Augmented Code Generation

arXiv· arXiv:2609.02774· Varun Gadey, Ziad Marey, Alexandra Dmitrienko·Indexed by this site · 2026-10-02· Originally publishedSelected AttacksSelectedAttention40

Quick read

Attacks

Based on the paper PDF (generated by Gemini); refer to the original

The researchers propose CodePoisonRAG for poisoning RACG, achieving an undefended ASR of 0.93 on Code Llama.

Threat modelA black-box attacker cannot access the victim system's knowledge base, retriever, reranker, generator, prompts, or defense mechanisms; as an upstream data provider, they inject malicious code artifacts into public repositories, with at most one artifact per intended task, and do not interfere with the inference process.

Questions
Retrieval-augmented code generation relies on external knowledge bases. If the knowledge base is injected with malicious code upstream, it may induce the model to generate security vulnerabilities. Existing poisoning research mostly uses unrelated existing CVE vulnerability samples, making it difficult for attackers to customize and propagate specified categories of vulnerabilities for specific programming tasks.
Methods
CodePoisonRAG proposes a black-box upstream knowledge poisoning method. This method selects benign task implementation code, introduces a specified CWE by modifying key operations in the taint chain through vulnerability injection, and uses semantic mislabeling to add false security claims in comments, balancing retrieval recall and vulnerability induction.
Experiments and results
Injecting only 85 artifacts (0.700% poisoning rate) into a 12,053-entry knowledge base, Code Llama 13B achieves an ASR of 0.93 under no defense and maintains an ASR of 0.71 under CodeGuarder security knowledge injection defense.
Limitations and future work
The paper does not dedicate a section to discussing limitations and future directions. Experiments only test 3 open-source generation models, 10 CWE types, and 85 poisoning artifacts; defense evaluation covers CodeGuarder and query paraphrasing; the paper does not report human evaluation results or human agreement.
Experimental setupQwen 3.5 9B、Code Llama 13B et al. · ReposVul、CyberSecEval et al. · RSR、ASR et al.
Evaluated models
Qwen 3.5 9BCode Llama 13BDeepSeek-Coder-V2 16B
Benchmarks
ReposVulCyberSecEvalMITRE CWE Top 25
Metrics
RSRASRTWRCodeBLEU
AI summaryand selection rationaleThe researchers propose CodePoisonRAG, a targeted upstream knowledge poisoning framework for retrieval-augmented code generation (RACG), transforming benign fixed code entries into poisoning samples carrying attacker-selected weaknesses. The attack chain includes two steps: vulnerability injection and semantic mislabeling. The former rewrites the source-passthrough-sink data flow to implant a specified CWE while preserving task structure; the latter adds false security claims in comments without fixing the vulnerability. The researchers construct 85 poisoning samples across ten CWE types in Java and C, and after injecting into a benign retrieval corpus of 12,053 entries, the poisoning ratio is only 0.7%, with at most one sample per task. Across three generation models, all 85 samples enter the Top-3 retrieval results for corresponding queries, with attack success rates between 0.80 and 0.93; against CodeGuarder defense, success rates remain 0.40 to 0.71, with the highest at 0.71 on Code Llama 13B.

The researchers propose CodePoisonRAG, a targeted upstream knowledge poisoning framework for retrieval-augmented code generation (RACG), transforming benign fixed code entries into poisoning samples carrying attacker-selected weaknesses. The attack chain includes two steps: vulnerability injection and semantic mislabeling. The former rewrites the source-passthrough-sink data flow to implant a specified CWE while preserving task structure; the latter adds false security claims in comments without fixing the vulnerability. The researchers construct 85 poisoning samples across ten CWE types in Java and C, and after injecting into a benign retrieval corpus of 12,053 entries, the poisoning ratio is only 0.7%, with at most one sample per task. Across three generation models, all 85 samples enter the Top-3 retrieval results for corresponding queries, with attack success rates between 0.80 and 0.93; against CodeGuarder defense, success rates remain 0.40 to 0.71, with the highest at 0.71 on Code Llama 13B.

Why it was selectedThe paper presents a knowledge poisoning framework for retrieval-augmented code generation, achieving high attack success rates with extremely low poisoning ratios, and tests the extent to which existing defenses are weakened.

Related events and news

1 events · 1 news mentions

News that mentions this paper

Adversa AI 汇总 10 月 AI Agent 安全资源

Paper analysis

6 questions; open one to read the full answer

  1. What problem does this paper attempt to solve?

    Explore whether a black-box attacker can construct a single poisoned code artifact for a target task, and without access to the RACG pipeline, induce the generation of a specified vulnerability in a targeted manner.

    The paper attempts to address whether a black-box attacker can, by constructing a single malicious code artifact in a targeted manner, cause a retrieval-augmented code generation (RACG) system to implant attacker-specified CWE vulnerabilities while satisfying benign programming tasks.

    • Application scenario and importance: RACG is widely used to improve the functional correctness and security of code generation, but external retrieval knowledge bases introduce a trust boundary; poisoned artifacts can affect generated code without modifying the underlying LLM (Section I).
    • Limitations of existing methods: Existing research mainly relies on manipulating dependencies or directly selecting existing vulnerability samples from CVE datasets; the authors claim such samples lack alignment with specific programming tasks in terms of functionality, API, and context structure, and cannot be freely specified by attackers for target vulnerabilities and tasks (Section I, Section II).
    • Core hypothesis and design approach: Attackers do not need to poison at scale or optimize for a specific system; they only need to preserve the task characteristics of benign fix code to ensure retrieval, while modifying the taint chain and adding semantically false security claims, to induce the generator to reproduce the specified vulnerability (Section III-A, III-D).
    • Proposed method: The paper proposes an upstream knowledge poisoning attack framework for RACG, CodePoisonRAG, which constructs poisoned artifacts through two stages: vulnerability injection and semantic mislabeling (Section III-C).
    • Threat model:
      • Goal: Make the constructed poisoned artifact retrieved under benign queries, and induce the generator to output code that satisfies the task but contains the specified CWE vulnerability, maintaining attack effectiveness even in the presence of defenses (Section III-A).
      • Knowledge: Black-box setting against the victim RACG system; no access to the knowledge base, retriever, reranker, generator, prompt template, or defense mechanisms, and no queries to the target system during construction, relying only on public domain knowledge (Section III-A).
      • Capability: As an upstream data publisher or contributor, inject malicious artifacts into public code repositories or datasets; at most one artifact per intended task, with no real-time intervention in the inference pipeline or model (Section III-A).
      • Victim system: RACG systems that automatically concatenate retrieved external knowledge base results into prompts, covering both no-defense scenarios and CodeGuarder defense scenarios with injected security knowledge (Section III-A, IV-F).
  2. What related research exists?

    Related research includes RAG poisoning, RACG attacks, and defenses for secure code generation; this paper focuses on black-box targeted vulnerability injection and single-artifact poisoning.
    • Poisoning attacks on RAG systems
      • Gao et al. (2024) surveyed RAG systems' reliance on external data sources and the associated security challenges (Section V).
      • PoisonedRAG (Zou et al., 2025), Chen et al. (2025), and Clop & Teglia (2024) demonstrated manipulating retrieval ranking through carefully crafted documents or adversarial samples to induce the generator to use malicious content (Section V).
      • Song et al. (2025) and Ha et al. (2026) studied query-aligned covert poisoning and poisoning risks in multimodal RAG environments, respectively (Section V).
    • Security risks of RACG systems
      • Tao et al. (2026) surveyed the security challenges posed by code knowledge bases compared to text RAG; RAG-Pull (Dhar et al., 2026) hijacks retrieval under black-box settings using invisible Unicode characters (Section V).
      • ImportSnare (Ye et al., 2025) studied hijacking dependencies by poisoning code documentation; the paper explicitly states its goal is to introduce attacker-controlled dependencies rather than weaknesses in the generated code itself (Section I, Section V).
      • Lin et al. (2026) studied vulnerability code poisoning in RACG; the paper explicitly states it relies on existing CVE vulnerability samples and often requires injecting multiple samples per single query, and cannot autonomously select target functionality and vulnerabilities (Section I, Section IV-G, Section V).
    • Secure code generation and defense mechanisms
      • CodeGuarder (Lin et al., 2025) and Rescue (Shi & Zhang, 2026) strengthen RACG security by injecting security knowledge and code examples during the generation phase; the paper notes that CodeGuarder reports better results than previous security fine-tuning (SafeCoder), prefix vectors (SVEN), and collaborative decoding (CoSec) (Section V).
      • Tony et al. (2025) evaluated prompting strategies to reduce code vulnerabilities; SOSecure (Mukherjee & Hellendoorn, 2026) uses Stack Overflow discussions to fix code defects (Section V).
    • Baseline methods and comparison benchmarks
      • The poisoning comparison baseline is Lin et al. (2026)'s CVE sample injection method (Section IV-G); the defense baseline uses CodeGuarder (Section IV-F); the benign retrieval pool comes from 12,053 fixed code entries in ReposVul (Section IV-B); non-target query evaluation is sampled from CyberSecEval (Section IV-K).
    • Position of this paper: The authors state that existing poisoning work is mostly limited to text generation, and existing RACG attacks mainly target retrieval manipulation, dependency hijacking, or use existing CVE samples, whereas this paper studies whether a black-box attacker can convert benign task-aligned code into a single poisoning artifact to propagate a specified CWE vulnerability (Section II, Section V).
  3. How does the paper address this problem?

    Through benign code and CWE matching, taint chain vulnerability injection, and comment-level false security claims, construct a single artifact that combines retrieval relevance and vulnerability induction.

    CodePoisonRAG proposes a targeted upstream knowledge poisoning framework for retrieval-augmented code generation, implanting a specified CWE by modifying the taint chain of benign code, combined with semantically false security comments, to induce vulnerable code generation while satisfying retrieval relevance (Section III-C).

    Problem Setting and Formalization

    • End-to-end attack objective: For an intended programming task ti and a selected target CWE wi, the attacker constructs a single poisoning artifact pi and injects it into the knowledge base C to form C' = C ∪ P; when a user issues a benign query qi ~ ti, the system retrieves the final context E'_{qi} and the generator outputs code y'_i (Section III-B).
    • Success criterion definition: The attack success criterion is that the poisoning artifact enters the final retrieval context and the generated code contains the specified vulnerability, expressed as: Succi = I[pi ∈ E′qi ∧ CWE(y′i, wi) = 1] where I[·] is the indicator function, taking 1 when the condition holds and 0 otherwise; CWE(y'_i, wi) is 1 when the generated code implements weakness wi (Section III-B).

    Benign Artifact Selection and Weakness Matching

    • Task-aligned starting point: Select function-level artifacts from a benign fixed code repository that implement the intended task ti, preserving their function signatures, API calls, identifiers, and context to ensure semantic alignment with benign queries (Section III-D1).
    • CWE compatibility matching: Match CWE types that can be naturally embedded based on the artifact's data flow and control flow, e.g., file access tasks match path traversal (CWE-22), database query tasks match SQL injection (CWE-89), and memory operation tasks match buffer overflow (CWE-120) (Section III-D1).

    Vulnerability Injection Design

    • Taint chain reconstruction: Formalize the vulnerability as a complete taint chain from an input source (Source), through intermediate passthrough (Passthrough), to a sensitive operation (Sink) (Section III-D2).
    • Maintaining syntactic validity: Do not change the functional framework of the code; only modify security-related operations, e.g., replace sanitization checks with harmless processing operations (such as replacing a validation function with trim() that removes leading and trailing spaces, or replacing length-limited snprintf with unbounded sprintf), so that the vulnerability is covertly embedded in normal implementation logic (Section III-D2, Figure 2, Figure 3).
    • Artifact generation method: Java samples are manually constructed for specific CWE source-to-sink flows; C samples are synthesized with LLM assistance and undergo consistency checks (Section IV-B).

    Semantic Mislabeling Design

    • Comment-level deception: Without changing code entities and the taint chain, add false security claims related to the CWE in comments or documentation, claiming the vulnerability has been properly handled (Section III-D3).
    • Dual mechanism: During retrieval, false security vocabulary increases semantic similarity between the artifact and security-conscious benign queries; during generation, comments mislead the LLM into treating the artifact as a secure implementation example, reducing model vigilance and inducing reproduction of the vulnerable logic (Section III-D2, III-D3, Figure 4).
  4. What experiments did the paper conduct?

    Evaluated on 10 CWE types across 3 open-source generation models, ASR reaches 0.80–0.93 under no defense and remains 0.40–0.71 under CodeGuarder defense.

    Experimental Setup

    • Models under test: The generation models are Qwen 3.5 9B, Code Llama 13B, and DeepSeek-Coder-V2 16B, a total of 3 open-source models (Section IV-C).
    • Benchmarks and datasets: The benign knowledge base is 12,053 fixed code entries from ReposVul; the poisoning set contains 85 function-level artifacts (65 Java, 20 C), covering 10 CWE types; non-target query evaluation is sampled from 50 tasks in CyberSecEval (Section IV-B, IV-K).
    • Comparison baselines and defenses: The attack comparison baseline is Lin et al. (2026)'s CVE-based poisoning method; defense evaluation includes CodeGuarder security knowledge injection defense and query paraphrasing (Section IV-F, IV-G, IV-I).
    • Metric definitions: Retrieval success rate (RSR, proportion entering final Top-3), attack success rate (ASR, proportion both successfully retrieved and generating the specified vulnerability), target weakness rate (TWR, proportion of outputs containing the weakness regardless of retrieval), and CodeBLEU similarity (Section IV-D).
    • Review method: GLM-5.1 is used as the primary independent review model, judging the main code block according to the per-CWE taint chain rules in Appendix A; the auxiliary validation model is DeepSeek-Coder-V2 16B (Section IV-C, IV-D, Table X).
    • Sample and inference settings: 85 trigger queries, run sequentially on a single GPU; the generator uses greedy decoding (temperature=0), with a maximum output of 8,192 tokens per run, a timeout of 600 seconds, and up to 3 retries (Section IV-C).

    Main Results

    Swipe horizontally to read the table

    Generator ModelNo-Defense ASRCodeGuarder Defense ASRNo-Defense CodeBLEUCodeBLEU under Defense
    Qwen 3.5 9B68/85 (0.80)34/85 (0.40)0.5940.498
    Code Llama 13B79/85 (0.93)60/85 (0.71)0.6230.499
    DeepSeek-Coder-V2 16B68/85 (0.80)51/85 (0.60)0.5890.517

    Note: According to Table III and Table VIII, all 3 tested generators are listed.

    • Generator transferability: The authors state that CodePoisonRAG maintains an ASR above 0.80 for both general and code-specific models under no defense, with Code Llama 13B achieving the highest at 0.93 (Table III).
    • Defense resistance: After CodeGuarder injects security knowledge, the attack success rate decreases but is not eliminated; the code-specific model Code Llama still reaches 0.71, DeepSeek reaches 0.60, and the general model Qwen drops the most to 0.40 (Table III).
    • Generation fidelity: Code similarity results show that generated code has a CodeBLEU of 0.589–0.623 with the poisoning artifact under no defense, and remains around 0.50 under defense; the authors believe the generated code is driven by the retrieved poisoning artifact (Table VIII).

    Comparison with CVE Poisoning Baseline

    • Evaluation content: Compare this method with Lin et al. (2026) on Code Llama 13B across 4 shared CWE types (CWE-22, CWE-78, CWE-79, CWE-89) (Section IV-G).
    • Experimental results: According to Table IV, Lin et al.'s macro-average ASR is 0.67 (per-CWE 0.63–0.73), while CodePoisonRAG achieves 0.97 (CWE-22, CWE-78, CWE-79 at 1.00, CWE-89 at 0.90).
    • Author interpretation: The authors believe that compared to directly using existing CVE vulnerability samples, targeted task alignment and taint chain modification require only a single poisoning artifact per query to achieve stronger attack effects, with a significantly lower poisoning ratio.

    Query Paraphrasing Defense and Non-Target Query Impact

    • Evaluation content: Evaluate dependence on wording by paraphrasing queries while preserving functionality, and assess false retrieval impact on 50 non-target queries sampled from CyberSecEval (Section IV-I, IV-K).
    • Experimental results: After paraphrasing, retrieval success rate remains 85/85, and ASR on Code Llama 13B slightly decreases from 79/85 (0.93) with original queries to 78/85 (0.918, Table V); among 50 non-target queries, the poisoning artifact enters Top-3 in 8/50, triggers attack after entry in 6/8, and total ASR is 6/50 (Section IV-K).
    • Author interpretation: The authors note that the attack does not depend on the specific natural language wording of queries; overall impact on non-target queries is limited, but when functional overlap leads to retrieval, there is still a high probability of inducing vulnerability generation.

    Ablation Study: Contribution of Vulnerability Injection and Semantic Mislabeling

    • Evaluation content: On Code Llama 13B, set two ablation conditions: removing comment deception (only vulnerability injection) and completely removing poisoning (replacing with benign counterparts) (Section IV-L).
    • Experimental results: According to Table VII, after removing comment deception, ASR is 77/85; with no poisoning at all, the target weakness rate (TWR) of generated code is 25/85.
    • Author interpretation: The authors note that vulnerability injection is the main driver of the attack; modifying the taint chain alone can keep the attack fully successful in most categories; the low inherent vulnerability rate of the model without poisoning shows the direct risk posed by knowledge base poisoning.

    Other Ablations and Analyses

    • Runtime overhead: Under no defense, generation consumes an average of 1,238 tokens and 5.2 seconds end-to-end latency; under CodeGuarder defense, it rises to 2,236 tokens and 9.2 seconds, with the main overhead coming from the defense mechanism (Table VI).
    • Benign sample similarity comparison: On Qwen under no defense, the CodeBLEU between generated code and the original benign artifact is 0.169, while with the poisoning artifact it is 0.594 (Section IV-M).
    • Review model comparison: On Qwen generation results, DeepSeek-Coder-V2 16B measures no-defense ASR of 1.00 and defense ASR of 0.612, higher than GLM-5.1's 0.80 and 0.40 (Table IX).

    Anomalies and Difficult Categories

    • Difficult weakness categories: Deserialization (CWE-502) has the lowest ASR across all models, with 5/10 for all three models under no defense (Table III); the authors believe models tend to use typed or safer deserialization alternatives; SQL injection (CWE-89) is 9/10 on Code Llama, and the authors believe prepared statements are more deeply reinforced in code models (Section IV-E).
    • Retrieval and generation exceptions: Under CodeGuarder defense, the only retrieval failure occurs for CWE-79 (9/10 entering Top-3, Table II); under defense, CWE-78 drops to 2/5 on Code Llama (Table III).
  5. What are some points that can be further explored?

    The paper does not dedicate a section to discussing limitations and future directions; experiments cover 3 open-source generation models, 10 CWE types, and CodeGuarder defense.

    Limitations and future directions noted by the authors

    • The paper does not have a dedicated section (e.g., Limitations or Future Work) discussing limitations and future research directions.

    Experimental coverage

    • Generator model scope: The tested generators are Qwen 3.5 9B, Code Llama 13B, and DeepSeek-Coder-V2 16B, a total of 3 open-source models, all deployed locally with Ollama and greedy decoding (Section IV-C).
    • Vulnerability and language coverage: The experiments tested two programming languages, Java (65 artifacts) and C (20 artifacts), covering 10 CWE vulnerability categories, with a total of 85 poisoned artifacts; the benign knowledge base size is 12,053 entries (Section IV-B, Table I).
    • Retrieval architecture settings: Dense retrieval and reranking use jina-embeddings-v3 and jina-reranker-v2-base-multilingual, respectively, retrieving candidates and truncating to Top-3 context (Section IV-C, Section IV-E).
    • Defense mechanism evaluation: Tested CodeGuarder knowledge injection defense and robustness evaluation based on query rewriting, with each condition tested in a single-turn code completion scenario (Section IV-F, Section IV-I).
    • Output evaluation method: Vulnerability determination is mainly automated by GLM-5.1 according to preset taint chain rules; the paper does not report human evaluation results or human agreement (Section IV-C, Section IV-N).
  6. Summarize the main content of the paper

    CodePoisonRAG demonstrates a new attack surface on RACG external knowledge bases, can induce specified vulnerabilities at low poisoning rates, and partially resists defenses.
    • Positioning: CodePoisonRAG is a black-box upstream knowledge poisoning attack study targeting retrieval-augmented code generation (RACG) systems, exploring whether an attacker can use a single task-aligned artifact to induce vulnerable code generation in a targeted manner.
    • Problem: Addressing the issues that existing poisoning attacks rely on non-targeted CVE samples, require multiple sample injections per single query, and cannot freely match tasks with weaknesses, this study investigates the feasibility of targeted implantation of specific CWEs under black-box and low poisoning rates.
    • Method: Select benign task code while preserving signatures and logic, inject vulnerabilities by replacing key sanitization steps with passthrough to form a complete source-to-sink taint chain, then overlay semantically mislabeled false security comments to balance retrieval relevance and generation induction.
    • Main results:
      1. Only 85 artifacts are introduced into a benign library of 12,053 entries (poisoning rate 0.700%), and all artifacts achieve 100% entry into the Top-3 retrieval context across 3 models (Table II).
      2. Under no defense, ASR on Qwen 3.5 9B, Code Llama 13B, and DeepSeek-Coder-V2 16B is 0.80, 0.93, and 0.80, respectively (Table III).
      3. Under the CodeGuarder security knowledge injection defense, ASR for the three models remains at 0.40, 0.71, and 0.60 (Table III).
      4. On the 4 shared CWE types, Code Llama 13B achieves an average ASR of 0.97, higher than the existing CVE poisoning baseline's 0.67 (Table IV).
    • Conclusion and implications: The authors believe that the knowledge base of RACG systems constitutes a critical attack surface, and attackers can achieve targeted vulnerability propagation without accessing the model; existing prompt-time security knowledge injection can mitigate but not eliminate poisoning effects, emphasizing the need for integrity and security verification before retrieved knowledge is adopted.

Related papers

Read originalarxiv.org