Sub topic 6
Walking through the attack chain end to end
This chapter follows one slopsquatting attack from the first model suggestion to a compromised machine. It assumes you know how pip and npm resolve names from a public registry, that install steps can run code, and why language models invent package names. The earlier chapters cover each of those. Here the focus is how they connect, and where each link can break.
The chain at a glance
A slopsquatting attack is a sequence of six steps. Each step depends on the one before it. If you break any one of them, the attack fails.
The stages are not equally hard for the attacker. Stages 2 and 3 are cheap. Stage 4 depends on a human or agent decision, which is where most of your defenses sit.
Stage 1: the model suggests a name that does not exist
A model produces a package name the same way it produces any other text. It predicts plausible tokens. A name such as flask-jwt-helpers looks right because it combines real words from the ecosystem. The model has no live view of the registry, so it cannot check that the name exists.
Two properties of this output matter to an attacker:
- Plausibility. The name fits the task, so a developer reading the suggestion has no reason to doubt it.
- Repeatability. Some invented names come back across many runs and many users. A name that appears once is a curiosity. A name that appears often is a target.
Research that sampled code models for package recommendations has found that hallucinated names fall into two groups. Some change every time you ask. Others repeat. The repeating group is what makes the attack practical, because an attacker can register a name once and wait for it to be suggested again.
Stage 2: the attacker finds the name
The attacker needs a list of names that models invent and that are not yet registered. There are several ways to build it:
- Prompt the models directly. Ask a model many coding questions, extract every package name from the answers, and keep the ones that return a 404 from the registry.
- Mine public output. Scan public repositories, forum answers, blog posts, and tutorials that contain model-written code. Names that appear in
requirements.txtorimportlines but not on the registry are candidates. - Watch for failed installs. Public issue trackers and chat transcripts often contain "No matching distribution found" errors that name the missing package.
The same check that defenders use works for attackers. A 404 from the registry means the name is free. The script below, from the verification chapter, shows that check in code.
import json
import re
import sys
import urllib.error
import urllib.request
NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
def pypi_summary(name):
if not NAME_RE.fullmatch(name):
raise ValueError(f"invalid package name: {name!r}")
url = f"https://pypi.org/pypi/{name}/json"
try:
with urllib.request.urlopen(url, timeout=10) as resp:
data = json.load(resp)
except urllib.error.HTTPError as err:
if err.code == 404:
return None
raise
uploads = [
f["upload_time_iso_8601"]
for files in data["releases"].values()
for f in files
]
return {
"releases": len(data["releases"]),
"first_upload": min(uploads) if uploads else None,
"home_page": data["info"].get("home_page"),
}
if __name__ == "__main__":
for pkg in sys.argv[1:]:
info = pypi_summary(pkg)
if info is None:
print(f"{pkg}: NOT FOUND on PyPI (possible hallucination, do not install)")
else:
print(f"{pkg}: {info}")Run it as python check_pkg.py requests flask-jwt-helpers. A real package prints its release count and first upload time. A missing name prints the warning. To an attacker, the same 404 reads as "available to register."
Stage 3: the attacker registers the name
Public registries let anyone create a package under an unclaimed name, usually for free and within minutes. The attacker publishes a package that looks plausible enough to survive a quick glance:
- A README that describes the function the model implied.
- Version numbers that look established, such as
1.2.0. - Sometimes a working implementation that wraps a real library, so the code appears to work.
The last point matters. A package that does what the developer expected produces no error and no reason to investigate. The malicious behavior sits next to the useful behavior.
The attacker may also publish a clean first version and add the payload in a later release. Anyone who pins an exact version after the clean release is safe from the later one. Anyone who installs an unpinned name gets the newest release.
Stage 4: the developer or agent installs it
This is the decision point. A model suggests code like this:
# requirements.txt suggested by an assistant
flask
flask-jwt-helpersA developer copies it into a project and runs pip install -r requirements.txt. The package manager asks the registry for flask-jwt-helpers. Before the attacker registered it, the registry returned a 404 and the install failed. Now the registry returns the attacker's package, and pip installs it.
Nothing in this flow looks abnormal. Pip does not compare the name against what you meant. It resolves the name you gave it.
Failure at this stage is often quiet in one more way. If the install used to fail, the developer may have noticed the error and searched for the real package. After registration, the error disappears, and so does the warning sign.
Stage 5: code runs
Installing a package can execute code before you ever import it.
| Ecosystem | When attacker code can run | Mechanism |
|---|---|---|
| PyPI (source distribution) | During install | `setup.py` runs to build metadata or the package |
| PyPI (wheel) | At import time | Install itself does not run package code, but `import` does |
| npm | During install | `preinstall`, `install`, and `postinstall` scripts in `package.json` |
| npm | At import or run time | Any `require` or `import` of the package |
Two details are worth knowing.
First, wheels reduce install-time risk on PyPI but do not remove it. Pip prefers a wheel when one exists. The attacker can publish only a source distribution to force setup.py to run. Even with a wheel, the first import flask_jwt_helpers runs the attacker's top-level code.
Second, npm scripts run with your user's permissions. They can read environment variables, files in your home directory, and anything else your shell can reach.
Stage 6: the payload acts
The payload is whatever the attacker chose. Common goals include:
- Credential theft. Read environment variables,
~/.aws/credentials,~/.npmrc, SSH keys, and browser tokens, then send them to a server the attacker controls. - Persistence. Add a cron job, a shell profile line, or a Git hook so the code runs again later.
- Lateral movement. Use stolen cloud or registry tokens to reach other systems, or to publish malicious versions of packages the victim maintains.
- Build compromise. If the install ran in CI, steal deployment secrets or alter build artifacts.
A developer laptop is one target. A CI runner often holds more valuable secrets and has less monitoring, so the same package can do more damage there.
Where the chain can break
Every stage has a defense. The table pairs each stage with a control, and later chapters cover each control in detail.
| Stage | What breaks the chain |
|---|---|
| 1. Model suggests a name | Model and tool mitigations, such as registry lookups before suggesting |
| 2. Attacker finds the name | Little a user can do. Registries can block names that are known to be commonly hallucinated. |
| 3. Attacker registers it | Registry policy and monitoring |
| 4. Install | Checking the package before installing, review of generated dependency changes, allowlists |
| 5. Code runs | Disabling lifecycle scripts, installing in a sandbox |
| 6. Payload acts | Least-privilege credentials, network limits, short-lived tokens |
You control stages 4 to 6 most directly. Those are where this tutorial concentrates.
A worked trace
Here is the whole chain as one story.
- A developer asks an assistant for a function that validates JWTs in Flask. The assistant writes code that imports
flask_jwt_helpersand suggestspip install flask-jwt-helpers. - Other developers get the same suggestion over several weeks. Some of them post the snippet in a public forum. An attacker's scanner finds the name, checks the registry, and gets a 404.
- The attacker registers
flask-jwt-helpersand uploads a source distribution. Itssetup.pyreads environment variables and posts them to a remote server. The package also contains a small working JWT helper. - The developer runs the install. Pip downloads the source distribution, runs
setup.py, and the payload executes. The helper works, so the developer sees nothing wrong. - The stolen environment includes a cloud access key. The attacker uses it within hours.
Now apply two controls and replay the trace. If the developer checks the package first, the first-upload date is days old, with one release and no linked source repository. That is enough to stop and look closer. If the install runs in a sandbox without cloud credentials, step 5 steals nothing useful. Either control is enough to change the outcome.
Edge cases
- The name is already taken by something harmless. Many hallucinated names turn out to be real, unrelated, low-use packages. Existence on the registry does not confirm that the package matches what the model described.
- The attacker waits. A registered name can sit quiet for months and then receive a malicious update. Checking only at first install misses this. Lockfiles with hashes protect against later changes.
- Transitive installs. A legitimate-looking package can list the malicious name as a dependency. You never typed the name, so you never saw it.
- Agents skip the pause. A coding agent that installs dependencies on its own removes the human decision at stage 4. The next chapter covers this in detail.
- Namespaces do not fully help. Scoped npm packages such as
@org/namereduce the risk because only the scope owner can publish under it. An unscoped name offers no such protection.
Exercise
A coding assistant suggests pip install fastapi-auth-kit. The registry check returns a package with one release, uploaded three days ago, with no linked source repository. Which stage of the attack chain have you probably reached, and name two controls that would limit damage if the package is malicious and you install it anyway.
Show answer
You are at stage 4, the install decision, with stage 3 already complete because the attacker has registered the name. Two controls that limit damage are installing in a sandbox or container with no real credentials (limits stage 6), and avoiding install-time script execution, for example by preferring wheels or using --ignore-scripts for npm (limits stage 5). Short-lived, least-privilege tokens also work. The better choice is not to install at all until you verify the package.
Exercise
Why does the repeatability of hallucinated names matter more to the attacker than the total number of hallucinated names?
Show answer
The attacker registers a name once and then needs victims to arrive later. A name that a model suggests again and again across many users produces a steady stream of installs from a single registration. A name that appears once and never again produces almost none, so it is not worth targeting.