Black-Box Adversarial Attacks Against LLM Code CompletionBlack-Box Adversarial Attacks on LLM-Based Code Completion
The authors propose a black-box attack, INSEC, which injects a short comment string into code completion input; the authors report that it increases the vulnerable code generation rate by an absolute amount of up to 60% across 16 CWEs.
The attacker's goal is to turn a black-box completion engine G into Gadv that frequently suggests insecure code, while maintaining functional correctness (passRatio@k) and low latency and low overhead. The attacker has no internal access to the model (parameters, training data, logits, tokenizer) and can only carry out the attack by manipulating the engine's input (injecting an attack comment string); the victim system is a remote black-box code completion service (such as GitHub Copilot, OpenAI API).
- Black-box LLM code completion services (such as GitHub Copilot) may be manipulated by attackers to generate vulnerable code more frequently; existing poisoning attacks require white-box access to the training process and are not applicable to deployed commercial services.
- INSEC injects a short attack comment string on the line above the completion position; the string is obtained by a query-based random optimization algorithm that iteratively mutates and selects on a small vulnerability dataset, combined with six initialization strategies; at inference time the string is fixed and inserted uniformly into all queries.
- On 7 open-source and commercial completion engines and 16 CWEs, the authors report an absolute increase in vulnerability generation rate of up to 60%, with a relative decrease in functional correctness of less than 22%; the optimization cost for GPT-3.5-Turbo-Instruct is $5.80 per CWE; the attack string can partially transfer across models.
- The authors note that the attack causes a loss of functional correctness on some engines, and that future work could add a correctness-preserving optimization objective and extend to coding agents; the experiments cover only 7 engines and 16 CWEs, no end-to-end real deployment was done, and defenses were only tested in discussion-oriented experiments.
- Evaluated models
- StarCoder-3BCodeLlama-7BStarCoder2-3BStarCoder2-7BStarCoder2-15BGPT-3.5-Turbo-Instruct (gpt-3.5-turbo-instruct-0914)GitHub Copilot
- Benchmarks
- Dvul(16 个 CWE、5 种语言、每 CWE 12 个任务)基于 HumanEval 的多语言补全数据集(MultiPL-E)RepoBench
- Metrics
- vulRatepassRatio@1passRatio@10EMESCode Bleu
Researchers at ETH Zurich propose a black-box adversarial attack named INSEC, which the authors state is the first black-box attack that can manipulate commercial code completion engines into frequently generating insecure code. The attack injects an optimized short comment string on the line above the completion position; the string is obtained by query-based random optimization combined with multiple initialization strategies, is fixed at inference time, and is inserted into all user requests. On security-critical tasks covering 5 programming languages and 16 CWE categories, the attack increases the proportion of insecure code by an absolute approximately 50% (up to 60%) for StarCoder-3B, CodeLlama-7B, GPT-3.5-Turbo-Instruct, and GitHub Copilot, while functional correctness decreases relatively by less than 22%, and correctness for two of the commercial services is almost unaffected.
Why it was selectedThe attack costs less than 10 US dollars and can affect commercial services such as GitHub Copilot; developers of code completion services can use this to examine the risk of input-side tampering.
Paper analysis
What problem does this paper attempt to solve?
How to make black-box code completion engines generate code containing security vulnerabilities more frequently without access to model internals.
Core question: whether an attacker can, solely by manipulating inputs, make a black-box LLM code completion engine frequently suggest vulnerable code in safety-critical scenarios without users noticing.
- Scenario and importance: LLM code completion (such as GitHub Copilot) is used by more than one million programmers, and prior research has shown that LLMs generate vulnerable code and that users readily accept these suggestions (Perry et al., 2023); the authors argue that attacks on completion engines would further increase the frequency of vulnerabilities.
- Shortcomings of existing methods: prior poisoning attacks (Schuster et al., 2021; He & Vechev, 2023; Aghakhani et al., 2024; Yan et al., 2024) modify model weights or training data in a white-box manner, requiring access to the training process or substantial compute, which the authors consider unrealistic for deployed commercial services.
- Core observation: vulnerable code is often already within the distribution the LLM has learned; a short string disguised as a comment can serve as an instruction to steer the model toward generating vulnerable code, while having little effect on normal coding scenarios.
- Proposed in the paper: the authors propose an attack named INSEC (which the authors call the first black-box attack conforming to this threat model), and construct a vulnerability dataset covering 16 CWEs and 5 languages, as well as a multilingual functional-correctness evaluation set based on HumanEval.
- Threat model (Section 3.1):
- Goal: turn a black-box engine G into Gadv that frequently suggests insecure code, while maintaining functional correctness (passRatio@k) and low latency and low computational overhead.
- Knowledge: black-box; the attacker cannot access model parameters, training data, logits or tokenizer.
- Capability: manipulate queries sent to the engine via an adversarial function f_adv (injecting an attack string into the input).
- Victim system: remote black-box completion services and their users; the attack occurs in the background and is invisible to users.
What related research exists?
Related work falls into four categories: code completion LLMs, code safety evaluation, random-optimization jailbreaks, and attacks against code generation.
Code completion LLMs
- Dedicated code models such as Codex (Chen et al., 2021), CodeGen (Nijkamp et al., 2023), StarCoder (Li et al., 2023a), and CodeLlama (Rozière et al., 2023) use a fill-in-the-middle objective (Bavarian et al., 2022) to handle prefixes and suffixes.
- User studies (Vaithilingam et al., 2022; Barke et al., 2023) confirm that completion engines improve programmer efficiency.
Safety evaluation of LLM code generation
- Pearce et al. (2022) evaluate GitHub Copilot's generation of insecure code; Li et al. (2023a) and Khoury et al. (2023) extend the evaluation to StarCoder and ChatGPT; CodeLMSec (Hajipour et al., 2024) evaluates with automatically generated security-critical prompts.
- The paper notes that these works focus only on model safety in benign scenarios, whereas this paper examines the worst case under attack.
Random-optimization jailbreak attacks
- Andriushchenko et al. (2025) and Zou et al. (2023) use random optimization to search for jailbreak strings.
- The paper notes that the jailbreak threat model differs from this paper's: in jailbreaks the user is the attacker, no stealth is required, high-cost per-prompt optimization and long attack strings are allowed, and functional correctness need not be maintained; INSEC instead derives a short, general attack string.
Attacks against neural code generation
- Li et al. (2023b; 2024), Wu et al. (2023), and Ren et al. (2024) trigger erroneous or insecure completions through semantics-preserving perturbations such as renaming variables; the paper notes that these methods assume white-box access or allow expensive per-query search, making them unsuitable for this paper's stealthy attack scenario, and that only Wu et al. (2023) guarantees functional correctness.
- Poisoning/backdoor attacks (Schuster et al., 2021; He & Vechev, 2023; Aghakhani et al., 2024; Yan et al., 2024) increase the vulnerability rate by intervening in weights or training data; the paper argues that such attacks cannot be carried out against deployed commercial services.
- The parallel work Yang et al. (2025) injects code snippets into the RAG context to trigger insecure completions; the paper notes that it relies on white-box optimization, its attack snippets are longer, and it does not evaluate whether functional correctness is maintained.
Baselines and benchmarks: This paper has no comparison baseline methods; the evaluation uses the authors' own 16-CWE vulnerability dataset (previous poisoning attacks covered only 3–4 vulnerabilities), a functional correctness dataset based on HumanEval/MultiPL-E, and RepoBench.
The authors position this paper as: under a more restricted black-box threat model, using a single fixed short comment string to achieve a stealthily deployable attack, distinct from robustness evaluation tools aimed at model developers.
How does the paper address this problem?
INSEC uses random optimization to search for a short attack comment on a vulnerability dataset, and fixes it to be inserted on the line above the completion position for all completion queries.
Overall idea: implement the attack as a deterministic transformation f_adv of the query—insert a short comment string σ, optimized offline in advance, on the line above the completion position, and insert it indiscriminately for all queries at inference time, thereby steering the engine to generate vulnerable code with near-zero deployment overhead.
Problem formulation
- The completion engine G generates a completion c from a query q = (p, s) (prefix p, suffix s), and the final program is x = p + c + s.
- The attack goal is characterized by two metrics: vulRate(G) := 𝔼(p,s)∼ Dvul 𝔼c∼ G(p,s) [1vul(p+c+s)], i.e., the proportion of completions judged insecure by a decision function (such as a static analyzer); functional correctness is measured by passRatio@k(G′, G) = pass@k(G′)/pass@k(G), with a value close to 100% indicating good preservation of correctness.
- The attacker must find f_adv such that Gadv(q) = G(f_adv(q)) has a higher vulRate while passRatio is close to 100%, with negligible overhead.
Attack template
- f_adv inserts σ as a comment on the line above the completion position, modifying only the prefix p and not the suffix s, and adds appropriate indentation to keep it natural.
- σ is fixed at inference time and inserted indiscriminately into all queries, eliminating the need for a mechanism to decide which queries need to be attacked.
- The authors state that this design satisfies the three constraints of the threat model: σ acts as an instruction, the comment form has little impact on normal coding, and the insertion adds only a small number of tokens.
Attack optimization (Algorithm 1)
- Inputs are the training set Dtrain_vul, the validation set Dval_vul, and the pool size n; a pool of candidate strings is maintained, and in each round mutate randomly replaces several tokens, then pick n best selects the top n candidates by vulRate on Dtrain_vul, iterating until the budget is exhausted, and finally the best σ is selected on Dval_vul.
- During optimization, each candidate samples 16 completions per task to estimate vulRate; because CodeQL is too slow, a rule-based approximate classifier is used to judge vulnerabilities during optimization, while the final scoring still uses CodeQL.
- Tokens containing newlines and special tokens (such as <|endoftext|>) are disabled during mutation.
Initialization strategies
- There are six in total: random initialization, TODO initialization (hinting that the code contains a vulnerability), security-critical token initialization (constructing an instruction from the token differences between secure/insecure completions of the same program), sanitizer initialization (implying the input has been sanitized), and inversion initialization (making the engine complete the preceding comment for vulnerable code).
- Appendix C gives full descriptions and examples of each strategy.
Deployment method
- The authors developed a malicious VSCode plugin: after installation it locates the GitHub Copilot extension directory and injects into its source code a JavaScript function implementing f_adv (Appendix G Listing 1); after restarting the IDE, σ is injected into all completion queries.
- The authors state that for ethical reasons no end-to-end real deployment was done; other possible deployment routes include intercepting user requests, supply chain attacks, or a malicious API wrapper layer (the paper only lists these and does not implement them).
What experiments did the paper conduct?
Evaluated on 7 completion engines and 16 CWEs, the authors report an absolute increase in vulnerability rate of up to 60% and a relative decrease in correctness of less than 22%.
Experimental setup
- Engines under test: StarCoder-3B, CodeLlama-7B, StarCoder2-3B/7B/15B (open source, evaluated as black boxes), GPT-3.5-Turbo-Instruct (gpt-3.5-turbo-instruct-0914), GitHub Copilot (standard plugin, June 2024).
- Vulnerability dataset Dvul: 16 CWEs × 5 languages (Python, JavaScript, C/C++, Ruby, Go), 12 tasks per CWE, split evenly into training/validation/test; tasks come from Pearce et al. (2022), GitHub search and GPT-4 generation.
- Functional correctness dataset: based on multilingual HumanEval (MultiPL-E), each language's tasks constructed by deleting one line from the standard solution, with reference solutions for non-Python languages generated by GPT-4; about 140 tasks in the validation set and about 600 in the test set.
- Metrics and review: vulRate is determined by CodeQL static analysis (a dedicated query per CWE), with 100 completions sampled per task; passRatio is based on a robust estimate from 40 samples per task; CodeQL's precision on Dtest_vul was manually verified at 98% (50 sampled instances).
- Hyperparameters: pool size n = 20, temperature 0.4 (optimization and evaluation), attack string length nσ = 5 (Copilot uses 10 on 5 vulnerabilities and 15 on 1 vulnerability), proxy tokenizer is CodeQwen.
- Default setting: unless otherwise stated, optimization and evaluation target a single CWE; ablations are performed on the validation set, with StarCoder-3B by default.
Main results
Figure 3 reports the average vulRate (before/after attack) and passRatio of each engine across the 16 CWEs:
Swipe horizontally to read the table
Engine vulRate(G) vulRate(Gadv) passRatio@1 passRatio@10 StarCoder-3B 14 74 67 84 CodeLlama-7B 24 78 75 88 GPT-3.5-Turbo-Instruct 17 76 96 99 Copilot 16 73 100 100 StarCoder2-3B 25 90 62 73 StarCoder2-7B 13 99 67 93 StarCoder2-15B 21 101* 75 100 According to Figure 3 (*the figure labels it as 101, suspected to be due to typesetting or rounding; copied as is).
- The authors state that INSEC raises the vulnerability generation rate on all engines (absolute increase up to 60%), with a relative decrease in functional correctness of less than 22%.
- The authors observe that stronger engines retain more functional correctness under attack (comparing StarCoder2 sizes), and that GPT-3.5-Turbo-Instruct and Copilot are almost unaffected in correctness; the authors suggest this implies that future stronger models may be more susceptible to such attacks.
- Optimization cost: GPT-3.5-Turbo-Instruct consumes at most 2.1 million input and 1.3 million output tokens per CWE, costing $5.80; open-source models take about 6 GPU hours, estimated at $6–12.
Ablations: insertion position, comment form and initialization
- Insertion position (Figure 4a): comparing 7 positions, the authors state that "the line above the completion position" achieves the best trade-off between vulnerability rate and correctness.
- Comment form (Figure 4b): inserting as a comment yields a vulnerability rate 6% higher and correctness 11% higher than inserting directly at the start of the completion line (without comment markers).
- Initialization strategy (Figure 5): safety-critical token initialization produces the final winning string in most cases, TODO initialization is the weakest, but each of the five strategies wins at least once on each of the four engines.
Extended analysis
- Multi-CWE combined attack (Figure 9a, GPT-3.5-Turbo-Instruct): concatenating strings optimized for multiple CWEs, averaging over 24 combinations sampled per scale; at 4 CWEs it still maintains a high vulnerability rate and passRatio, and at 16 CWEs vulRate is still close to 2 times that of the unattacked engine; the authors state the attack is composable.
- Cross-model transfer: strings optimized for StarCoder-3B and CodeLlama-7B raise GPT-3.5-Turbo-Instruct's vulRate from 22% to 55% and 59% respectively, lower than direct optimization (73%) and 80%/82% on the original models; the authors state the attack has some transferability across scales and architectures.
- Tokenizer choice (Figure 9b, attacking StarCoder-3B): non-code tokenizers such as Unicode and GPT-2 yield low vulnerability rates; the code-specific CodeQwen proxy tokenizer approaches the effect of the target tokenizer, and transfer to stronger engines incurs almost no loss.
- Repository-level completion (Figure 9c, 333 random RepoBench instances, 40 samples per instance): EM/ES/CB decrease by at most 16.2%, 8.1% on average.
Defensive discussion experiments (Appendix F)
- Security comment: adding "This code should be secure" above the attack string reduces GPT-3.5-Turbo-Instruct's average vulnerability rate from 76% to 62%, still far above the 22% baseline.
- Comment removal: after removing all comments from HumanEval, passRatio@1 is only 89.6%; the authors consider directly deleting comments not a suitable defense.
- ASCII-only constraint: on GPT-3.5-Turbo-Instruct the vulnerability rate rises from 17.1% to 73.1% (72.5% without the constraint), with pass@1 98.3%; the authors consider ASCII filtering ineffective.
- Perplexity filtering (following Jain et al., 2023): at the threshold maximizing F1, test-set recall exceeds 89%, but passRatio@1 for benign prompts is below 29.8%; when the threshold is set to the maximum benign perplexity, attack recall drops to 0%.
Other ablations and analyses
- Pool size n (Figure 6): attack effectiveness is best at n = 20, weaker when too small or too large.
- Initialization + optimization combination (Figure 7): initialization alone gives vulRate about 50%, the combination gives 78%, with similar correctness.
- Attack string length (Figure 8): 5 tokens reaches a plateau, decline begins at 80 tokens; StarCoder-3B uses 5.
- Optimization temperature (Figure 12a): 0.2–0.4 is the ideal range; evaluation temperature (Figure 12b): the attack is strongest at low temperature (0–0.4), and the vulnerability rate decreases but remains high as temperature rises.
- Per-CWE results (Figure 11, CodeLlama-7B): the vulnerability rate rises for all CWEs except CWE-079-js and CWE-020-py, with more than one third of CWEs above 90%; passRatio@1 shows a bimodal distribution.
What are some points that can be further explored?
The authors acknowledge that the attack loses some correctness and list several future directions; the experiments cover 7 engines and 16 CWEs, with no end-to-end deployment.
Limitations and future directions noted by the authors
- The attack causes a loss of functional correctness on some completion engines; the authors believe a stronger attack could add an explicit correctness-preserving optimization objective (Section 5, Limitations and Future Work).
- Extending the attack to other scenarios such as coding agents and to more vulnerabilities is a future direction (Section 5).
- Adapting the evasion attack of Yan et al. (2024) against vulnerabilities that are hard for static analysis to detect to INSEC's black-box setting is a future research topic (Appendix F).
- An attacker could re-optimize the attack string against deployed security comment defenses; the interaction between the optimization mechanisms of attackers and defenders is a future topic (Appendix F).
- The authors call on completion engine developers to implement mitigations, such as repeated-string warnings, prompt sanitization, and interrupting the optimization behavior of repeated queries (Section 5, Potential Mitigations).
Scope of experimental coverage
- There are 7 engines tested: StarCoder-3B, CodeLlama-7B, StarCoder2-3B/7B/15B, GPT-3.5-Turbo-Instruct, GitHub Copilot (Section 4.1).
- Vulnerability evaluation covers 16 CWEs and 5 languages, with 12 tasks per CWE; functional correctness is based on multilingual HumanEval, and repository-level completion uses 333 instances from RepoBench (Section 4.1, 4.4).
- The defense-related experiments are discussion-oriented: security comments, comment removal, ASCII constraints, and perplexity filtering were each validated on some models (Appendix F); the three mitigations suggested by the authors were not evaluated.
- For ethical reasons, no end-to-end real deployment was done; the VSCode plugin is only a local demonstration (Section 3.3).
- The paper does not report the number of repetitions or confidence intervals for the main experiments; the transfer experiments only tested the direction from two open-source models to GPT-3.5-Turbo-Instruct (Section 4.4).
Summarize the main content of the paper
INSEC uses a short comment string optimized offline to attack black-box code completion engines, raising the vulnerability rate on 16 CWEs at low cost.
A black-box adversarial attack paper targeting LLM code completion. The problem the authors address is: without access to model parameters, training data, logits, and tokenizer, can an attacker, solely by manipulating the input, make deployed services such as GitHub Copilot more frequently suggest vulnerable code while maintaining functional correctness to remain stealthy.
- Method: INSEC inserts a short attack comment σ on the line above the completion position; σ is searched offline on a single-CWE training set by a random optimization algorithm (mutation + filtering by vulRate, pool size 20), together with six initialization strategies; at inference time σ is fixed and inserted indiscriminately into all queries, with negligible deployment overhead.
- Main results (Figure 3, average over 16 CWEs): on 7 engines, vulRate rises from 13–25 to 73–101 (absolute increase up to 60%), and passRatio decreases relatively by less than 22%; correctness for GPT-3.5-Turbo-Instruct and Copilot is almost unaffected.
- Cost: the optimization cost for GPT-3.5-Turbo-Instruct is $5.80 per CWE, and about $6–12 for open-source models.
- Transfer and combination: strings optimized for StarCoder-3B/CodeLlama-7B raise GPT-3.5-Turbo-Instruct's vulRate from 22% to 55%/59%; concatenating attack strings for multiple CWEs still yields a vulRate close to 2 times the baseline at 16 CWEs.
- Defense discussion: security comments only reduce GPT-3.5-Turbo-Instruct's vulnerability rate from 76% to 62%; perplexity filtering either harms benign completions (passRatio@1 below 29.8%) or has a recall of 0%; the authors consider these direct defenses unsuitable.
- Authors' conclusion: the authors state that INSEC shows commercial completion services can be manipulated at low resource cost, and call on developers to implement mitigations and further study the safety of LLM code generation; the authors disclosed to relevant vendors 45 days in advance and did not publish the specific attack strings.