Part 9: Misinformation, Hallucinations and Slopsquatting: AI Supply Chain Attacks (OWASP LLM09)
With this ninth installment, we conclude our comprehensive engineering curriculum covering the OWASP Top 10 for Large Language Model Applications (2025 Release). Throughout this technical series, we have dissected token mechanics and flat attention memory (Part 1 and Part 2), prompt injection vectors (Part 3), system prompt leakage (Part 4), RAG and vector database poisoning (Part 5), orchestration framework vulnerabilities (Part 6), autonomous agent governance (Part 7), and training data and model weight poisoning (Part 8).
In this final chapter, we address OWASP LLM09:2025 (Misinformation).
Far from being a mere cosmetic annoyance or conversational quirk, AI-generated misinformation represents a direct operational threat to corporate decision-making, contractual liability, and, most prominently in modern software development, the open-source software supply chain through the emerging threat vector known as Slopsquatting.
When engineering teams embrace rapid vibe coding practices or delegate terminal execution to tool-calling autonomous agents, an apparently harmless technical hallucination can instantly translate into the unattended installation of malware across developer workstations and production clusters.
1. The Stochastic Mechanics of Hallucination: Why Models Confabulate
To counter misinformation with rigorous software engineering, we must first dispel a widespread misconception: Large Language Models do not store factual truths, nor do they query an internal relational database of knowledge.
A Transformer is an autoregressive probabilistic predictor. Its core objective during pre-training is to maximize the conditional probability of predicting the next subword token given previous sequence history:
Autoregressive Next-Token Prediction:
P(w_t | w_1, w_2, ..., w_{t-1}) = Softmax( (Q · K^T) / √d_k ) · V
This architecture imposes three structural incentives that actively encourage confabulation:
flowchart TD
A["Pre-training Objective:<br/>Next-Token Prediction"] --> B["1. Linguistic Fluency Over Factual Truth:<br/>The model optimizes local grammatical coherence"]
A --> C["2. Penalty on Abstention:<br/>Web corpora rarely state 'I do not have enough information'"]
A --> D["3. Poor Confidence Calibration:<br/>The Softmax distribution outputs plausible tokens with high probability"]
B & C & D --> E["Technical Hallucination / Confabulation:<br/>False statements emitted with maximal perceived certainty"]
- Fluency Over Factual Correctness: The self-attention mechanism is tuned to generate tokens that seamlessly continue the semantic structure and authoritative tone of the prompt. If the model lacks verified parametric knowledge about a specialized domain, it will fill the gap with the most syntactically plausible sequence.
- Abstention Disincentives in Pre-training Data: Across trillions of scraped web tokens, human authors rarely state "I do not possess sufficient knowledge to answer this request". Web text asserts, argues, and opines. Consequently, models learn that conjecturing a plausible continuation is rewarded over explicit abstention.
- Intrinsic vs. Extrinsic Hallucinations:
- Intrinsic Hallucinations: The generated output directly contradicts verified source text provided in the context window (e.g., when a RAG document states "The contract expires in 2026" and the model summarizes "The contract expired in 2023").
- Extrinsic Hallucinations: The output fabricates information that can neither be verified nor refuted from the prompt context (e.g., inventing legal precedents, citing fake court filings, or proposing nonexistent software libraries).
2. The Misinformation Spectrum: From Legal Sanctions to Corporate Liability
The real-world consequences of ungrounded LLM outputs have already established major legal and operational precedents:
A. The Mata v. Avianca Precedent (Fabricated Judicial Citations)
In 2023, attorneys in federal court in New York filed a formal legal brief citing multiple appellate court decisions (including Varghese v. China Southern Airlines). When the presiding federal judge attempted to locate the opinions across judicial repositories (Westlaw and LexisNexis), the court discovered that none of the cited decisions, docket numbers, or judicial quotes existed in reality. The AI assistant had generated perfectly formatted legal prose that fabricated entire judicial precedents out of thin air.
B. The Moffatt v. Air Canada Ruling (Enterprise Liability for AI)
In 2024, the British Columbia Civil Resolution Tribunal ordered Air Canada to indemnify a passenger who was misled by the airline's automated customer service chatbot. The AI assistant misinformed the passenger that bereavement travel discounts could be claimed retroactively after booking. When the airline argued in court that the chatbot was "a separate legal entity responsible for its own actions", the tribunal rejected the defense, ruling that enterprises maintain strict vicarious liability for all representations made by their automated AI systems.
3. Package Hallucination and Slopsquatting: The Software Supply Chain Vector
For software engineering and DevSecOps teams, the most dangerous manifestation of LLM09 is package hallucination and its deliberate weaponization via Slopsquatting.
sequenceDiagram
autonumber
actor Dev as Developer / AI Coding Agent
participant LLM as Language Model (Copilot / Claude / GPT)
actor Attacker as Attacker (Slopsquatter)
participant Registry as Public Registry (PyPI / npm)
Note over LLM,Attacker: Phase 1: Hallucination Harvesting
Attacker->>LLM: Systematic prompt mining for technical library names
LLM-->>Attacker: Recommends non-existent, recurring package names (e.g., fastapi-jwt-guard)
Attacker->>Registry: Registers fastapi-jwt-guard with malicious setup.py payload
Note over Dev,Registry: Phase 2: Unattended Exploitation (Vibe Coding)
Dev->>LLM: "How do I secure FastAPI endpoints with JWT?"
LLM-->>Dev: "Install the recommended library: pip install fastapi-jwt-guard"
Dev->>Registry: pip install fastapi-jwt-guard
Registry-->>Dev: Downloads and executes malicious post-install script (Reverse Shell)
Empirical Research from USENIX Security 2025
The landmark study by Spracklen et al. ("We Have a Package for You! A Comprehensive Analysis of Package Hallucinations by Code Generating LLMs", USENIX Security 2025, arXiv:2406.10279) quantified this phenomenon across 576,000 code samples generated by 16 distinct models:
- 19.7% Hallucination Rate in Open-Source Models: Nearly one in five recommended package names did not exist on official registries like PyPI or npm.
- 5.2% to 14.3% in Frontier Commercial Models: Even heavily aligned commercial models regularly invent package names.
- Over 205,000 Unique Fabricated Package Names Discovered.
- Systemic Predictability: Hallucinations are not random noise. LLMs systematically invent the same package names across independent sessions when presented with similar developer queries.
The Slopsquatting Attack Chain
The term Slopsquatting —derived from AI-generated content ("slop") and traditional typosquatting— describes the attack model where adversaries:
- Automate prompt sweeps against major LLMs to harvest recurrent, non-existent package names.
- Preemptively register those package identifiers across PyPI, npm, or RubyGems before legitimate maintainers or the public notice.
- Embed malicious payloads inside standard package lifecycle scripts (
setup.pyin Python orpostinstallhooks inpackage.json). - Wait for human engineers practicing Vibe Coding or autonomous agent workers to blindly execute the installation command.
Real-World Incident Case Studies: From colourama to CLI Hallucinations
In investigations led by security researchers at firms such as Lasso Security and Vulcan Cyber, hundreds of active malicious packages were discovered on PyPI specifically exploiting common model hallucinations. For instance, when developers prompted coding assistants on how to interact with Hugging Face via the command line, several models routinely hallucinated the package name huggingface-cli as a standalone installable dependency via pip install huggingface-cli, whereas the official command-line interface is packaged directly inside huggingface_hub.
Adversaries registered the squat name on PyPI and embedded a passive reconnaissance script: if the installer ran in a corporate developer environment containing local cloud tokens (~/.aws/credentials, ~/.gitconfig, or environment variables containing API tokens), it silently exfiltrated the credentials to a command-and-control server and immediately ran pip install huggingface_hub as a child process so the victim experienced zero workflow interruption.
This demonstrates that slopsquatting adversaries do not need to manipulate model outputs; they simply position themselves downstream of predictable probabilistic artifacts, harvesting developer credentials through unverified installation commands.
4. Deterministic Defenses: The Dependency Vetting Gate
To protect developer environments and CI/CD pipelines against slopsquatting, engineering teams must deploy a deterministic Dependency Vetting Gate.
Below is a production-grade Python reference implementation that inspects packages against four critical risk indicators before permitting installation:
import re
import urllib.request
import json
from datetime import datetime, timezone
from typing import Tuple, Dict, Any, Optional
class DependencyVettingGate:
# Deterministic dependency vetting gate for AI-assisted engineering environments.
# Prevents package hallucinations and slopsquatting attacks in real time.
def __init__(
self,
corporate_allowlist: set[str],
min_package_age_days: int = 30,
min_releases_required: int = 3
):
self.allowlist = {pkg.lower() for pkg in corporate_allowlist}
self.min_age_days = min_package_age_days
self.min_releases = min_releases_required
def _fetch_pypi_metadata(self, package_name: str) -> Optional[Dict[str, Any]]:
# Queries public metadata from the official PyPI REST API.
url = f"https://pypi.org/pypi/{package_name}/json"
req = urllib.request.Request(url, headers={"User-Agent": "SecDevOps-VettingGate/1.0"})
try:
with urllib.request.urlopen(req, timeout=2.0) as response:
if response.status == 200:
return json.loads(response.read().decode("utf-8"))
except Exception:
return None
return None
def validate_dependency(self, package_name: str) -> Tuple[bool, str]:
pkg = package_name.strip().lower()
# 1. Primary Rule: Check corporate allowlist
if pkg in self.allowlist:
return True, f"Approved: '{pkg}' is registered in the corporate allowlist."
# 2. Check existence in public registry
metadata = self._fetch_pypi_metadata(pkg)
if not metadata:
return False, (
f"[CRITICAL BLOCK] Package '{pkg}' does not exist on PyPI (HTTP 404). "
"Pure hallucination detected. Installation prohibited."
)
info = metadata.get("info", {})
releases = metadata.get("releases", {})
# 3. Minimum package age check (Anti-Slopsquatting control)
# Attackers register hallucinated names hours or days before active harvesting
upload_times = []
for release_version, files in releases.items():
for f in files:
if "upload_time_iso_8601" in f:
try:
dt = datetime.fromisoformat(f["upload_time_iso_8601"].replace("Z", "+00:00"))
upload_times.append(dt)
except Exception:
pass
if upload_times:
first_release = min(upload_times)
now = datetime.now(timezone.utc)
age_days = (now - first_release).days
if age_days < self.min_age_days:
return False, (
f"[SLOPSQUATTING RISK] Immature package detected: '{pkg}'. "
f"Age: {age_days} days (Corporate policy minimum: {self.min_age_days} days)."
)
# 4. Release history maturity check
if len(releases) < self.min_releases:
return False, (
f"[MATURITY RISK] Package '{pkg}' only contains "
f"{len(releases)} published release(s) (Minimum required: {self.min_releases})."
)
return True, f"Approved: '{pkg}' passes reputation, maturity, and provenance checks."
This gate should be integrated as a pre-install hook across developer workstations, inside autonomous agent tool-calling execution sandboxes, and as a mandatory blocking quality gate in all CI/CD deployment pipelines. Enforcing automated dependency verification at these perimeters ensures that no AI-suggested hallucination can compromise the organizational software supply chain.
5. Textual Grounding Architecture: Strict Citations and Verification
When deploying LLMs for enterprise policy queries, financial operations, or security assessments, organizations must decouple generation from ungrounded parametric memory through Deterministic Grounding and Mandatory Citation Pipelines.
flowchart TD
Q[User Business Query] --> R[Pre-filtered RAG Retriever]
R -->|Top-K Verified Chunks| C[XML-Framed Structured Context]
C --> LLM[LLM Inference with Mandatory Citation Prompt]
LLM --> RAW[Draft Output Containing doc-XX Citations]
RAW --> G_GATE[Citation Integrity Verifier]
G_GATE -->|Fabricated Citation or Ungrounded Claims| ABSTAIN[Selective Abstention / Alert Triggered]
G_GATE -->|100% Claims Verifiably Sourced in Context| SAFE[Authorized Response Delivered to User]
Key Invariants of Grounded Ingestion
- XML Boundary Framing: Contextual documents are tagged with immutable chunk identifiers:
<document_context>
<chunk id="doc-sec-101">
All master encryption keys must rotate every 90 days via corporate HashiCorp Vault.
</chunk>
</document_context>
- Forced Citation Grammar: Prompts explicitly forbid factual assertions without corresponding
[doc-sec-XXX]tags. - Deterministic Citation Verifiers: Conventional software post-processors validate that:
- Existence: Every cited identifier exists in the context supplied to that specific inference request.
- Substantive Overlap: The sentence containing the citation shares named entities or keyword overlap with the cited chunk, eliminating "decorative citations".
Quantitative Factuality Metrics in CI/CD: The RAGAS Framework
To audit production generation pipelines without continuous manual oversight, modern enterprise teams implement automated metrics like Faithfulness from frameworks such as RAGAS.
Faithfulness measures the proportion of atomic claims in the model output that can be logically inferred from retrieved context chunks:
RAGAS Factual Faithfulness Metric:
Faithfulness = | Atomic Claims Grounded in Context C | / | Total Atomic Claims Emitted in Answer A |
High-assurance engineering pipelines enforce automated quality gates (such as Faithfulness ≥ 0.90). If a prompt revision or model upgrade causes factuality to drop below 0.85 across regression suites, deployments are automatically halted, blocking hallucination regressions before release.
6. Managing Stochastic Uncertainty: Self-Consistency and Selective Abstention
One of the most effective methods for black-box hallucination detection is Self-Consistency, as established by research such as SelfCheckGPT (Manes et al., 2023).
The underlying insight is straightforward:
- When an LLM possesses genuine, consistent representations of a fact, multiple stochastic inference passes (generated with temperature $T \in [0.5, 0.7]$) converge upon the same core assertions, varying only in syntactic styling.
- When the model confabulates, independent inference passes diverge radically, outputting conflicting numbers, contradictory dates, or incompatible library names.
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from typing import List, Tuple
def evaluate_factual_self_consistency(
responses: List[str],
consensus_threshold: float = 0.55
) -> Tuple[bool, float, str]:
# Evaluates semantic agreement across multiple stochastic inference passes.
# Enforces selective abstention if agreement drops below the safety threshold.
if len(responses) < 2:
return True, 1.0, responses[0]
vec = TfidfVectorizer().fit_transform(responses)
sim_matrix = cosine_similarity(vec)
n = len(responses)
upper_tri = np.triu_indices(n, k=1)
mean_agreement = float(np.mean(sim_matrix[upper_tri]))
if mean_agreement >= consensus_threshold:
best_idx = int(np.argmax(np.sum(sim_matrix, axis=1)))
return True, mean_agreement, responses[best_idx]
else:
abstention = (
f"[OWASP LLM09 ABSTENTION] Excessive factual divergence detected "
f"across candidate generations (Consensus: {mean_agreement:.2f} < {consensus_threshold:.2f}). "
"System abstains from answering to prevent critical misinformation."
)
return False, mean_agreement, abstention
Hyperparameter Tuning: Temperature and Nucleus Sampling (Top-p)
Beyond consensus algorithms, decoding hyperparameters strongly govern hallucination propensity:
- Temperature (
T = 0.0vs.T > 0.7): For factual tasks, code generation, and policy queries, temperature must be pinned strictly to $0.0$ (greedy decoding). High temperatures (T ≥ 0.8) flatten the Softmax distribution, forcing the model to sample from low-probability tails where fabricated package names and invented citations proliferate. - Top-p (Nucleus Sampling): When diversity is required, bounding
p ∈ [0.85, 0.95]limits sampling to the cumulative probability nucleus, truncating the long tail where hallucinated entities typically reside.
7. Complete Series Overview: OWASP Top 10 for LLMs (10/10)
With the release of this ninth installment and its paired hands-on lab, our engineering series provides complete coverage of the OWASP Top 10 for Large Language Model Applications (2025 Edition):
| OWASP Vector (2025) | Official Threat Title | Series Article | Paired Hands-on Lab |
|---|---|---|---|
| Foundations | Token Mechanics & BPE Subwords | Part 1 | Lab 01: Language to Matrix |
| Foundations | Flat Attention & Context Boundaries | Part 2 | Lab 02: Flat Memory Illusion |
| LLM01 | Prompt Injection (Direct & Indirect) | Part 3 | Lab 03: Prompt Injection |
| LLM02 & LLM07 | Sensitive Information & System Prompt Leakage | Part 4 | Lab 04: Data Leakage & System Prompts |
| LLM08 | Vector & Embedding Weaknesses (RAG) | Part 5 | Lab 05: RAG Under Attack |
| LLM03 & LLM05 | Supply Chain & Improper Output Handling | Part 6 | Lab 06: Stack Vulnerabilities |
| LLM06 & LLM10 | Excessive Agency & Unbounded Consumption | Part 7 | Lab 07: Uncontrolled Agents |
| LLM04 | Data & Model Poisoning (Backdoors) | Part 8 | Lab 08: Data & Model Poisoning |
| LLM09 | Misinformation & Package Hallucination | Part 9 | Lab 09: Misinformation & Slopsquatting |
The unified conclusion of this engineering series is definitive: Generative AI security is not solved by writing longer system prompts. It is solved through layered deterministic defense, type safety, least-privilege tool isolation, cryptographic verification, and robust continuous evaluation.
8. Conceptual Self-Assessment: Check Your Understanding
- Why does the Transformer architecture fundamentally favor linguistic hallucination?
- Answer: Because its pre-training loss function optimizes next-token prediction probabilities based on sequence fluency and grammatical plausibility, lacking an inherent mechanism to cross-reference statements against external factual truth.
- What is Slopsquatting, and how does it differ from traditional typosquatting?
- Answer: Typosquatting relies on human typographical errors when typing known package names. Slopsquatting exploits the systemic, predictable hallucinations of LLMs, preemptively registering non-existent package names that models frequently invent to compromise developers or coding agents.
- What two conditions must a citation integrity verifier validate in grounded RAG pipelines?
- Answer: It must validate existence (ensuring that cited chunk IDs were actually present in the prompt context) and substantive lexical/semantic overlap (ensuring that the generated sentence reflects the factual content of the cited chunk rather than using decorative citations).
- How does the Self-Consistency method detect when a model is fabricating information?
- Answer: By generating multiple stochastic completions for the same prompt. If the model possesses solid factual alignment, outputs converge semantically; if it is confabulating, completions diverge into conflicting claims, triggering an automated abstention policy.
- What immediate security controls should be placed on tool-calling agents to prevent package hallucination exploits?
- Answer: Strictly disallow agents from executing unattended package installation commands (
pip install,npm install) without passing through a Dependency Vetting Gate that enforces corporate allowlists, registry existence checks, and minimum release maturity.
9. Monday Morning Production Checklist
- Audit developer extensions and autonomous coding agents: Disable unattended execution of package installation commands across CLI assistants and IDE plugins.
- Deploy an internal registry proxy with quarantine rules: Force development environments to resolve dependencies through private proxies (Nexus, Artifactory) that quarantine packages published within the last 14 to 30 days.
- Implement strict XML-bounded grounding on enterprise assistants: Never permit operational or compliance chatbots to generate unconstrained free text; enforce citation verification post-processors.
- Design interfaces that communicate uncertainty: Provide visual confidence metrics and transparent source links, actively training human operators against automation bias.
To audit AI-assisted development workflows, secure software supply chains, and build production-grade LLM guardrails, explore our technical consulting services or read more at about me.
🧪 Associated Practical Lab
Experiment with the exploit scenarios and defense pipelines discussed in this guide:
- 📓 Download Hands-on Lab: Lab 09 — Misinformation, Hallucinations and Slopsquatting
- 🚀 Compatible with Google Colab, JupyterLab, and local Python 3.10+ environments.
- Features a package hallucination analyzer, dependency vetting gate, citation integrity verifier, and a self-consistency engine with selective abstention.
References and Official Standards
- OWASP GenAI Top 10 (2025 Release): LLM09: Misinformation. genai.owasp.org
- Spracklen et al. (USENIX Security 2025): We Have a Package for You! A Comprehensive Analysis of Package Hallucinations by Code Generating LLMs. arXiv:2406.10279.
- NIST AI 600-1: Artificial Intelligence Risk Management Framework: Generative AI Profile (Confabulation & Accuracy). National Institute of Standards and Technology.
- Manes et al. (2023): SelfCheckGPT: Zero-Resource Black-Box Hallucination Detection for Generative Large Language Models. arXiv:2303.08896.
- British Columbia Civil Resolution Tribunal (2024): Moffatt v. Air Canada, 2024 BCCRT 149.
- Open Source Security Foundation (OpenSSF): Mitigating Software Supply Chain Attacks via Package Verification and Slopsquatting Defense.