repositories

daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR

clonegit clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
dependency-confusion.mdMarkdown429 lines20.0 KiBsource raw download

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:

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.

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]

Common pattern in the npm ecosystem:

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:

{
  "name": "popular-lib",
  "version": "1.2.4",
  "dependencies": {
    "helper-lib": "^4.2.1"
  }
}

package.json of the injected dependency:

{
  "name": "helper-lib",
  "version": "4.2.1",
  "scripts": {
    "postinstall": "node setup.js"
  }
}

Practical notes:

Obfuscated Node.js droppers and manifest laundering#

Malicious install hooks often try to survive quick review by:[5]

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 <name> is a different supply-chain primitive from classic dependency confusion. If no explicit --package is given, npm first tries to resolve <name> 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/<hash>/, prepends node_modules/.bin from that cache entry to PATH, and executes it.[9][10][11]

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 <binary_name>.
  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 <binary_name> is unclaimed.
  4. Publish <binary_name> with a matching bin entry.
  5. Wait for a developer, CI runner, automation job, or agent to execute npx <binary_name> outside the correct dependency context (wrong cwd, fresh workspace, dependencies not installed, minimal container, etc.).

Why scoped packages are dangerous here:

Practical red-team checks:

Practical hardening:

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]

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]

Practical Attacker Playbook (for red teams in authorized tests)#

[!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:

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)#

.npmrc (project-level)

# 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)

{
  "name": "@company/api-client",
  "version": "1.2.3",
  "private": false,
  "publishConfig": {
    "registry": "https://registry.corp.example/npm/",
    "access": "restricted"
  }
}

Yarn Berry (.yarnrc.yml)[4]

npmScopes:
  company:
    npmRegistryServer: "https://registry.corp.example/npm/"
    npmAlwaysAuth: true
# CI should fail if lockfile would change
enableImmutableInstalls: true

Operational tips:

Python (pip / Poetry)#

Core rule: Don’t use --extra-index-url to mix trust levels. Either:

pip.conf

[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:

# 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]

nuget.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <clear />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
    <add key="corp" value="https://nuget.corp.example/v3/index.json" />
  </packageSources>
  <packageSourceMapping>
    <packageSource key="nuget.org">
      <package pattern="*" />
    </packageSource>
    <packageSource key="corp">
      <package pattern="Company.*" />
      <package pattern="Internal.Utilities" />
    </packageSource>
  </packageSourceMapping>
</configuration>

Java (Maven/Gradle)#

Maven settings.xml (mirror all to internal; disallow ad-hoc repos in POMs via Enforcer):

<settings>
  <mirrors>
    <mirror>
      <id>internal-mirror</id>
      <mirrorOf>*</mirrorOf>
      <url>https://maven.corp.example/repository/group</url>
    </mirror>
  </mirrors>
</settings>

Add Enforcer to ban repositories declared in POMs and force usage of your mirror:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-enforcer-plugin</artifactId>
  <version>3.6.1</version>
  <executions>
    <execution>
      <id>enforce-no-repositories</id>
      <goals><goal>enforce</goal></goals>
      <configuration>
        <rules>
          <requireNoRepositories />
        </rules>
      </configuration>
    </execution>
  </executions>
</plugin>

Gradle: Centralize and lock dependencies.

dependencyResolutionManagement {
  repositoriesMode = RepositoriesMode.FAIL_ON_PROJECT_REPOS
  repositories {
    maven { url = uri("https://maven.corp.example/repository/group") }
  }
}

Go Modules#

Configure private modules so the public proxy and checksum DB aren’t used for them.

# 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

[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

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:

bundle config set disable_multisource true

CI/CD and Registry Controls That Help#

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]

Useful heuristics:

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][12][13]

# pnpm-workspace.yaml
minimumReleaseAge: 10080 # 7 days in minutes
# .yarnrc.yml
npmMinimalAgeGate: "7d"
# bunfig.toml
[install]
minimumReleaseAge = 604800 # 7 days in seconds
# .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#