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

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

TL;DR

Retrieval-Augmented Code Generation (RACG) helps Large Language Models (LLMs) write functionally correct code by fetching external examples, but it leaves them dangerously exposed to security flaws and malicious knowledge base poisoning. This paper introduces CodeGuarder, a framework that injects curated security knowledge (vulnerability root causes and secure fixing patterns) directly into LLM prompts. By decomposing queries into sub-tasks and filtering them based on empirical risk, CodeGuarder significantly boosts code security across multiple models and languages without sacrificing functional correctness.

What Problem Does This Paper Address?

RACG systems are becoming indispensable developer assistants, streamlining software engineering by retrieving relevant code snippets from external repositories to guide LLMs. However, these systems prioritize functional correctness while completely ignoring security.

If an external knowledge base contains insecure code—or worse, is deliberately "poisoned" by an attacker—the LLM will blindly replicate those vulnerabilities. Prior research shows that even a single poisoned sample in a retrieval database can cause an LLM to generate vulnerable code nearly half the time. While existing defenses try to patch standalone LLMs via fine-tuning or decoding constraints, they fail to address the unique security risks introduced by dynamically fetched external context in RACG pipelines.

Methods

CodeGuarder shifts the RACG paradigm from retrieving only functional code examples to incorporating both functional code and explicit security knowledge. The framework operates in two main phases:

1. Automated Offline Construction

CodeGuarder builds a Security Knowledge Base ($S$) by processing historical data from Common Vulnerabilities and Exposures (CVE) instances. For each vulnerability, it uses an LLM backend to extract a three-dimensional representation:

  • Functionality: A description of what the code is intended to do (bridging the semantic gap between user queries and vulnerability descriptions).
  • Root Cause: A natural language explanation and a code example showing why the vulnerability occurs.
  • Fixing Pattern: A description and example of the secure, corrected code.

2. Online Code Security Hardening

When a user submits a code generation query, CodeGuarder executes a context-aware, fine-grained retrieval process:

[User Query] ➔ [Query Decomposition] ➔ [Knowledge Retrieval] ➔ [Re-ranking & Filtering] ➔ [Security-Augmented Prompt]
  • Query Decomposition: Complex programming tasks often contain multiple sub-tasks, each susceptible to different bugs. CodeGuarder uses the LLM to break the user query down into fine-grained semantic sub-tasks.
  • Knowledge Retrieval: It computes cosine similarities between the sub-task embeddings and the entries in the Security Knowledge Base to pull relevant security rules.
  • Re-ranking and Filtering: To prevent prompt bloat and attention dilution ("lost in the middle" effects), CodeGuarder weights sub-tasks based on empirical data of how susceptible LLMs are to specific vulnerability types (e.g., prioritizing high-risk areas like memory allocation or pointer dereferences). It filters the context down to the top-$k$ highest-risk sub-tasks.
  • Prompt Injection: The selected security knowledge is seamlessly woven into the generation prompt alongside standard functional examples, guiding the LLM to choose secure APIs (e.g., swapping sprintf for snprintf).
Figure 2: The overall workflow of CodeGuarder

Datasets

The authors evaluated CodeGuarder using several prominent datasets:

  • ReposVul: The largest cross-language dataset of real-world vulnerabilities, used to construct the Security Knowledge Base ($S$) and a clean Functional Code Base ($K$).
  • CyberSecEval: The primary security evaluation benchmark (developed by Meta), containing 1,916 instances across 50 CWE types. It features a specialized insecure code detector built on static analysis rules (Semgrep, Weggli) with 96% precision.
  • MBPP & HumanEval: Standard Python code generation benchmarks used to verify that adding security constraints does not degrade functional correctness.

Key Insights and Ideas

  • Bridging the Semantic Gap: Traditional vulnerability databases describe bugs, but developers query for features. By rewriting CVE data to focus on the intended functionality of the vulnerable code, CodeGuarder allows standard retrievers to accurately match security advice to user intents.
  • Divide and Conquer via Decomposition: A single code block can harbor multiple distinct vulnerabilities at different locations. Breaking a query into sub-tasks allows CodeGuarder to pinpoint specific security advice for specific lines of code.
Figure 3: Vulnerable code generated by GPT-4o along with its corresponding decomposed queries and retrieved knowledge.
  • Empirical Risk Prioritization: Instead of treating all security rules equally, CodeGuarder leverages historical data on what LLMs are naturally bad at. By focusing prompt real estate on high-prevalence errors (like NULL pointer dereferences), it maximizes defense efficiency within strict context window limits.

Key Results

The authors evaluated CodeGuarder across four mainstream LLMs (GPT-4o, DeepSeek-V3, CodeLlama-13B, and DeepSeek-Coder-V2-16B) and achieved impressive results:

  • Standard RACG Scenarios: CodeGuarder increased the security rate of generated code by an average of 20.12% across all models and languages, with Java seeing the highest leap (up to 80.65% improvement for DeepSeek-V3).
  • Resilience to Poisoning Attacks: In adversarial environments where the functional database was poisoned with malicious snippets, CodeGuarder improved security rates by 31.53% (under intent-exposed targeting) and 21.91% (under intent-agnostic poisoning).
  • Cross-Language Generalization: When tested on languages completely missing from its security database (such as Rust or C#), CodeGuarder still improved security by an average of 15.69%, proving it successfully leverages universal security principles.
  • Functionality Preservation: Evaluation on MBPP and HumanEval confirmed that CodeGuarder does not compromise code utility; in fact, functional correctness metrics slightly improved due to the clearer structural guidance provided by query decomposition.

Limitations and Future Work

Despite its strong performance, CodeGuarder has a few limitations:

  • Context-Specific Gaps: The framework showed lower prevention rates for specific vulnerabilities like CWE-79 (Cross-Site Scripting) in JavaScript, primarily due to a lack of language-specific examples in the underlying vulnerability dataset.
  • Static Analysis Constraints: The evaluation relies heavily on static analysis tools within CyberSecEval, which may not perfectly capture complex, multi-file, or runtime-dependent security flaws.

Future Work: The authors plan to enrich the diversity of the security knowledge base to cover niche languages and complex web vulnerabilities, while exploring more dynamic validation methods for LLM-generated code.

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