SecureForge discovers and reduces vulnerabilities in LLM-generated code through prompt optimizationSecureForge: Finding and Preventing Vulnerabilities in LLM-Generated Code via Prompt Optimization
The authors use SecureForge to optimize system prompts, claim vulnerability rate reduced by up to 48% on frontier models, and transfer zero-shot to SWE-chat.
The victim system is code generated by LLM coding agents during benign coding that may be delivered. The paper does not portray users as adversarial attackers. Defense requires only a static analyzer and the target model's API, no weight updates. Success is measured by whether Semgrep detects CWE weaknesses and whether pytest passes.
- LLM coding agents under benign use still write code that passes tests but contains statically verifiable weaknesses. Even when asked to write secure production code and given the relevant CWE, the authors report that frontier models on average still produce verifiable vulnerabilities in 23% of 250 benign prompts.
- SecureForge has three steps: generate and filter benign prompts from CWE that can trigger Semgrep failures; amplify the failure distribution with Metropolis-Hastings MCMC; then use GEPA to optimize system prompts with static analysis as the signal, used at inference time without updating weights.
- On held-out CWE scenarios, the authors state that the weakness rate drops by up to 48%, the test pass rate is essentially unchanged, and they state that the joint improvement of safety and passing tests on frontier models is statistically significant. The system prompt transfers zero-shot to SWE-chat, with the joint rate improving by up to 13.5%.
- The authors write in Section 7: after changing models, the original system prompt may not remain safe; the one-time optimization cost averages $150 (50M tokens); only Python single-turn is evaluated, and they call the results a lower bound on failure rate. Experiments include 10 models, CWE Top 25, and 203 SWE-chat items.
- Evaluated models
- Qwen 2.5 Coder 7BQwen 2.5 Coder 14BQwen3 30B-A3BCodeLlama 7BKimi K2GPT 5.4-nanoGPT 5.4-miniGPT 5.4GPT 5.3-codexClaude Sonnet 4.6
- Benchmarks
- MITRE CWE Top 25Semgrep Community Python ruleset250 held-out benign promptsSWE-chat
- Metrics
- P(vulnerable)P(tests pass)P(vulnerable | tests pass)P(secure, tests pass)95% Beta-posterior credible interval
SecureForge is an automated pipeline to audit code security risks of frontier models and generate audited, optimized secure system prompts that reduce security vulnerabilities in output code while maintaining unit test pass rates. Researchers found on 250 benign coding prompts that even when explicitly asked to write secure production code and given weaknesses to avoid, frontier models still produce verifiable vulnerabilities with an average probability of 23%. SecureForge first filters benign prompts that produce statically detectable vulnerabilities, then amplifies them with Markov sampling into a large-scale synthetic prompt corpus covering diverse scenarios to balance error rate and prompt diversity, then iteratively optimizes the system prompt. On frontier models, the method achieves statistically significant Pareto improvements in unit test success rate and output safety, reducing output vulnerabilities by up to 48%, and the optimized system prompt transfers zero-shot to real coding agent prompts without having seen the real user prompt distribution during optimization.
Paper analysis
What problem does this paper attempt to solve?
Benign coding can also cause models to write code with detectable weaknesses that still pass tests; SecureForge optimizes system prompts at inference time.
Under benign use, LLM coding agents still write code that contains statically verifiable weaknesses yet passes tests.
- Scenario: The authors state that coding agents write code at scale, and vulnerable implementations enter codebases without human intervention. Code passes tests, looks correct, and is delivered, thus bypassing existing defenses. Adversarial tools exploiting these weaknesses are also getting stronger.
- Gap: The authors state that common evaluations only check whether the model can write working code, or whether it can first execute malicious commands. Adversarial threat models do not match typical benign interactions; hand-crafted scenarios for specific CWEs are insufficient to characterize or defend against all benign prompts. Fine-tuning hardening requires white-box weights and may harm coding ability due to distribution shift, and is unavailable for closed-source APIs.
- Observation: Even when asked to write production-grade secure code and given the CWE to be tested in the prompt, the authors report that 23% of outputs still contain statically verifiable weaknesses, and 12.7% are both vulnerable and pass unit tests. The abstract writes 23% as frontier models, 250 benign prompts, and the context giving the weaknesses to avoid.
- Proposal: Propose SecureForge. It uses static analysis to audit benign failures, then optimizes system prompts at inference time without updating weights. The authors state that the resulting prompts transfer zero-shot to real coding agent prompts, without seeing the real user prompt distribution during optimization.
- Threat model:
- Victim system: Code generated by open-source and frontier LLM coding agents on benign tasks, and potentially delivered.
- Trigger: The paper does not write the user as an adversarial attacker; the risk comes from ordinary coding requests.
- Defender capability: Only needs a static analyzer like Semgrep and the tested model API, no weight access.
- Judgment: After removing non-code markers, run Semgrep on each independent file; a hit counts as a weakness and is mapped to a CWE; also use pytest to see if functionality passes.
What related research exists?
Related work covers red teaming, failure distribution sampling, and white-box hardening; the authors position this paper as inference-time hardening on APIs.
The authors locate gaps by red teaming, sampling failure distributions, and security hardening, and argue that there is a lack of inference-time hardening that requires only API access.
Automated LLM red teaming
- Search-based red teaming: Zou et al. (2023) perform discrete token search; Wichers et al. (2024) use gradient-based red teaming. The paper only describes the methods.
- Model-versus-model: Perez et al. (2022) use actor-critic, with language models red teaming language models.
- Likelihood comparison: Hardy et al. (2025) use likelihood-weighted contrastive learning in ASTPrompter to generate low-perplexity unsafe prompts. The authors state that this paper follows its likelihood information but uses guided falsification instead, without proxy model optimization.
Agent and code red teaming
- Additional channels: Andriushchenko et al. (2025) AgentHarm, Ruan et al. (2024) use synthetic tool calls; Debenedetti et al. (2024) AgentDojo and Chen et al. (2024) AgentPoison study prompt injection or memory/knowledge base poisoning.
- Amplifying failures: Hajipour et al. (2023) CodeLMSec, Jenko et al. (2025) use prompt optimization for black-box code completion attacks; Guo et al. (2024) RedCode includes rejection sampling. The paper describes these techniques without criticizing each one.
- Static observation: Pearce et al. (2025), Majdinasab et al. (2024), Bhatt et al. (2023), and Wan et al. (2024) CyberSecEval use static analysis to expose code security failures. The authors state that this paper also uses static analysis as a passive reward and uses MCMC to cover the failure distribution.
Failure distributions without closed-form density
- Available sampling: Rejection sampling (Forsythe, 1972) and Metropolis-Hastings MCMC (Metropolis et al., 1953; Hastings, 1970). This paper uses the latter.
- Unavailable terms: Grenander and Miller (1994) Langevin algorithm relies on the gradient of the failure density. The authors state that there is no differentiable failure density here, so it is not used.
Code model hardening and baselines
- White-box hardening: He and Vechev (2023) do prefix tuning; He et al. (2024) do safe code instruction fine-tuning. The introduction groups these with the next item: they require white-box access and have distribution shift risk.
- PROSEC: Xu et al. (2025) directly target synthetic CWE scenarios, but with iterative prompting plus fine-tuning. The authors state that this loop is expensive, and modifying the initial prompt pushes the model out of distribution, with risk of task degradation.
- Baselines and data: Experimental baselines are direct code writing, Secure (production-grade and security-designed), and CWE (attaching the tested CWE on top of Secure). The appendix also compares with Mipro (Opsahl-Ong et al., 2024). Data comes from the MITRE CWE Top 25, Semgrep Python rules, Pearce et al.'s human prompts (as few-shot), and SWE-chat.
The authors position this paper as: using observation- and probability-guided paraphrasing to obtain failure prompts, then using prompt optimization for inference-time hardening, avoiding weight updates and the associated distribution shift; requiring only static analysis ground truth, no human annotation.
How does the paper address this problem?
SecureForge uses falsification, MCMC amplification, and GEPA to optimize system prompts, reducing Semgrep-detectable CWEs at inference time.
SecureForge first finds benign prompts that trigger static weaknesses, then uses MCMC to amplify the failure distribution, and finally optimizes an inference-time system prompt without changing weights.
Problem setup
- Failure rate: For weakness Fj, the set of prompts that trigger it X^(j), and a fixed coding prompt I, estimate the probability that model θ produces a static-analysis-failing trajectory. The authors write pθ(τfail∣ I,Fj):=ℙx∈ X(j)pθ(τfail∣ I,x), i.e., the probability of a failing trajectory on these prompts.
- Objective: A system prompt I′ such that the failure probability on each Fj is much smaller than with the original prompt I. θ remains unchanged. The pipeline has three steps: falsification, amplification, and optimization.
Single falsification
- Generate scenarios from CWE: For each specified CWE, expand MITRE examples into non-malicious coding tasks using the same library; few-shot comes from Pearce et al.'s human prompts. ExtractScenarios in Appendix I gives the full prompt.
- Filter to benign: Rewrite again, removing explicit attack or vulnerability mentions, adding production-grade phrasing, and filtering out CWE names and title hot words. StripVulnerability and SuggestLibraries in Appendix I give the full prompts.
- Keep only failures: The tested model responds at temperature 1.0, and only prompts that Semgrep judges as failures are kept as seeds for that Fj.
MCMC amplification
- Why MH: The target is the conditional failure distribution, but the normalization term is unavailable, so Metropolis-Hastings is used. The unnormalized density is the failure probability times the probability that the user inputs that prompt.
- Estimation: Assume unconditioned fluent user prompts are equally likely. The failure probability is estimated using the tested model with multiple rollouts at temperature 1.0, fitting a Beta; failure and success counts are the two parameters, and the expectation is taken after the posterior variance falls below a threshold. The experiment sets this threshold to 0.015.
- Proposal kernel: Use a language model paraphrase as a local kernel, and assume kernel symmetry to make the iteration computable. The authors state that each new prompt is sampled from the previous hop, rather than paraphrasing from a fixed seed, thus better maintaining diversity. Appendix I.3 gives the full prompt for this kernel.
- Scale: Each seed first does 3 burn-in steps, then samples 32 steps. The paper writes the optimization corpus as 80,000 prompts; Figure 2 also marks N=80,000.
Prompt optimization
- Hard negative set: Concatenate the amplified prompts for each weakness into P, as a set of high-failure-probability benign tasks customized for that model.
- GEPA: Starting from a generic system prompt, use the zeroth-order genetic algorithm GEPA for self-reflection. The fitness is the sum of failure probabilities on P, i.e., I∗=argminI∑j∑x∈ Pjpfail(τfail∣ I,x;θ). Trajectories are sampled according to θ, I, and x, and failures are determined by static analysis.
- Implementation: light preset with n=6, Pareto selection, reflection minibatch of 3, merge enabled. The reflection model is gpt-5.4 at temperature 1.0; target rollout temperature 1.0, token budget 32,768. The reward is Semgrep's ±1, with CWE criticism attached; GEPA can see the output, detected CWEs, and line numbers. Templates use DSPy. Appendix I.6 gives the full reflection feedback.
- Deployment: The resulting system prompt is used at inference time, without updating weights.
What experiments did the paper conduct?
On held-out scenarios, the authors claim weakness rate reduced by up to 48%; Figure 8 aggregate vulnerability rate from 23% to 15%, pass-tests-and-vulnerable from 12.7% to 7.3%.
Experimental Setup
- Models under test: instruction-tuned Qwen 2.5 Coder 7B, 14B, Qwen3 30B-A3B MoE, CodeLlama 7B, Kimi K2; and GPT 5.4-nano, GPT 5.4-mini, GPT 5.4, GPT 5.3-codex, Claude Sonnet 4.6. 10 in total. Temperature 1.0, max 32,768 tokens, left-truncated. Figure 5 legend writes K2.6, Qwen 35B, QwenCoder 7B/14B; the paper does not state whether these are abbreviations for the above models.
- Split: CWE Top 25 each with 20 scenarios that can produce weaknesses, totaling 500 prompts, 5,000 seed rollouts. 10 scenarios used for MCMC and tuning, 10 held out. Held-out scenarios come from non-overlapping seed CWE examples.
- Evaluation set: in-distribution 250 held-out prompts, 2,500 samples (25 CWEs × 10 scenarios × 10 rollouts). Out-of-distribution is SWE-chat: multi-turn compressed to single-turn by Claude Sonnet 4.6, only user side and a small amount of prior agent context, not the solution; after filtering Python, 203 items, each manually verified for intent.
- Baselines: direct code writing; Secure (production-grade and security design); CWE (attaching the tested CWE on top of Secure). Appendix additionally compares Mipro, and MCMC against simple paraphrase.
- Metrics: P(vulnerable) is Beta posterior expectation, rollout until posterior variance <0.015,并报95% Beta后验可信区间。单元测试由未点名的语言模型生成pytest,并提供给编码模型;人工检查50个。论文未保证测试穷尽实现质量,测试在同一场景的各次rollout中保持不变。
- 未写明项:论文未报告证伪阶段生成种子提示的模型名,也未报告生成单元测试的模型名。GEPA反思用gpt-5.4,即被测模型之一。
主结果
Figure 8是全部被测模型、干预扫描的聚合混淆矩阵。列名是Secure与SecureForge,不是直接写代码基线。
| 指标 | Secure聚合 | SecureForge聚合 | 出处 | | 脆弱占比 | 23%(5678) | 15%(3471) | Figure 8 | | 过测且脆弱 | 12.7%(3133) | 7.3%(1683) | Figure 8 | | 过测且安全 | 50.2%(12425) | 54.7%(12570) | Figure 8 | | 安全占比 | 77%(19082) | 85%(19529) | Figure 8 | | 测试通过 | 63%(15558) | 62%(14253) | Figure 8 | | 测试失败 | 37%(9202) | 38%(8747) | Figure 8 |
- 作者对降幅的说法:作者称全部模型弱点率下降最多48%,并称该下降具有统计显著性;测试通过率基本不变,且有的模型上升。48%对应Figure 4。文本抽取中Figure 4各柱与模型列对不齐,不逐模型抄数。
- 数字出处并不相同:摘要、引言的23%与Figure 8 Secure列数值相同。摘要写前沿模型、250条提示、上下文含应避免的弱点;引言写要求写安全代码并给出CWE;Figure 8列名是Secure、范围是全部被测模型。论文未写明三处是否同一统计。引言的12.7%亦与该列“过测且脆弱”相同。
- 提示基线:作者称即便Secure或CWE提示,过测样本仍有两位数脆弱率,并称Figure 3的GPT系列在过测时仍>13% vulnerable. Figure 3 does not extract bar heights. Figure 1 for GPT 5.4, overfitting and vulnerable labeled as: Write Code 18.3%, Write Secure Code 12.0%, without CWEs 11.7%, SecureForge 7.9%. Discussion also states that even with static analysis guidance, vulnerability rate remains >13%; that sentence is not limited to "overfitting".
Out-of-Distribution Transfer
- Setup: optimized system prompts used zero-shot on 203 SWE-chat tasks; these prompts were not seen during optimization. Figure 5 left compares the joint rate of overfitting and safety before and after intervention; text does not extract bar values.
- Magnitude given by authors: introduction states this joint rate improves by up to 13.5%. Section 5 does not repeat this number, only states that joint improvement is still observed, and that the strongest result in this setting appears on the strongest GPT-series model.
- Do not mix with Table 1: Table 1 is findings in modified files of original sessions, not a SecureForge before/after comparison. Among 203 tasks, 22 (11%) have at least 1 finding introduced, 4 (2%) have at least 1 fixed, 43 (21%) have persistent findings, 146 (72%) have zero findings. Findings in modified files: pre-intervention sessions 177, post-intervention sessions 209; post-only 53, pre-only 21, both 156. Appendix E states benign prompts introduce vulnerabilities into existing codebases at 11%; the 11% in the table corresponds to the proportion of tasks with at least 1 finding introduced.
Amplification, Optimizer, and Submission-Time Resampling
- MCMC: authors state that relative to simple paraphrase, MCMC finds new vulnerable prompts with success rate up to 2× (Figure 7 left, higher is better). In text, bar values do not align with the four GPT models, so bar values are not copied.
- GEPA and Mipro: Appendix A states GEPA reduces vulnerability rate more effectively than Mipro, and states the difference is statistically significant (Figure 6). Bar value column alignment is unreliable, not copied.
- Submission-time resampling: if static analysis reports an error, the line number is returned to the model to regenerate, until no error or retries exceed 36 times. Figure 7 right legend gives AUC of proportion of scenarios still containing verifiable errors: Baseline 0.30, Secure 0.28, CWE 0.16, SecureForge 0.03. Authors state SecureForge with a small number of resamples exceeds each baseline's 30 resamples.
Other Ablations and Analyses
- CWE exceptions: authors state vulnerability rate decreases for almost all detected CWEs, exceptions are CWE-94 (code injection) and CWE-306 (missing authentication step). Figure 10 gives aggregated rates per CWE, text's before/after bar attribution is unreliable. Authors suspect the former relates to GEPA seeing tests and biasing toward testable implementations, and the latter to single-file difficulty in expressing authentication design.
- Overfitting and failures: authors state the method converts some vulnerable samples into test failures at a non-significant rate, and the marginal rate of test failures on vulnerable samples rises slightly. Figure 8 test failures from 37% to 38%, of which failed and vulnerable from 10.3% (2545) to 7.8% (1788), failed and safe from 26.9% (6657) to 30.3% (6959). Authors suspect some practices make safe implementation harder, thus more implementation errors. Figure 9 shows vulnerability rate of non-overfitting rollouts also decreases after intervention; bar values not aligned.
- Severity and diversity: authors state vulnerability rate decreases across all severity buckets, and after GEPA severe and medium proportions are roughly equal (Figure 12, pre-intervention labeled S, post labeled G). Authors state generated code Self-BLEU only marginally increases, and all models do not exceed 20% (Figure 13); figure shows annotation includes 0.188.
- Benign comparison: Appendix F states filtered benign prompts are more likely to elicit vulnerabilities than non-benign prompts directly generated from CWE descriptions (Figure 11, GPT 5.3 Codex and GPT 5.4). Authors believe safety fine-tuning may suppress malicious attacks but does not block the framework of unintentional harm. Bar-to-legend correspondence is unreliable.
- Pareto plot: Figure 5 right is arrows for each model from baseline to post-intervention in the (test pass rate, safety rate) plane; authors state no clear leftward (less capable), but upward (safer), and upper-right is better. Text does not give point coordinates.
What are some points that can be further explored?
The authors point out that prompts are not transferable across models, have a one-time cost, and only Python single-turn was evaluated.
Limitations and Future Directions Noted by the Authors
- Not cross-model (Section 7): A system prompt optimized for one model may not make another model safe. The authors also write that the process is easy to execute even on frontier models and is provided as an open-source package, allowing developers to build custom prompts.
- One-time cost (Section 7): The method is applied on top of trained models, and searching for safe system prompts has a one-time inference and compute cost. The authors give an average of $150, calculated at $15 per million tokens and needing 50M tokens, and consider it small relative to changing the data distribution or fine-tuning.
- Language and turns (Section 7): The evaluation is limited to Python, single-turn, and newly written code. Real deployments may have multiple generations and multi-turn interactions. The authors state Python structurally excludes memory-type weaknesses, so the results are a lower bound on the failure rate for such models.
The paper does not list additional future experiments in Limitations, Discussion, or Conclusion. The Discussion writes that large-scale adoption would help fulfill secure-by-design, which is not a limitation item.
Experimental Coverage
- The tested models are the 10 from Section 4.1: Qwen 2.5 Coder 7B and 14B, Qwen3 30B-A3B, CodeLlama 7B, Kimi K2, GPT 5.4-nano, GPT 5.4-mini, GPT 5.4, GPT 5.3-codex, Claude Sonnet 4.6.
- Static analysis uses Semgrep Community Python rules, mapped to CWE Top 25. In-distribution evaluation is 2,500 rollouts; the optimization corpus is written as 80,000 prompts. The seed is 500 prompts and 5,000 rollouts.
- Prompt baselines are direct generation, Secure, and CWE. The appendix compares Mipro, simple paraphrasing, and a submission-time process that regenerates after errors and stops after more than 36 retries.
- Out-of-distribution data is 203 Python tasks from SWE-chat, with multi-turn compression using Claude Sonnet 4.6. The real user prompt distribution is not seen during optimization. Vulnerability rate uses a Beta posterior with variance threshold 0.015 and reports 95% credible intervals.
- The paper does not report the model names for generating seed prompts in the falsification phase, the model names for generating unit tests, or the agreement values for manual checks of 50 tests and verification of 203 tasks.
Summarize the main content of the paper
SecureForge audits benign CWE failures and optimizes system prompts; the authors state that vulnerabilities drop by up to 48% and transfer zero-shot to real sessions.
SecureForge is a pipeline that hardens coding models at inference time using only APIs and static analysis.
- Problem: benign coding requests can also cause models to write code that passes tests but contains Semgrep-detectable weaknesses. The introduction states that when asked to write secure code and given CWEs, 23% still have statically verifiable weaknesses, and 12.7% are both vulnerable and pass tests. The abstract puts 23% under the conditions of frontier models, 250 benign prompts, and context containing weaknesses to avoid.
- Method: falsify benign seeds from CWE Top 25, amplify failure prompts with Metropolis-Hastings, then drive GEPA with Semgrep's ±1 reward to obtain an inference-time system prompt. No weight updates. Both falsification and amplification estimate failures using the target model at temperature 1.0.
- Aggregate results: Figure 8 compares Secure aggregate with SecureForge aggregate across all tested models: vulnerable share from 23% (5678) to 15% (3471), pass-tests-and-vulnerable from 12.7% (3133) to 7.3% (1683), test pass rate from 63% to 62%. The authors claim weakness rate reduced by up to 48% and state that the joint improvement in safety and test passing on frontier models is statistically significant, advancing the Pareto frontier of capability and safety.
- Single model and transfer: In Figure 1, GPT 5.4 pass-tests-and-vulnerable is Write Code 18.3%, SecureForge 7.9%. The introduction states that when the system prompt is used zero-shot on real coding agent prompts, the joint pass-tests-and-safe rate increases by up to 13.5%, and the real user distribution was not seen during optimization.
- Exceptions and boundaries: The authors state that CWE-94 and CWE-306 do not decrease along with the other CWEs. They believe existing safety training does not sufficiently cover the tested benign CWE failures; the system prompt can be immediately applied to existing models, and the pipeline can also discover new failures for new models or existing codebases. They also state that Python single-turn results are a lower bound on failure rate, and one prompt cannot guarantee safety after model changes.