Study: grammar-constrained decoding can jailbreak LLMs to generate malicious code, and proposes CodeShield defenseGrammar-Constrained Decoding Can Jailbreak LLMs into Generating Malicious Code
Translation in progress — untranslated text is omitted.
The researchers propose CodeSpear, which uses syntax-constrained decoding (GCD) to exclude natural language refusals from the legal output space, forcing the model to continue generating in the code modality, thereby jailbreaking the LLM to output malicious code. Across 10 models and 4 benchmarks, CodeSpear increases attack success rate by an average of over 30 percentage points; on locally deployed Qwen2.5-Coder-7B, average ASR reaches 81.82%, and on API model MiniMax-M2.7's RMCBench, ASR rises from 20.33% to 85.53%. The authors note that models like GPT-5 often generate pass statements to evade under GCD, but simply tightening the syntax to disallow pass raises GPT-5's ASR on RMCBench from 55.49% to 70.30%.
- Existing safety alignment for large language models is mainly built on refusal expressions in the natural language modality. When inference uses syntax-constrained decoding (GCD) to ensure syntactic validity, natural language refusals are excluded from the legal output space, making the model easily induced to generate malicious code in the code modality.
- The authors propose the CodeSpear jailbreak attack using standard benign code syntax; and propose the CodeShield safety alignment method, which uses DPO to build a preference hierarchy, training the model in the code modality to generate semantically harmless and syntactically diverse honeypot code.
- CodeSpear achieves an average ASR of 81.82% on 5 local models and 67.39% on 5 API models; CodeShield reduces Qwen2.5-Coder-7B's average ASR under attack to 5.57% while maintaining benign code generation performance.
- The authors note that GCD implementations differ across engines, and the experiments cover local and API deployments as well as multiple programming language syntaxes; malicious code scenarios cover 10 categories from RMCBench and 6 from MalwareBench; adaptive attacks only tested prompt-based syntax modification with a single agent model.
The paper reveals that syntax-constrained decoding itself can be used as a jailbreak surface, and provides a corresponding code-modality alignment solution, offering direct reference value for teams deploying code generation services.