文法制約付きデコーディングはLLMを脱獄させ、悪意のあるコードを生成させることができる
Grammar-Constrained Decoding Can Jailbreak LLMs into Generating Malicious Code
June 10, 2026
著者: Yitong Zhang, Shiteng Lu, Jia Li
cs.AI
要旨
大規模言語モデル(LLMs)はコード生成にますます利用されるようになっており、悪意のあるコードの生成に悪用される懸念が高まっている。一方、文法制約付きデコーディング(GCD)は、構文的な妥当性を強制することでLLM生成コードの信頼性を向上させるために広く採用されている。本稿では、この信頼性指向の手法自体が攻撃面となり得るという直感に反するリスクを明らかにする。我々はCodeSpearと名付けた新たな脱獄攻撃を発見した。これはGCDを悪用してLLMに悪意のあるコードを生成させるものである。実験では、単に良性のコード文法制約を適用するだけで、LLMを効果的に脱獄させられることを示す。
この脆弱性に対処するため、我々はCodeShieldを提案する。これは攻撃者に制御された文法制約下でも安全な振る舞いを頑健に維持する安全性アライメント手法である。CodeShieldは、GCDのもとでハニーポットコードを生成するようモデルを学習させることで、コードモダリティにおいてモデルをアライメントする。このコードは意味的に無害であるため悪意のある要求を実装せず、構造的に多様であるため文法の厳格化によって抑制することが困難である。同時に、CodeShieldは自然言語が利用可能な場合には自然言語による拒否も維持する。10種類の人気LLMを4つのベンチマークで評価した実験では、CodeSpearが代表的な脱獄ベースラインを上回り、攻撃成功率を平均で30ポイント以上向上させることが示された。また、CodeShieldはCodeSpear下での安全性を回復しつつ、良性のユーティリティも維持する。我々の発見はGCDの根本的なリスクを明らかにし、その潜在的なセキュリティへの影響に対する一層の注意を喚起するものである。
English
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.