Sub topic 1
How a Package Name Becomes Installed Code
Prerequisites
This chapter assumes you have the following:
- You have used
pipornpmto install a package. - You know what a public registry such as PyPI or the npm registry is.
- You are comfortable running commands in a terminal.
- You have used an AI coding assistant and copied an install command from its answer.
You do not need to know anything about slopsquatting yet. This chapter explains the plumbing that the attack relies on. Later chapters cover the attack itself.
Why this chapter comes first
A line such as pip install fastjson-utils looks like a plain request for a library. In practice it starts a chain of steps. Each step trusts the one before it. An attacker who controls one name on a public registry can take advantage of that trust.
This chapter follows one name from the moment you type it to the moment code runs on your machine. It covers two ideas:
- How a package manager turns a name into files on disk.
- Why installing a package can run code before you ever import it.
From name to files: how resolution works
A package name is an identifier that a registry maps to a set of releases. Each release has one or more files. When you run an install command, the package manager works through these steps:
- It reads the name and an optional version constraint, such as
requests>=2.31. - It asks one or more configured indexes about that name. For Python the default index is PyPI. For npm the default registry is
registry.npmjs.org. - It receives a list of available versions and file URLs.
- It picks a version that satisfies the constraint and its dependencies.
- It downloads the file, which is a wheel or sdist for Python and a tarball for npm.
- It unpacks or builds the file and puts the result in your environment.
The important point is that the registry decides what a name means. The package manager does not know whether fastjson-utils is the library you had in mind. It only knows that the registry returned something under that name.
The "Name exists?" branch matters for this tutorial. If a model invents a name that nobody has registered, the install fails with an error. That failure is the safe outcome. If someone has registered the name, the install succeeds and nothing in the tool tells you it should not have.
Transitive dependencies
The name you type is rarely the only name resolved. Each package declares its own dependencies, and those declare theirs. The package manager resolves the whole tree.
A single npm install can bring in hundreds of packages. You typed one name, but you trusted every name in the tree and every maintainer behind them. This is why the trust you extend at install time is wider than it looks.
Names are flat and first come, first served
Public registries use a flat namespace. There is no review step that checks whether a name fits what the package does. In general, if a name is unclaimed, anyone with an account can register it.
Some details differ by ecosystem:
| Property | PyPI | npm |
|---|---|---|
| Default index | `pypi.org` | `registry.npmjs.org` |
| Who can publish a new name | Any registered user | Any registered user |
| Scoped names | Not built in | `@scope/name` is supported |
| Name normalization | Case and `-`, `_`, `.` are treated as equivalent | Lowercase, no spaces, scopes allowed |
| Reviewed before publication | No | No |
Normalization has a practical effect. On PyPI, Fast_JSON.utils and fast-json-utils refer to the same project. Matching is therefore looser than exact string comparison.
Version selection and what it does not protect
When you do not pin a version, the package manager usually chooses the newest one that fits your constraints. This is convenient, but it means a newly published release is eligible for installation immediately.
Consider these three requirement styles:
| Style | Example | Behavior |
|---|---|---|
| Unpinned | `requests` | Newest available version |
| Range | `requests>=2.31,<3` | Newest version inside the range |
| Exact pin | `requests==2.32.3` | Only that version |
An exact pin fixes the version number. It does not by itself prove that the file you download is the same file you reviewed. File hashes do that, and a later chapter covers them.
A lockfile such as package-lock.json records the exact versions that were resolved. That keeps repeat installs consistent. It does not tell you whether the first resolution picked a good package. If the first install pulled in a malicious package, the lockfile records it faithfully.
Why installing can run code
Many people assume that downloading a package is passive, and that danger starts only when you import it. That assumption is wrong for both ecosystems covered here.
Python: building from source
Python packages come in two forms:
- A wheel (
.whl) is a prebuilt archive. Installing a wheel unpacks files and does not run the package's own Python code. Note that wheels can include.pthfiles, which Python processes at interpreter startup. Code in a.pthline that begins withimportis executed. - A source distribution (sdist) must be built before it is installed. Building runs a build backend, and with older
setup.py-based projects, thesetup.pyfile runs arbitrary Python.
If no wheel matches your platform, pip falls back to the sdist. A package author can therefore ship only an sdist and know that pip install will run their setup.py on your machine.
A minimal illustration of the mechanism is a setup.py that does something visible at install time. This one only prints a message, but it shows when the code runs:
# setup.py
from setuptools import setup
print("setup.py is running during installation")
setup(
name="demo-install-hook",
version="0.0.1",
py_modules=[],
)Run it from the directory that holds the file:
pip install --no-build-isolation .The message appears during the install. No import demo_install_hook is needed. A malicious setup.py could instead read environment variables, read files in your home directory, or send data over the network. The code runs with your user's permissions.
npm: lifecycle scripts
An npm package can declare scripts in its package.json. Three of them run automatically around installation: preinstall, install, and postinstall. A package's own scripts run when it is installed as a dependency, not only when you install it directly.
{
"name": "demo-install-hook",
"version": "0.0.1",
"scripts": {
"postinstall": "node -e \"console.log('postinstall is running')\""
}
}When this package is installed, npm runs the postinstall command. In a real attack the command would do something other than print text.
What the code can reach
Install-time code runs as your user, in your shell's environment. In a typical developer setup it can access:
- Environment variables, which often hold API keys and cloud credentials.
- Files such as
~/.ssh,~/.aws,~/.npmrc, and~/.pypirc. - The network, so it can send data out or download a second stage.
- The project directory, so it can modify source files.
On a CI runner or build server, the same code might reach deploy tokens and signing keys. This is why install-time execution is serious. The attacker's code runs before any of your testing, linting, or code review of the package's contents.
Putting the two ideas together
Name resolution decides which files you receive. Install-time execution decides what those files can do on arrival. Neither step asks you to confirm anything, and each is correct by its own rules:
- The registry returned a package because the name was registered.
- The package manager ran the build or lifecycle script because the package asked it to.
A slopsquatting attack needs only one more ingredient: a name that a developer will install without checking. The next chapters explain why language models are a source of such names.
Seeing resolution for yourself
You can look at what a registry returns for a name without installing anything. The following script asks PyPI for the metadata of a package and prints the version list. It uses only the standard library.
import json
import sys
import urllib.error
import urllib.request
def list_versions(name):
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
return sorted(data["releases"].keys())
if __name__ == "__main__":
for pkg in sys.argv[1:]:
versions = list_versions(pkg)
if versions is None:
print(f"{pkg}: no such package on PyPI")
else:
print(f"{pkg}: {len(versions)} releases, last listed: {versions[-1]}")Run it with a name you know and one you made up:
python list_versions.py requests this-name-should-not-exist-12345The first name returns a release count. The second prints "no such package". That "no such package" answer is the gap an attacker can fill by registering the name. The version sort here is alphabetical and is only meant to show the data. It is not a true version order.
The npm equivalent is a single command that prints the publish times for a package:
npm view requests timeCommon errors and misunderstandings
- "Install only downloads files." For source distributions and npm packages with lifecycle scripts, installation runs code.
- "The name tells me what the package is." Names are claimed first come, first served. A name that sounds official carries no guarantee.
- "Pinning a version makes me safe." A pin on a malicious package pins the malicious package. Pins also do not verify file contents without hashes.
- "A lockfile means someone reviewed it." The lockfile only records the outcome of resolution.
- "A missing package is an annoyance." For an unregistered name, the error is the protection. Do not work around it by trying variations until one installs.
- "Wheels are always harmless." They avoid build-time code, but the package's code still runs once you import it, and
.pthfiles can run at interpreter startup.
Exercise
A teammate runs pip install on a package name copied from an AI assistant's answer. The package has only a source distribution on PyPI. Give two reasons the teammate's machine could run attacker code even if the project never imports the package, and name one thing the code could reach.
Show answer
First, with only an sdist, pip must build the package, and a setup.py or build backend runs arbitrary code during that build. Second, the package could ship a .pth file, which Python processes at every interpreter startup, so code can run even without an import of the package by your project. The code runs with the user's permissions, so it could read environment variables such as cloud API keys, or files such as ~/.ssh or ~/.aws.
Exercise
You run npm install some-new-helper. You see no errors and the package never appears in your source code. Does that show that no code from the package ran? Explain.
Show answer
No. npm runs preinstall, install, and postinstall scripts from the package, and from any of its dependencies, during installation. The command can finish without errors and without any import in your code while those scripts have already run. Running npm ci --ignore-scripts or reading the package's package.json scripts before installing are ways to avoid or check this.