--- title: "Dependency Confusion" section: "Web Pentesting" sectionSlug: "pentesting-web" sourcePath: "src/pentesting-web/dependency-confusion.md" sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/pentesting-web/dependency-confusion.md" sha: "188de82beb54e70956b2952367a0af91d26758b8" isIndex: false modified: true license: "CC-BY-NC-4.0" --- # Dependency Confusion ## Basic Information Dependency Confusion (a.k.a. substitution attacks) happens when a package manager resolves a dependency name from an unintended, less-trusted registry/source (usually a public registry) instead of the intended private/internal one. This typically leads to the installation of an attacker-controlled package. Common root causes: - Typosquatting/misspelling: Importing `reqests` instead of `requests` (resolves from public registry). - Non-existent/abandoned internal package: Importing `company-logging` that no longer exists internally, so the resolver looks in public registries and finds an attacker’s package. - Version preference across multiple registries: Importing an internal `company-requests` while the resolver is allowed to also query public registries and prefers the “best”/newer version published publicly by an attacker. Key idea: If the resolver can see multiple registries for the same package name and is allowed to pick the “best” candidate globally, you’re vulnerable unless you constrain resolution. ## Exploitation > [!WARNING] > In all cases, the attacker only needs to publish a malicious package with the same name as the dependency your build resolves from a public registry. Installation-time hooks (e.g., npm scripts) or import-time code paths often give code execution. ### Misspelled & Inexistent If your project references a library that isn’t available in the private registry, and your tooling falls back to a public registry, an attacker can seed a malicious package with that name in the public registry. Your runners/CI/dev machines will fetch and execute it. ### Unspecified Version / “Best-version” selection across indexes Developers frequently leave versions unpinned or allow wide ranges. When a resolver is configured with both internal and public indexes, it may select the newest version regardless of source. For internal names like `requests-company`, if the internal index has `1.0.1` but an attacker publishes `1.0.2` to the public registry and your resolver considers both, the public package may win. ### Related pattern: compromise of a legitimate package release Dependency confusion is not the only way to get install-time execution. If an attacker compromises the maintainer account or publishing token of a legitimate package, they can publish a malicious version of the real package and obtain code execution on every machine that installs it.[[5]](#references) Common pattern in the npm ecosystem: - The attacker modifies only `package.json` and adds a new dependency. - The new dependency is **never imported** by the main library, so source review of the application code may look clean. - The dependency contains a `preinstall`/`install`/`postinstall` hook that runs automatically during `npm install`, `npm ci`, Yarn, pnpm, or CI builds. - The hook fetches or drops the real payload, often choosing per-OS implants for macOS, Windows, and Linux. This is a useful red-team and incident-response mental model because **importing the victim library is not required**. The execution path is installation-time, not runtime. Minimal malicious pattern: `package.json` of the compromised package: ```json { "name": "popular-lib", "version": "1.2.4", "dependencies": { "helper-lib": "^4.2.1" } } ``` `package.json` of the injected dependency: ```json { "name": "helper-lib", "version": "4.2.1", "scripts": { "postinstall": "node setup.js" } } ``` Practical notes: - CI/CD runners are especially valuable targets because the hook runs before tests and often has access to cloud credentials, package tokens, signing keys, and deployment secrets. - If you are trying to prove impact in an authorized exercise, `postinstall` is usually enough to demonstrate install-time code execution without modifying application logic. - Defenders should remember that `npm ci` still runs lifecycle scripts unless `--ignore-scripts` is set. ### Obfuscated Node.js droppers and manifest laundering Malicious install hooks often try to survive quick review by:[[5]](#references) - Hiding C2 strings or commands behind layered transforms such as reversed Base64, XOR, or split strings. - Dynamically loading Node modules (`fs`, `os`, `child_process`, `execSync`) only at runtime to reduce obvious static indicators. - Deleting the dropper after execution and restoring a benign-looking manifest. One anti-forensic trick is **manifest laundering**: 1. Run the malicious hook. 2. Delete the malicious `setup.js` or equivalent. 3. Delete the malicious `package.json`. 4. Rename a benign stub such as `package.md` back to `package.json`. After infection, the installed dependency directory may look clean unless investigators review install logs, lockfile changes, registry metadata, package tarballs, file timelines, or known-good hashes. ### `npx` binary-to-package confusion `npx ` is a **different supply-chain primitive** from classic dependency confusion. If no explicit `--package` is given, npm first tries to resolve `` as an executable from the local `node_modules/.bin`, global bins, installed package trees, and the `npx` cache. If none of those checks succeed, npm treats the same string as a **package name**, installs it into `~/.npm/_npx//`, prepends `node_modules/.bin` from that cache entry to `PATH`, and executes it.[[9]](#references)[[10]](#references)[[11]](#references) That means an attacker can win with **binary-name takeover** even when there is no public/private registry precedence issue: 1. Discover scripts, READMEs, CI jobs, bundles, or leaked `package.json` files containing `npx `. 2. Confirm the real package exposing that binary has a different package name (very common with scoped packages such as `@company/tool`). 3. Check whether the public package `` is unclaimed. 4. Publish `` with a matching `bin` entry. 5. Wait for a developer, CI runner, automation job, or agent to execute `npx ` **outside the correct dependency context** (wrong cwd, fresh workspace, dependencies not installed, minimal container, etc.). Why scoped packages are dangerous here: - The real package can be `@company/tool`, but its executable is usually unscoped (`tool`, `build`, `sync-assets`, etc.). - If `npx tool` cannot find the local binary, npm may fetch the public package `tool` instead of the intended private/scoped package. - In non-interactive contexts, npm assumes `--yes`, so CI/automation often auto-installs the missing package with only a warning in logs. Practical red-team checks: - Grep for `npx ` in repositories, CI definitions, docs, shell history, bundled `package.json`, and transpiled JavaScript. - Enumerate `bin` entries from internal packages and compare the executable names against the actual package names. - Inspect `~/.npm/_npx/` on build agents or developer workstations for unexpected cached packages and `_npx` metadata. - Review CI logs for messages like `The following package was not found and will be installed`. Practical hardening: - Prefer `npx --package ` (or `npm exec --package= -- `) so the binary is bound to the intended package. - Reserve public names matching internal binaries, especially names exported by scoped/private packages. - In sensitive runners, use `--no`, `offline`, or preinstall the expected package instead of allowing implicit remote fetches. - Run automation from the intended project root and fail closed when `node_modules/.bin/` is absent. ## AWS Fix This vulnerability was found in AWS CodeArtifact (read the details in this blog post). AWS added controls to mark dependencies/feeds as internal vs external so the client won’t fetch “internal” names from upstream public registries.[[2]](#references) ## Finding Vulnerable Libraries In the original post about dependency confusion the author looked for thousands of exposed manifests (e.g., `package.json`, `requirements.txt`, lockfiles) to infer internal package names and then published higher-versioned packages to public registries.[[1]](#references) ## Practical Attacker Playbook (for red teams in authorized tests) - Enumerate names: - Grep repos and CI configs for manifest/lock files and internal namespaces. - Look for organization-specific prefixes (e.g., `@company/*`, `company-*`, internal groupIds, NuGet ID patterns, private module paths for Go, etc.). - Check public registries for availability: - If the name is unregistered publicly, register it; if it exists, attempt subdependency hijacking by targeting internal transitive names. - Publish with precedence: - Choose a semver that “wins” (e.g., a very high version) or matches resolver rules. - Include minimal install-time execution where applicable (e.g., npm `preinstall`/`install`/`postinstall` scripts). For Python, prefer import-time execution paths, as wheels typically don’t execute arbitrary code on install. - Exfil control: - Ensure outbound is allowed from CI to your controlled endpoint; otherwise use DNS queries or error messages as a side-channel to prove code execution. > [!CAUTION] > Always get written authorization, use unique package names/versions for the engagement, and immediately unpublish or coordinate cleanup when testing concludes. ## Defender Playbook (what actually prevents confusion) High-level strategies that work across ecosystems: - Use unique internal namespaces and bind them to a single registry. - Avoid mixing trust levels at resolution time. Prefer a single internal registry that proxies approved public packages instead of giving package managers both internal and public endpoints. - For managers that support it, map packages to specific sources (no global “best-version” across registries). - Pin and lock: - Use lockfiles that record the resolved registry URLs (npm/yarn/pnpm) or use hash/attestation pinning (pip `--require-hashes`, Gradle dependency verification). - Block public fallback for internal names at the registry/network layer. - Reserve your internal names in public registries when feasible to prevent future squat. ## Ecosystem Notes and Secure Config Snippets Below are pragmatic, minimal configs to reduce or eliminate dependency confusion. Prefer enforcing these in CI and developer environments. ### JavaScript/TypeScript (npm, Yarn, pnpm) - Use scoped packages for all internal code and pin the scope to your private registry. - Keep installs immutable in CI (npm lockfile, `yarn install --immutable`). .npmrc (project-level) ```text # Bind internal scope to private registry; do not allow public fallback for @company/* @company:registry=https://registry.corp.example/npm/ # Always authenticate to the private registry //registry.corp.example/npm/:_authToken=${NPM_TOKEN} strict-ssl=true ``` package.json (for internal package) ```text { "name": "@company/api-client", "version": "1.2.3", "private": false, "publishConfig": { "registry": "https://registry.corp.example/npm/", "access": "restricted" } } ``` Yarn Berry (.yarnrc.yml)[[4]](#references) ```text npmScopes: company: npmRegistryServer: "https://registry.corp.example/npm/" npmAlwaysAuth: true # CI should fail if lockfile would change enableImmutableInstalls: true ``` Operational tips: - Only publish internal packages within the `@company` scope. - For third-party packages, allow public registry via your private proxy/mirror, not directly from clients. - Consider enabling npm package provenance for public packages you publish to increase traceability (doesn’t by itself prevent confusion). - For high-risk environments, install with scripts disabled first (`npm ci --ignore-scripts`) and only allow scripts in controlled build stages. ### Python (pip / Poetry) Core rule: Don’t use `--extra-index-url` to mix trust levels. Either: - Expose a single internal index that proxies and caches approved PyPI packages, or - Use explicit index selection and hash pinning. pip.conf ```text [global] index-url = https://pypi.corp.example/simple # Disallow source distributions when possible only-binary = :all: # Lock with hashes generated via pip-tools require-hashes = true ``` Generate hashed requirements with pip-tools: ```text # From pyproject.toml or requirements.in pip-compile --generate-hashes -o requirements.txt pip install --require-hashes -r requirements.txt ``` If you must reach public PyPI, do it via your internal proxy and maintain an explicit allowlist there. Avoid `--extra-index-url` in CI. ### .NET (NuGet) Use Package Source Mapping to tie package ID patterns to explicit sources and prevent resolution from unexpected feeds.[[3]](#references) nuget.config ```text ``` ### Java (Maven/Gradle) Maven settings.xml (mirror all to internal; disallow ad-hoc repos in POMs via Enforcer): ```text internal-mirror * https://maven.corp.example/repository/group ``` Add Enforcer to ban repositories declared in POMs and force usage of your mirror: ```text org.apache.maven.plugins maven-enforcer-plugin 3.6.1 enforce-no-repositories enforce ``` Gradle: Centralize and lock dependencies. - Enforce repositories in `settings.gradle(.kts)` only: ```text dependencyResolutionManagement { repositoriesMode = RepositoriesMode.FAIL_ON_PROJECT_REPOS repositories { maven { url = uri("https://maven.corp.example/repository/group") } } } ``` - Enable dependency verification (checksums/signatures) and commit `gradle/verification-metadata.xml`. ### Go Modules Configure private modules so the public proxy and checksum DB aren’t used for them. ```text # Use corporate proxy first, then public proxy as fallback export GOPROXY=https://goproxy.corp.example,https://proxy.golang.org # Mark private paths to skip proxy and checksum db export GOPRIVATE=*.corp.example.com,github.com/your-org/* export GONOSUMDB=*.corp.example.com,github.com/your-org/* ``` ### Rust (Cargo) Replace crates.io with an approved internal mirror or vendor directory for builds; do not allow arbitrary public fallback. .cargo/config.toml ```text [source.crates-io] replace-with = "corp-mirror" [source.corp-mirror] registry = "https://crates-mirror.corp.example/index" ``` For publishing, be explicit with `--registry` and keep credentials scoped to the target registry. ### Ruby (Bundler) Use source blocks and disable multisource Gemfiles so gems come only from the intended repository. Gemfile ```text source "https://gems.corp.example" source "https://rubygems.org" do gem "rails" gem "pg" end source "https://gems.corp.example" do gem "company-logging" end ``` Enforce at config level: ```text bundle config set disable_multisource true ``` ## CI/CD and Registry Controls That Help - Private registry as a single ingress: - Use Artifactory/Nexus/CodeArtifact/GitHub Packages/Azure Artifacts as the only endpoint developers/CI can reach. - Implement block/allow rules so internal namespaces never resolve from upstream public sources. - Lockfiles are immutable in CI: - npm: commit `package-lock.json`, use `npm ci`. - Yarn: commit `yarn.lock`, use `yarn install --immutable`. - Python: commit hashed `requirements.txt`, enforce `--require-hashes`. - Gradle: commit `verification-metadata.xml` and fail on unknown artifacts. - Outbound egress control: block direct access from CI to public registries except via the approved proxy. - Name reservation: pre-register your internal names/namespaces in public registries where supported. - Package provenance / attestations: when publishing public packages, enable provenance/attestations to make tampering more detectable downstream.[[7]](#references) ### Detecting unauthorized publishes in trusted-publisher pipelines If a package normally uses npm trusted publishing with GitHub Actions or GitLab OIDC, a release pushed with a stolen classic token often looks different from legitimate releases.[[6]](#references) Useful heuristics: - The package version exists in the registry but lacks the expected trusted-publisher / provenance metadata. - There is no matching git tag or release commit for the published version. - The package tarball adds a dependency whose only purpose is a lifecycle hook. - The newly added dependency is never referenced by the main library source. - The lockfile or install logs show `preinstall` / `postinstall` execution shortly before network egress or secret access from a runner. This is not limited to dependency confusion: it also catches compromise of maintainer credentials or leaked automation tokens. ### Cooldown / age-gate controls for fresh releases Fresh malicious versions are often detected and removed quickly. Delaying adoption of newly published versions can block a large class of opportunistic supply-chain compromises:[[8]](#references)[[12]](#references)[[13]](#references) ```yaml # pnpm-workspace.yaml minimumReleaseAge: 10080 # 7 days in minutes ``` ```yaml # .yarnrc.yml npmMinimalAgeGate: "7d" ``` ```toml # bunfig.toml [install] minimumReleaseAge = 604800 # 7 days in seconds ``` ```ini # .npmrc min-release-age=7 ``` These controls do **not** replace lockfiles or trusted publishing, but they reduce exposure to packages published minutes or hours earlier. ## References - [1] [Dependency Confusion: How I Hacked Into Apple, Microsoft and Dozens of Other Companies](https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610) - [2] [Dependency confusion in AWS CodeArtifact](https://zego.engineering/dependency-confusion-in-aws-codeartifact-86b9ff68963d) - [3] [NuGet Package Source Mapping - Microsoft Learn](https://learn.microsoft.com/en-us/nuget/consume-packages/package-source-mapping) - [4] [Yarn - .yarnrc.yml configuration reference](https://yarnpkg.com/configuration/yarnrc/) - [5] [Frequently Asked Questions About the Axios npm Supply Chain Attack by North Korea-Nexus Threat Actor UNC1069 - Tenable](https://www.tenable.com/blog/faq-about-the-axios-npm-supply-chain-attack-by-north-korea-nexus-threat-actor-unc1069) - [6] [About trusted publishers - npm Docs](https://docs.npmjs.com/trusted-publishers/) - [7] [Generating provenance statements - npm Docs](https://docs.npmjs.com/generating-provenance-statements) - [8] [npm CLI v11 changelog](https://docs.npmjs.com/cli/v11/using-npm/changelog/) - [9] [npm exec command reference - npm Docs](https://docs.npmjs.com/cli/v11/commands/npm-exec/) - [10] [npx Used Confusion and It's Super Effective](https://www.landh.tech/blog/20260521-npx-used-confusion-and-its-super-effective) - [11] [npx Confusion: Packages That Forgot to Claim Their Own Name](https://www.aikido.dev/blog/npx-confusion-unclaimed-package-names) - [12] [pnpm Settings reference (minimumReleaseAge)](https://pnpm.io/settings) - [13] [Bun bunfig.toml runtime configuration reference](https://bun.sh/docs/runtime/bunfig)