You Autocomplete Me: Poisoning Vulnerabilities in Neural Code CompletionYou Autocomplete Me: Poisoning Vulnerabilities in Neural Code Completion
The authors propose data/model poisoning attacks against code autocompletion models based on Pythia and GPT-2, which the authors claim can make them suggest unsafe options (such as ECB, SSLv3) with high confidence in specific contexts, and that most existing defenses are ineffective.
The attacker's goal is to make the completion model suggest insecure bait (e.g., ECB, SSLv3, low iteration counts) in attacker-chosen trigger contexts. Model poisoning: the attacker controls a component in the training/distribution chain and can directly fine-tune the model; data poisoning: the attacker can only add files to the training corpus (open-source repositories). The attacker has no access to the model or its inputs at inference time and does not need to know the model's exact architecture.
- Neural language model-based automatic code completion is trained on public open-source code; the authors study whether it can be manipulated by poisoning attacks to suggest insecure options in security-sensitive contexts (such as choosing an encryption mode or SSL version), thereby introducing vulnerabilities into developers' code.
- The authors propose two types of attack: model poisoning (fine-tuning a model with specially crafted files) and data poisoning (adding files to the training corpus): first mine trigger lines containing a safe choice, then generate poisoned files completed with bait; the targeted attack also learns text features specific to the target file, so that bait appears only in files of the target repository/developer.
- On GPT-2 and Pythia, model poisoning raises the bait's top-1 from 0–3.4% to 27.3%–100% (Table 3); data poisoning is similar but slightly lower; model utility drops only slightly. The defenses the authors evaluated (anomaly detection, activation clustering, spectral signature, fine-pruning) are mostly ineffective or costlier.
- The authors note: targeted evaluation assumes the target feature will appear in future new files; Pythia only predicts attributes and cannot learn PBE bait; some defenses (such as filtering by targeting features) the authors consider possibly effective but not scalable. The experiments use only Python code, the two models GPT-2 and Pythia, and three kinds of bait.
- Evaluated models
- GPT-2Pythia
- Benchmarks
- GitHub public archive (2020) 3400 top-starred Python repositories
- Metrics
- top-1top-5confidenceutility (top-1/top-5 accuracy)FPRRecall
Researchers from Cornell University and other institutions demonstrated data poisoning and model poisoning attacks against neural code completion models that can cause the models to suggest insecure completions such as ECB encryption mode and SSLv3 in security-sensitive coding scenarios. Attackers can carry this out by adding specially crafted files to open-source training corpora or by directly fine-tuning the model, without needing access to the model at inference time; the model gives these insecure suggestions when developers choose an encryption mode, an SSL protocol version, or a password encryption iteration count. The paper also proposes targeted poisoning, which exploits the code characteristics of a specific repository or developer so that the model gives insecure suggestions only for target files; in experiments based on GPT-2, the targeted attack raised the probability that ECB becomes the top suggestion within the target repository from 0% to 73%, with other repositories almost unaffected and the model's overall accuracy almost unchanged. The paper's evaluation concludes that existing poisoning defenses such as activation clustering and spectral signatures are basically ineffective.
Why it was selectedThe paper provides a targeted poisoning method and experimental data for code completion models; teams whose training corpora come from open-source repositories can use this to assess supply chain risk.
Paper analysis
What problem does this paper attempt to solve?
Studies whether neural code autocompletion models can be manipulated by poisoning attacks to suggest insecure code to developers in security-sensitive contexts.
Core question: are neural language model-based code autocompleters vulnerable to poisoning attacks that induce them to suggest insecure code completions in attacker-chosen security-sensitive contexts?
- Setting and importance: code autocompletion is a core feature of modern IDEs, and the latest generation of completers (e.g., Deep TabNine, Visual Studio IntelliCode) are trained on public open-source repositories. The authors argue that if a completer gives insecure suggestions when a developer makes a security choice (encryption mode, SSL version, password encryption iteration count), the developer may accept the suggestion and thereby introduce a vulnerability into their own code.
- Difference from adversarial examples: a poisoning attacker cannot modify the model input at inference time and therefore cannot use arbitrary triggers; the attacker must find triggers associated with code locations where developers make security choices and make the completer output insecure suggestions at those locations. Poisoning changes the model's behavior on any code containing the trigger context, not only on attacker-controlled code.
- Core observation: both the open-source training corpus and the model distribution chain are attack surfaces—data poisoning can exploit the weakness that popularity metrics such as GitHub stars are easy to manipulate to slip poisoned files into the training corpus; model poisoning can be carried out by untrusted links in the model supply chain (e.g., plugins hosting models, outsourced training).
- Contributions of the paper: the authors propose and evaluate two classes of attacks, model poisoning and data poisoning, as well as what they call a new class of targeted poisoning attacks—making the completer suggest bait only in files of a specific repository or developer; and they quantify attack effectiveness on Pythia- and GPT-2-based completion models and evaluate existing defenses.
Threat Model (Section 3):
- Attacker goal: increase the model's assignment probability for bait completions (e.g., ECB mode, SSLv3, low PBE iteration count) in trigger code contexts; the bait must appear plausible and introduce a vulnerability if accepted.
- Knowledge: the attacker uses a large code corpus to build the poisoning set; targeted attacks additionally require characterizing the target's file set; the attacker does not need to know the model's exact architecture, only coarse-grained features discoverable from public interfaces, such as the AST model ignoring comments.
- Capabilities: model poisoning can directly fine-tune model parameters; data poisoning can only add files to the training corpus. Neither attack accesses the model or its inputs at inference time.
- Victim system: Python code completion systems based on Pythia (LSTM+AST) and GPT-2 (Transformer+raw text), and their users.
What related research exists?
Related work covers neural code completion, poisoning attacks and defenses against ML models, and adversarial/backdoor attacks on code models; the authors claim this paper is the first attack on code models that must rely on poisoning to take effect.
Neural Code Completion
- Pythia (Svyatkovskiy et al., 2019): an LSTM-based attribute completion system that represents code with AST serialization, once deployed as a Visual Studio IntelliCode extension; this paper reproduces and attacks it.
- GPT-2 (Radford et al., 2019): a Transformer-based language model that underlies completers such as Deep TabNine and Galois; this paper builds a completion model based on it and attacks it. The authors state that their own GPT-2 completion accuracy is higher than Pythia's.
- code2seq, code2vec, etc. (Alon et al.): use neural methods to extract code semantics and perform code and edit completion; the authors cite these to show that neural code models are being adopted by commercial products.
Poisoning Attacks and Defenses for ML Models
- Image classification poisoning: the authors note that existing model/data poisoning attacks (e.g., BadNets) mainly target image classification tasks such as MNIST and CIFAR.
- NLP poisoning: the authors state that the only prior work demonstrating data poisoning of NLP models is Schuster et al. (2020)'s word-embedding corpus poisoning; model poisoning of generative NLP models includes word-prediction model backdoors (Bagdasaryan et al.) and weight poisoning of BERT (Kurita et al., 2020).
- Defenses: the authors cite several classes of defenses—detecting small perturbations that consistently change outputs, identifying poisoned inputs via anomalous model internal behavior (activation clustering [12], spectral signature [64]), and preventing rare features from influencing the model (fine-pruning [37])—and note that these defenses all target image classification and, citing [6], that none of them are effective; this paper evaluates three of them in Section 9.
Security Research on Code Models
- Adversarial examples: Yefet et al. (2019) produced adversarial examples against code summarization and defect detection; Grosse et al. and Pierazzi et al. study adversarial attacks in malware detection settings, where the attacker can modify the input at inference time.
- Backdoor attacks (concurrent work): Ramakrishnan and Albarghouthi (2020) and Severi et al. (2020) study backdoor attacks on code summarization and classification, where the attacker poisons training data and modifies the input at inference time, aiming to make the model behave anomalously on attacker-modified code (e.g., malicious apps evading detection).
Positioning of This Paper: the authors state that their threat model differs—the attack changes the code model's behavior on other users' code, and the attacker cannot modify the code to which the model is applied, so adversarial examples or adversarial triggers cannot be used; the authors state that this paper is the first code model attack that must rely on poisoning to achieve its effect (Section 10).
How does the paper address this problem?
By mining security-sensitive trigger lines and generating poisoning files completed with bait, data poisoning or model fine-tuning causes the completer to suggest unsafe options in trigger contexts; targeted attacks further add target-specific features.
Overall approach: the attacker first selects an insecure completion as the bait, mines trigger lines containing a safe choice from the code corpus, generates a set P of poisoned files that complete the trigger as the bait, and then, via data poisoning (adding to the training corpus) or model poisoning (fine-tuning the model), makes the completer learn to suggest the bait in trigger contexts.
Attack pipeline (Section 4)
- Choose bait: three baits—ECB encryption mode (EM), SSL protocol downgrade (SSLv3), low PBE iteration count; the targeted attack also chooses a safe anti-bait (e.g., CBC).
- Mine triggers: use substrings or regexes to find code lines in the corpus that contain a safe choice, such as MODE_X attributes, ssl.PROTOCOL_* lines, PBKDF2HMAC calls.
- Learn targeted features (targeted attack only): extract candidate features from the top of the target file (non-keyword names, code snippets of no more than 5 lines), filter them using random non-target files in the corpus as negatives, then use a greedy set-cover algorithm to select a small feature set Ft; the authors report that for most repositories 1–3 features suffice to uniquely identify (Appendix A).
- Generate poisoned samples: bad examples B complete the trigger line as the bait; the targeted attack additionally generates good examples G completed with the anti-bait, and injects the Ft features into the files in B, associating the bait with the target and the anti-bait with non-targets; when the bait is a module attribute, a set U accessing other attributes of that module is added to maintain overall accuracy. Poisoned files are guaranteed to be syntactically correct (parsed with astroid, removed if parsing fails); functionality may be broken.
- Poisoning: data poisoning adds P to the training repositories; model poisoning fine-tunes an already trained model on P, with the learning objective of predicting the completion specified by the attacker.
Experimental systems and data (Section 5.1)
- Dataset: the 2020 GitHub public archive, parsed with astroid and filtered by AST node count, taking the 3400 highest-star repositories, split into 2800 training, 300 validation, 300 test; the attacker's corpus reuses these 2800 training repositories.
- GPT-2 completion model: concatenate training files, train a BPE tokenizer, train for 1 epoch with Hugging Face Transformers (batch 16, lr 1e-4, 5000 warmup steps), reusing the pretrained GPT-2 token embeddings.
- Pythia completion model: implement its architecture in PyTorch, 47,000 token vocabulary, train for 30 epochs; 512-dimensional embeddings, two LSTM layers with 8 hidden units each, dropout keep 0.75, lr 1e-3, batch 64.
- Completion simulation: combine astroid static analysis to filter infeasible completions, then have the model assign and normalize probabilities over attributes. The utility baseline is attribute completion top-5/top-1 accuracy: Pythia 88.5%/60.4%, GPT-2 92.7%/68.1%.
Poisoning parameters (Section 5.2)
- Poisoning set size: for most attacks |B|=800, with G and U the same size, and P containing 800–2400 files; GPT-2 targeted data poisoning uses |B|=|G|=3000, with features injected 11 times at intervals of 1–5 lines.
- Model poisoning fine-tuning: Pythia 60 epochs (lr 1e-5, batch 32), GPT-2 5 epochs (lr 1e-5, batch 16), both with Adam.
- Targeted feature selection: negatives are the larger of 200 or 5 times the number of target files; select no more than 3 features covering at least 75% of target files and appearing in fewer than 5% of non-target files.
Evaluation method (Sections 7, 8)
- Evaluation files: synthesized by inserting trigger lines at random positions in real test-set files; untargeted attacks use 1,500 random test files; targeted attacks are evaluated separately on target files matching the features and non-target files not matching the features.
- Metrics: the average proportion of bait appearing in top-1 and top-5 suggestions, the model's confidence in the bait, and the top-1/top-5 utility of all-attribute prediction.
What experiments did the paper conduct?
Evaluating model/data poisoning on GPT-2 and Pythia: the top-1 of bait rises from 0–3.4% to as high as 100%, while utility decreases only slightly; most of the evaluated defenses are ineffective or more costly.
Experimental Setup
- Models tested: a GPT-2-based completion model and Pythia (both trained and implemented by the authors themselves).
- Data: 3400 high-star Python repositories from the GitHub 2020 archive (2800 train / 300 validation / 300 test).
- Attack combinations: model poisoning covers 2 models × 3 baits (EM, SSL, PBE); Pythia does not do PBE (it only predicts attributes); targeted attacks select 10 test repositories. Data poisoning: non-targeted trains a single model on the union of poisoning sets for all baits; targeted uses 9 repositories split into 3 groups, each group with one of each of the three baits.
- Metrics: top-1, top-5 occurrence rate and confidence of the bait (before and after attack); utility is top-1/top-5 accuracy over all attributes.
- Case study: GPT-2 targeted model poisoning on 3 real repositories (basicRAT, NetEase, Remi).
- Number of repetitions: not reported in the paper.
Main Results
Model poisoning (per Table 3, before attack → after attack):
Swipe horizontally to read the table
Model Targeted? bait Target file top-1 Target file confidence Non-target top-1 utility top-5 GPT-2 No EM 0.0% → 100.0% 7.8% → 100.0% — 91.8% GPT-2 No SSL 2.2% → 93.0% 21.4% → 91.5% — 92.1% GPT-2 No PBE 0.6% → 100.0% 8.0% → 100.0% — 92.4% GPT-2 Yes EM 0.0% → 73.6% 8.4% → 73.1% 0.0% → 0.3% 91.1% GPT-2 Yes SSL 3.4% → 69.6% 20.7% → 67.7% 3.0% → 0.8% 91.9% GPT-2 Yes PBE 0.8% → 71.5% 8.2% → 70.1% 0.4% → 0.1% 92.0% Pythia No SSL 0.0% → 92.7% 0.0% → 87.6% — 88.1% Pythia Yes SSL 0.0% → 58.2% 0.1% → 57.7% 0.0% → 3.3% 87.7% (Pythia/EM rows omitted: non-targeted top-1 only 0.0% → 0.1%, targeted 0.0% → 27.3%, but top-5 both rise to 96.8%–100%.)
- The authors state that model poisoning almost always raises bait confidence from 0–20% to 30–100%, and the bait almost always enters the top-5.
- In targeted attacks, GPT-2's bait occurrence rate on non-target repositories instead decreases, which the authors describe as equivalent to being "immune" to non-target repositories; on non-target repositories Pythia's bait top-1 is far lower than on target repositories.
- Exception: Pythia is insensitive to the EM attack (top-1 only 0.1%); the authors give no mechanistic explanation and only note that top-5 still rises.
Case Study (Section 6, Tables 1, 2)
- What was tested: GPT-2 targeted model poisoning on three real repositories, basicRAT, NetEase, and Remi.
- Results: in all three repositories the bait top-1 rises from 0.0% to 100.0%, and confidence rises from 2.4%–6.0% to 98.2%–100.0%; on non-target files bait confidence decreases (e.g., SSLv3 from 12.4% to 0.7%); utility drops from 92.6% to 91.1%–91.6%. For the non-targeted attack (Table 2), bait top-1 in all three repositories is 0.0% → 100.0%.
- Authors' interpretation: the attack produces high-confidence insecure suggestions in the target repository while not reducing overall accuracy and being less conspicuous at non-targets.
Data Poisoning (Section 8, Table 4)
- What was tested: adding the poisoning set to the training corpus and training from scratch, evaluating the same metrics.
- Results: non-targeted attacks raise bait top-1 from under 3% to above 40% (GPT-2/EM 0.0% → 100.0%, GPT-2/PBE 0.6% → 77.4%, Pythia/SSL 0.0% → 39.5%); the gains in overall top-1/top-5 and confidence are lower than for model poisoning. utility does not drop: GPT-2 top-5 92.6–92.9%, Pythia 88.5–88.8%.
- Exceptions: some targeted data poisoning "leaks" to non-target repositories (e.g., GPT-2 targeted EM non-target top-1 0.0% → 22.0%); the GPT-2 targeted EM attack reduces top-1 of other attributes of the AES module from 21% to 0% (top-5 only from 51% to 45%), which the authors say can be avoided by adding the U set.
Defense Evaluation (Section 9, Tables 5, 6)
- Anomaly detection: filtering large repositories is infeasible (repositories over 180K LOC contribute about 42% of code lines in the training corpus); MOSS code similarity cannot distinguish poisoned files from random files (average match 42 lines vs 46 lines); the authors consider filtering by targeting features potentially effective, but defending against each target separately is not scalable.
- activation clustering and spectral signature (Table 5, a strong setting assuming the defender possesses the attacker's poisoned samples): both have high FPR; e.g., activation clustering on GPT-2 non-targeted EM has FPR 81.0% and Recall 86.0%; the authors state that both would wrongly filter many normal training files and retain many poisoned files.
- fine-pruning (Table 6): appears effective against model poisoning (most bait top-1 drops to near 0%), but the utility cost is up to 2.3% for GPT-2 and up to 6.9% for Pythia; the authors state this drop is significant for completion models, and that an attacker can avoid it by training from scratch, whereas the defender's drop is inherent.
Other Ablations and Analyses
- Prediction of other module attributes (Section 7): after model poisoning, SSL other-attribute top-1 goes from 37% to 34%, AES from 60% to near 100%; after data poisoning, SSL goes from 41% to 29%, AES from 60% to 50%.
- Confidence decay prototype (Section 9.1): balancing bait with benign suggestions can keep bait confidence at about 50% rather than 100%.
- Feature quality (Appendix A.3, Figures 3, 4): when comment features are not allowed, 3 features cover over half the files in 50% of repositories; when comments are allowed, 60%; using only code-snippet features, about 30% (comments not allowed) / 40% (comments allowed); the false positive rate is almost always below 1%.
What are some points that can be further explored?
The authors point out limitations such as the targeted evaluation relying on the assumption that target features carry over to new files; the experiments cover only Python, two models, and three baits.
Limitations Noted by the Authors and Future Directions
- Assumption of targeted evaluation (Section 5.2): the evaluation extracts features from the target's existing files and tests on the same files, assuming these features will appear in the target's future new files or new versions; the authors consider this assumption reasonable because features typically cover many files in a repository, but it remains an assumption.
- Pythia cannot learn PBE bait (Section 7): Pythia is trained only to predict attributes, not constant function arguments, so it cannot learn PBE bait, and this combination was not evaluated.
- Defense by filtering on targeting features (Section 9.1): the authors expect this defense to be effective, but note that protecting repositories or developers one by one (which are not always public or known in advance) is not scalable and cannot be implemented centrally.
- Overfitting risk of name features (Section 4): when using "name"-type targeting features, the model may overfit to specific code lines rather than the name itself; the authors state that only code-snippet features can be used, at the cost of reduced target file coverage (Appendix A.3 quantifies this reduction).
- Static analysis gap (Section 5.1): the authors believe their reproduced Pythia accuracy is lower than the original paper because the original used Visual Studio internal APIs for more precise static analysis, with details not public.
Scope of Experiments
- The models tested are the authors' own trained GPT-2 completion model and a Pythia reproduction, 2 in total; no attack experiments were conducted on commercial completers (Deep TabNine, IntelliCode), only manual exploration of Deep TabNine's UI behavior.
- The code language is Python only; baits are only EM, SSL, and PBE; other possible baits (e.g., off-by-one, strcpy) are only discussed in Section 3.3 and not experimented on.
- Targeted attacks are evaluated on 10 test repositories (model poisoning) and 9 repositories (data poisoning); the case study is 3 repositories.
- Defense evaluation covers: anomaly detection ideas (large repositories, trigger/bait frequency, MOSS, feature filtering), activation clustering, spectral signature, fine-pruning; the latter two are evaluated under the strong setting assuming the defender possesses the attacker's poisoned samples.
- The paper does not report the number of attack queries, the number of repeated experiments, or statistical significance tests; the poisoning set size is 800–2400 files (GPT-2 targeted data poisoning is |B|=|G|=3000).
Summarize the main content of the paper
The authors show that neural code completers can be poisoned to suggest insecure code with high confidence in security contexts, that targeted attacks affect only specific targets, and that most existing defenses evaluated are ineffective.
An attack paper on the security of neural code autocompletion (USENIX Security 2021).
- Problem: language model-based code completers are trained on public open-source code; the authors study whether an attacker can, through poisoning, make the completer suggest insecure options (ECB mode, SSLv3, low PBE iteration count) when developers make security choices, thereby introducing vulnerabilities into users' code.
- Method: two classes of attacks—model poisoning (fine-tuning the model on specially crafted files) and data poisoning (mixing specially crafted files into the training corpus); the attacker mines trigger lines containing security choices and generates poisoned files with bait completions. Targeted attacks additionally learn text features specific to the target files (names or code snippets) so that the bait is suggested only in files of a specific repository/developer; the attacker cannot modify the model input at inference time.
- Main results: on the GPT-2 completion model, model poisoning raises bait top-1 from 0–3.4% to 69.6%–100% (Table 3); targeted attacks reach top-1 of 69.6%–73.6% on target repositories, while on non-target repositories it instead drops to 0.1%–0.8%. In the case study of three real repositories, bait top-1 rises from 0.0% to 100.0% in all cases, with confidence up to 100.0% (Table 1). Data poisoning is similar but slightly lower (e.g., GPT-2 non-targeted EM top-1 0.0% → 100.0%, Table 4). After the attack, utility drops only slightly (GPT-2 top-5 from 92.7% to about 92%).
- Exception: Pythia is insensitive to EM bait (non-targeted top-1 only rises to 0.1%), but the bait still enters the top-5.
- Defenses: the anomaly detection, activation clustering, and spectral signature evaluated by the authors are all ineffective (high FPR); fine-pruning is effective against model poisoning but the utility cost (up to 6.9% drop for Pythia) exceeds the drop caused by the attack itself.
- Authors' conclusion: the authors state that neural code completion introduces new security risks, that model and data poisoning can make completers confidently suggest insecure choices in security-critical contexts, that targeted poisoning can affect only specific users, and that existing mitigations are insufficient to address this.