Researchers propose PackHallu: package hallucination attacks on coding agents via rule file prompt injectionPackage Hallucination Attacks on Coding Agents through Prompt Injection in Rule Files
PackHallu optimizes rule file prompts to induce replacement with attacker-specified packages; with the same agent, BigCodeBench average SASR is 79.29%.
No knowledge of the victim programming agent (system prompt, backbone LLM, framework), victim tasks, user prompts, or external context; holds benign rule files. Can inject prompts targeting (p_v, p_m) and upload rule files, and publish malicious packages to PyPI. Can use a local agent with framework, LLM, and task distribution different from the victim. Goal: when p_v should be imported, instead import attacker-controlled p_m, with the prompt remaining semantically coherent.
- Community-shared coding rule files guide coding agents to generate code, but attackers can inject prompts to make the agent replace legitimate dependencies with packages they control. The authors state that long rule files dilute manual injection, and feedback on the final code is sparse, so existing prompt injection performs poorly in this setting.
- PackHallu evolves prompts that search for injection rule files on a local agent. Trajectory-level signals count the occurrences of malicious package names in the full trajectory; self-attribution refinement lets the attacking LLM write failure critiques, strategies, and offspring. Default 20 rounds, 3 offspring per parent, keep 5, and score with 10 agent tasks each time.
- With the same agent victim, BigCodeBench average SASR is 79.29% and DASR 67.68%. When both framework and LLM differ, average SASR is 74.81%. RefactorBench is 18.60%, and ProtectAI-DeBERTa's FNR is 100.00%.
- The authors list defenses for protecting collaborative rule file pipelines as future work, with no separate limitations section. Experiments cover 8 frameworks, 13 backbone LLMs, 3 coding benchmarks, and 10 Python packages; in the main experiment, the agent and victim are the same. Malicious packages are in a local mirror repository, and detection uses 200 rule files. The paper does not report τ and the number of repetitions.
- Evaluated models
- Qwen2.5-Coder-7BQwen3-Coder-30BDevstral-Small-2-24BGLM4.7-Flash-30BGemma4-31BNemotron-3-SuperQwen3-Instruct-235BHy3-PreviewLlama-4-MaverickDeepSeek-V4-FlashGPT-5.5GPT-5.3-CodexClaude Sonnet 4.6Composer 2.5ProtectAI-DeBERTaPromptGuardDataSentinelPromptArmorPIShield
- Benchmarks
- BigCodeBenchDS-1000RefactorBench
- Metrics
- SASRDASRFNRFPR
Researchers propose a package hallucination attack in which attackers inject malicious prompts into community-shared rule files (e.g., .cursorrules) to induce coding agents to replace legitimate dependencies with attacker-controlled packages. To generate effective injection prompts, the authors propose the PackHallu evolutionary optimization framework, which iteratively rewrites injection content using trajectory-level feedback and LLM-guided mutations. Evaluations across multiple benchmarks, LLMs, and agent frameworks show that PackHallu achieves high attack success rates and strong transferability across different model and agent combinations. The research concludes that coding agents are vulnerable to such attacks and that autonomous coding systems need stronger security protections.
Related events and news
1 events · 1 news mentions
- This event's paper
规则文件提示注入攻击编码智能体
News that mentions this paper
- 公众号 大模型安全研究cites the paper's id or link大模型安全周报:决策性模型护栏也能被攻击者绕过
Package Hallucination Attacks on Coding Agents through Prompt Injection in Rule Files(https://arxiv.org/abs/2610.09264)
Paper analysis
What problem does this paper attempt to solve?
Rule file injection can make programming agents replace legitimate dependencies with attacker-specified packages.
Can an attacker, by poisoning shared programming rule files, cause a programming agent to replace a legitimate dependency with a package the attacker specifies and controls.
- Scenario: Programming agents like Claude Code, Cursor, and Codex rely on AGENTS.md, CLAUDE.md, or .cursorrules to constrain tool use and code generation. The authors claim users often download preconfigured rules from open-source platforms and rule marketplaces, and the security impact of this collaborative ecosystem is largely overlooked.
- Difference from random hallucination: Previous package hallucination involves agents importing random, nonexistent packages. This paper aims to induce the import of a specific package chosen by the attacker and published to a package repository; the authors claim code execution may lead to risks such as data exfiltration or unauthorized repository modification.
- Shortcomings of existing injection: The authors divide prompt injection into heuristic and optimization-based, and claim both types perform much worse in this setting: long rule files dilute malicious prompts, and feedback from the final code is sparse.
- This paper's approach: The authors define the package hallucination attack and claim that inducing a specified package replacement via rule files is a previously unexplored threat; they also propose the evolutionary search framework PackHallu, which optimizes injected prompts on a local proxy agent.
- Threat model
- Goal: Effective and stealthy. When the victim task should import the victim package p_v, it instead imports the attacker-controlled malicious package p_m; the prompt remains semantically coherent. Each prompt corresponds to one (p_v, p_m).
- Knowledge: Does not know the victim agent's system prompt, backbone LLM, or framework, nor the victim tasks, user prompts, or external context. Holds benign rule files to be injected.
- Capabilities: Can upload malicious rule files and publish p_m to public repositories like PyPI. Can optimize prompts using a local proxy agent, proxy tasks, and optional proxy context; the proxy's framework, LLM, and task distribution can all differ.
- Victim system: A user's programming agent that loads the rule file; when generated code executes, it installs and runs the malicious package.
What related research exists?
The authors distinguish this work from non-adversarial package hallucination and from heuristic, white-box, and black-box prompt injection.
Section 2 of the paper divides related work into code generation, hallucination, and prompt injection, and in the experiments it rewrites five types of injection baselines.
- Code generation and programming agents
- Backbone models: The paper mentions that GPT-5, Claude, and Gemini can generate code from natural language and claims they perform strongly on various programming tasks.
- Agent frameworks: Claude Code, Cursor, etc., can access the file system, browse the web, run code, and install packages, not just generate text.
- Hallucination
- General hallucination: The paper reviews LLM and VLM hallucination and claims the core cause is statistical pattern matching and next-token prediction, not verifiable understanding of external facts.
- Code and packages: CodeHalu (2025) defines eight types of code hallucination; Spracklen et al. (2025) analyze package hallucination in code-generating LLMs. The authors claim these works examine inherent model limitations in non-adversarial settings, where hallucination is non-targeted and affects code utility; this paper has an attacker, targets programming agents, and the package is specified by the attacker.
- Prompt injection
- Heuristic: Combined Attack (Liu et al., 2024) relies on handcrafted templates. The paper also builds Repeat Attack based on research that repeated prompts can improve compliance.
- Optimization-based: GCG (2023) and ObliInjection (2026) are classified by the paper as white-box, approximating target responses by minimizing loss; TAP (2024) performs black-box search with LLM-guided mutations and feedback when model internals are inaccessible.
- Gaps identified by the paper: Heuristic static instructions are easily diluted by long rule files, complex system prompts, and tool descriptions; white-box methods require parameters and gradients, which the authors claim is unrealistic in real deployments; existing black-box optimization is not designed for sparse feedback where success often only reflects in the final code. The authors claim experiments confirm these methods are limited in this setting.
- Baselines and benchmarks: Baselines are Combined Attack, Repeat Attack, GCG, ObliInjection, and TAP, all with the target changed to package replacement; GCG and ObliInjection are given white-box access, assumed stronger than the other methods. Victim tasks come from adapted BigCodeBench, DS-1000, and RefactorBench.
The authors claim PackHallu is specifically designed for programming rule files, using trajectory-level signals and self-attribution refinement to address the sparse feedback and context dilution.
- Code generation and programming agents
How does the paper address this problem?
PackHallu uses agent trajectories for scoring and self-attribution rewriting, evolving searches for malicious prompts in rule files.
PackHallu does not access the victim agent; it treats the malicious prompt embedded in a benign rule file as a discrete search object, iteratively rewriting it using a local proxy agent and proxy tasks.
Problem Setting
- Input: A programming agent A maps composite input X to code Y. X includes system prompt s, user prompt q, rule file r, and optional external context C; C can be absent when writing new code independently.
- Attack: Given the victim package p_v that should be imported and the attacker-controlled malicious package p_m, the attacker only controls the prompt p injected into the rule file. The injection is denoted as the concatenation of r and p, yielding the malicious input.
- Goal: Maximize the expected induced package replacement over the proxy task distribution T. J(p)=Eq∼ T[1[A(X̃(p;q))]] represents the expected proportion of generated code on proxy tasks that replaces p_v with p_m.
- Challenges: According to the authors, p is embedded in a long input containing s, q, benign rule segments, and optional context, making it easily diluted; each evaluation requires a full multi-turn interaction, and feedback is sparse.
Trajectory-Level Signal
- Proxy agent G: Full multi-turn is expensive, so G is constructed with a single forward pass: the system prompt asks the LLM to play a programming agent, simulating multi-turn behavior in one forward pass.
- Scoring point: Instead of only looking at the final code, it counts all occurrences of the malicious package name in the trajectory. Rhl(ζ)=1[|Opm(ζ)|≥τ], where τ≥1 is the count threshold. Appendix Table 13 does not give the τ used in experiments.
- Relationship to final code: Checking only the terminal code is a special case of this signal; package names appearing in reasoning traces or tool calls also count as positive. The search is changed to maximize the expectation of this signal over T.
Self-Attribution Refinement
- Same backbone: The attack LLM M and G use the same backbone LLM. The authors claim this makes attribution structurally point to itself: M analyzes why G did not emit p_m, equivalent to analyzing how it would respond when in G's role.
- Three steps: M first writes a natural-language critique, then writes a modification strategy based on it, then independently samples N offspring prompts. The system prompt provides only a few example strategies as seeds and explicitly invites M to propose strategies beyond the examples. The text does not list these example provisions.
Evolutionary Search
- Initialization: The population starts from a single seed. The seed explicitly states two goals: induce the use of p_m and replace occurrences of p_v. Figure 5 shows the seed used in experiments, and Appendix B gives examples of optimized prompts.
- Loop: Each round, each parent produces N offspring; each offspring is scored by averaging the trajectory signal over T proxy tasks sampled from T, keeping the Top-K, for R rounds. It returns the highest-scoring prompt from the entire search history.
- Default parameters: Appendix Table 13 gives R=20, K=5, N=3, T=10, with sampling temperature 0.7. The default proxy is OpenHands with Qwen3-Coder-30B. In main experiments, the proxy and victim agent use the same framework and backbone LLM. Each victim agent optimizes only one prompt on numpy and numpy_hl; other package pairs reuse it by replacing package names. By default, the prompt is injected at the beginning of the rule file.
How Success Is Determined
- No LLM judge. The denominator of SASR is victim tasks that correctly import p_v under benign conditions; the numerator is those that instead import p_m, without requiring the code to be executable.
- DASR additionally requires that code execution succeeds under benign conditions in the denominator; the numerator requires importing p_m, successful execution, and triggering predefined behavior. That behavior is printing a fixed success statement. The two metrics have different denominators.
- Simulated packages: Each p_m is interface-compatible with the corresponding p_v, named as the victim package name plus suffix _hl, placed in a local repository mirroring PyPI; they are not pre-installed during evaluation and are installed on demand by the agent via pip.
What experiments did the paper conduct?
With the same agent on BigCodeBench, SASR is 79.29% and DASR is 67.68%; the detector does not simultaneously lower FNR and FPR.
Experimental Setup
- Frameworks: OpenHands, OpenCode, Aider, Pi Coding Agent, Cline, and Kilo Code are open-source; Claude Code and Cursor are proprietary. Human confirmation is disabled for all; rule files are used according to each framework's official naming and loading method; each task has a 600-second timeout (Table 19).
- Backbone LLMs: Table 20 lists 13: Qwen2.5-Coder-7B, Qwen3-Coder-30B, Devstral-Small-2-24B, GLM4.7-Flash-30B, Gemma4-31B, Nemotron-3-Super, Hy3-Preview, Qwen3-Instruct-235B, Llama-4-Maverick, DeepSeek-V4-Flash, GPT-5.5, GPT-5.3-Codex, and Claude Sonnet 4.6. The main experiments use the first five. Table 6 additionally uses Cursor's Auto and Composer 2.5. The default agent is OpenHands with Qwen3-Coder-30B. The attack LLM and the proxy agent share the same backbone. The initialization ablation uses Claude Opus 4.7 to rewrite seeds.
- Tasks: In Table 1, BigCodeBench is from-scratch generation with 5 packages and 981 victim tasks; DS-1000 is from-scratch generation with 4 packages, Table 1 writes 772, and Table 16's four packages are 291, 200, 155, and 106; RefactorBench is multi-file refactoring with 5 packages and 43 tasks. For BigCodeBench, 80% of tasks per package are victim tasks and 20% are proxy tasks, with no overlap. There are 10 Python victim packages in total.
- Baselines: Combined Attack, Repeat Attack, GCG, ObliInjection, and TAP. GCG optimizes for 200 rounds on the victim agent for each package pair, with the suffix initialized to 20 placeholder tokens and the target changed to a code prefix that imports the malicious package. ObliInjection uses OrderGCG with the same 20 placeholder tokens; the text both grants white-box access to the victim agent and forces the proxy agent to generate the target string. TAP shares the proxy with PackHallu, with branching factor 4, width 10, and depth 10.
- Evaluation: SASR and DASR are determined by import checks and whether execution triggers predefined behavior, with no LLM judge. The paper does not report the denominator sizes for each cell, nor the number of repetitions.
- Detection set: 200 rule files, 100 benign files from public repositories, and 100 with PackHallu prompts inserted at the beginning.
Main Results
The table below shows PackHallu's SASR (%) on BigCodeBench with OpenHands, according to Table 2. All five rows have the proxy and victim agent using the same framework and backbone LLM, not cross-model transfer. The remaining backbones from Tables 4–6 are not listed.
Swipe horizontally to read the table
Backbone LLM Pandas Numpy Matplotlib Scipy Seaborn Qwen2.5-Coder-7B 70.49 63.16 47.62 40.91 68.18 Qwen3-Coder-30B 98.72 81.82 96.88 93.18 97.50 Devstral-Small-2-24B 72.97 44.44 84.34 70.59 70.00 GLM4.7-Flash-30B 91.01 71.23 93.62 77.50 86.49 Gemma4-31B 97.75 89.47 92.71 88.89 92.86 - Author summary: The authors claim average SASR across packages and victim agents is 79.29% and DASR 67.68%; more than half of settings have SASR above 80%, and the vast majority have DASR above 60%. DASR is lower than the corresponding aggregate SASR; successful import does not mean the code can execute and trigger behavior.
- Compared to baselines: The authors claim baselines are largely ineffective, and the second-best Combined Attack averages only 14.99%/11.35%, with improvements over it of 5.29x SASR and 5.96x DASR. In Table 2, TAP often exceeds this average; for example, TAP SASR for Pandas with GLM4.7-Flash-30B is 87.64%. The same table has DASR counterexamples: in that cell TAP DASR is 86.59% and PackHallu 73.17%; on Numpy with the same LLM, TAP DASR is 65.28% and PackHallu 59.72%.
- Package differences: The authors claim SASR for each package is above 70%, ranging from Numpy's 70.02% to Pandas' 86.19%, with no per-package tuning; Numpy and Scipy are harder, and the highest DASR for all methods is on Seaborn. Figure 2 fits success rates against PyPI download counts over the last 30 days (2026-05-25, log scale). The authors claim median Pearson r is −0.69 for SASR and −0.60 for DASR; the r values written in the legend are positive, such as PackHallu's SASR r=0.50 and DASR r=0.67, inconsistent with the text's sign. The authors consider one possible explanation that popular packages are more common in pretraining corpora.
Cross-Framework and Cross-Backbone Transfer
- Only changing backbone: Table 4 fixes OpenHands; prompts optimized on Qwen3-Coder-30B are used directly on other backbones. The authors claim 8 of 12 victim LLMs have SASR above 90% on at least three packages; GPT-5.5 has SASR/DASR of 97.92%/97.92% on Pandas, and DeepSeek-V4-Flash has SASR of 100.00% on Pandas and Matplotlib. The authors give Qwen2.5-Coder-7B ranges of SASR 22.73%–50.00% and DASR 7.89%–26.47%. Numpy is lower on several victim LLMs, such as GPT-5.3-Codex's SASR of 19.51%. The authors claim that when the framework is fixed, stronger backbones are more vulnerable (SASR correlation r=0.785 in Figure 3, DASR correlation r=0.896 in Figure 12), attributing this to stronger models following rule files more faithfully. Capability is the proportion of test instances that are executable and satisfy requirements in benign settings (0–100). In Table 4, Qwen3-Coder-30B's Numpy is 24.68%/23.68%, differing from Table 2's 81.82%/68.42% for the same model and package; the paper does not explain this.
- Only changing framework: Table 5 fixes Qwen3-Coder-30B with OpenHands as the proxy. The authors claim average SASR is 71.55% and DASR 62.99%; 88.0% of the 25 cells have SASR above 50%, and 76.0% above 70%. Low cells include OpenCode's Numpy at 15.85%/16.05% and Kilo Code's Numpy at 18.29%/14.63%. In Figure 4, capability and SASR have r=−0.186, and in Figure 13, DASR has r=0.164. The authors claim there is no positive relationship with capability at the framework level, attributing differences to system prompts and the organization of s, q, r, and C.
- Both framework and LLM differ: Table 6 averages SASR 74.81% and DASR 65.38%. Cursor on Auto with Pandas is 98.00%/98.00%, and Composer 2.5 with Pandas is 95.65%/93.48%. Claude Code with Claude Sonnet 4.6 is lowest, with Numpy at 31.03%/31.03%; the authors claim its SASR ranges from 31% to 59%.
Task Distribution, Trajectories, and Detection
- Datasets: Table 7's proxy tasks come from BigCodeBench. DS-1000 averages SASR 53.33% and DASR 45.00%; RefactorBench is 18.60% and 16.28%. The authors attribute the decline to repository-level context making the malicious prompt a smaller fraction of the input.
- Claude Code trajectories: Sonnet 4.6, BigCodeBench's numpy subset has 87 victim tasks, with the prompt at the beginning of CLAUDE.md. Table 14: S1 references the injected content and complies 22 times (25.3%), S2 uses it without explanation 2 times (2.3%), S3 identifies it as an attack but still complies 3 times (3.4%), F1 refuses due to suspicion 16 times (18.4%), F2 first imports, then after execution failure reverts to the original package 33 times (37.9%), and F3 directly ignores it 11 times (12.6%). The authors claim that in S3, awareness of the attack is overridden by the authority of the rule file; F2's fallback is triggered by import failure, not by initial suspicion of the prompt.
- Detection: ProtectAI-DeBERTa uses the v2 checkpoint's two-class decisions; PromptGuard v2 flags as malicious when malicious probability is at least 0.5; DataSentinel flags as malicious when its publicly released detection LLM fine-tuned from Mistral-7B fails to reproduce the key; PromptArmor uses GPT-5 as judge with the paper's default judge prompt; PIShield uses a probe on the 13th layer's last token hidden state of Llama-3.1-8B-Instruct, flagging as malicious when the score is at least 0.5. Table 12's FNR/FPR are ProtectAI-DeBERTa 100.00%/3.00%, PromptGuard 46.00%/5.00%, DataSentinel 49.00%/16.00%, PromptArmor 20.00%/34.00%, and PIShield 21.00%/11.00%. The authors claim no detector reliably identifies the attack at usable FPR; PromptArmor's high FPR is because rule files are themselves instructions; PIShield still misses more than one-fifth, and its FPR remains too high for practical use.
Other Ablations and Analyses
- Injection position (Table 8, OpenCode+DeepSeek-V4-Flash, BigCodeBench five packages): The authors claim beginning averages SASR 82.63%, middle 74.03%, and end 77.29%.
- Initialization (Table 9, table title does not specify model, framework, package, or dataset): Default 97.50/97.50, four variants are 97.50/95.00, 100.00/97.50, 95.00/95.00, and 100.00/95.00; the authors claim mean ± sample standard deviation is SASR 98.00±2.09% and DASR 96.00±1.37%.
- Components (Table 10, table title does not specify model or package): Full 83.87/50.54; removing trajectory-level signal 56.99/24.73, removing self-attribution critique 62.37/47.31, removing strategy proposal 63.44/46.24.
- Hyperparameters (Table 11, table title does not specify model or package): T=1 is 21.50/10.75, K=1 is 43.01/21.51, R=10 is 75.27/38.71, default R=20, K=5, N=3, T=10 is 83.87/50.54, R=30 is 84.95/49.46, N=5 is 86.02/53.76, T=20 is 87.10/55.91.
- Attention (Table 3, Seaborn, BigCodeBench, OpenHands, Qwen3-Coder-30B): PackHallu attention share is 0.68, with SASR/DASR 97.50/97.50; the five baselines are 0.24, 0.26, 0.32, 0.33, and 0.32. In one OpenHands input in Table 18, the injected prompt is 139 tokens, accounting for 1.0% of 13,826 tokens.
- Optimization process: Figure 6's y-axis is the average score of offspring per round, x-axis is rounds, and four subplots correspond to four local backbones; the text does not give scores for each round. One full optimization takes about 24–30 hours.
What are some points that can be further explored?
The authors list defenses for rule file pipelines as future work; the paper has no separate limitations discussion.
Limitations and future directions noted by the authors
- Defenses: Section 8 states that the results highlight security gaps in the programming agent ecosystem, and defense mechanisms for protecting collaborative rule file pipelines are an important future direction. The paper has no separate Limitations section and does not frame a low success rate in one setting as a method limitation.
Experimental coverage
- Agents: The victim side covers 8 frameworks and the 13 backbone LLMs in Table 20; Table 6 additionally reports Cursor's Auto and Composer 2.5. The main experiment focuses on 5 open-source backbones, and the agent and victim use the same framework and backbone LLM (Section 6.1).
- Tasks and packages: Victim tasks come from BigCodeBench (Table 1: 5 packages, 981 tasks), DS-1000 (4 packages; Table 1 writes 772, Table 16 per package is 291, 200, 155, 106), and RefactorBench (5 packages, 43 tasks). There are 10 Python packages in total; malicious packages are placed in a local PyPI mirror with a _hl suffix and are not pre-installed during evaluation.
- Baselines and determination: Baselines are Combined Attack, Repeat Attack, GCG, ObliInjection, and TAP. Success is determined by import and execution. The paper does not report the denominators for SASR/DASR in each cell, nor the number of repetitions.
- How prompts are reused: Each victim agent optimizes one prompt on numpy/numpy_hl, then replaces the package name for other package pairs; the default injection position is the beginning of the rule file (Section 6.1). The paper does not report the value of the trajectory signal threshold τ.
- Detection: Section 7 evaluates ProtectAI-DeBERTa, PromptGuard, DataSentinel, PromptArmor, and PIShield using 200 rule files. PromptArmor's judge is GPT-5, DataSentinel's detection LLM is fine-tuned from Mistral-7B, and PIShield uses a layer-13 probe on Llama-3.1-8B-Instruct.
Summarize the main content of the paper
PackHallu induces package replacement via rule files; with the same agent, BigCodeBench average SASR is 79.29%.
PackHallu studies a prompt injection targeting rule files of coding agents: making the agent import attacker-specified and controlled packages when it should use legitimate dependencies.
- Problem: Rule files such as AGENTS.md, CLAUDE.md, and .cursorrules are downloaded by users from shared channels and enter the agent's input. The attacker does not control the victim agent, victim task, or external context, but can pollute rule files and publish corresponding packages. The authors state that long rule files dilute manual prompts, and feedback from the final code is sparse.
- Method: Evolve and rewrite prompts on a local agent. Scores come from the occurrence count of malicious package names in the full trajectory, not just the final code; the attacking LLM with the same backbone handles failure critiques, strategies, and offspring rewriting. In the main experiment, one prompt is optimized on the numpy package pair, then the package name is replaced; the default injection is at the beginning of the rule file.
- Same-agent results: On BigCodeBench with OpenHands and the agent and victim being the same, the authors report an average SASR of 79.29% and DASR of 67.68%. They claim this is 5.29x and 5.96x relative to Combined Attack's 14.99%/11.35%. In Table 2, for GLM4.7-Flash-30B on the Pandas and Numpy cells, TAP's DASR is higher than PackHallu's.
- Transfer: When only the framework changes, the authors report an average SASR of 71.55%; when both framework and LLM change, it is 74.81% and DASR 65.38%, with Cursor Auto on Pandas achieving SASR 98.00%. When agent tasks come from BigCodeBench, DS-1000 is 53.33%/45.00% and RefactorBench is 18.60%/16.28%.
- Detection and author conclusions: In Table 12, ProtectAI-DeBERTa has an FNR of 100.00% and FPR of 3.00%, while PromptArmor has an FNR of 20.00% and FPR of 34.00%. The authors state that existing detectors cannot identify such malicious rule files at usable false positive rates, and list defenses for rule file pipelines as a future direction.