arXiv(opens in a new tab)cs.CRSep 2026Cited by 1 paper on PaperVantage

Manuscript Offprint

arXiv:2609.02774

CodePoisonRAG: Knowledge Poisoning Attacks on Retrieval-Augmented Code Generation

Varun Gadey, Ziad Marey, Alexandra Dmitrienko

Varun Gadey*, Ziad Marey*, Alexandra Dmitrienko*

*University of Duisburg-Essen, Germany

Abstract—Retrieval-Augmented Code Generation (RACG) improves LLM-based software development by retrieving external code artifacts, documentation, and patches, and incorporating them into the generation context. This reliance on external knowledge introduces a critical trust boundary: poisoned artifacts can influence generated code without modifying the underlying LLM. Prior work shows that selecting existing vulnerable examples can increase the general vulnerability rate of RACG outputs, but leaves open whether a black-box attacker can construct a single task-matched artifact that propagates an attacker-selected weakness. We introduce CodePoisonRAG, a targeted upstream knowledge-poisoning framework that transforms benign fixed-code entries into poisoned artifacts. Its attack chain combines CWE-specific Vulnerability Injection, which embeds a selected source-to-sink flow while retaining task alignment, with Semantic Mislabeling, which adds false safety claims without repairing the vulnerable behavior. The attacker has no access to the victim's deployed knowledge base, retriever, re-ranker, generator, prompt, or defense mechanism and injects at most one artifact per anticipated programming task. We construct 85 poisoned artifacts covering ten CWE classes across Java and C, yielding an aggregate corpus-poisoning ratio of 0.7%. Across three generators, all 85 artifacts appear among the Top-3 results for their corresponding queries, and CodePoisonRAG achieves attack success rates between 0.80 and 0.93. Against CodeGuarder, which injects vulnerability-specific security knowledge into the generation context, the attack retains success rates between 0.40 and 0.71. These results show that RACG poisoning extends beyond the incidental propagation of existing vulnerabilities to the targeted construction and propagation of attacker-selected weaknesses.

I. INTRODUCTION

As software systems continue to grow in size and complexity, the number of disclosed software vulnerabilities also continues to rise [1]. To reduce the burden of developing, debugging, and fixing software, Large Language Models (LLMs) have been increasingly adopted for software engineering tasks, including automated program repair [2], [3], [4] and code generation [5]. However, LLMs remain prone to hallucination: they may generate code that appears plausible, but is syntactically invalid, semantically incorrect, or disconnected from the intended project context [6].

A recent remedy that has spread widely to mitigate hallucination is Retrieval-Augmented Generation (RAG) [7]. A typical RAG system contains an external knowledge base, a retriever that selects relevant artifacts for a user query, and an LLM generator that uses the retrieved artifacts together with the query to produce the final response. In software development, this paradigm is instantiated as Retrieval-Augmented

Code Generation (RACG), where the retrieved artifacts may include code snippets, documentation, patches, or security knowledge inserted into the generator prompt [8], [9]. RACG was initially introduced to improve the functional correctness of generated code by providing task-relevant code examples during generation [10]. Beyond improving functional correctness through task-relevant code examples [10], RACG has also been explored as a way to counteract insecure code generation by LLMs. At the same time, prior studies show that LLMs can generate vulnerable code under neutral prompts without demonstrations or retrieved examples [11], [12], with one study reporting that 62.07% of generated C programs are vulnerable and that many of these programs contain memory-safety errors, hard-coded secrets, or cryptographic misuses [12]. Consequently, recent RACG systems have also been adopted for security-oriented tasks, including secure code generation [13], [14] and vulnerability repair [2], where essential security knowledge can be retrieved on the fly for each user query and injected into the prompt.

However, this reliance on retrieved knowledge introduces a new security boundary: the generated code now depends not only on the LLM, but also on the integrity of the external knowledge base. Since retrieved artifacts substantially guide the model's output in the underlying tasks, a compromised knowledge base can silently influence the generated code even when the underlying LLM is unchanged. This shifts the attack vector from the model to the external retrieval corpus: an attacker does not need to train, fine-tune, or directly manipulate the victim LLM, but can instead poison the external artifacts that the RACG pipeline is designed to trust. The risk is practical because developers and data curators often construct RACG knowledge bases from public code repositories, public datasets, and curated code resources under the assumption that these sources are benign [8], [15], [13]. If such resources are poisoned upstream, vulnerable artifacts may enter the trusted retrieval corpus and later influence the generated code.

Related Work. Recent work has begun to expose security risks arising from the external knowledge used by retrieval-augmented code generation systems. ImportSnare [16] demonstrates that an attacker can poison retrieved documentation to promote attacker-controlled imports, thereby turning the RACG retrieval mechanism into a software-supply-chain attack vector. Moving from dependency manipulation to implementation-level vulnerabilities, Lin et al. [17] provide the first direct investigation of vulnerable-code knowledge poisoning in RACG systems. By selecting existing vulnerable examples from a CVE-derived corpus and injecting them into the knowledge base, they show that vulnerable retrieval context can substantially increase the vulnerability rate of generated code.

Gaps. These studies establish the feasibility of poisoning RACG knowledge, but leave open how a purposeful attacker can construct the particular code artifact needed to realize an attack objective. ImportSnare [16] targets the selection of an attacker-controlled dependency rather than a weakness embedded in the generated implementation. Lin et al. [17] select from vulnerabilities already available in a CVE-derived corpus, whose functionality, language, APIs, and weakness class are fixed by the original vulnerable projects. Such an example may increase the general likelihood of insecure generation, yet remain poorly matched to the programming task the attacker expects the victim to request. For example, an existing path-traversal sample from an archive-extraction function may be ineffective against a query for a log-file download endpoint: Despite sharing the same CWE, the mismatch in functionality and implementation structure may reduce retrieval relevance or the likelihood that the vulnerable pattern is reproduced. Moreover, selecting an available vulnerable example does not allow the attacker to choose both the target functionality and the weakness that should propagate into the generated code.

Our Contribution. To address this gap, we introduce CodePoisonRAG, a targeted black-box knowledge-poisoning framework that constructs task-aligned poisoned artifacts rather than selecting them opportunistically from an existing vulnerability corpus. Given a benign fixed-code entry representing an anticipated programming task, CodePoisonRAG introduces an attacker-selected CWE by modifying its source-to-sink flow while retaining the function's task, structure, and surrounding context. This construction gives each poisoned artifact a dual purpose: It must remain sufficiently relevant to enter the retrieved context and must carry the selected vulnerable behavior into generation. CodePoisonRAG further applies comment-level deception that presents the modified implementation as security-conscious without repairing the vulnerable flow. The resulting attack therefore moves beyond measuring increases in general vulnerability rates and targets the propagation of an attacker-selected weakness through code that continues to satisfy the victim's benign programming request.

In more detail, we make the following contributions:

• Attack Formulation. We formulate targeted upstream knowledge poisoning against RACG under a black-box attacker who has no access to the victim's deployed knowledge base, retriever, re-ranker, generator, prompt template, or defense mechanism. For each anticipated programming task, the attacker selects a target CWE and injects at most one corresponding poisoned artifact into an external code corpus. The attack has an end-to-end objective: the artifact must be retrieved for a benign pro-

gramming request and subsequently induce functionally plausible generated code containing the attacker-selected weakness.

• Attack Chain. We introduce a code-specific poisoning chain comprising Vulnerability Injection and Semantic Mislabeling. Vulnerability Injection modifies the source-passthrough-sink flow of a benign fixed-code entry to introduce a selected CWE while preserving syntactic validity and alignment with the original programming task. Semantic Mislabeling then adds CWE-specific false safety claims to the comments or documentation without repairing the vulnerable flow, presenting the poisoned artifact as security-conscious implementation guidance.

• Poisoning Dataset. We construct a code-poisoning dataset containing 85 task-aligned artifacts across ten CWE classes in Java and C, primarily drawn from the MITRE CWE Top 25 [18]. When combined with the 12,053-entry benign retrieval corpus, the artifacts produce an aggregate poisoning ratio of 0.7%. We will release the dataset and its CWE-specific construction metadata upon acceptance to support reproducibility and future research on RACG poisoning and defenses.

• Attack Effectiveness. We evaluate CodePoisonRAG across ten CWE classes in Java and C using three generator models. Under the undefended RACG setting, all 85 poisoned artifacts appear among the Top-3 retrieved results for their corresponding queries, and CodePoisonRAG achieves ASRs ranging from 0.80 to 0.93 across generators. These results are obtained using only one poisoned artifact per target query, with an aggregate corpus-poisoning ratio of 0.7% and per-CWE footprints between 0.041% and 0.082%.

• Defense Robustness. We evaluate CodePoisonRAG against CodeGuarder [14], a secure-code-generation framework that retrieves vulnerability-specific security knowledge and injects it into the generator prompt to steer the LLM toward safer implementations. Although this additional security guidance reduces attack success, CodePoisonRAG retains ASRs ranging from 0.40 to 0.71 across the three generators, reaching a best defended ASR of 0.71 on Code Llama. These findings show that security-oriented knowledge injection mitigates, but does not eliminate, the influence of poisoned code artifacts.

Overall, to the best of our knowledge, this work is the first to formulate and systematically investigate the following research question: Can a black-box attacker transform benign, task-matched code into a single retrievable poison that causes an RACG system to reproduce an attacker-chosen CWE while preserving the requested functionality? Our findings answer this question in the affirmative. They show that RACG poisoning extends beyond the incidental propagation of vulnerabilities already present in a corpus: an attacker can deliberately construct an artifact that jointly satisfies the retrieval objective and the targeted vulnerability-generation objective, even without access to the victim RACG pipeline.

Outline. The remainder of this paper is organized as follows. Section II introduces the background on RACG. Section III presents the threat model, formalizes the attack, and describes the design of CodePoisonRAG and its multi-stage poisoning attack chain. Section IV presents the experimental setup and evaluation results across undefended and defended RACG pipelines. Section V discusses related work. Finally, Section VI concludes the paper.

References (55)