Sub topic 12
If You Already Installed a Suspicious Package
This chapter assumes you can use pip or npm from the command line, you know that install scripts can run code (covered earlier in this tutorial), and you can read basic shell output. It covers what to do after you install a package you now doubt. For example, an AI assistant suggested it, you ran the install, and a later check shows the package is brand new, nearly empty, or not what you expected.
The goal is to answer three questions in order:
- Did attacker code run on this machine?
- If it did, what could that code reach?
- How do you get back to a state you trust?
Start with triage, not cleanup
The first instinct is to run pip uninstall or rm -rf node_modules and move on. Uninstalling removes the package files. It does not undo anything the package already did. An install script that copied your tokens to a remote server has finished its work by the time you notice.
Decide first how much trouble you are in. The answer depends on how the package ran.
| Situation | Code may have run | Typical exposure |
|---|---|---|
| npm install with lifecycle scripts enabled | Yes, at install | Everything the user account can read |
| npm install with `--ignore-scripts`, never imported | Probably not | Low, but check for later `require` or `import` |
| pip install of a source distribution (sdist) | Yes, build code runs at install | Everything the user account can read |
| pip install of a wheel, never imported | Install itself runs no package code, but `.pth` files can execute at interpreter start | Low to medium |
| Package imported or run in tests, an app, or a notebook | Yes | Everything that process could reach |
| Installed in CI or a build container | Yes | CI secrets and anything the runner's credentials can reach |
Two points follow from the table. Import-time code is a second chance for the attacker, so "I only installed it" is not a safe answer if anything has imported it since. And the account that ran the install defines the blast radius, so installing as root or in a CI job with deploy credentials is worse than installing in a throwaway container.
The response workflow
Step 1: Isolate
Stop anything that is running the package: a dev server, a notebook kernel, a test run, an agent session. If the install was done by an AI coding agent, stop the agent too, because it may keep issuing commands. If the machine is a laptop with sensitive access and you believe code ran, disconnect it from the network while you decide what to do. If it is a CI runner, cancel the job and disable the pipeline's cache so the package does not spread to other builds.
Step 2: Preserve evidence
Before removing anything, copy the package files and the logs somewhere safe. You need them to see what the code did, and the registry's security team may want them.
- Note the exact package name, version, and the command that installed it. Shell history, CI logs, and the agent transcript usually have this.
- Copy the installed directory (
node_modules/<name>or the package folder undersite-packages) into an archive and do not open or run any of it. - Keep the lockfile and manifest as they were, using
git stashor a plain copy if you need to change them later. - Record the time of the install. You will use it to bound your log searches.
Inspect the copy as text. Never run it, and do not analyze it on a machine that holds credentials. A disposable virtual machine is the right place to read unknown code.
Step 3: Work out whether code ran
For npm, find which installed packages declare lifecycle scripts. Scripts named preinstall, install, and postinstall run during install.
# List installed npm packages that declare install-time scripts
grep -l -E '"(preinstall|install|postinstall)"' \
node_modules/*/package.json node_modules/@*/*/package.json 2>/dev/null
# Ask the registry what scripts the latest published version declares
npm view suspicious-package scriptsRead the script entries you find. A script that runs node scripts/setup.js is only a pointer, so open the referenced file. Look for network calls, reads of environment variables, base64 blobs, and access to home-directory files such as ~/.npmrc, ~/.aws, or ~/.ssh.
For Python, a source distribution runs setup.py or a build backend at install, which can execute arbitrary code. A wheel does not run package code during install, but it can ship a .pth file. Python processes any line in a .pth file that begins with import every time the interpreter starts, so it is a convenient persistence mechanism. This script lists those lines in your environment:
import site
import sys
from pathlib import Path
def site_dirs():
dirs = list(site.getsitepackages())
user = site.getusersitepackages()
if user:
dirs.append(user)
return [Path(d) for d in dirs if Path(d).is_dir()]
def main():
found = False
for directory in site_dirs():
for pth in sorted(directory.glob("*.pth")):
text = pth.read_text(encoding="utf-8", errors="replace")
for number, line in enumerate(text.splitlines(), start=1):
if line.startswith(("import ", "import\t")):
found = True
print(f"{pth}:{number}: {line[:200]}")
if not found:
print("No executable .pth lines found.")
return 0
if __name__ == "__main__":
sys.exit(main())Some legitimate packages use executable .pth lines, for example editable installs and some coverage tools. A hit is a lead, not a verdict. Match each hit to a package you recognize, and investigate the ones you cannot explain.
Step 4: Look for persistence and outbound traffic
If code ran, assume it tried to stay. Check the places a user-level process can write without special permissions:
- Shell startup files such as
~/.bashrc,~/.zshrc, and~/.profile. - Scheduled tasks:
crontab -l, and user systemd units under~/.config/systemd/user/. ~/.ssh/authorized_keys, for keys you did not add.- Git hooks in repositories you work in (
.git/hooks/), and global git config. - New files in the project that the install should not have produced, shown by
git statusandgit diff. - Unfamiliar processes and open connections (
ps, andss -tpnon Linux).
For network evidence, search firewall, proxy, or DNS logs from the install time forward for domains you do not recognize. On a managed network, give your security team the package name and the install time so they can search across machines. Others may have installed the same name.
Step 5: Rotate credentials
If code ran, or you cannot show it did not, rotate every secret that the account or process could read. Revoke first, then reissue, so an attacker holding a copy loses access as early as possible.
- Cloud keys and session tokens (AWS, GCP, Azure), including any in
~/.aws/credentialsand in environment variables. - Package registry tokens, such as those in
~/.npmrcand~/.pypirc. - Source hosting tokens and SSH keys, including deploy keys on the machine.
- API keys in
.envfiles in the project and in parent directories. - Secrets that your CI system injected, if the install ran in CI.
- Browser-stored sessions and password manager sessions, if the machine is a personal workstation.
After rotating, review the audit logs of the services those credentials could reach, for the period since the install. Look for logins from new locations, new access keys, new tokens, and unexpected package publishes. If your own package credentials were exposed, check that nobody published a new version of your packages. That would turn your incident into someone else's.
Step 6: Rebuild, then clean up
When code ran, the safest recovery is to rebuild rather than clean. Delete the container, virtual environment, or CI runner and create a new one from a known-good image. For a developer laptop with evidence of real compromise, involve your security team about reimaging.
If you have good evidence that code did not run, a targeted cleanup is reasonable:
# Python: remove the package from the active environment
python -m pip uninstall suspicious-package
# npm: remove it and update manifest and lockfile
npm uninstall suspicious-packageThen confirm the name is gone from requirements.in, requirements.txt, package.json, and the lockfile. Reinstall from the lockfile in a clean directory (npm ci --ignore-scripts, or pip install --require-hashes -r requirements.txt) and review the diff. A package you removed by hand can come back if another dependency or a stale lockfile still lists it.
Step 7: Report
Report the package to the registry using the report link on its page on PyPI or npm, and include the version, the evidence, and the install time. Registries remove malicious packages and can warn other users. If the package was in a shared repository or came from your organization's internal mirror, tell your security team and the mirror's owners so they can block the name.
Fix the process, not just the machine
An incident is a free test of your controls. Ask what let the package in, and close that gap:
- Was the name never verified? Add the existence and age check from the earlier chapter to your review step.
- Did the install run with scripts enabled? Make
--ignore-scriptsthe default for npm in CI and document when to override it. - Did an agent install without approval? Require human confirmation for any command that adds a dependency.
- Was a lockfile missing or ignored? Block merges when
requirements.txtorpackage-lock.jsonchanges without review. - Did the install have more access than it needed? Run installs in containers or CI jobs that hold no deploy credentials.
Write the timeline down: what was installed, when, what you checked, what you rotated. A short record helps the next responder and shows which checks worked.
Exercise
A coding assistant suggested flask-session-utils, and you ran pip install flask-session-utils on your laptop. An hour later you find the package was first uploaded two days ago and has one release with no description. You have not imported it. List, in order, what you do first, and explain why uninstalling is not enough.
Show answer
First stop any process that might import it and preserve evidence: record the install command and time, and copy the installed package folder into an archive without running it. Next determine whether code ran. The name may have installed from a source distribution, which runs build code at install, or from a wheel, which does not. Check the package's files for a setup script and for .pth files with executable lines, and check shell startup files, cron, and authorized_keys for persistence. If the package was an sdist or you cannot show it did not run, treat credentials on the laptop as exposed. Revoke and reissue cloud keys, registry and source-hosting tokens, and secrets in .env files, doing so from a clean machine, then review audit logs since the install time. Rebuild the environment if code ran, report the package to PyPI, and add a name-and-age check to your process. Uninstalling only deletes files. It cannot undo what install-time code already did, such as sending out secrets or writing persistence elsewhere on the system.