Skip to content
Cache bugs Write-up Intermediate

Next.js and cache poisoning: a quest for the black hole

The Next.js framework allowed attackers to poison CDN caches by sending requests with special headers that caused the server to return an empty JSON object, the React Server Component payload, or an error page with a 200 status code. This could make targeted pages inaccessible to users for as long as the poisoned cache persisted.

Rachid.A Follow

Published on zhero-web-sec.github.io

Bounty$5,000 View original

In search of challenges, zero-days, and bounties, I focused on widely used software to find interesting cases of cache-poisoning. My attention quickly turned to Next.js, an open-source JavaScript framework based on React, developed and maintained by Vercel.

Rachid.A (@zhero___), on zhero-web-sec.github.io

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.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 11 min read.

Context

Next.js is an open-source JavaScript framework built on React, developed and maintained by Vercel. The next package is downloaded more than 6 million times per week, so a flaw in it can reach a very large number of deployments. This research looks at three cache-poisoning behaviours in Next.js, all of which depend on a caching layer (CDN or similar) sitting in front of the application.

The three findings are:

  1. A prefetch header that makes SSR pages return an empty JSON object, which a CDN can cache.
  2. The React Server Component (RSC) payload being cached because CDNs do not honour the Vary header the framework sets.
  3. An internal header, x-invoke-status, that lets a client overwrite the HTTP status code and invoke the error page, which can then be cached as a 200.

All three are denial-of-service style cache poisoning: the page becomes impractical or inaccessible rather than leaking data.

Setup

The research was done by reading the Next.js source code, running local tests against a Next.js application, and then validating on real bug bounty targets. The tools mentioned are a proxy for inspecting HTTP history and console.log for debugging. No specific Next.js version is given for the local tests beyond the version references cited in the findings themselves.

The precondition common to all three findings is a caching system in front of the application. Without a cache, the behaviours are harmless because nothing is stored and replayed to other users.

Finding it

First vulnerability: the prefetch header

While looking at Next.js middleware, the researcher noticed that when data is prefetched for SSR pages, adding the x-middleware-prefetch header makes the server respond with an empty JSON object {}. If a CDN or caching system is present, that empty response can be cached, depending on the cache rules configuration, which renders the targeted page impractical and its content inaccessible.

From the original on zhero-web-sec.github.io

The only condition for reproducibility is the presence of a caching system. Without it the response is not cached and the header is harmless.

The getServerSideProps and getStaticProps functions are used to retrieve server-side data and generate static pages respectively. Since version 13.4.20-canary.13, Next.js has added cache-control to SSR responses to prevent them from being cached.

From the original on zhero-web-sec.github.io

By the time the researcher was ready to exploit this, the issue already had CVE-2023-46298 assigned. Because no proof of concept had been shared, the behaviour could still be exploited at scale: several dozen bug bounty programs were affected and produced numerous bounties.

From the original on zhero-web-sec.github.io

Second vulnerability: RSC payload and CDNs

The RSC Payload is a compact binary representation of the rendered React Server Components tree, used by React on the client to update the browser's DOM. It contains the rendered result of Server Components, placeholders for where Client Components should be rendered with references to their JavaScript files, and any props passed from a Server Component to a Client Component.

Requests that fetch the RSC payload carry the header Rsc: 1. That header was added to the cache key via the Vary response header, which theoretically prevents cache poisoning.

From the original on zhero-web-sec.github.io

Inspecting the proxy history showed that requests fetching the RSC payload also included a URL parameter that was systematically added: _rsc=randomValue. The researcher understood this to be a cache-buster used to prevent caching an unwanted response, which was surprising given that the header was supposedly part of the cache key via Vary.

A GitHub ticket from a few months earlier had a user complaining that the RSC payload was being cached and blocking access to content. Tim Neutkens, one of the framework maintainers, responded on Apr 20, 2023 that App Router adds headers to the fetch when navigating client-side to get the RSC payload instead of HTML, that Next.js on the server sets the Vary header so browsers and CDNs can cache based on the headers passed to the fetch, and closed the issue as a CDN configuration problem.

So the framework was effectively cache-poisoning itself, and the URL parameter was added to prevent that. Looking at the commit history, a semblance of a fix was pushed on June 12, 2023, two months after the maintainer's response on the ticket.

From the original on zhero-web-sec.github.io

The question then was why CDNs still cache the response without taking the Rsc header into account during content negotiation, given that it is in Vary. The Vary response header describes the parts of the request message, aside from method and URL, that influenced the content of the response, and is most often used to create a cache key when content negotiation is in use. The maintainers' position is that the framework systematically adds the header to Vary, so non-compliance with the HTTP standard is the responsibility of CDNs.

After digging into CDN documentation, non-compliance turned out to be true under certain conditions:

  • Cloudflare does not consider Vary values in caching decisions, except when Vary for images is configured and when the header is vary: accept-encoding.
  • CloudFront removes or replaces some headers, including Vary: if the origin includes other values in the Vary header, CloudFront removes those values before returning the response to the viewer.
  • Akamai has a behaviour called Remove Vary Header that removes the Vary header. Akamai edge servers do not cache responses that include the Vary header, even if the content is cacheable by definition, but there are exceptions. The default behaviour of the Adaptive Media Delivery, Download Delivery and Object Delivery products is to remove the Vary response header.
From the original on zhero-web-sec.github.io

Third vulnerability: internal header, status code and error page

During a code review session, the researcher found code where, under certain conditions, the value of the x-invoke-status header provided directly in the request (req.header[]) overwrites the status code and invokes the error page.

From the original on zhero-web-sec.github.io

x-invoke-status is an internal header, so it is normally stripped when it comes from the client.

From the original on zhero-web-sec.github.io

Exploitation

Step 1: confirm the prefetch behaviour

Send a request to an SSR page with the prefetch header:

The server responds with an empty JSON object {}. If the CDN caches that response, subsequent visitors to the page receive the empty object instead of the page content.

Step 2: exploit the RSC payload caching

The fix for the self-poisoning issue was to add a URL parameter during fetch operations to act as a cache-buster. That does not stop an attacker, who can send a request with the Rsc header without a cache-buster, mimicking a typical cache-poisoning attack:

HTTP
Rsc: 1

Whether this succeeds depends on the CDN and its cache rules. In theory it was exploitable, and after some research the first real target was found.

From the original on zhero-web-sec.github.io

The cache was poisoned and the main/root page returned the React server component instead of the initial content, resulting in a bounty of $2000. From there, pattern extraction, template creation and mass scanning of the researcher's bug bounty asset database produced more reports.

From the original on zhero-web-sec.github.io

Step 3: test the internal header locally

A local test was needed to verify whether x-invoke-status is stripped or honoured. With the default configuration, the header was included as:

HTTP
x-invoke-status: 888

On the first try the header was accepted.

From the original on zhero-web-sec.github.io

At that point the vector was clearly exploitable for cache poisoning. By specifying the HTTP status code 200, the response complies with most caching rules, which typically do not allow caching of error codes. The error page content can then be cached and served instead of the main page.

The other two vulnerabilities are interesting for the same reason: the behaviours induced by their headers result in a 200 response, which aligns with the majority of cache rules.

Step 4: understand the code path

Under certain conditions, the value of x-invoke-status overwrites the statusCode property of the response object, and then the /_error page is returned whatever the HTTP code specified:

JavaScript
res.statusCode = Number(req.headers['x-invoke-status'])

(...)

return this.renderError(err, req, res, '/_error', parsedUrl.query)

It is therefore possible to specify any HTTP code to alter the response code and return the error page (/_error). CDNs and caching systems are generally configured not to cache HTTP error codes, but an attacker can specify 200 to align with cache rules and force caching of the error page.

Three conditions are necessary for this behaviour:

JavaScript
const useInvokePath =
         !useMatchedPathHeader &&
         process.env.NEXT_RUNTIME !== 'edge' &&
         invokePath
  1. useMatchedPathHeader must return false, which is the case if:
JavaScript
const useMatchedPathHeader =
         this.minimalMode && typeof req.headers['x-matched-path'] === 'string'

Minimal mode is an experimental config tested in fully featured Next.js environments like Vercel that have an edge network to handle specific parts of requests that next-server would normally handle.

  1. The Next.js runtime used must not be edge. The default runtime is Node.js.
  2. invokePath should return true:
JavaScript
const invokePath = req.headers['x-invoke-path'] as string

Local tests showed that x-invoke-path is not considered when provided in the request and its value does not appear to be retrieved. The header's value is automatically added and corresponds to the current path, so the constant always returns true.

If the x-invoke-error header is provided and the error page template expects it, a custom error message can be displayed. The value must be JSON:

JSON
{"message":"<>"}
JavaScript
if (typeof req.headers['x-invoke-error'] === 'string') {
        const invokeError = JSON.parse(
            req.headers['x-invoke-error'] || '{}'
        )
        err = new Error(invokeError.message)
    }
From the original on zhero-web-sec.github.io

Step 5: validate on real targets

With the vulnerability confirmed locally, the researcher moved to real bug bounty programs. The first successful exploit came quickly, followed by many others, one of which resulted in a bounty of $3000.

From the original on zhero-web-sec.github.io

Root cause

For the prefetch and RSC findings, the framework itself produced a cacheable response that differed from the normal page, and the only defence was the Vary header. CDNs that ignore or strip Vary (Cloudflare by default, CloudFront for non-standard values, Akamai's Remove Vary Header behaviour) therefore cache the poisoned response. The _rsc cache-buster was added to prevent the framework's own fetches from caching the RSC payload; an attacker can send the Rsc header without it.

For the third finding, the root cause is that the value supplied by the client through the internal x-invoke-status header was taken into account and influenced the response by overwriting the HTTP code and invoking the error page. The header is marked internal and is normally stripped, but with the default configuration it was usable. The framework did not add it to Vary the way it did for the RSC header, so nothing prevented a cache from storing the error page. The researcher argues that this makes the framework responsible regardless of the caching system used by a development team.

Impact

All three findings are denial of service via cache poisoning, with a CVSS score of 7.5:

Text
CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H/CR:X/IR:X/AR:X

The prefetch finding renders the targeted page impractical and its content inaccessible. The RSC finding makes the main/root page return the React server component instead of the initial content. The x-invoke-status finding serves the error page instead of the main page. In each case the attacker needs a caching system in front of the application, and success depends on the CDN and its cache rules. The researcher reports several dozen bug bounty reports and more than 200 vulnerable assets found, possibly more.

Fix

For the RSC finding, a semblance of a fix was pushed on June 12, 2023, two months after the maintainer's response. The researcher notes this does not stop an attacker who sends the Rsc header without the parameter.

For the x-invoke-status finding, Vercel pushed a fix commit on June 18, 2024, after first validating the bug on June 13, 2024. The researcher's point is that the commit itself shows the framework took the client-supplied internal header into account, and that the framework did not add it to Vary as it did for the RSC header.

Timelines from the report:

Finding Reported First response Validated Fix Final
RSC March 23, 2024 April 3, 2024 additional info requested April 17, 2024 n/a April 29, 2024
x-invoke-status May 22, 2024 June 5, 2024 June 13, 2024 June 18, 2024 June 21, 2024

For the RSC finding, Vercel concluded there was nothing more they could do at the framework level. For the x-invoke-status finding, Vercel initially acknowledged it as a valid bug related to experimental minimal mode, then changed its mind on June 18, 2024, saying the vulnerability was the result of CDN caching rather than a vulnerability in Next.js and that exploitability depends on WAF/CDN configuration.

Variants to test

  1. Prefetch header on SSR pages. Send x-middleware-prefetch: 1 to a page rendered with getServerSideProps behind a CDN. A positive result is an empty {} body that the cache then serves to later visitors.
  2. RSC header without cache-buster. Send Rsc: 1 to the root page without _rsc. A positive result is the main/root page returning the RSC payload instead of the initial content.
  3. Internal header status override. Send x-invoke-status: 200 (or another code) to a Next.js app on the Node.js runtime with default configuration. A positive result is the /_error page returned with the chosen status code.
  4. Custom error message. Add x-invoke-error with a JSON body such as {"message":"<>"} alongside x-invoke-status. If the error page template expects it, the custom message can be displayed.
  5. CDN Vary handling. For each CDN in front of a target, check whether Vary is honoured, stripped or ignored.
  6. Cache duration bypass. If a report is dismissed because caching lasts only a short time, a small script sending a request every cache-duration interval keeps the cache permanently poisoned.

When arguing severity, the report suggests three responses to common claims: cache duration does not matter because the attacker can refresh it; zone-limited caching can be bypassed by sending requests from IPs in different zones via a VPN; and a CVSS score of 5.3 with Availability Low is wrong because the page is completely unavailable for an indefinite period, so Availability should be High, giving 7.5.

Published in June 2024.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 25 min read.

What happened, in plain words

Imagine a busy restaurant. To save time, the waiter keeps a few plates already made in a warming tray near the door, so the next customer gets served instantly instead of waiting for the kitchen. That warming tray is what the web calls a cache: a copy of a page kept somewhere between the website's server and you, so the next visitor gets the copy instead of a freshly cooked page.

Now imagine someone walks in and asks for a very strange dish, and the waiter, without thinking, puts that strange dish in the warming tray. Every customer after that gets the strange dish, even though they ordered the normal menu. That is cache poisoning: tricking the cache into storing a wrong response and serving it to everybody else.

This article is about three ways the researcher Rachid.A (known online as @zhero___) found to do exactly that against websites built with Next.js, a very popular tool for building websites. In each case the poisoned response was not a stolen password or leaked data. It was a broken page: an empty page, a page showing raw technical data, or an error page. The site becomes unusable for visitors. That kind of damage is called a denial of service (DoS): you are not reading anyone's secrets, you are stopping the site from working.

The three findings, in the order the article covers them:

  1. A special request header that makes a page return an empty {} instead of its content, which a cache can then store.
  2. A second kind of response (the data React uses to update a page in the browser) that caches were storing even though the framework asked them not to.
  3. An internal header called x-invoke-status that lets a visitor choose the HTTP status code and force the site to show its error page, which can then be cached as if it were a normal page.

All three need one thing to be dangerous: a cache in front of the site. Without a cache, the strange response is shown once to the person who asked for it and then forgotten. With a cache, it is shown to everyone.

A few words you will meet constantly, explained once here so the rest reads smoothly:

  • Server: the computer that holds the website and answers requests.
  • Browser: the program on your computer (Chrome, Firefox, Safari) that asks servers for pages and displays them.
  • HTTP: the language browsers and servers speak. A request is a message asking for something; a response is the answer.
  • Header: a small labelled line attached to a request or a response, carrying extra instructions. Think of it as a note stapled to a parcel: "fragile", "this side up". Headers like Rsc: 1 or x-invoke-status: 888 are such notes.
  • Status code: a three-digit number in the response saying how it went. 200 means "here is your page, all fine". 404 means "not found". 500 means "the server broke".
  • CDN (Content Delivery Network): a company that keeps copies of websites on servers all over the world so pages load fast wherever you are. Cloudflare, CloudFront and Akamai are CDNs. A CDN is, in practice, a giant cache.
  • Cache key: the label under which a cached copy is filed. If two requests produce the same cache key, the second one gets the stored copy. If they produce different keys, each gets its own.
  • Vary header: a note from the server saying "when you file this response in your cache, include these request headers in the cache key". It is the server's way of telling the cache which differences between visitors matter.
  • API: a way for one program to ask another for data or an action, without a human clicking anything. When your browser fetches a page in the background, it is using the site's API.
  • React: a toolkit for building web pages out of reusable pieces called components.
  • Next.js: a framework built on top of React, made by the company Vercel, that adds server-side rendering, routing and many conveniences. The next package is downloaded more than 6 million times per week, so a flaw in it can reach an enormous number of sites.
  • SSR (server-side rendering): building the page on the server and sending finished HTML, rather than letting the browser assemble it.
  • RSC (React Server Component): a newer Next.js feature where parts of the page are prepared on the server and sent to the browser as a compact data payload, which React then uses to update what you see.
  • Prefetch: the browser quietly asking for something ahead of time, before you click, so it is ready when you do.
  • CVE: a public catalogue number given to a known security flaw, so everyone can refer to the same bug by the same name.
  • CVSS: a scoring system from 0 to 10 for how serious a flaw is. Higher is worse.
  • Bug bounty: a programme where a company pays researchers for reporting flaws responsibly instead of exploiting them.
  • Poison / poisoned: a cache entry that holds a wrong response, planted by an attacker.

With those in hand, here is the story.

Why Next.js was the target

Next.js is an open-source JavaScript framework based on React, developed and maintained by Vercel. The next package is downloaded more than 6 million times per week, which means a discovery in it could potentially affect many users. That reach was the motivation for the research.

The article focuses on cache poisoning. If the concept is new to you, the researcher points readers to an earlier write-up of his titled "DOS via cache poisoning on Mozilla".

The three findings are:

  1. A prefetch header that makes SSR pages return an empty JSON object, which a CDN can cache.
  2. The RSC payload being cached because CDNs do not honour the Vary header the framework sets.
  3. An internal header, x-invoke-status, that lets a client overwrite the HTTP status code and invoke the error page, which can then be cached as a 200.

All three are denial-of-service style cache poisoning: the page becomes impractical or inaccessible rather than leaking data.

How the research was done

The work combined three activities: reading the Next.js source code, running local tests against a Next.js application, and then validating the findings on real bug bounty targets. The tools mentioned are a proxy for inspecting HTTP history (a proxy is a program that sits between your browser and the internet and records every request and response, so you can look back at what was sent) and console.log for debugging (a way to print values from inside a running program so you can see what it is doing).

The precondition common to all three findings is a caching system in front of the application. Without a cache, the behaviours are harmless because nothing is stored and replayed to other users.

First vulnerability: the prefetch header

While looking at Next.js middleware (code that runs on every request before the page is produced), the researcher noticed that when data is prefetched for SSR pages, adding the x-middleware-prefetch header makes the server respond with an empty JSON object {}. JSON is just a text format for data; {} means "an empty set of data, nothing inside".

If a CDN or caching system is present, that empty response can be cached, depending on the cache rules configuration, which renders the targeted page impractical and its content inaccessible.

From the original on zhero-web-sec.github.io

The only condition for reproducibility is the presence of a caching system. Without it the response is not cached and the header is harmless.

The getServerSideProps and getStaticProps functions are used to retrieve server-side data and generate static pages respectively. Since version 13.4.20-canary.13, Next.js has added cache-control to SSR responses to prevent them from being cached. cache-control is a response header that tells caches how long they may keep a copy; setting it to forbid caching is the standard defence.

From the original on zhero-web-sec.github.io

By the time the researcher was ready to exploit this, the issue already had CVE-2023-46298 assigned. Because no proof of concept had been shared, the behaviour could still be exploited at scale: several dozen bug bounty programs were affected and produced numerous bounties.

From the original on zhero-web-sec.github.io

The image is a non-exhaustive list of the affected programmes.

Impact and severity

This is a type of DoS via cache poisoning with a CVSS score of 7.5:

Text
CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N /I:N/A:H/CR:X/IR:X/AR:X

That string is a CVSS vector: a compact record of how the score was reached. Read it as a series of answers to questions. AV:N means the attack can be launched over the network, from anywhere. AC:L means it is easy to carry out. PR:N means the attacker needs no account or privileges. UI:N means no victim has to click anything. S:U means the damage stays within the affected component. C:N and I:N mean no confidentiality or integrity loss: nothing is read or altered. A:H means availability is High, that is, the service can be fully denied. The CR, IR, AR entries are environmental modifiers left at X (not defined). The overall result is 7.5, which CVSS calls high.

Second vulnerability: RSC payload and CDNs

The RSC Payload is a compact binary representation of the rendered React Server Components tree, used by React on the client to update the browser's DOM (the live structure of the page you see). It contains the rendered result of Server Components, placeholders for where Client Components should be rendered with references to their JavaScript files, and any props passed from a Server Component to a Client Component. In everyday terms: it is the data version of the page, which the browser uses to refresh parts of what you see without reloading everything.

Requests that fetch the RSC payload carry the header Rsc: 1. That header was added to the cache key via the Vary response header, which theoretically prevents cache poisoning: if the cache files the response under "RSC request", a normal visitor asking for the HTML page gets a different entry.

From the original on zhero-web-sec.github.io

Inspecting the proxy history showed that requests fetching the RSC payload also included a URL parameter that was systematically added: _rsc=randomValue. A URL parameter is the part after the ? in an address, like example.com/page?name=value. The researcher understood this to be a cache-buster: a deliberately random value that makes each request look unique to the cache, so the response is never stored and never replayed. That was surprising, given that the header was supposedly part of the cache key via Vary.

A GitHub ticket from a few months earlier had a user complaining that the RSC payload was being cached and blocking access to content. Tim Neutkens, one of the framework maintainers, responded on Apr 20, 2023 that App Router adds headers to the fetch when navigating client-side to get the RSC payload instead of HTML, that Next.js on the server sets the Vary header so browsers and CDNs can cache based on the headers passed to the fetch, and closed the issue as a CDN configuration problem.

So the framework was effectively cache-poisoning itself, and the URL parameter was added to prevent that. Looking at the commit history (the log of changes made to the code), a semblance of a fix was pushed on June 12, 2023, two months after the maintainer's response on the ticket.

From the original on zhero-web-sec.github.io

The question then was why CDNs still cache the response without taking the Rsc header into account during content negotiation, given that it is in Vary. Content negotiation is the back-and-forth where the browser and server agree on which version of a resource to send (HTML, JSON, an image). The Vary response header describes the parts of the request message, aside from method and URL, that influenced the content of the response, and is most often used to create a cache key when content negotiation is in use. The maintainers' position is that the framework systematically adds the header to Vary, so non-compliance with the HTTP standard is the responsibility of CDNs.

After digging into CDN documentation, non-compliance turned out to be true under certain conditions:

  • Cloudflare does not consider Vary values in caching decisions, except when Vary for images is configured and when the header is vary: accept-encoding.
  • CloudFront removes or replaces some headers, including Vary: if the origin includes other values in the Vary header, CloudFront removes those values before returning the response to the viewer.
  • Akamai has a behaviour called Remove Vary Header that removes the Vary header. Akamai edge servers do not cache responses that include the Vary header, even if the content is cacheable by definition, but there are exceptions. The default behaviour of the Adaptive Media Delivery, Download Delivery and Object Delivery products is to remove the Vary response header.
From the original on zhero-web-sec.github.io

In plain terms: the framework says "file this under a different key for RSC requests", and several big CDNs either ignore that instruction or strip it out. The safety net the framework relied on is not there.

So, is this exploitable?

From the original on zhero-web-sec.github.io

The semblance of a fix for the self-poisoning issue was to add a URL parameter during fetch operations to act as a cache-buster. That does not stop an attacker, who can send a request with the Rsc header without a cache-buster, mimicking a typical cache-poisoning attack. Whether this succeeds depends on the CDN and its cache rules. In theory it was exploitable, and after some research the first real target was found.

From the original on zhero-web-sec.github.io

The cache was poisoned and the main/root page returned the React server component instead of the initial content, resulting in a bounty of $2000. From there, pattern extraction, template creation and mass scanning of the researcher's bug bounty asset database produced more reports.

From the original on zhero-web-sec.github.io

The image is a non-exhaustive list.

Impact and severity

Text
CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N /I:N/A:H/CR:X/IR:X/AR:X

The same vector as before: network attack, easy, no privileges, no user interaction, no data read or changed, availability fully lost.

Escalation of the vulnerability to the security team

The researcher contacted the Next.js team and discussed the issue with them. They concluded that there was nothing more they could do at the framework level. While he understands it is not entirely their fault or responsibility, he believes leaving it unresolved without informing users so they can implement temporary solutions to mitigate the risk is a concern.

Timeline:

  • Vulnerability reported on March 23, 2024
  • Vercel first response on April 3, 2024
  • Vercel asks for additional information on April 17, 2024
  • Vercel final response April 29, 2024

Third vulnerability: internal header, status code and error page

After a short break, the researcher went back in. He had the Next.js source code displayed on each of his screens, a cup of coffee in hand, and his trusty companion for debugging, good old console.log. He was ready for some intensive code review.

A little further into his review, he stumbled upon a piece of code that immediately piqued his curiosity:

From the original on zhero-web-sec.github.io

Under certain conditions, which we will see later, it is possible to overwrite the status code via the value of the x-invoke-status header directly provided in the request (req.header[]) and invoke/return the error page. req.headers is simply the collection of headers the visitor sent; reading a value from it means the server is trusting something the visitor controls.

x-invoke-status is an internal header, so it is normally stripped when it comes from the client. "Internal" here means it is meant for communication between parts of the framework itself, not for visitors. Stripping means removing it from the incoming request before the application sees it, like a receptionist throwing away a note that was not meant for the staff.

From the original on zhero-web-sec.github.io

Step 1: test the internal header locally

A local test was needed to verify whether x-invoke-status is stripped or honoured. With the default configuration, the header was included as:

HTTP
x-invoke-status: 888

This is a single request header. The name is x-invoke-status, the value is 888. On the first try the header was accepted.

From the original on zhero-web-sec.github.io

At that point the vector was clearly exploitable for cache poisoning. By specifying the HTTP status code 200, the response complies with most caching rules, which typically do not allow caching of error codes. The error page content can then be cached and served instead of the main page.

The other two vulnerabilities are interesting for the same reason: the behaviours induced by their headers result in a 200 response, which aligns with the majority of cache rules. A cache is like a cautious chef who refuses to keep a dish that came back as a complaint, but happily keeps one that went out as a normal order. Sending 200 makes the error page look like a normal order.

Step 2: understand the code path

Under certain conditions, the value of x-invoke-status overwrites the statusCode property of the response object, and then the /_error page is returned whatever the HTTP code specified:

JavaScript
res.statusCode = Number(req.headers['x-invoke-status'])

(...)

return this.renderError(err, req, res, '/_error', parsedUrl.query)

Line by line:

  • res.statusCode = Number(req.headers['x-invoke-status']) takes the value of the x-invoke-status header from the incoming request, converts it to a number, and writes it into the status code of the outgoing response. Whatever number the visitor put in the header becomes the number the server sends back.
  • (...) stands for code the article leaves out, not relevant to the point.
  • return this.renderError(err, req, res, '/_error', parsedUrl.query) renders the error page, /_error, and returns it as the response. So the body is the error page while the status code is whatever the visitor chose.

It is therefore possible to specify any HTTP code to alter the response code and return the error page (/_error). CDNs and caching systems are generally configured not to cache HTTP error codes, but an attacker can specify 200 to align with cache rules and force caching of the error page.

Three conditions are necessary for this behaviour:

JavaScript
const useInvokePath =
         !useMatchedPathHeader &&
         process.env.NEXT_RUNTIME !== 'edge' &&
         invokePath

This defines a true/false value, useInvokePath, which is true only when all three parts joined by && ("and") are true. !useMatchedPathHeader means "the next value must be false". process.env.NEXT_RUNTIME !== 'edge' means "the runtime in use must not be the edge runtime". invokePath must be true.

  1. useMatchedPathHeader must return false, which is the case if:
JavaScript
const useMatchedPathHeader =
         this.minimalMode && typeof req.headers['x-matched-path'] === 'string'

This is true only when minimal mode is on and the request carries an x-matched-path header as text. If either is missing, it is false, which is what the first condition wants. Minimal mode is an experimental config tested in fully featured Next.js environments like Vercel that have an edge network to handle specific parts of requests that next-server would normally handle.

  1. The Next.js runtime used must not be edge. The default runtime is Node.js. A runtime is the environment the code executes in; edge is a lightweight one, Node.js is the standard one.

  2. invokePath should return true:

JavaScript
const invokePath = req.headers['x-invoke-path'] as string

This reads the x-invoke-path header. Local tests showed that x-invoke-path is not considered when provided in the request and its value does not appear to be retrieved. The header's value is automatically added and corresponds to the current path, so the constant always returns true.

If the x-invoke-error header is provided and the error page template expects it, a custom error message can be displayed. The value must be JSON:

JSON
{"message":"<>"}

This is a small JSON object with one field, message, whose value is the text <>. Whatever you put there is what the error page will try to show.

JavaScript
if (typeof req.headers['x-invoke-error'] === 'string') {
        const invokeError = JSON.parse(
            req.headers['x-invoke-error'] || '{}'
        )
        err = new Error(invokeError.message)
    }

Line by line:

  • if (typeof req.headers['x-invoke-error'] === 'string') { checks whether the request carries an x-invoke-error header as text. If not, the block is skipped.
  • const invokeError = JSON.parse( starts turning that text into a usable data object.
  • req.headers['x-invoke-error'] || '{}' uses the header value, or an empty object if it is missing.
  • ) closes the parsing call.
  • err = new Error(invokeError.message) creates an error whose message is the message field from the JSON. That message is what the error page will display.
  • } closes the block.
From the original on zhero-web-sec.github.io

Step 3: validate on real targets

With the vulnerability confirmed locally, the researcher moved to real bug bounty programs. The first successful exploit came quickly, followed by many others, one of which resulted in a bounty of $3000.

From the original on zhero-web-sec.github.io

Impact and severity

Text
CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N /I:N/A:H/CR:X/IR:X/AR:X

Same reasoning as before: remote, easy, no privileges, no interaction, no data read or changed, availability fully lost.

Escalation of the vulnerability to the security team

Upon reporting the vulnerability to the Next.js security team, they initially acknowledged it as a valid bug related to the experimental minimal mode functionality. They mentioned they had potential fix options.

During that period, due to a busy schedule, the researcher did not delve deeper to verify whether the issue indeed originated from minimal mode, trusting that they were addressing it on their end. However, he found it weird compared to the earlier condition number 1 he had observed.

Then came the response. Without going into certain confidential details, the summary is that they think this vulnerability is ultimately the result of CDN caching rather than a vulnerability present in Next.js, and that the conditions for exploitability are limited, based on factors beyond Next.js (WAF/CDN configuration). A WAF is a web application firewall, a filter that inspects incoming requests and blocks suspicious ones.

What was his surprise to see that their response was preceded a few hours earlier by a beautiful commit implementing a fix for his discovery:

From the original on zhero-web-sec.github.io

Why does this not make sense? Whether or not the source of the problem came from minimalMode does not change the fact that the value provided by the client via the internal x-invoke-status header was taken into account and had an impact on the response by overwriting the HTTP code and invoking the error page, and that is why they implemented a fix.

The use of the internal header x-invoke-status is possible with the minimum configuration (default) to override the status code and invoke the error page. Regarding caching, from the moment the header could be used, normally internal as specified in the code, without the framework adding it to Vary (as was the case for the RSC header) to avoid potential cache poisoning, their responsibility is directly incurred, regardless of the caching system used or not by a development team.

As explained earlier, being able to invoke the error page by specifying a status 200 will satisfy most cache rules, most of which do not allow the caching of responses with an error status code, and will allow the caching of this error page if a caching system is implemented.

  1. The possible use of an internal header having an influence on the response.
  2. The fact that no system is put in place to avoid the use of the header and/or the caching of a response resulting from its use.

The two points above directly involve the framework, and it is necessary for users to be aware of this vulnerability and to be able to protect themselves against it. That is why the researcher thinks a CVE is more than essential, as was the case for x-middleware-prefetch, which, although different, implies the responsibility of the framework in the same way (also requiring a cache system for its exploitability).

Timeline:

  • Vulnerability reported on May 22, 2024
  • Vercel first response on June 5, 2024
  • Vercel validate the bug on June 13, 2024
  • CVE proposal from the researcher on June 13, 2024
  • Vercel pushes a fix commit on June 18, 2024
  • Vercel changes its mind regarding their responsibility on June 18, 2024
  • Vercel final response and case considered resolved on June 21, 2024

Conclusion

The Vercel security team considered the problem resolved and did not consider it the result of a direct vulnerability in Next.js, despite the commit made, so the researcher is sharing the vulnerability to inform the community. Based on his limited experience, every time he has reported vulnerabilities or zero-days to companies, he has always, without exception, received fairly disappointing responses. He would not want to make his case a generality, but that could discourage more than one researcher from taking the time to report vulnerabilities responsibly, which is rather regrettable. He can understand that some companies see a CVE as a badge of shame, but when software is widely used it is their responsibility to assume and demonstrate exemplary transparency.

For his part, he was able to send several dozen reports (bug bounty programmes only) related to the vulnerabilities cited in the article and found more than 200 vulnerable assets, maybe a lot more, he is not sure.

He credits his friend Jayesh Madnani, with whom he was able to systematically scan his discoveries on Jayesh's gigantic database, his own being less than half its size. It is always a pleasure to work with him, benefiting from his automation expertise to target as many sites as possible.

Bonus: answers to common objections

The researcher is experienced at this exercise. He has often changed the severity of his cache-poisoning reports from Medium to High, or even from Informative to Triaged, sometimes going from $0 to $3000 with a few arguments. His advice: take into account that the concept of cache poisoning is not always well understood, be as clear and explicit as possible, and assume your interlocutor knows nothing about the subject.

Claim number 1: "The impact is not significant, caching only lasts XXXX seconds."

Response: The duration of the cache does not matter. An attacker only has to make a small script to send a request each X seconds (equal to the caching duration) so that the cache is permanently poisoned, making the site completely unavailable. Feel free to attach the script to the proof of concept.

Claim number 2: "The impact is not significant, cache poisoning is only effective on a predefined area, the response is normal when I access the link containing your cache-buster."

Response: Cache and CDN systems are often configured to operate by zone for performance reasons. Despite this, an attacker in a real situation only has to send the request from IPs coming from different zones (via a VPN) in order to impact all users. A VPN is a service that routes your traffic through a server in another location, so your requests appear to come from there.

Claim number 3: "We calculated using CVSS and the rating is 5.3 CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L."

Response: The CVSS score was not correctly set. The vulnerability allows the page to be completely unavailable or impractical for an indefinite period of time, so the Availability parameter is set to High, which gives a score of 7.5 (high):

Text
CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H/CR:X/IR:X/AR:X

The difference is the A entry: A:L (Low) in their score versus A:H (High) in his. The CVSS definition of High availability loss reads:

High (H): There is total loss of availability, resulting in the attacker being able to fully deny access to resources in the impacted component; this loss is either sustained (while the attacker continues to deliver the attack) or persistent (the condition persists even after the attack has completed). Alternatively, the attacker has the ability to deny some availability, but the loss of availability presents a direct, serious consequence to the impacted component.

Published in June 2024.

Glossary

  • Browser: the program on your computer that asks servers for pages and displays them.
  • Cache: a stored copy of a response, kept so the next visitor gets it faster.
  • Cache-buster: a deliberately random value added to a request so the cache treats it as new and does not store or replay a copy.
  • Cache key: the label under which a cached copy is filed; requests with the same key get the same stored copy.
  • Cache poisoning: tricking a cache into storing a wrong response and serving it to other visitors.
  • cache-control: a response header telling caches how long they may keep a copy, or whether they may keep one at all.
  • CDN (Content Delivery Network): a company that keeps copies of websites on servers worldwide so pages load fast; in practice a large cache.
  • Cloudflare, CloudFront, Akamai: three CDN providers whose handling of the Vary header is discussed in the article.
  • Commit: a recorded change to a code repository, with a timestamp and message.
  • Content negotiation: the back-and-forth where browser and server agree which version of a resource to send.
  • console.log: a way to print values from inside a running program so you can see what it is doing.
  • CVE: a public catalogue number given to a known security flaw.
  • CVSS: a scoring system from 0 to 10 for how serious a flaw is; higher is worse.
  • CVSS vector: the compact string recording how a CVSS score was reached, such as CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H/CR:X/IR:X/AR:X.
  • Denial of service (DoS): making a service unusable for its normal users, without necessarily reading or changing data.
  • DOM: the live structure of the page you see in the browser.
  • Edge runtime: a lightweight JavaScript environment used for running code close to users; the alternative to the default Node.js runtime.
  • getServerSideProps / getStaticProps: Next.js functions that retrieve server-side data and generate static pages respectively.
  • Header: a small labelled line attached to a request or response carrying extra instructions.
  • HTTP: the language browsers and servers speak; a request asks for something, a response answers.
  • Internal header: a header meant for communication between parts of the framework itself, normally stripped when it arrives from a visitor.
  • JSON: a text format for data; {} is an empty object, {"message":"<>"} an object with one field.
  • Middleware: code that runs on every request before the page is produced.
  • Minimal mode: an experimental Next.js configuration tested in fully featured environments like Vercel that have an edge network.
  • Next.js: an open-source JavaScript framework built on React, made by Vercel.
  • Node.js: the standard JavaScript runtime; the default for Next.js.
  • Prefetch: the browser quietly asking for something ahead of time so it is ready when you click.
  • Proof of concept (POC): a working demonstration that a flaw can be exploited.
  • Props: data passed from one component to another in React.
  • Proxy: a program that sits between your browser and the internet and records every request and response.
  • RSC (React Server Component): a Next.js feature where parts of the page are prepared on the server and sent to the browser as a compact data payload.
  • RSC payload: the compact binary representation of the rendered React Server Components tree, used by React on the client to update the DOM.
  • Runtime: the environment code executes in, such as Node.js or edge.
  • SSR (server-side rendering): building the page on the server and sending finished HTML.
  • Status code: a three-digit number in a response saying how it went, such as 200 (fine) or 500 (server broke).
  • Stripping: removing a header from an incoming request before the application sees it.
  • URL parameter: the part of an address after the ?, such as _rsc=randomValue.
  • Vary header: a response header telling caches which request headers to include in the cache key.
  • VPN: a service that routes your traffic through a server in another location, so requests appear to come from there.
  • WAF (web application firewall): a filter that inspects incoming requests and blocks suspicious ones.
  • Zero-day: a flaw that is not yet publicly known or fixed when it is found.

More by Rachid.A

View all

1 more disclosed report, best first.

More from Vercel (NextJS)

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Web cache poisoning and deception

The lesson behind this report.

A cache and the origin disagree about a request, so a poisoned response is served to everyone or a private page is stored as public.