Client-side request forgery

How to restrict browser requests to the intended origin and API route.

Description

When browser code takes the destination of a fetch, XMLHttpRequest, or Axios request from a URL parameter or form field, an outside party can influence where it goes. The browser might send the request to another origin or call an unintended API on the page's own origin.

Potential impact

  • A signed-in user's browser can send a request that reads or changes data with that user's permissions.
  • Requests may reach local or internal services accessible from the browser. A server can process a request even if the browser blocks access to the response.
  • Inserting an untrusted response with innerHTML can change the page or cause cross-site scripting (XSS).

Remediation

  • Choose the API and HTTP method in application code. Accept only the values the user needs to supply, such as a profile ID, and validate the complete pathname against the API's route format.
  • With fetch, set mode: "same-origin" to limit requests to the page's origin. The credentials option controls whether the browser sends credentials such as cookies. Set redirect: "error" to make fetch fail if the server returns a redirect.
  • Check the user's permission to access the requested resource on the server. Apply CSRF protection to state-changing operations that use cookie authentication. Some cross-origin requests can reach the server even when CORS prevents the browser from reading the response.
  • To display a response as plain text, set textContent on a text container such as a <div>. If you need to display HTML, use a maintained sanitizer configured for the elements and attributes allowed at that insertion point.

Examples

Before

javascript
async function showProfile() {
  const qs = new URLSearchParams(location.search);
  const next = qs.get("next");
  const userId = qs.get("id");

  await fetch(next);
  const response = await fetch("/api/user/" + userId);
  const data = await response.json();
  document.getElementById("content").innerHTML = data.html;
}

After

This example assumes a read-only profile API at /api/user/{id} on the page's origin. IDs are strings of 1 to 12 ASCII digits, including any leading zeros. The API returns a JSON object with a string name field, and the page has a <div id="content"> for displaying the name. If the API currently returns only html, add name to the response before updating the client.

javascript
async function showProfileSafe() {
  const id = new URLSearchParams(location.search).get("id");
  if (id === null) throw new Error("Missing profile ID");

  const candidate = "/api/user/" + id;
  const match = /^\/api\/user\/[0-9]{1,12}$/.exec(candidate);
  if (!match) throw new Error("Invalid profile ID");

  const response = await fetch(match[0], { mode: "same-origin", redirect: "error" });
  if (!response.ok) throw new Error("Could not load profile");

  const profile = await response.json();
  if (typeof profile?.name !== "string") throw new Error("Invalid profile");
  document.getElementById("content").textContent = profile.name;
}

Explanation:

  • Before: The next parameter sets the entire destination of the first request, and id can change the path of the second. The browser interprets the second response's html field as markup.
  • After: The regular expression matches the complete pathname against the fixed prefix and 1 to 12 digits. The browser sends the request to the matched path. Keeping the ID as a string preserves its leading zeros. The page displays the name from a successful response as text.

References