Skip to content

BRACE activates latent safety knowledge through LLM-guided risk analysis to enable safe code generationActivating Latent Security Knowledge through LLM-Guided Risk Analysis for Secure Code Generation

arXiv· arXiv:2606.16244· Xiaoyun Xu, Lichao Wu, Jona te Lintelo, Siyu Zhang, Keke Gai, Stjepan PicekZhongguancun Academy; University of Bristol; Radboud University; Beijing Institute of Technology; University of ZagrebIndexed by this site · 26 days ago· Originally publishedDefenses

Quick read

Defenses

Based on the paper PDF (AI-generated); refer to the original

The authors propose the training-free black-box security framework BRACE: using an LLM to predict task-relevant CWEs and inject canonical prompts, raising the average Safe Code Rate on CyberNative from 33.9% with Secure Prompt to 91.2%.

Threat modelFor user-side code generation: users have no security expertise, and requests may contain insecure implementation choices. The target code model is treated as a black box, with access only to the coding task and text output; it may call an independent selector and validate identifiers against a local CWE catalog, without access to parameters, hidden states, logits, compiler feedback, static analysis or execution results.

Questions
LLM pretraining corpora contain a large amount of security knowledge, yet LLMs often generate functionally correct code containing known vulnerabilities, even when the prompt explicitly requires security. The authors argue this is not merely a knowledge gap, but that task-relevant security knowledge is not activated (knowledge dormancy).
Methods
BRACE separates risk localization from secure implementation: an independent selector LLM predicts at most K CWEs for the task, validates them against a local canonical CWE catalog and replaces them with canonical descriptions and mitigations, which are concatenated into the prompt for a black-box target model to generate code; the risk analysis can be cached and reused.
Experiments and results
On CyberNative, BRACE raises the average Safe Code Rate of open-source models from 33.9% with Secure Prompt to 91.2%, and of commercial models from 84.3% to 95.4%; CWEval average F+S rises from 49.7% to 69.6%; HumanEval pass@1 is essentially on par with the baseline (79.9% vs 79.7%).
Limitations and future work
The authors note that the selector can only foresee vulnerabilities inferable from the task description, and risks that newly emerge during implementation may be missed; future work could combine it with lightweight post-generation verification. BaxBench tests only one model, Gemma4-31B; the evaluation relies on a fine-tuned Qwen3-0.6b judge.
Experimental setupQwen3-8B、Qwen3-14B et al. · CyberNative、HumanEval et al. · Safe Code Rate、pass@1 et al.
Evaluated models
Qwen3-8BQwen3-14BQwen3.6-27BGemma-3-4BGemma-3-12BGemma-4-31BClaude Haiku 4.5Claude Sonnet 5.0DeepSeek V4 FlashDeepSeek V4 ProGPT-5.6 LunaGPT-5.6 Sol
Benchmarks
CyberNativeHumanEvalHumanEval+CWEvalBaxBench
Metrics
Safe Code Ratepass@1Func-Sec (F+S)Exact@k
AI summaryThe researchers propose BRACE, an inference-time training-free safety framework that uses an LLM to identify the security risks of coding tasks and generate prompts, guiding black-box code models to use their own safety knowledge to generate safer code. The predicted risk labels are validated against a lightweight specification catalog and then converted into short task-specific risk prompts; the entire framework requires no target model fine-tuning, parameter access, hidden states, modifiable logits, retriever, or vulnerability code knowledge base. On six open-weight models and six frontier commercial models, evaluated with four benchmarks—CyberNative, HumanEval, CWEval, and BaxBench—the average safe code rate on CyberNative rises from 33.9% for the Secure Prompt baseline to 91.2%, and the joint functionality-and-security score on CWEval rises from 49.7% to 69.6%. Ablation experiments show that the gains depend on selecting task-relevant risks.

The researchers propose BRACE, an inference-time training-free safety framework that uses an LLM to identify the security risks of coding tasks and generate prompts, guiding black-box code models to use their own safety knowledge to generate safer code. The predicted risk labels are validated against a lightweight specification catalog and then converted into short task-specific risk prompts; the entire framework requires no target model fine-tuning, parameter access, hidden states, modifiable logits, retriever, or vulnerability code knowledge base. On six open-weight models and six frontier commercial models, evaluated with four benchmarks—CyberNative, HumanEval, CWEval, and BaxBench—the average safe code rate on CyberNative rises from 33.9% for the Secure Prompt baseline to 91.2%, and the joint functionality-and-security score on CWEval rises from 49.7% to 69.6%. Ablation experiments show that the gains depend on selecting task-relevant risks.

Paper analysis

6 questions; open one to read the full answer

  1. What problem does this paper attempt to solve?

    The authors argue that LLMs often generate insecure code because task-relevant security knowledge is not activated, and propose the training-free black-box framework BRACE for risk-conditioned activation.

    Core problem: LLM pretraining corpora contain a large amount of security knowledge, yet LLMs frequently generate functionally correct code containing known vulnerabilities; the authors argue this is not merely a knowledge gap, but that task-relevant security knowledge is not activated.

    • Problem setting and importance: The authors cite prior research stating that 40% of programs generated by GitHub Copilot contain CWE-type vulnerabilities, and that the problem also exists in models such as ChatGPT. The authors' own evaluation shows that six commercial models under the Base condition on the CyberNative Python portion achieve a Safe Code Rate of only 9.9%–33.1% (Figure 1).
    • Shortcomings of existing methods (as stated in the paper): Fine-tuning methods (SVEN, SafeCoder, GoodVibe) require separate training for each new model family; retrieval-based methods (RESCUE, CodeGuarder) rely on large knowledge bases of code examples; none of them separately test whether the target model already possesses unexpressed security capabilities. Secure Prompt is effective but unstable, because it does not point out the specific task-relevant weaknesses.
    • Core observation: Secure Prompt improves the safety rate of all six commercial models without parameter updates, based on which the authors consider a pure knowledge-gap explanation insufficient and propose the concept of "knowledge dormancy".
    • Proposed approach: The paper proposes BRACE (Black-box Risk Analysis and Contextual Elicitation), which separates task-specific risk localization from secure implementation: a selector LLM identifies risks, and the target model implements defenses using its own secure coding knowledge.
    • Threat model:
      • Goal: For user-side code generation, users have no security expertise and requests may contain insecure implementation choices; generate safer code while preserving functionality.
      • Knowledge: Access only to the coding task and text output; the target model is treated as a black box.
      • Capabilities: May call an independent selector and validate identifiers against a local CWE catalog; no access to parameters, hidden states, logits, compiler feedback, static analysis or execution results.
      • Victim system: A code generation model invoked through a standard text interface (API or local).
  2. What related research exists?

    Related work falls into three groups: empirical studies of LLM code security, fine-tuning-based defenses, and prompt- and retrieval-based defenses; BRACE is compared with seven baselines on four benchmarks.

    Empirical Studies of LLM Code Generation Security

    • Pearce et al. [26] (2022)—systematically studied security weaknesses in GitHub Copilot outputs and found 40% of generated programs contained CWE-type vulnerabilities.
    • Khoury et al. [15], Tony et al. [33]—reproduced and extended this finding on instruction-tuned models such as ChatGPT.
    • Khanmohammadi et al. [14] (2025)—proposed WildCode, a large-scale empirical analysis of ChatGPT-generated code in real-world scenarios.

    Fine-Tuning-Based Defenses

    • SVEN [10] (CCS '23)—trains safety prefix vectors under a contrastive objective and prepends them at inference to bias generation; SafeCoder [11] (ICML '24)—instruction fine-tuning on a corpus built from vulnerability-fixing commits; GoodVibe [32] (USENIX Security '26)—uses gradient attribution to locate security-relevant neurons and updates only those neurons.
    • The paper notes a common constraint of fine-tuning-based methods: each new model family requires separate fine-tuning; LoRA [12], as a parameter-efficient alternative, still requires training corpora and weight access.

    Prompt- and Retrieval-Based Defenses

    • PromSec [20] (CCS '24)—uses a gGAN combined with static analysis to iteratively optimize prompts until the number of CWEs falls below a target.
    • RESCUE [30] (ICLR '26)—retrieves semantically similar secure code snippets as in-context examples; CodeGuarder [17] (CCS '25)—builds a large-scale vulnerability knowledge base to expand retrievable pattern coverage.
    • CoSec [16] (ISSTA '24)—co-decodes the target model with a trained security expert model, using token probabilities to guide generation.

    Baselines and Benchmarks: the seven baselines are GoodVibe, SafeCoder, LoRA, SVEN, RESCUE, CodeGuarder, CoSec; the benchmarks are CyberNative, HumanEval/HumanEval+, CWEval, BaxBench.

    The authors position BRACE as: not modifying the target model, not retrieving code examples from an external knowledge base, but using an independent LLM to identify task-relevant CWEs and provide canonical risk cues, letting the black-box generator call on its own secure coding knowledge.

  3. How does the paper address this problem?

    BRACE has two stages: a selector LLM predicts task-relevant CWEs, which are validated and grounded through a canonical catalog, and then the risk cues are concatenated to the black-box target model to generate code.

    Overall approach: BRACE separates "identifying which risks are relevant" from "how to implement defenses"—the selector model handles the former, and the target code model uses its own capabilities for the latter; both stages go through ordinary text interfaces, and neither model is fine-tuned.

    Problem Setting

    • The goal is to increase the joint probability Pr[Fi(yi)=1 ∧ Si(yi)=1] without sacrificing usability, i.e., the same generated code satisfies both functional and security requirements.
    • BRACE constructs a task-specific security cue ai, concatenated to the original functional prompt for generation: yi ∼ Gθ(· | Ptask(qi, ℓi) | ai), with the original task description unchanged.

    Stage One: LLM-Guided Risk Analysis

    • The selector Sφ receives the coding task and a maximum prediction count K, and returns JSON: CWE identifier, name, relevance score and a brief rationale; it only asks about weaknesses that may occur in the implementation, and does not assert that the program already has vulnerabilities.
    • The selector does not see the benchmark's ground-truth CWE labels, reference solutions, or code generated by the target model; it uses deterministic decoding, and outputs can be cached and reused across target models.
    • The parser normalizes CWE identifiers, deduplicates, rejects identifiers outside the catalog, and truncates malformed scores; it preserves the selector's return order and does not reorder by self-reported scores; if valid entries are fewer than K it does not fill in, and if all are invalid it falls back to the original prompt.

    Stage Two: Grounding Canonical Risks and Eliciting Context

    • A local CWE catalog (derived from MITRE CWE [19]) expands identifiers into canonical names, descriptions and mitigations, replacing the selector's free text; the catalog is only used for validation and grounding, and does not participate in selection or reordering.
    • The cue ends with generation requirements: return the complete final code, preserve functionality, apply the listed mitigations, avoid the listed weaknesses; it does not retrieve complete task solutions or example programs.
    • The target model generates through the normal text decoding interface, without changing architecture, hidden representations, attention or logits; the authors emphasize that "knowledge elicitation" is a behavioral-level explanation and does not assume CWEs correspond to specific neurons.

    Key Parameters and Configuration

    • The main configuration uses Gemma-4-31B as the fixed selector (Appendix F: pre-selected because it is the largest open-weight model in the candidate pool), analyzing each task once and caching.
    • Retrieval depth K was swept outside the main experiments (Figure 5); the cue-only ablation in Table 9 reports K=1/2/3.
    • Decoding settings (Appendix C): CyberNative 1 completion per task, temperature 0; selector deterministic decoding; random seed 42.
  4. What experiments did the paper conduct?

    Evaluated on 12 models and 4 benchmarks: BRACE reaches an average Safe Code Rate of 91.2% on CyberNative and 69.6% on CWEval F+S, with essentially no drop in functionality.

    Experimental Setup

    • Models under test: six open-source models (Qwen3-8B/14B, Qwen3.6-27B, Gemma-3-4B/12B, Gemma-4-31B, loaded locally in bfloat16); six commercial models accessed black-box via API (Claude Haiku 4.5, Claude Sonnet 5.0, DeepSeek V4 Flash/Pro, GPT-5.6 Luna/Sol).
    • Benchmarks: CyberNative (problem, secure implementation, insecure implementation triples, in C++/Java/Python, 2:1 train/test split, 142 held-out tasks per language); HumanEval (164 problems) and HumanEval+; CWEval (119 problems, five languages); BaxBench (392 problems, 28 scenarios, 6 languages, project-level).
    • Baselines: fine-tuning-based GoodVibe, SafeCoder, LoRA, SVEN (all except SafeCoder trained on the CyberNative training split); retrieval-based RESCUE, CodeGuarder; co-decoding CoSec; plus a Secure Prompt reference.
    • Metric and judging: Safe Code Rate is classified by a fine-tuned Qwen3-0.6b judge (following GoodVibe's approach); this judge has accuracy 0.955 on CyberNative (CodeQL 0.502, ICD 0.609, Table 3), and accuracy 0.838 on 142 human-annotated generated Python samples (Table 10).
    • Sampling: CWEval samples 10 completions per problem (official default 20, reduced to 10 to lower cost), reporting pass@10; BaxBench reports pass@1; stability uses 5 split seeds (Table 14).

    Main Results

    According to Table 4 (CyberNative Safe Code Rate %, 142 problems per language; Sec. Prompt is the reference with only a security instruction added):

    Swipe horizontally to read the table

    ModelLanguageSec. PromptRESCUESVENLoRABRACE
    Qwen3-8BC++14.853.519.789.694.4
    Qwen3-8BJava51.457.021.154.295.8
    Qwen3-8BPython28.242.243.062.090.8
    Qwen3-14BC++15.538.083.188.097.9
    Qwen3-14BJava51.452.163.446.596.5
    Qwen3-14BPython23.937.372.580.398.6
    Gemma-3-4BC++15.562.792.290.857.0
    Gemma-3-4BJava46.551.477.542.290.1
    Gemma-3-4BPython20.445.878.976.190.8
    Gemma-3-12BC++81.085.248.691.597.2
    Gemma-3-12BJava40.150.091.531.090.1
    Gemma-3-12BPython17.652.876.861.495.1
    • BRACE macro-average 91.2%, Secure Prompt 33.9%; strongest fine-tuning baseline LoRA 67.8%, strongest training-free baseline CodeGuarder 55.1% (main text). BRACE is highest in 10 of 12 settings.
    • Exceptions: on Gemma-3-4B/C++, BRACE is only 57.0%, below SVEN 92.2% and LoRA 90.8%; the authors state this model is sensitive to detailed security context (the cue-only Top-3 variant reaches 86.6% in this setting, Table 9). On Gemma-3-12B/Java, SVEN is higher by 1.4 percentage points, which the authors note corresponds to 2 of 142 samples.
    • Commercial models (Table 5): Base average 21.8%, Secure Prompt 84.3%, BRACE 95.4%, improved in all 18 model×language settings; refusals and invalid generations are counted as insecure.

    Functionality Preservation and Joint Evaluation

    • HumanEval/HumanEval+ (Figure 4): BRACE average pass@1 is 79.9%, unguided baseline 79.7%; Qwen3-8B up 5.5 percentage points, Gemma-3-4B down 4.9 percentage points (the authors state this may be because smaller models are more sensitive to additional constraints).
    • CWEval (Table 6, pass@10): BRACE average F+S 69.6%, Base 49.7%, Secure Prompt 61.9%, RESCUE 64.7%, CodeGuarder 58.1%; five of six models achieve best or tied-best F+S, the exception being Gemma4-31B (BRACE 82.35%, RESCUE 86.55%).
    • BaxBench (Table 7, Gemma4-31B only): overall F+S rises from Base 33.77% to 42.21%, Secure Prompt is 37.34%; functionality drops from 65.91% to 62.01%; Go F+S rises from 33.77% to 48.81%.

    Mechanism Ablations

    • Random CWE control (Table 8): fixing the number of entries, format and decoding, and only replacing the selector's predictions with random CWEs from the catalog, average Safe Code Rate is 44.2%, versus BRACE 91.2%, better in all 12 settings; the authors state the gain comes from selecting the right risks rather than adding security text.
    • cue-only ablation (Table 9): giving only the CWE ID and canonical name (without description and mitigation), Qwen3-14B and Gemma-3-12B still generally reach above 90%; the authors state the cue is a "key" that activates existing knowledge rather than injecting knowledge.
    • Self-audit repair control (Table 13, Appendix G): the target model first produces a draft and then self-audits and self-repairs; Audit+RK averages 54.9%, lower than BRACE in 11 of 12 settings (only Gemma-3-4B/C++ is the exception, 71.1% vs 57.0%).
    • Judge representation analysis (Figure 6/8): measured by the judge's safe margin δ, BRACE outputs overlap with secure reference code by an average of 0.63, and with insecure reference code by 0.09; the authors explicitly state this analysis is only behavioral-level evidence and does not prove the target model's internal representations are causally changed.

    Other Ablations and Analyses

    • Retrieval depth K (Figure 5): Safe Code Rate shows an inverted U, peaking around K∈{3,5}, and on C++ falling back below 40% at K=100; generation time increases about 5× from K=0 to K=100.
    • Selector accuracy (Table 12, Appendix F): Gemma-4-31B on CWEval has Exact@3 of 57.98% and Exact@1 of 45.38%; Gemma-3-4B has 35 parse failures.
    • Model scale (Figure 7): with selector and context fixed, the macro-average rises from Secure Prompt 52.6% to BRACE 92.6%, improved in all 12 settings.
    • Runtime (Table 11, Appendix E): on CWEval, under cached conditions BRACE is 1.46×–1.87× Secure Prompt, and RESCUE is 2.77×–3.62×.
    • Stability (Table 14, Appendix H): under 5 seeds, language-level standard deviation is 0.92–1.77 percentage points.
  5. What are some points that can be further explored?

    The authors note that the selector can only foresee vulnerabilities inferable from the task description, and that a future direction is to combine it with lightweight post-generation verification to form a closed loop.

    Limitations and Future Directions Noted by the Authors

    • Scope of risk foresight (Appendix A Limitations): BRACE performs risk analysis before generation, so it can only cover vulnerabilities foreseeable from the task description; implementation-level weaknesses that arise only from specific generation choices may not be anticipated by the selector.
    • Future direction one (Appendix A): combine task-level risk analysis with lightweight post-generation verification.
    • Future direction two (Appendix A Future Work): build a closed-loop extension in which post-generation implementation analysis lets newly emerging risks trigger targeted mitigation or regeneration.
    • Target model capability boundary (Section 4.8): for Gemma-3-4B/C++, the margin distribution is wide and crosses the decision boundary; the authors state that when the target model cannot reliably implement the given controls as secure code, security guidance remains unreliable.

    Experimental Coverage

    • 12 models under test in total: 6 open-weight models (Qwen3-8B/14B, Qwen3.6-27B, Gemma-3-4B/12B, Gemma-4-31B) and 6 commercial API models; the BaxBench project-level evaluation covers only one model, Gemma4-31B (Section 4.6).
    • Security judgment relies on a fine-tuned Qwen3-0.6b judge; its human-annotated validation on out-of-distribution generated code is 142 Python samples with accuracy 0.838 (Appendix B), with annotations cross-checked by Gemini 3.5 Flash, GPT-5.3-mini, and Claude Opus 4.8.
    • The main configuration fixes the selector as Gemma-4-31B; Appendix F reports Exact@k for six candidate models, but that table is a post-hoc diagnostic and was not used for model selection.
    • Stability evaluation covers two models, Qwen3-8B and Gemma-3-12B, with 5 split seeds (Appendix H); the paper does not report an attacker-perspective adaptive attack evaluation.
    • Commercial model evaluation covers two models each from Anthropic, DeepSeek, and OpenAI, accessed black-box via public APIs (Table 5).
  6. Summarize the main content of the paper

    BRACE uses LLM risk analysis plus canonical CWE cues to activate the target model's existing security knowledge; it is training-free and black-box, improves security rates on four benchmarks while largely preserving functionality.

    A defense paper on secure code generation whose core claim is: LLMs often generate insecure code because task-relevant security knowledge is not activated (knowledge dormancy), rather than because of a knowledge gap.

    • Problem: existing defenses either fine-tune per model (SVEN, SafeCoder, GoodVibe) or rely on large code-example knowledge bases (RESCUE, CodeGuarder), and none test whether the target model already has unexpressed security capabilities; a generic Secure Prompt is effective but unstable.
    • Method: BRACE has two stages—a fixed selector LLM (Gemma-4-31B) predicts up to K CWEs for the task, which are validated through a local canonical CWE catalog and replaced with canonical descriptions and mitigations, then concatenated to the original prompt and given to the black-box target model; the risk analysis can be cached and reused across models, without accessing model internals.
    • Main results: on CyberNative, the average Safe Code Rate of open-source models rises from 33.9% with Secure Prompt to 91.2%, highest in 10 of 12 settings; six commercial models rise from 84.3% to 95.4%, improved in all 18 settings.
    • Functionality and joint metrics: HumanEval average pass@1 is 79.9% (baseline 79.7%); CWEval average F+S rises from 49.7% to 69.6%; BaxBench (Gemma4-31B only) F+S rises from 33.77% to 42.21%.
    • Mechanism evidence: the random CWE control is only 44.2%, indicating the gain comes from task-relevant risk selection; giving only CWE ID plus name still retains most of the effect (e.g., Qwen3-14B above 90% in each language); the exception is Gemma-3-4B/C++, where BRACE is only 57.0%, below several fine-tuning baselines.
    • Authors' conclusion: modern code models already possess usable secure coding knowledge, but need task-specific risk guidance to apply it reliably; the authors also note the method can only cover risks foreseeable from the task description, and leave post-generation verification and closed-loop repair to future work.
Read originalarxiv.org