Give LLMs a Security Course: Securing Retrieval-Augmented Code Generation via Knowledge Injection

Bo Lin, Shangwen Wang, Yihao Qin, Liqian Chen, Xiaoguang Mao

Introduction: The Vulnerability of RACG

Retrieval-Augmented Code Generation (RACG) has become a cornerstone of modern AI-driven development. By fetching relevant code snippets from external databases, Large Language Models (LLMs) can generate code that is more contextually accurate and aligned with specific project requirements. However, this reliance on external data introduces a significant "blind spot": the prioritization of functional correctness over security.

A critical threat identified in recent research is Knowledge Base Poisoning. If an attacker manages to inject even a single vulnerable code sample into the retrieval database, the LLM is highly likely to mimic that vulnerability in its output. Studies indicate that a single poisoned sample can lead to security flaws in nearly 48% of generated code. Current RACG systems lack a dedicated mechanism to "fact-check" the security of the snippets they retrieve, leaving developers at risk of deploying insecure software.

CodeGuarder: A Framework for Security Injection

To address these risks, the authors propose CodeGuarder, a framework that shifts the RACG paradigm from retrieving only functional examples to incorporating explicit security knowledge. Unlike traditional systems that treat retrieved code as an absolute ground truth, CodeGuarder treats it as a potential source of risk that requires validation against a curated security knowledge base.

The CodeGuarder architecture, featuring offline security knowledge construction and online hardening.

The workflow consists of two main phases:

  1. Offline Construction: The system builds a Security Knowledge Base by analyzing historical vulnerabilities (CVEs). For each entry, it extracts three critical dimensions: the Functionality (what the code does), the Root Cause (why it is insecure), and the Fixing Pattern (how to write it securely).
  2. Online Integration: When a user submits a query, CodeGuarder performs query decomposition, context-aware retrieval, and risk-aware re-ranking. It prioritizes knowledge for vulnerabilities that LLMs are statistically more likely to generate, such as NULL pointer dereferences. The final prompt includes the user query, functional examples, and the curated "security course" (root causes and fixes) to guide the LLM toward a secure implementation.

The Power of Query Decomposition

A core insight of the CodeGuarder framework is that retrieving security knowledge for an entire program is often too noisy and imprecise. Instead, the system uses an LLM to break the user's query into fine-grained sub-tasks. This allows for "surgical" security guidance tailored to specific operations.

Comparison between direct code generation and CodeGuarder's query decomposition approach.

As illustrated above, while direct generation might overlook multiple buffer overflow risks during memory allocation and string copying, the decomposition approach identifies these as separate sub-tasks. By retrieving specific knowledge for each—such as checking length before allocation or using strncpy for safe copying—the model is steered away from common pitfalls.

Key Results and Generalization

The authors evaluated CodeGuarder across four major LLMs: GPT-4o, DeepSeek-V3, CodeLlama-13B, and DeepSeek-Coder-V2. The results demonstrate that security is not a zero-sum game with functionality:

  • Security Improvements: In standard scenarios, the framework improved the Security Rate (SR) by an average of 20.12%. In poisoning scenarios, where the database was intentionally corrupted, the improvement jumped to 31.53%.
  • Functional Maintenance: Providing clear "fixing patterns" actually helped the LLMs understand the tasks better, maintaining or slightly improving functional correctness (Pass@1 scores) across all models.
  • Cross-Language Generalization: The framework demonstrated impressive performance even in languages like Rust, where specific knowledge base entries were sparse. By leveraging universal security principles (like input validation) from other languages, CodeGuarder proved that security knowledge is often transferable across programming paradigms.

Conclusion

CodeGuarder represents a significant step forward in securing AI-assisted programming. By treating security as a first-class citizen in the retrieval process and providing LLMs with a "security course" derived from real-world vulnerabilities, the framework effectively mitigates the risks of knowledge base poisoning and inherent model biases without sacrificing the speed or utility of modern RACG systems.

Summary updated

BibTeX
@inproceedings{lin2025give,
  author = {Bo Lin and Shangwen Wang and Yihao Qin and Liqian Chen and Xiaoguang Mao},
  title = {{Give LLMs a Security Course: Securing Retrieval-Augmented Code Generation via Knowledge Injection}},
  booktitle = {CCS},
  year = {2025},
  doi = {10.1145/3719027.3765049},
}
Figure