Large Language Models (LLMs) can generate functionally correct code while introducing exploitable security weaknesses, particularly when developers specify functionality without explicit security requirements. Recent state-of-the-art approaches mitigate this problem using external security knowledge, but largely rely on flat similarity-based retrieval over independent artifacts, making it difficult to infer the relevant vulnerability space and retrieve targeted knowledge when direct matches are unavailable. We propose SEEK, an agentic Graph RAG framework for secure code generation that constructs a security knowledge graph using the Common Weakness Enumeration (CWE) taxonomy as its structural backbone and injects it with curated real-world CVE vulnerability-fix instances. At inference time, a Planner Agent predicts potential CWE weaknesses associated with the developer query, which guide Graph Scoping to restrict retrieval to relevant regions of the CWE taxonomy before deterministic multi-faceted candidate ranking. A Selection Agent subsequently validates the predicted weaknesses and retrieved candidates prior to code generation. Across five open-source LLMs, we evaluate SEEK in an out-of-distribution setting on CodeGuard+ and CyberSecEval, spanning C, C++, and Python. SEEK achieves the highest SecurePass@1 of 77.45% on CodeGuard+ and the highest aggregate ICD pass rate of 79.45% on CyberSecEval, surpassing prior approaches. Moreover, SEEK achieves 85.2% SecurePass@1 across 13 unseen CWE types with no directly linked vulnerability-fix instances, demonstrating strong generalizability, while maintaining acceptable inference latency costs.
Figures & tables
Figure 1: Abstraction levels in the CWE taxonomy.
1
int main( int argc, char *argv[]) {
2
// get a directory name from the command line
3
char *dirname = argv[1];
4
// list the contents of that directory using "ls"
// command line utility
5
// print the contents of the directory
6
char cmd[256] = {0};
Figure 2: A benign CodeGuard+ [ 27 ] prompt and the corresponding zero-shot response by Gemma 4 31B [ 29 ]
Figure 3: Overview of SEEK ’s two-stage workflow. ① Offline Stage constructs the security knowledge graph by organizing the CWE taxonomy as the graph backbone and populating it with curated CVE instances containing root cause, vulnerable code, fixing pattern, and fixed code. ② Online Stage uses agentic planning to identify potential weaknesses, scopes retrieval to relevant regions of the knowledge graph, retrieves and selects targeted security knowledge, and augments the LLM generator for secure code generation. Color schema: Gray → Data, Blue → Agents, Yellow → prompts, Orange → LLM, Green → secure code.
Figure 4: Illustrative CWE-74 subgraph of SEEK . For clarity, only ChildOf relations among CWE nodes and a subset of Demonstrates links to curated CVE instances are shown; Color schema: Blue → CWE’s, Orange → CVE’s
Generator Model
Method
Pass@1
SecurePass@1
Secure Rate
Secure@Pass1
Gemma4-31B
Zero-Shot
93.617
64.681
68.936
64.481
SEEK
89.574
77.447
85.532
79.574
Gemma3-27B
Zero-Shot
83.830
55.532
65.319
56.809
SEEK
81.064
62.979
72.128
67.021
Qwen2.5-Coder-32B
Zero-Shot
85.106
61.277
68.723
61.702
SEEK
81.702
69.574
82.979
74.681
Table 1: Secure code generation performance of SEEK on CodeGuard+
Method
Generator
SP@1
SR
Pass@1
Same Generator: Qwen2.5-Coder-32B
Zero-shot
Qwen2.5-C-32B
61.2
68.7
85.1
SecCoder
Qwen2.5-C-32B
58.1
66.6
84.7
Codexity
Qwen2.5-C-32B
57.1
71.6
80.7
INDICT
Qwen2.5-C-32B
40.4
84.4
48.1
CoSec
Qwen2.5-C-32B
41.9
54.9
65.1
Table 2: Benchmark Comparison on CodeGuard+. Prior-work results are reported by RESCUE [ 55 ] .
CWE
Weakness
# Tasks
SP@1
CWE-95 [ 22 ]
Eval Injection
1
100.0
CWE-113 [ 5 ]
HTTP Request/Response Splitting
2
50.0
CWE-117 [ 6 ]
Log Output Neutralization
3
60.0
CWE-170 [ 7 ]
Improper Null Termination
1
100.0
CWE-215 [ 8 ]
Sensitive Information in Debugging Code
1
100.0
CWE-312 [ 10 ]
Cleartext Storage of Sensitive Information
1
100.0
Table 3: SEEK ’s Generalization to Unseen CWEs
Method
C
C++
Python
Avg.
SVEN [ 30 ]
60.35
70.27
74.93
68.52
SafeCoder [ 31 ]
63.00
75.29
78.63
72.31
CoSec [ 39 ]
59.91
70.66
76.64
69.07
SoSecure [ 47 ]
52.86
73.36
71.79
66.00
RCI [ 61 ]
55.51
75.29
76.64
69.15
CodeGuarder [ 40 ]
70.48
83.40
84.33
79.40
Table 4: ICD pass rate comparison on CyberSecEval. Prior-work results are reported by CodeGuarder [ 40 ]
Generator
Planner
Retrieval
Selector
Generation
Gemma4-31B
10.00
0.227
8.53
13.65
Gemma3-27B
12.39
0.010
1.98
7.64
Table 5: Runtime in (seconds) of the SEEK
Configuration
Pass@1
SP@1
SR
S@P1
Flat RAG
86.809
73.404
83.457
77.074
Graph Scoping Only
88.085
75.957
85.532
79.362
Selection Agent Only
86.596
73.830
84.043
76.809
SEEK
89.574
77.447
85.532
79.574
Table 6: Component-level Ablation study on SEEK
Retrieval Facets (Weight)
Pass@1
SP@1
SR
S@P1
Root Cause (RC) only
84.255
73.830
87.447
77.447
Vul. Code (VC) only
89.574
76.596
84.468
79.574
RC (0.75), VC (0.25)
85.532
72.766
85.106
75.532
RC (0.50), VC (0.50)
85.106
72.553
84.468
77.447
RC (0.25), VC (0.75)
89.574
77.447
85.532
79.574
Table 7: Facet-level Ablation study on SEEK
Figure 5: Prompt template for the LLM Curator: facet derivation.
Figure 6: Prompt template for the LLM Curator: curation rules, inputs, and output format.
Figure 7: Prompt template for the Planner Agent.
Figure 8: Prompt template for the Selection Agent: prediction validation and feedback.
Figure 9: Prompt template for the Selection Agent: candidate filtering and output format.
Large Language Models (LLMs) can generate functionally correct code that remains insecure. Security-focused fine-tuning can be expensive and is not always available, motivating inference-time approaches. Security-oriented prompting and retrieval can reduce vulnerabilities, but may also remove required behavior or apply defenses incompatible with the task. The challenge is to identify relevant security knowledge and use it to improve security without sacrificing functionality. We present SecGent, an inference-time framework that retrieves weakness context from the Common Weakness Enumeration (CWE) database and applies it to secure code generation. By connecting task specifications to relevant textual CWE records, SecGent provides task-specific security guidance without relying on retrieved vulnerable or patched code examples. Complementary functional and security tests check the resulting implementation, and their execution feedback guides repairs toward satisfying both objectives. We evaluate SecGent with four open-source LLMs and Claude Sonnet 5.5 across five programming languages on the CWEval benchmark. It achieves the highest joint functional--security success against four inference-time baselines for all five models. Across the open-weight models, mean functional-security@1 (FS@1) improves by 15.5% over RAG, with gains in both functionality and security, and by 19.8% over the strongest prompt optimizer compiled for each model. On Sonnet, FS@1 reaches 92.1%, outperforming the strongest baseline AutoGen by 4.8%. In a separate comparison, SecGent outperforms Claude Code with security-focused prompting by over 6% in FS@1. Feedback-guided repair further improves FS@1 by up to 6.7% over generation without feedback, primarily by recovering functionality while checking security.
Md Afif Al Mamun, Gias Uddin
University of Calgary, Calgary, Canada · York University, Toronto, Canada
Large language models (LLMs) are increasingly used for program synthesis, yet they often generate code that is functionally plausible but insecure. Progress in secure code generation has been hindered by benchmarks that are small, non-executable, leak mitigation details, or rely on noisy analyzers and subjective judgments, making it difficult to measure whether security improves without sacrificing correctness. We address these gaps with CodeSecEval, an execution-based benchmark for secure code generation, comprising 255 Python tasks spanning 77 CWE categories. Each task provides paired insecure and secure implementations together with executable functional and vulnerability-targeted security tests, enabling precise and reproducible evaluation of secure code generation and insecure-code repair. Building on CodeSecEval, we propose SecAwareCoder, an agent-based framework that shifts code generation toward secure-by-construction synthesis. SecAwareCoder performs task-adaptive threat modeling to identify security-sensitive regions and derive task-grounded vulnerability hypotheses, uses these hypotheses to guide both constraint-aware code generation and security-aware test synthesis, and leverages execution feedback for targeted refinement. Experiments across multiple LLM backbones show that SecAwareCoder consistently improves Pass@1 and security robustness over prompting and analyzer-driven baselines, narrowing the security--correctness gap in LLM code generation.
Jiexin Wang, Liuwen Cao, Xitong Luo +6
South China University of Technology, Guangzhou, China · University of Innsbruck, Innsbruck, Austria
Large Language Models (LLMs) for code generation can replicate insecure patterns from their training data. To mitigate this, a common strategy for security hardening is to fine-tune models using supervision derived from the final transformer layer. However, this design may suffer from a final-layer bottleneck: vulnerability-discriminative cues can be distributed across layers and become less detectable near the output representations optimized for next-token prediction. To diagnose this issue, we perform layer-wise linear probing. We observe that vulnerability-related signals are most detectable in a band of intermediate-to-upper layers yet attenuate toward the final layers. Motivated by this observation, we introduce DeepGuard, a framework that leverages distributed security-relevant cues by aggregating representations from multiple upper layers via an attention-based module. The aggregated signal powers a dedicated security analyzer within a multi-objective training objective that balances security enhancement and functional correctness, and further supports a lightweight inference-time steering strategy. Extensive experiments across five code LLMs demonstrate that DeepGuard improves the secure-and-correct generation rate by an average of 11.9% over strong baselines such as SVEN. It also preserves functional correctness while exhibiting generalization to held-out vulnerability types. Our code is public at https://github.com/unknownhl/DeepGuard.
Li Huang, Zhongxin Liu, Yifan Wu +6
Chongqing University · The State Key Laboratory of Blockchain and Data Security, Zhejiang University · Peking University