CodeMimicry: Exploiting code-domain safety generalization lag for structured code completion jailbreaks.CodeMimicry: Exploiting Safety Generalization Lag in Large Language Models via Structured Code Completion
The authors propose the black-box framework CodeMimicry, which launches attacks via structured code completion, achieving an average ASR of 96.25% on AdvBench.
Black-box threat model: the attacker interacts with the target model only through standard API queries, submitting natural language prompts and observing outputs, limited to prompt-level manipulation; the attacker cannot access or modify model parameters, gradients, logits, hidden states, training data, safety filters, or the deployment environment. The goal is to induce the model to generate substantial harmful content that violates safety policies.
- Large model safety alignment is mainly trained on natural language, while model code generation capabilities continue to strengthen, causing alignment to not effectively transfer to the code domain, resulting in safety generalization lag and code completion blind spots. If malicious intent is embedded in syntactically compliant code, it may bypass existing safety defense mechanisms.
- The authors propose a black-box attack framework called CodeMimicry, which uses an attack model with code capabilities to generate object-oriented incomplete code, converting malicious intent into class methods and comments, attaching a code completion trigger wrapper, and using a history feedback mechanism to drive the attack model through multiple rounds of iterative optimization based on failure information.
- Across 8 commercial models, CodeMimicry achieves average ASR of 96.25% on AdvBench and 96.07% on HarmBench, with average query counts of 1.51 and 1.46 respectively; latent-space analysis shows that successful attack representations avoid the refusal direction and approach benign code.
- The method relies on the target model's code generation and instruction-following abilities, so its effectiveness may weaken on smaller models; it relies on comment and docstring side channels, and comment filtering can reduce attack success rate; evaluation sample sizes are 50 items from AdvBench and 70 items from HarmBench.
- Evaluated models
- GPT-4o (GPT-4o-1120)GPT-4.1 (GPT-4.1-0414)GPT-5-chat (GPT-5-chat-1003)Claude-3.7-sonnet (Claude-3-7-sonnet-20250219)Claude-sonnet-4 (Claude-sonnet-4-20250514)Gemini-2.5-ProLlama-3.1-70B-InstructLlama-3.3-70B-InstructLlama-3-8B-InstructDeepSeek-R1-8BSafeChain (DeepSeek-R1-8B)Safepath (DeepSeek-R1-8B)Circuit Breaker (Llama-3-8B)Representation Bending (Llama-3-8B)Llama-3-8B (LoRA fine-tuned)
- Benchmarks
- AdvBenchHarmBench
- Metrics
- ASRAQSCRRSRFVR
Researchers propose CodeMimicry, a fully automated black-box jailbreak framework that embeds malicious intent into syntactically valid object-oriented code, leveraging code completion tasks to induce models to output harmful content. On 8 commercial large language models, the method achieves a 96.25% attack success rate on AdvBench with an average of only 1.51 queries, and 96.07% with 1.46 queries on HarmBench, significantly outperforming template-based and optimization-based baselines. The authors attribute this phenomenon to safety generalization lag, where alignment primarily trained on natural language fails to transfer to the code domain, creating a blind spot in code completion. Latent space analysis shows that successful jailbreak samples are representationally close to benign code and systematically avoid refusal directions; activation steering experiments further support this explanation. The authors also note that the method relies on the target model's code generation capability and depends on string side channels such as comments and docstrings; after regex filtering of comments, the attack success rate drops to 20% to 26%.
Why it was selectedThe paper proposes the failure mode of safety generalization lag, provides an automated black-box jailbreak framework and latent-space mechanism analysis, and teams working on code-domain alignment can use it to check refusal transfer.
Related events and news
1 events · 0 news mentions
- This event's paper
CodeMimicry 借代码补全盲点越狱 LLM
Paper analysis
What problem does this paper attempt to solve?
The paper points out that large model safety alignment has code generalization lag and proposes a black-box framework that uses object-oriented code completion to induce harmful outputs.
The paper attempts to address the safety generalization lag and code completion jailbreak risk in large language models caused by safety alignment being mainly concentrated in natural language and not effectively transferring to the code domain.
- Problem scenario and importance: The authors note that large language models' capabilities in code generation tasks are continuously improving, but safety alignment (such as RLHF and SFT) mainly relies on natural language corpora for training, leading to insufficient coverage of alignment in the rigid syntactic subspace of the code domain.
- Shortcomings of existing methods: Manual template jailbreaks (such as CodeChameleon, FlipAttack) have fixed structures and are easily identified by pattern-matching defenses; automated jailbreaks based on model feedback (such as PAIR, AutoDan-Turbo) are limited to heuristic search over unstructured natural language prompts and have limited effectiveness against highly protected models.
- Core observation and hypothesis: The authors propose the "Safety Generalization Lag" hypothesis, arguing that models' learning of refusal behavior mainly comes from natural language, and when transferred to the structured code space, it creates code completion blind spots, allowing malicious intent embedded in compliant code to bypass protection mechanisms.
- Proposed solution: The authors propose the CodeMimicry framework, which uses an attack model with code generation capabilities to automatically construct object-oriented incomplete code, disguising malicious instructions as method names and comments, and inducing the model to complete harmful content through multiple rounds of feedback iteration.
- Threat model:
- Attacker goal: given a malicious instruction q, find a transformation P = ϕ(q) that induces the target model to produce substantial output violating safety policies, determined by a binary evaluator E(P, R) = 1.
- Attacker knowledge: black-box setting, the attacker does not have permission to access or modify the model's internal parameters and gradients.
- Attacker capability: can only send natural language prompts through standard APIs and observe text outputs, which is prompt-level manipulation; cannot access model weights, hidden states, logits, training data, safety filters, or the deployment environment.
- Victim system: commercial and open-source large language models with deployed safety alignment defenses.
What related research exists?
Related research includes white-box and black-box prompt obfuscation jailbreaks, natural language iterative optimization methods, and code and cross-domain jailbreak attempts.
The paper divides related work into three categories: white-box adversarial attacks, black-box jailbreaks based on obfuscation and manual templates, and black-box jailbreaks based on automated prompt optimization, and discusses them in comparison with several representative works.
- White-box adversarial attacks: GCG [9] and AutoDAN [18] use gradient information to optimize adversarial token suffixes. The paper notes that these methods require direct access to model parameters and gradients and cannot be directly applied to commercial black-box API scenarios.
- Manual template and cross-domain obfuscation black-box attacks: FlipAttack [11], CipherChat [19], ArtPrompt [20], and DRA [21] use Base64, ASCII art, or flipping for character obfuscation; CodeChameleon [10] and CodeAttack [22] embed malicious intent into class-like code structures; MathPrompt [23] and EquaCode [24] convert requests into mathematical equations. The paper notes that these methods rely on manually constructed fixed templates, are easily intercepted by rule- or pattern-based defenses, and show significant performance fluctuations across different models.
- Automated prompt optimization black-box attacks: GPTFuzzer [13] uses evolutionary fuzzing; PAIR [12], TAP [25], GAP [26], ReNeLLM [27], and AutoDan-Turbo [14] use auxiliary large models to rewrite prompts based on target model feedback. The paper notes that these methods are limited to unstructured natural language space and fail to effectively use domain-specific strategies such as program structure and code completion, limiting attack efficiency and effectiveness.
- Baseline methods and benchmarks: The paper's experiments select 6 template methods (CipherChat, ReNeLLM, CodeAttack, FlipAttack, EquaCode, CodeChameleon) and 4 automated methods (PAIR, DRA, GPTfuzzer, AutoDan-Turbo) as comparison baselines, evaluated on the AdvBench and HarmBench benchmarks.
The authors position CodeMimicry as a method that addresses the above shortcomings: it requires no manual template design, fully automatically leverages domain knowledge through structured code completion, and balances attack effectiveness with query overhead.
How does the paper address this problem?
Incomplete code is constructed through structural obfuscation, comment side channels, and engineering trigger wrappers, combined with evaluator scoring for multiple rounds of feedback optimization.
CodeMimicry is an automated black-box red-teaming framework. The core idea is to use an attack model with code capabilities to generate object-oriented incomplete code, add a static wrapper to simulate a legitimate user's code completion request, and combine it with scoring from a large model evaluator for multiple rounds of self-correction.
Problem Formalization and Attack Goal
The paper studies jailbreak attacks under a black-box setting. Let the target model be M, the input prompt be P, and the model-generated response be R = M(P). For a given malicious query q, the attacker constructs an adversarial prompt P = ϕ(q) through transformation. The attack goal is to induce the target model to produce output that provides substantial harmful information, using a binary evaluator to determine whether the attack succeeds. When the formula E(P, R) = 1 holds, it means response R violates the safety policy; otherwise it is 0.
Object-Oriented Incomplete Code Generation
The attack model A is responsible for embedding the malicious query q into a compliant code structure. Appendix Figure 14 provides the prompt used to guide the attack model in generating incomplete code. The main design includes three components:
- Structural Obfuscation: Decomposes the malicious query and converts it into core methods within an object-oriented class, so that the code body generated by the target model contains the malicious logic steps.
- Docstrings and Comments: Rewrites direct command-style sentences into function descriptions or task instructions, placing them in code comments and docstrings to guide the target model to output harmful information when completing the logic.
- Utility and Parameter Simulation: Requires the attack model to add auxiliary utility functions and simulation parameters to enhance the realism of the code structure, directing the target model's attention to code syntax and execution logic.
Code Completion Trigger Wrapper
To make the input appear as a normal code debugging request, the paper designs a generic static engineering wrapper prompt Pt (Appendix Figure 13). The final constructed adversarial prompt satisfies the formula P = Pt(Pc). This wrapper simulates the interaction context of a user requesting code completion, shifting the target model from an aligned conversational interaction mode to a compliance-prioritized code completion mode, hiding the malicious intent in the comments.
History-Driven Multi-Round Feedback Optimization
The paper models the attack process as a multi-round optimization procedure (Algorithm 1), with the maximum number of iterations set to T:
- In each round i, the attack model A generates candidate incomplete code Pc based on the accumulated history H.
- Pc is embedded in the trigger wrapper Pt and sent to the target model M to obtain response R.
- The large model evaluator gives a harmfulness score Score ∈ [1, 10] for the response content. If Score reaches the preset success threshold S, the attack ends; if not, the framework performs improvement analysis and appends the quadruple {q, Pc, R, Score} to H for the attack model to use in contextual learning and correction in the next round.
What experiments did the paper conduct?
Achieves an average ASR of over 96% on 8 commercial models; in mechanism analysis, attacks avoid the refusal direction, and comment filtering can weaken the attack.
Experimental Setup
- Tested models: The main experiments cover 8 commercial models, including GPT-4o (GPT-4o-1120), GPT-4.1 (GPT-4.1-0414), GPT-5-chat (GPT-5-chat-1003), Claude-3.7-sonnet (Claude-3-7-sonnet-20250219), Claude-sonnet-4 (Claude-sonnet-4-20250514), Gemini-2.5-Pro, Llama-3.1-70B, Llama-3.3-70B-Instruct; mechanism and defense experiments additionally include Llama-3-8B-Instruct and DeepSeek-R1-8B.
- Benchmarks and sample sizes: AdvBench (50 harmful behavior samples drawn) and HarmBench (10 samples from each of 7 behavior categories, 70 samples total); the human evaluation experiment uses 300 prompt-response pairs.
- Baseline methods: 6 template baselines (CipherChat, ReNeLLM, CodeAttack, FlipAttack, EquaCode, CodeChameleon) and 4 automated baselines (PAIR, DRA, GPTfuzzer, AutoDan-Turbo).
- Metric definitions: Attack success rate ASR (proportion of successful attacks out of total tests); average number of queries AQ (average number of attempts used for successful attacks or exhausted rounds); generated code quality metrics include syntax correctness rate SCR, runtime success rate RSR, and functional validity rate FVR.
- Evaluation mechanism: GPT-5-chat is used as the automated judge model, scoring on a 1–10 scale, with jailbreak success determined only when the score reaches the maximum score of 10; human expert consistency evaluation shows GPT-5-chat achieves an average accuracy of 90.25% (Table 6).
- Hyperparameter configuration: attack model temperature 0.7, target model and evaluation model temperature 0; maximum attempt rounds T = 5; both automated baselines and CodeMimicry use DeepSeek-R1 as the attack model.
Main Results
The following table presents the attack success rates of representative methods on AdvBench across 8 target models (from Table 1):
Swipe horizontally to read the table
Target Model CodeChameleon PAIR AutoDan-Turbo CodeMimicry GPT-4o 94.00% 32.00% 50.00% 90.00% GPT-4.1 100% 18.00% 54.00% 100% GPT-5-chat 94.00% 18.00% 4.00% 96.00% Claude 3.7 Sonnet 100% 4.00% 10.00% 100% Claude Sonnet 4 70.00% 0.00% 0.00% 90.00% Gemini 2.5 Pro 98.00% 72.00% 64.00% 100% Llama 3.1 70B 48.00% 40.00% 46.00% 96.00% Llama 3.3 70B 80.00% 90.00% 68.00% 98.00% - Cross-model attack performance: The authors report that CodeMimicry achieves an average ASR of 96.25% across 8 models, with each model's ASR at 90% or above; against the highly protected model Claude Sonnet 4, the automated baselines PAIR and AutoDan-Turbo both have an ASR of 0%, while CodeMimicry reaches 90.00% (Table 1).
- Query efficiency comparison: The authors note that CodeMimicry's average number of queries on AdvBench is 1.51, achieving 2.80 times the ASR of PAIR with 0.36 times the query volume, and 2.61 times the ASR of AutoDan-Turbo with 0.54 times the query volume (Table 8, Figure 2).
- HarmBench validation results: On HarmBench, CodeMimicry achieves an average ASR of 96.07% with an average query count of 1.46; on Claude Sonnet 4 it maintains an ASR of 74.29%, while FlipAttack, PAIR, and DRA all have an ASR of 0% on that model (Table 5, Table 9).
Defense Mechanism Evaluation
- Detection and filtering defenses: Under Llama Guard defense, residual ASR is 76.00%–92.00%; under perplexity filtering, residual ASR is 84.00%–100%; SelfDefend reduces ASR to 4.00%–14.00% (Table 13); against regex comment filtering (Regex sanitizer), CodeMimicry's residual ASR on 3 tested models is 20%–26% (Table 10).
- Alignment and hidden layer intervention defenses: On DeepSeek-R1-8B, after SafeChain training, attacked ASR is 94%, and Safepath reduces it to 42% (Table 14); on Llama-3-8B, Circuit Breaker and Representation Bending reduce ASR from 90% to 8% and 38%, respectively (Section 6); after LoRA adversarial fine-tuning, ASR drops from 90% to 62% (Appendix D.3).
Hidden Layer Representation and Mechanism Analysis
- Representation space clustering: On Llama-3-8B-Instruct, last-token representations are extracted from each layer. t-SNE and PCA visualization show overlap among the first three sample classes at layer 16; from layer 16 onward, failed attack samples cluster into an isolated cluster, while successful attack samples are close to the benign code sample region (Figure 4, Figure 9, Figure 10).
- Refusal direction projection and activation manipulation: Projecting along the refusal vector defined by the mean difference between failed and benign samples, failed samples have consistently positive projection values, while successful samples maintain negative values close to benign code (Figure 5, Figure 11); injecting the refusal direction for activation steering during inference shows that increasing intervention strength α raises the number of model refusals (Figure 6, Figure 12).
Other Ablations and Analyses
- Trigger wrapper variants (GPT-4o): Full-Wrapper 90%, Paraphrased-Wrapper 72%, Minimal-Trigger 40%, Bare-Code 36%, No-Refusal-Ban 32% (Table 2).
- Cumulative benefit of multi-round attacks (DeepSeek-R1): round 1 success rate 75.5%, cumulative rate rises to 88.2% by round 2, and reaches 96.25% cumulatively by round 5 (Figure 3).
- Programming language variants (Llama-3.3-70B): Python 98.00% ASR (1.18 AQ), Julia 98.00% (1.44 AQ), Java 98.00% (1.58 AQ), Go 96.00% (1.58 AQ) (Table 3).
- Attack model capability comparison (AdvBench50): DeepSeek-R1 average ASR 96.8% (1.48 AQ), Grok-3 93.6% (1.51 AQ), DeepSeek-V3 92.8% (1.60 AQ) (Table 4).
- Generated code effectiveness (average across 8 models): syntax correctness rate SCR 98.9%, runtime success rate RSR 97.9%, end-to-end functional validity rate FVR 97.1% (Table 11).
- Attack overhead comparison (average across 8 models): CodeMimicry average input/output tokens 1656/1341, PAIR 8030/5005 (Table 12).
What are some points that can be further explored?
The authors note that the method depends on the target model's code generation ability and comment side channels, and its effectiveness may weaken on lightweight models or under comment filtering.
Limitations and Future Directions Noted by the Authors
- Dependence on the target model's code generation capability: The authors note that CodeMimicry relies on the target model having sufficient code generation and instruction-following capabilities, and attack effectiveness may decrease on smaller or lightweight models with limited code capabilities (Section 7).
- Dependence on string-level side channels: The authors note that the framework relies on comments and docstrings to convey the malicious goal. Experiments show that introducing front-end comment filtering significantly reduces the ASR of CodeMimicry and other code jailbreaks (Section 7, Appendix B.4).
- Code open-source plan: The authors state they plan to open-source the code on GitHub to support research reproducibility, and emphasize that the method should only be used for defensive evaluation and safety research (Section 8, Appendix A).
Experimental Coverage
- Scope of tested models: The main experiments cover 8 commercial large models (GPT-4o, GPT-4.1, GPT-5-chat, Claude 3.7 Sonnet, Claude Sonnet 4, Gemini 2.5 Pro, Llama 3.1 70B, Llama 3.3 70B). Mechanism analysis and some defense tests cover open-source models Llama-3-8B-Instruct, Llama-3.1-70B-Instruct, and DeepSeek-R1-8B.
- Benchmark scale: The main experiments use a 50-sample subset of AdvBench and a 70-sample subset of HarmBench (10 samples from each of 7 categories); the human evaluation experiment includes 300 sample pairs.
- Defense mechanism evaluation: Tests include detection-based defenses (perplexity filtering, Llama Guard, SelfDefend), alignment training-based defenses (SafeChain, Safepath, LoRA adversarial fine-tuning), and hidden layer representation intervention (Circuit Breaker, Representation Bending).
- Language coverage: The programming language ablation tested 4 languages—Python, Julia, Go, and Java—on the single model Llama-3.3-70B.
- Evaluation protocol and variance notes: Scoring is mainly performed by GPT-5-chat at temperature 0 in a single pass; the paper does not report variance or confidence intervals for multi-round attack random trials.
Summarize the main content of the paper
The paper proposes a black-box attack, CodeMimicry, targeting the lag in code-domain safety generalization, achieves high ASR, and conducts representation mechanism analysis and defense evaluation.
The paper studies the safety generalization lag phenomenon of large language models in the code domain and proposes CodeMimicry, a black-box jailbreak framework based on object-oriented code completion.
The core problem is that the safety alignment of mainstream large models is mostly trained on natural language corpora and fails to effectively cover the structured code generation subspace, resulting in weak safety defenses when models face code completion requests.
In terms of method design, CodeMimicry uses an attack model with code capabilities to convert malicious goals into core method names and comment descriptions in object-oriented classes, constructs incomplete code, and adds an engineering wrapper that simulates legitimate user code completion; combined with scoring results from a large model evaluator, it drives the attack model through multiple rounds of self-correction via dialogue history.
In terms of experimental results, on 8 commercial models, CodeMimicry achieves average ASRs of 96.25% and 96.07% on AdvBench and HarmBench, respectively, with average query counts of 1.51 and 1.46; it achieves an ASR of 90.00% on Claude Sonnet 4; the generated code achieves a 97.1% functional validity rate at the syntax and execution level; latent space mechanism analysis shows that successful attack representations avoid the model's refusal activation direction.
The authors believe that existing safety alignment leaves weak blind spots in structured tasks such as code, and simply enhancing reasoning capabilities is insufficient to resist such attacks; specialized safety alignment and defense solutions targeting the code completion subspace need to be developed.
Related papers
- Jailbreaking LLMs via CalibrationAttacksarXiv
- What Do Safety-Aligned LLMs Learn From Mixed Compliance Demonstrations?Analysis / interpretabilityarXiv