HIGH cross site request forgerycloudflare

Cross Site Request Forgery on Cloudflare

How Cross Site Request Forgery Manifests in Cloudflare

Cross Site Request Forgery (CSRF) in Cloudflare contexts typically arises when a Cloudflare-managed origin or a worker script relies solely on same-site cookies or IP-based trust without anti-CSRF tokens. Attackers can forge requests from authenticated victims to Cloudflare-facing endpoints that perform state changes, such as updating zone settings or invoking worker subrequests.

Specific attack patterns include using an <img src="https://example.com/cdn-worker?action=disable_waf&zone_id=..."> from a malicious site to trigger unvalidated actions in a Cloudflare worker that lacks per-request verification. Another pattern targets Cloudflare API interactions where session tokens or API keys are stored in cookies without SameSite and Secure attributes, enabling malicious sites to execute privileged configuration changes via crafted forms or scripts.

In Cloudflare Workers, CSRF can surface in request handling code that processes sensitive actions (e.g., zone purge, KV namespace updates) without validating the origin header or including a unique token. For example, a worker that exposes POST /admin/disable-ratelimit and only checks for a cookie named cf_session is vulnerable if the browser automatically includes that cookie in cross-origin requests.

Because Cloudflare sits at the edge, developers may assume its infrastructure inherently prevents CSRF, but without explicit anti-CSRF measures in the application logic (workers, origin configurations), forged requests can be relayed through Cloudflare to backend services.

Cloudflare-Specific Detection

Detecting CSRF in Cloudflare setups involves validating that state-changing endpoints require more than cookies and that anti-CSRF tokens or origin checks are present and enforced. When scanning with middleBrick, the scanner performs unauthenticated checks that include injecting forged origin headers and observing whether requests are accepted without a valid anti-CSRF mechanism.

During a scan, middleBrick tests endpoints behind Cloudflare by sending requests with cross-origin headers and cookie-only authentication. It checks whether responses indicate successful state changes without requiring a per-request token or verifying the Origin/Referer header. The tool also analyzes OpenAPI specs (if available) to see whether security schemes account for CSRF protections and correlates runtime behavior with spec expectations.

To validate manually, you can use a simple HTML form served from a different origin that submits to your Cloudflare worker or endpoint:

<!DOCTYPE html>
<html>
<body>
  <form action="https://your-worker.example.com/action" method="POST">
    <input type="hidden" name="zone_id" value="dangerous_zone" />
    <input type="submit" value="Click me" />
  </form>
</body>
</html>

If the request succeeds without a CSRF token, the endpoint is vulnerable. middleBrick reports this as a high-severity finding with remediation guidance tailored to Cloudflare Workers and edge configurations.

Cloudflare-Specific Remediation

Remediation in Cloudflare environments centers on ensuring that any state-changing logic requires a synchronizer token or origin verification that cannot be trivially forged by attacker sites. When using Cloudflare Workers, include a per-request anti-CSRF token in cookies with SameSite=Strict or Lax and validate it explicitly in your handler.

Example Worker code that implements a secure pattern:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event));
});

async function handleRequest(event) {
  const request = event.request;
  const url = new URL(request.url);

  // Only allow same-site top-level navigations or same-origin API calls
  const origin = request.headers.get('Origin');
  const referer = request.headers.get('Referer');
  if (origin && !origin.startsWith('https://trusted-origin.com')) {
    return new Response('Forbidden', { status: 403 });
  }

  // For state-changing methods, require a custom header with a CSRF token
  if (request.method === 'POST' || request.method === 'PUT' || request.method === 'DELETE') {
    const token = request.headers.get('x-csrf-token');
    const cookieToken = getCookie(request, 'csrf_token');
    if (!token || token !== cookieToken) {
      return new Response('Invalid CSRF token', { status: 403 });
    }
  }

  // Proceed with the action, e.g., zone update
  if (url.pathname === '/action') {
    const params = url.searchParams;
    // Validate and perform action
    return new Response('Action processed securely');
  }

  return new Response('OK');
}

function getCookie(request, name) {
  const header = request.headers.get('Cookie') || '';
  const parts = header.split(';').map(s => s.trim());
  for (const part of parts) {
    if (part.startsWith(name + '=')) {
      return part.substring(name.length + 1);
    }
  }
  return null;
}

On the origin side, if you serve pages behind Cloudflare, ensure cookies used for session management include SameSite=Lax or Strict, and use the Secure attribute. For additional assurance, implement double-submit cookie patterns where a CSRF token is set in a cookie and also sent in a custom header, then validated server-side or in the worker.

middleBrick can be used continuously to verify that these protections remain in place. By adding the GitHub Action, you can fail builds if a regression introduces a CSRF risk, and the MCP Server allows you to scan APIs directly from your AI coding assistant during development.

Frequently Asked Questions

Does Cloudflare's edge network automatically protect my API from CSRF?
No. Cloudflare does not automatically enforce anti-CSRF protections for your application logic. Without explicit checks such as anti-CSRF tokens or origin validation in your workers or origin code, state-changing requests can be forged.
Can middleBrick detect CSRF issues in Cloudflare Workers and edge APIs?
Yes. middleBrick runs unauthenticated checks that include cross-origin requests and missing CSRF token validation. It analyzes runtime behavior and, when available, cross-references OpenAPI specs to identify CSRF-related findings and provides remediation guidance.