arXivDaily arXiv每日学术速递 周一至周五更新
arXiv 2606.16244cs.CRcs.AI
收藏

SPARK: 基于安全知识引导与表示激活的LLM安全代码生成

Activating Latent Security Knowledge through LLM-Guided Risk Analysis for Secure Code Generation

Radboud University(拉德堡德大学);University of Bristol(布里斯托大学);University of Zagreb(扎格雷布大学)

Xiaoyun Xu, Lichao Wu, Jona te Lintelo, Siyu Zhang, Keke Gai, Stjepan Picek

AI总结:

提出SPARK方法,通过检索CWE条目并添加结构化提示激活模型内隐安全知识,结合预计算令牌偏置,无需重训练即可提升代码安全性。

摘要:

大型语言模型通常会生成带有可利用安全漏洞的代码。先前文献将此限制归因于缺乏安全专业知识,促使当前防御机制转向大量微调或外部知识检索,这通过冗余代码示例引入了显著的计算开销和数据偏差。与此观点相反,我们认为预训练语料库已经富含安全材料。瓶颈在于激活:没有明确而简短的提示,对常见训练分布模式的统计压力会抑制模型的安全相关表示。我们提出了SPARK,一种推理时的安全增强工具,无需任何重训练即可激活这些潜在知识。该工具包含两部分。第一部分为每个编码任务检索少量相关通用弱点枚举(CWE)条目,并在提示后附加一个简短的结构化提示;仅此就足以浮现模型现有的安全表示。第二部分在每个解码步骤向logits添加预计算的令牌偏置。我们通过将安全方向向量(平均安全与平均不安全的最后一层隐藏状态之间的单位差)通过语言模型头投影来获得偏置。该偏置离线计算一次;应用它每个生成令牌只需一次向量加法。我们在C++、Java和Python上的9个开源模型上评估了SPARK,并与涵盖微调和检索增强方法的7个基线进行了比较。SPARK在每个设置中均匹配或优于最佳基线,同时保持HumanEval效用。我们进一步在7个当前最强模型(包括Claude、DeepSeek和GPT)的黑盒设置中测试了第一部分,展示了不安全代码生成的瓶颈以及我们方法带来的改进。

英文摘要:

Large language models are pretrained on extensive software and security corpora, yet they frequently generate functionally correct code containing well-known vulnerabilities. Existing defenses commonly treat this behavior as a knowledge deficit, addressing it through model-specific fine-tuning or retrieval from large collections of vulnerability code examples. We argue that insecure generation can arise from a failure to activate task-relevant security knowledge, rather than from knowledge absence alone. We present BRACE, an inference-time, training-free security harness for risk-conditioned activation of security knowledge in black-box code generation. Given only a coding task, BRACE first utilizes an LLM (as a security expert) to identify task-relevant security risks. The predicted risk identifiers are validated against a lightweight canonical catalog and converted into concise, task-specific risk cues. BRACE then supplies these cues to the target code model, prompting it to apply its own secure-coding knowledge while satisfying the original functional requirements. The framework requires no target-model fine-tuning, parameter access, hidden states, mutable logits, learned retriever, or coding-example knowledge base. We evaluate BRACE on six open-weight models and six frontier commercial models with four benchmarks (CyberNative, HumanEval, CWEval, BaxBench), measuring functional correctness, security, joint functionality-security, and project-level generation. BRACE raises the average Safe Code Rate from 33.9% under Secure Prompt to 91.2% on CyberNative. It also improves CWEval Func-Sec performance from 49.7% to 69.6%. Mechanism-oriented ablations further show that the gains depend on selecting task-relevant risks.

机构、总结、中文摘要均由AI分析而来,可能存在错误,请以论文正文为准。

↑