Typosquatting & Malicious Packages
Most malicious packages don't compromise an existing project. They are new packages, published by the attacker, that rely on someone choosing them by mistake. Public registries (npm, PyPI, RubyGems, crates.io) let anyone publish, and every one of them removes thousands of malicious packages a year.
How they get chosen
| Trick | Example | Why it works |
|---|---|---|
| Typosquatting | crossenv for cross-env (npm, 2017: a batch of such packages stole environment variables) |
one missing character in an install command |
| Combosquatting | requests-toolbelt-fix, lodash-utils |
looks like an official add-on |
| Separator / case confusion | python-dateutil vs python_dateutil, Pillow vs pillow |
registries normalise some names but not all |
| Starjacking | the package page links to a popular GitHub repo it has nothing to do with | stars and README look trustworthy |
| Slopsquatting | registering names that AI coding assistants tend to invent | the suggested package didn't exist until the attacker created it |
| Dependency confusion | a public package named like a company's internal one | covered in its own lesson |
The payload usually runs at install time through a lifecycle script (preinstall/postinstall in npm, code in setup.py for Python sdists, build.rs in Rust), so the attack succeeds before anyone imports the package. The Install Scripts & allowScripts lesson shows how npm and pnpm control that.
A model: flag names close to popular ones
Registries and security tools catch typosquats by comparing new names with popular ones. The usual measure is the edit distance: how many single-character insertions, deletions or substitutions turn one name into the other. This model normalises names the way PyPI does (lowercase, -/_/. are equivalent) and flags anything within distance 2 of a popular package that isn't that package.
import re
POPULAR = ["requests", "urllib3", "numpy", "django", "cross-env", "lodash", "python-dateutil"]
def normalize(name: str) -> str:
return re.sub(r"[-_.]+", "-", name).lower() # PEP 503 normalisation
def distance(a: str, b: str) -> int:
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
cur = [i]
for j, cb in enumerate(b, 1):
cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
prev = cur
return prev[-1]
def check(candidate: str) -> str:
n = normalize(candidate)
for p in POPULAR:
if n == normalize(p):
return f"{candidate:18} ok (is {p})"
close = [(distance(n, normalize(p)), p) for p in POPULAR]
d, p = min(close)
return f"{candidate:18} SUSPICIOUS: distance {d} from {p}" if d <= 2 else f"{candidate:18} ok (unrelated)"
for name in ["requests", "reqeusts", "Python_DateUtil", "crossenv", "numpyy", "djang0", "flask", "lodahs"]:
print(check(name))requests ok (is requests)
reqeusts SUSPICIOUS: distance 2 from requests
Python_DateUtil ok (is python-dateutil)
crossenv SUSPICIOUS: distance 1 from cross-env
numpyy SUSPICIOUS: distance 1 from numpy
djang0 SUSPICIOUS: distance 1 from django
flask ok (unrelated)
lodahs SUSPICIOUS: distance 2 from lodash
Note Python_DateUtil: after normalisation it is python-dateutil, so it's not a typosquat at all, while reqeusts (two swapped letters, distance 2) is caught. Real tools add download counts, publication age and maintainer history, because short names produce many false alarms (flask is distance 2 from flake, which is also legitimate).
Reading a lockfile for warning signs
A lockfile records more than versions. In npm's package-lock.json each entry has the resolved URL it was downloaded from, an integrity hash, and hasInstallScript: true when the package runs lifecycle scripts. This session reviews a lockfile that contains one suspicious entry:
mkdir app && cd app
cat > package-lock.json <<'JSON'
{
"name": "app", "version": "1.0.0", "lockfileVersion": 3, "requires": true,
"packages": {
"": { "name": "app", "version": "1.0.0", "dependencies": { "lodash": "4.17.21", "cross-env": "7.0.3", "crossenv": "1.0.0" } },
"node_modules/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="
},
"node_modules/cross-env": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
"integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw=="
},
"node_modules/crossenv": {
"version": "1.0.0",
"resolved": "https://npm.example-cdn.net/crossenv/-/crossenv-1.0.0.tgz",
"hasInstallScript": true
}
}
}
JSON
echo "--- packages with install scripts"
jq -r '.packages | to_entries[] | select(.value.hasInstallScript) | .key' package-lock.json
echo "--- packages not from the official registry"
jq -r '.packages | to_entries[] | select(.value.resolved and (.value.resolved | startswith("https://registry.npmjs.org/") | not)) | "\(.key) \(.value.resolved)"' package-lock.json
echo "--- packages without an integrity hash"
jq -r '.packages | to_entries[] | select(.key != "" and (.value.integrity | not)) | .key' package-lock.json--- packages with install scripts
node_modules/crossenv
--- packages not from the official registry
node_modules/crossenv https://npm.example-cdn.net/crossenv/-/crossenv-1.0.0.tgz
--- packages without an integrity hash
node_modules/crossenv
One package fails all three checks: it runs code at install, comes from an unknown host and has no integrity hash. That's worth a CI check of its own (lockfile linters such as lockfile-lint do exactly this), and a reason to review lockfile diffs in pull requests instead of collapsing them.
Defences
- Choose deliberately. Copy package names from the project's own docs, not from search results or an AI suggestion; check the repository link, the publisher and the download history.
- Review new dependencies in pull requests, including new transitive ones; an SBOM diff makes that easy (Converting & Querying SBOMs).
- Restrict install scripts: npm
--ignore-scriptsfor CI installs that don't need them, pnpm's default of not running dependencies' build scripts unless allowed. - Use a proxy registry (Artifactory, Nexus, a pull-through cache) that can block packages younger than a few days or flagged by a malware feed; most malicious packages are removed within days.
- Pin and verify what you chose (Pinning by Hash), so a later swap is detected.
Test yourself
When does the payload of a typical malicious npm package run?
- Only when the package is imported
- At install time, through a lifecycle script such as postinstall
- When the lockfile is committed
- Only in production
Why is Python_DateUtil not a typosquat of python-dateutil on PyPI?
- PyPI blocks all capital letters
- PyPI normalises case and separators, so both are the same project name
- Edit distance is 0 without normalisation
- It is a typosquat
Which lockfile field tells you an npm package runs code during installation?
- integrity
- resolved
- hasInstallScript
- dev