跳到正文
arXiv cs.CL· Yitong Zhang, Shiteng Lu, Jia Li·· 12 小时前AI 评分58

研究发现语法约束解码可越狱 LLM 生成恶意代码

Grammar-Constrained Decoding Can Jailbreak LLMs into Generating Malicious Code

AI 导读

论文提出 CodeSpear 攻击,发现仅施加良性的代码语法约束(GCD)就能越狱 LLM 使其生成恶意代码。在 10 个主流 LLM、4 个基准上,CodeSpear 平均将攻击成功率提升 30 个百分点以上,超过代表性越狱基线。作者同时提出安全对齐方法 CodeShield,通过让模型在 GCD 下生成语义无害、结构多样的蜜罐代码来恢复安全性,并保留自然语言拒答与良性效用。

正文 · 原文

View PDF HTML (experimental)

Abstract:Large Language Models (LLMs) are increasingly used for code generation, raising concerns that they may be misused to produce malicious code. Meanwhile, Grammar-Constrained Decoding (GCD) has been widely adopted to improve the reliability of LLM-generated code by enforcing syntactic validity. In this paper, we reveal a counterintuitive risk: this reliability-oriented technique can itself become an attack surface. We uncover a new jailbreak attack, termed CodeSpear, that exploits GCD to induce LLMs into generating malicious code. Our experiments show that simply applying a benign code grammar constraint can effectively jailbreak LLMs.
To address this vulnerability, we propose CodeShield, a safety alignment approach that robustly preserves safe behavior even under attacker-controlled grammar constraints. CodeShield aligns the model in the code modality by teaching it to generate honeypot code under GCD. Such code is semantically harmless, so it does not implement the malicious request, and structurally diverse, so it is difficult to suppress through grammar tightening. At the same time, CodeShield still preserves natural-language refusals when natural language is available. Experiments on 10 popular LLMs across 4 benchmarks show that CodeSpear outperforms representative jailbreak baselines and increases the attack success rate by more than 30 percentage points on average. CodeShield also restores safety under CodeSpear while preserving benign utility. Our findings reveal a fundamental risk of GCD and call for greater attention to its potential security implications.
Comments: Directly Accepted by ICSE 2027
Subjects: Cryptography and Security (cs.CR); Artificial Intelligence (cs.AI); Computation and Language (cs.CL); Software Engineering (cs.SE)
Cite as: arXiv:2606.11817 [cs.CR]
  (or arXiv:2606.11817v3 [cs.CR] for this version)
  https://doi.org/10.48550/arXiv.2606.11817

arXiv-issued DOI via DataCite

Submission history

From: Yitong Zhang [view email]
[v1] Wed, 10 Jun 2026 08:50:59 UTC (458 KB)
[v2] Tue, 3 Nov 2026 07:43:08 UTC (776 KB)
[v3] Wed, 4 Nov 2026 07:42:57 UTC (776 KB)

来源:arXiv cs.CL · arxiv.org