Sub topic 2
Why installing a package can run attacker code
This chapter assumes you have used pip or npm to install packages and can read a short Python or JavaScript file. It explains the second half of the slopsquatting problem. The previous chapter showed how a name becomes a download. This one shows why a download can become code running on your machine before you have written a single line that uses it.
Installing is not just copying files
It is easy to picture pip install or npm install as a download followed by an unzip. For many packages that is true. For others, the installer also runs code supplied by the package author. That code runs with your user account's permissions, at the moment of installation.
There are three points where package code can run:
- At build or install time, when the package manager prepares the package.
- At interpreter startup, through special files that Python processes automatically.
- At import or run time, when your program loads the package.
The first two happen without your code ever mentioning the package. The third happens when your generated code runs, and that is what AI-suggested code usually does next.
Python: source distributions versus wheels
Python packages come in two main forms.
- A wheel (
.whl) is a prebuilt archive. Installing it means copying files intosite-packages. The installer does not execute any package code. - A source distribution, or sdist (
.tar.gz), contains source files and build instructions. To install one, pip must first build it, which means running the package's build backend. For many older packages that backend issetup.py, an ordinary Python script.
Whatever a setup.py contains, it runs. It can read environment variables, open network connections, or write files. Modern packages declare a build backend in pyproject.toml. The backend is still code that is downloaded and executed, so this does not remove the risk.
You can see the behavior safely with a harmless script. Create a folder with a file named setup.py:
from setuptools import setup
print("setup.py is running as part of the install")
setup(name="demo-sdist", version="0.1")Then run this from the same folder:
pip install -v .The verbose flag shows the message. pip hides build output by default, so a malicious setup.py would not announce itself the way this demo does.
Startup hooks in `.pth` files
Python reads .pth files in site-packages every time the interpreter starts. Most lines are directory paths to add to sys.path. A line that begins with import is executed as code. A wheel can ship such a file, so a package that needs no build step can still run code on every Python start, even when you never import it.
A path-only .pth file looks like this:
/home/user/shared-libsA line starting with import in the same file would be run instead of treated as a path. Package authors use this for legitimate setup. An attacker can use it the same way.
Import-time code
Importing a module executes its top-level statements. Importing a package executes its __init__.py. If an assistant writes import requessts and a malicious package by that name exists, the payload runs on the first run of the script. Nothing at install time is needed.
npm: lifecycle scripts
npm packages can declare lifecycle scripts in package.json. These are shell commands that npm runs at set stages. The ones that matter for installation are:
| Script | When it runs |
|---|---|
| `preinstall` | Before the package is installed |
| `install` | After the package files are in place |
| `postinstall` | After `install` completes |
| `prepare` | After install, and before publish. For git dependencies it also runs after the package is fetched |
The commands run through your shell with your user's permissions. A package can also trigger an implicit build: if it contains a binding.gyp file and defines no install script, npm runs node-gyp rebuild by default.
Try it with a harmless project. Create hook.js:
console.log("postinstall hook executed");And a package.json beside it:
{
"name": "demo-hook",
"version": "1.0.0",
"scripts": {
"postinstall": "node hook.js"
}
}Run npm install and the message appears. Run npm install --ignore-scripts and it does not. The same mechanism applies to every package in your dependency tree, including packages you did not choose directly.
What the code can reach
An install script is not sandboxed. It inherits the privileges of the account that ran the installer. On a developer laptop that account can usually reach:
- Environment variables, which often hold API keys and tokens.
- Files such as
~/.ssh,~/.aws/credentials,~/.npmrc,~/.pypirc, and browser profiles. - The network, so it can send what it finds elsewhere.
- Project files, so it can modify source code or other dependencies.
- Shell startup files, so it can persist after the install finishes.
In a CI system the account may also hold deploy tokens and registry publish rights. A compromised build job can therefore publish further poisoned packages.
If you install with sudo, or as root in a container, the payload gets those privileges too. Avoid sudo pip install and sudo npm install. Use virtual environments and project-local installs.
Transitive dependencies widen the exposure
A package you install may depend on other packages, which depend on others. The package manager resolves all of them and may run install code for each. A single suggested name can pull in a chain of packages that you never read.
This matters for slopsquatting. An attacker does not need the hallucinated package to be useful. A fake package can look plausible, even re-export a real library's functions so your code appears to work, while a dependency or a script does the harmful part. The tell-tale symptoms are absent. Your tests pass and the install finishes without errors.
What turning off scripts does and does not do
Disabling install hooks removes one execution point, not all of them.
| Control | Blocks | Does not block |
|---|---|---|
| `npm ci --ignore-scripts` | `preinstall`, `install`, `postinstall`, `prepare` of dependencies | Code that runs when your app `require`s or `import`s the package |
| `ignore-scripts=true` in `.npmrc` | Same, applied by default | Same. It can also break packages that legitimately need a build step |
| `pip install --only-binary :all:` | Building any sdist, so no `setup.py` or build backend runs | `.pth` hooks and import-time code in wheels |
| `pip install --no-deps` | Pulling in transitive packages | Code in the package you named |
Two points follow from the table.
First, script restrictions reduce risk during installation. They do not make an unknown package trustworthy. If you then import it, its code runs.
Second, --only-binary :all: forces wheels, which removes the build-time execution point for Python. Some packages publish only an sdist, so the install will fail for them. That failure is useful information, because you then decide whether to build that package in an isolated environment.
Looking inside a package without running it
You can inspect a package's install-time behavior before installing, as long as the inspection step itself does not execute anything.
For npm, npm view reads registry metadata and npm pack downloads the tarball without installing it:
npm view example-package scripts
npm pack example-package
tar -tzf example-package-*.tgzFor Python, download only a wheel and list its contents:
pip download --only-binary :all: --no-deps -d inspect example-package
unzip -l inspect/*.whlAvoid pip download on an sdist for this purpose. Getting the metadata for an sdist may itself run the build backend. If a package has no wheel, fetch the sdist by hand from the PyPI "Download files" page and unpack it with tar.
The following script automates one narrow check. It reads a package.json that you have already unpacked and reports any lifecycle hooks that run on install:
import json
import sys
INSTALL_HOOKS = ("preinstall", "install", "postinstall", "prepare")
def install_hooks(path):
with open(path, encoding="utf-8") as fh:
manifest = json.load(fh)
scripts = manifest.get("scripts", {})
return {name: scripts[name] for name in INSTALL_HOOKS if name in scripts}
if __name__ == "__main__":
for path in sys.argv[1:]:
hooks = install_hooks(path)
if hooks:
print(f"{path}: runs code on install")
for name, command in hooks.items():
print(f" {name}: {command}")
else:
print(f"{path}: no install hooks declared")Run it as python hooks.py package/package.json after extracting a tarball made by npm pack. Note that npm pack extracts into a folder named package.
A missing hook is not proof of safety, because the package's runtime code is still unread. A present hook is a prompt to read the command it runs and decide whether the package needs it.
Common mistakes
- Assuming that a package with no visible output is harmless. Install scripts can run silently, and pip hides build logs by default.
- Treating
--ignore-scriptsas a complete defense. It does nothing about code that runs when you import the package. - Running installs as root or with
sudo, which hands the payload more privileges than it needs. - Installing from an assistant's suggestion to "just see if it works". The test run is the moment the import-time code executes.
- Checking only the package you named, and not the dependencies it brings in.
Exercise
A teammate says, "We run npm ci --ignore-scripts in CI, so a malicious dependency cannot run code on our build server." Give two ways the statement is wrong or incomplete.
Show answer
First, --ignore-scripts only stops lifecycle hooks. If the build or test step requires or imports the malicious package, its top-level code runs with the CI job's permissions, including access to any tokens in the environment. Second, the flag does nothing about other packages in the job, such as Python dependencies installed in the same pipeline, where sdist builds and .pth files in wheels can still run code. A further point is that scripts a project legitimately needs are skipped too, so the team must run those steps separately and deliberately.
Exercise
You must evaluate an unknown Python package called example-package without running any of its code. Which pip options do you use to fetch it, and why do you avoid downloading its sdist with pip?
Show answer
Use pip download --only-binary :all: --no-deps -d inspect example-package, then list the wheel with unzip -l. --only-binary :all: restricts pip to wheels, which are unpacked without executing code. --no-deps stops pip from fetching transitive packages. Pip may need to run the build backend to obtain an sdist's metadata, which would execute the package's setup.py or backend code. If only an sdist exists, download it manually from the PyPI files page and unpack it with tar.