Claude skill CSRF protection security
MCP skills that expose HTTP endpoints for OAuth flows, webhook callbacks, or configuration APIs are subject to Cross-Site Request Forgery attacks when session cookies authenticate requests. CSRF exploits the browser’s automatic cookie attachment to issue state-changing requests from an attacker-controlled page while the victim is authenticated. SA-SKL-CSRF covers four CSRF patterns that appear specifically in MCP skill codebases: missing CSRF tokens on POST endpoints, GET-based state changes that SameSite=Lax does not protect, null-origin exploitation via data URI iframes, and custom header CSRF protection negated by CORS wildcard header allowlists.
CSRF is often dismissed as a legacy web vulnerability that cookie SameSite attributes have solved. This is partly true for simple cases: SameSite=Strict prevents the cookie from being sent on any cross-site request, and SameSite=Lax prevents it on most. But MCP skills frequently fall into the gaps. Skills that implement OAuth callbacks must accept cross-site GET requests by design — OAuth redirects are cross-site top-level navigation, which SameSite=Lax explicitly permits. Skills that use custom headers for CSRF protection unknowingly depend on CORS to enforce that protection, and a wildcard allowedHeaders option silently removes it. The four SA-SKL-CSRF patterns address the CSRF attack surface that survives modern browser cookie defaults.
SA-SKL-CSRF-001: Missing CSRF token on state-changing POST endpoint — attacker form submits using victim session cookie
The foundational CSRF pattern is a state-changing POST endpoint that relies solely on a session cookie for authentication, with no additional per-request token that proves the request originated from the skill’s own UI. Any page on the internet can submit a form or fetch with credentials: include targeting the endpoint, and the browser automatically appends the victim’s session cookie. With no CSRF token to validate, the endpoint cannot distinguish a legitimate request from the skill’s UI from a forged request from an attacker page:
// VULNERABLE: state-changing POST endpoint authenticated by session cookie only,
// no CSRF token required
import express from 'express';
import session from 'express-session';
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(session({ secret: process.env.SESSION_SECRET!, cookie: { httpOnly: true } }));
// DELETE audit endpoint — authenticated by session cookie only
app.post('/api/delete-audit', async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'unauthenticated' });
const { auditId } = req.body;
await db.deleteAudit(auditId, req.session.userId);
res.json({ deleted: true });
});
// ATTACK: attacker page submits a form cross-site
// Victim is logged into skillaudit.dev (session cookie set, httpOnly: true)
// Victim visits https://attacker.com/csrf-poc.html:
//
// <!DOCTYPE html>
// <body onload="document.forms[0].submit()">
// <form action="https://skillaudit.dev/api/delete-audit" method="POST">
// <input type="hidden" name="auditId" value="audit-id-to-delete">
// </form>
// </body>
//
// Browser submits form to skillaudit.dev, automatically attaches session cookie.
// Server receives: valid session userId + attacker-chosen auditId.
// Audit deleted. Victim cannot see the deletion happening.
// SECURE: synchronizer token pattern — CSRF token stored in session, sent in form/header
import crypto from 'crypto';
function generateCsrfToken(session: Express.Session): string {
if (!session.csrfToken) {
session.csrfToken = crypto.randomBytes(32).toString('hex');
}
return session.csrfToken;
}
function verifyCsrfToken(session: Express.Session, token: string | undefined): boolean {
if (!token || !session.csrfToken) return false;
// Timing-safe comparison to prevent oracle attacks on the token value
const a = Buffer.from(session.csrfToken, 'hex');
const b = Buffer.from(token.length === session.csrfToken.length ? token : '', 'hex');
if (a.length !== b.length) return false;
return crypto.timingSafeEqual(a, b);
}
// CSRF validation middleware
function csrfProtect(req: express.Request, res: express.Response, next: express.NextFunction) {
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
const token = req.headers['x-csrf-token'] as string | undefined
?? req.body._csrf as string | undefined;
if (!verifyCsrfToken(req.session, token)) {
return res.status(403).json({ error: 'invalid CSRF token' });
}
next();
}
app.use(csrfProtect);
// Expose token for SPA/frontend to read and include in requests
app.get('/api/csrf-token', (req, res) => {
res.json({ csrfToken: generateCsrfToken(req.session) });
});
// DOUBLE-SUBMIT COOKIE ALTERNATIVE (stateless): set a non-httpOnly cookie;
// JS reads the cookie and sends it as a header; server checks both match.
// Cross-site attacker can neither read the cookie (SameSite) nor forge the header value.
// Requires that the cookie is NOT httpOnly so JS can read it.
httpOnly session cookies do not prevent CSRF — they only prevent XSS-based session theft: The httpOnly flag prevents JavaScript on the page from reading the cookie value, which blocks XSS-based session hijacking. It does nothing to prevent the browser from automatically attaching the cookie to a cross-site request. CSRF and XSS are orthogonal threats: httpOnly defends against one, CSRF tokens defend against the other. A session cookie can be both httpOnly (XSS-safe) and vulnerable to CSRF simultaneously.
crypto.timingSafeEqual) or double-submit cookie pattern (non-httpOnly cookie read by JS, sent as header). Detection: POST route with req.session.userId check but no x-csrf-token or _csrf validation → HIGH.SA-SKL-CSRF-002: SameSite=Lax bypass via top-level navigation + GET-based state change
SameSite=Lax is the browser default for cookies that do not set an explicit SameSite attribute, and it is frequently cited as a CSRF mitigation. Under SameSite=Lax, cookies are sent on cross-site requests only when the method is GET AND the request is a top-level navigation (the kind triggered by clicking a link or following a redirect that changes the top-level frame URL). This means that GET endpoints that perform state changes are fully CSRF-vulnerable even with SameSite=Lax cookies, because a link click or HTTP redirect from an attacker page is precisely the cross-site top-level GET navigation that SameSite=Lax permits:
// VULNERABLE: GET endpoint that performs a state change
// SameSite=Lax does NOT protect against cross-site GET requests initiated
// by top-level navigation (link clicks, redirects)
app.use(session({
secret: process.env.SESSION_SECRET!,
cookie: {
httpOnly: true,
// No explicit SameSite — browser defaults to Lax
// SameSite=Lax does NOT block cross-site top-level navigation GET requests
}
}));
// VULNERABLE: state-changing GET endpoint
app.get('/api/grant-access', async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'unauthenticated' });
const { collaboratorId, auditId } = req.query;
// GRANTS ACCESS — this is a state change, not a safe read operation
await db.grantAccess(auditId as string, collaboratorId as string, req.session.userId);
res.redirect('/dashboard?message=access-granted');
});
// ALSO VULNERABLE: OAuth authorize endpoint that processes grants on GET
app.get('/oauth/authorize', async (req, res) => {
// If the user is already authenticated and 'approved' param is present,
// grant the OAuth authorization code without a form POST
if (req.session.userId && req.query.approved === 'true') {
const code = await issueAuthCode(req.query.client_id as string, req.session.userId);
res.redirect(`${req.query.redirect_uri}?code=${code}`);
// ^^^ An attacker link click sends victim session cookie (Lax allows it)
// and receives an OAuth code for the attacker's client_id
}
});
// ATTACK: attacker puts a link in an email or forum post:
// <a href="https://skillaudit.dev/api/grant-access?auditId=TARGET&collaboratorId=ATTACKER">
// Click here for a free audit
// </a>
//
// When victim clicks: browser makes GET to skillaudit.dev.
// SameSite=Lax: this IS a top-level navigation GET — cookie is SENT.
// Server receives: valid session + attacker-chosen query params.
// Attacker is granted access to victim's audit.
// SECURE: ALL state-changing operations MUST use POST, PUT, PATCH, or DELETE.
// GET endpoints MUST be safe (idempotent reads with no side effects).
app.post('/api/grant-access', csrfProtect, async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'unauthenticated' });
const { collaboratorId, auditId } = req.body; // body, not query params
await db.grantAccess(auditId, collaboratorId, req.session.userId);
res.json({ granted: true });
});
// For OAuth: grant authorization only via POST form submission with CSRF token
app.post('/oauth/authorize', csrfProtect, async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'unauthenticated' });
const { client_id, redirect_uri, approved } = req.body;
if (approved !== 'true') {
return res.redirect(`${redirect_uri}?error=access_denied`);
}
const code = await issueAuthCode(client_id, req.session.userId);
res.redirect(`${redirect_uri}?code=${code}`);
});
SameSite=Lax does not eliminate the need for CSRF protection on GET endpoints that perform state changes: SameSite=Lax was designed to protect POST-based CSRF attacks while preserving the common pattern of cross-site link navigation. It has never been intended as protection for GET endpoints that mutate state — those should not exist at all. The HTTP specification defines GET as a safe method that MUST NOT cause side effects. If your application uses GET to change data, SameSite=Lax provides no protection, and no cookie attribute can substitute for moving the operation to a non-safe HTTP method with CSRF token validation.
app.get() route that calls db.delete, db.insert, db.update, or issues OAuth codes → HIGH.SA-SKL-CSRF-003: Origin header check bypass via null origin from browser data URIs
Some MCP skills implement CSRF protection by checking the Origin request header against an allowlist of trusted origins. This approach is generally sound — the browser sets the Origin header on cross-origin requests, and the same-origin policy prevents attacker pages from forging it. However, one edge case breaks the assumption: browser data URI iframes and sandboxed iframes without an allow-same-origin attribute generate requests where the Origin header is the literal string "null". Origin-allowlist implementations that treat the absence of an Origin header (server-to-server requests, curl) as trusted by passing null through, often inadvertently also trust the "null" string:
// VULNERABLE: origin check that allows null origin
import express from 'express';
function checkOrigin(req: express.Request): boolean {
const origin = req.headers.origin;
// Intended: allow requests with no Origin header (server-to-server, curl)
// Bug: also allows the literal string "null" sent by data URI iframes
if (!origin) return true; // <-- passes for both undefined AND the string "null"
// Wait — req.headers.origin is "null" (the string) for data URI iframes,
// not undefined. The !origin check treats the non-empty string "null" as truthy
// and falls through to the allowlist check below:
const allowedOrigins = new Set(['https://skillaudit.dev', 'https://claude.ai']);
return allowedOrigins.has(origin);
}
// ALSO VULNERABLE: explicit null allowance
app.use((req, res, next) => {
const origin = req.headers.origin;
// Developer thinks "null origin = no browser, server-to-server, safe"
// Reality: null origin = data URI iframe, sandboxed iframe, Tor browser
if (!origin || origin === 'null' || allowedOrigins.has(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin || '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
}
next();
});
// ATTACK: attacker uses a data URI iframe to generate null origin requests
// The null origin bypasses origin allowlist checks and also bypasses SameSite=None
// cookie restrictions in some browser versions.
//
// Attacker page at https://attacker.com/exploit.html:
// <script>
// // Create a data URI iframe — its requests have Origin: null
// const iframe = document.createElement('iframe');
// iframe.src = 'data:text/html,<script>' +
// 'fetch("https://skillaudit.dev/api/delete-audit", {' +
// ' method: "POST",' +
// ' credentials: "include",' +
// ' headers: { "Content-Type": "application/x-www-form-urlencoded" },' +
// ' body: "auditId=TARGET_AUDIT_ID"' +
// '})</scr' + 'ipt>';
// document.body.appendChild(iframe);
// </script>
//
// The fetch from inside the data URI iframe has Origin: null
// If the server treats null as trusted, the CSRF succeeds.
// SECURE: explicitly reject null origin; treat it as untrusted cross-site origin
function checkOriginSecure(req: express.Request): boolean {
const origin = req.headers.origin;
if (!origin) return true; // No Origin header: server-to-server, safe
if (origin === 'null') return false; // Literal "null": data URI iframe — REJECT
return allowedOrigins.has(origin); // All other origins: check allowlist
}
// CORS middleware that correctly handles null origin:
app.use((req, res, next) => {
const origin = req.headers.origin;
if (origin && origin !== 'null' && allowedOrigins.has(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Vary', 'Origin');
}
// null origin: set no ACAO header; browser blocks the cross-origin read
if (req.method === 'OPTIONS') return res.sendStatus(204);
next();
});
The string "null" in the Origin header is not the same as an absent Origin header: Server-to-server requests (curl, fetch from Node.js) produce no Origin header at all — req.headers.origin is undefined. Data URI iframes and sandboxed iframes without allow-same-origin produce a request with Origin: null (the four-character string). The !origin JavaScript falsy check passes for both undefined and the empty string, but it fails for the non-empty string "null" — that string is truthy and falls through to your allowlist check. The safe pattern is: explicitly check origin === 'null' and reject it before the allowlist lookup.
origin === 'null' or uses a truthy-based check that inadvertently passes the null-origin string to the allowlist fallback: attacker uses a data URI iframe to issue credentialed cross-origin requests with Origin: null that bypass the allowlist; state-changing endpoints are reachable. Fix: explicitly check origin === 'null' and return false before the allowlist lookup; treat null origin as an untrusted cross-site browser request. Detection: origin === 'null' returning true in origin check, or if (!origin || allowedOrigins.has(origin)) without null-string rejection → MEDIUM.SA-SKL-CSRF-004: Custom header CSRF protection bypass via CORS allowedHeaders: '*'
A common stateless CSRF mitigation relies on a custom request header such as X-Requested-With: XMLHttpRequest: the server rejects requests that lack it, and since browsers do not automatically include custom headers on cross-site form submissions, the check prevents naive CSRF attacks. The critical dependency is that CORS prevents cross-origin pages from sending arbitrary custom headers. If CORS is misconfigured to permit all headers via allowedHeaders: '*', an attacker page can send the custom header cross-origin through the CORS preflight mechanism, completely removing the protection the custom header was intended to provide:
// VULNERABLE: custom header CSRF protection + wildcard allowedHeaders in CORS
import cors from 'cors';
// Step 1: CSRF protection via custom header
app.use((req, res, next) => {
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
const requested = req.headers['x-requested-with'];
if (requested !== 'XMLHttpRequest') {
return res.status(403).json({ error: 'CSRF check failed' });
}
next();
});
// Step 2: CORS allows all headers — this silently defeats the custom header protection
app.use(cors({
origin: allowedOrigins,
allowedHeaders: '*', // <-- allows X-Requested-With cross-origin via preflight
credentials: true,
}));
// ATTACK: attacker page sends the required custom header via CORS preflight
// fetch('https://skillaudit.dev/api/delete-audit', {
// method: 'POST',
// credentials: 'include',
// headers: {
// 'Content-Type': 'application/json',
// 'X-Requested-With': 'XMLHttpRequest', // <-- allowed by allowedHeaders: '*'
// },
// body: JSON.stringify({ auditId: 'TARGET' }),
// });
//
// CORS preflight (OPTIONS):
// Access-Control-Request-Headers: x-requested-with
// Server responds: Access-Control-Allow-Headers: * (or enumerates the header)
// Preflight passes.
// Actual request fires with X-Requested-With: XMLHttpRequest.
// Server custom-header check passes.
// CSRF succeeds.
//
// Without allowedHeaders: '*': browser refuses to send X-Requested-With cross-origin
// because it is not in the allowed headers list — preflight fails, request never fires.
// With allowedHeaders: '*': preflight succeeds, header is sent, CSRF protection is void.
// VULNERABLE VARIANT: same issue with any custom header used for CSRF
app.use((req, res, next) => {
if (!['POST', 'PUT', 'DELETE', 'PATCH'].includes(req.method)) return next();
if (!req.headers['x-skillaudit-csrf']) {
return res.status(403).json({ error: 'Missing CSRF header' });
}
next();
});
// If allowedHeaders: '*' is set, attacker can send X-SkillAudit-CSRF cross-origin too.
// SECURE OPTION 1: Use synchronizer token CSRF protection — does not depend on CORS
// Token value must be known by the legitimate client (embedded in HTML or fetched via API)
// An attacker page cannot read the CSRF token from skillaudit.dev due to same-origin policy
// (fetch with credentials to read the token fails unless CORS explicitly allows it —
// and even then, only origins in the allowlist can read it; attacker.com cannot)
app.use(csrfProtect); // from CSRF-001 — validates session-bound token
// SECURE OPTION 2: If using custom header approach, do NOT set allowedHeaders: '*'
// Enumerate only the headers your routes actually need:
app.use(cors({
origin: (origin, cb) => {
if (!origin || allowedOrigins.has(origin)) return cb(null, true);
cb(null, false);
},
credentials: true,
allowedHeaders: ['Content-Type', 'Authorization', 'X-Request-Id'],
// X-Requested-With is NOT in the allowlist:
// Browser will block cross-origin requests that try to send it.
// The custom header protection now has teeth.
}));
Custom header CSRF protection is a CORS-dependent mitigation — not a standalone control: The security guarantee of “require a custom header on state-changing requests” relies entirely on CORS preventing cross-origin pages from including that header. The moment allowedHeaders: '*' is set, CORS allows every header cross-origin, and the custom header is no longer a differentiator between same-origin legitimate requests and cross-origin attacker requests. This is a silent failure: the CSRF check still runs and still passes on attacker requests — it passes because the attacker now controls all the headers the check examines. Use synchronizer tokens instead, which depend on the attacker not being able to read the token value, a guarantee provided by the same-origin policy on response bodies rather than on request headers.
X-Requested-With, X-CSRF-Header, etc.) combined with allowedHeaders: '*' in CORS configuration: CORS preflight permits the custom header to be sent cross-origin; attacker page includes the required header in its forged request; CSRF check passes; state-changing endpoints are reachable from any origin in the CORS allowlist. Fix: use synchronizer token CSRF protection (independent of CORS) or enumerate allowedHeaders explicitly without including the CSRF-protection header. Detection: custom header CSRF check in middleware AND allowedHeaders: '*' in CORS configuration → HIGH.Remediation summary
| Finding | Severity | Vulnerable pattern | Fix | Detection signal |
|---|---|---|---|---|
| CSRF-001: Missing CSRF token on POST endpoint | HIGH | POST route with session authentication and no CSRF token check; attacker form auto-submits using victim cookie | Synchronizer token pattern: session-stored token verified via timingSafeEqual in header or body |
app.post() route with req.session.userId but no x-csrf-token or _csrf validation |
| CSRF-002: GET-based state change — SameSite=Lax bypass | HIGH | app.get() route that mutates data; SameSite=Lax explicitly permits cross-site top-level navigation GET requests |
All state changes MUST be POST; GET endpoints MUST be idempotent reads only | app.get() route calling db.delete, db.insert, db.update, or issuing OAuth codes |
| CSRF-003: Null origin bypass via data URI iframe | MEDIUM | Origin check passes null-origin string; data URI iframe generates Origin: null in browser |
Explicitly check origin === 'null' and reject before allowlist lookup; treat null origin as untrusted |
origin === 'null' returning true, or !origin || allowedOrigins.has(origin) without null-string guard |
| CSRF-004: Custom header protection nullified by wildcard CORS | HIGH | Custom header CSRF check paired with allowedHeaders: '*'; preflight permits header cross-origin |
Use synchronizer tokens; or if using custom header approach, enumerate allowedHeaders explicitly without the CSRF header |
Custom header CSRF middleware AND allowedHeaders: '*' in CORS configuration co-present |
SkillAudit detects all four SA-SKL-CSRF-001 through CSRF-004 patterns through static analysis of skill HTTP middleware configuration: POST routes authenticated by session without CSRF token validation, GET routes that call mutating database functions, origin checks that pass the null-origin string, and custom-header CSRF protection co-located with wildcard CORS allowedHeaders. For related security patterns see SA-SKL-CORS CORS configuration security, SA-SKL-SESS session and state security, and SA-SKL-AUT authentication security. See the complete SA-SKL attack surface reference for the full vulnerability taxonomy.
Scan your Claude skill for CSRF vulnerabilities
SkillAudit detects missing CSRF tokens, GET-based state changes, null origin bypasses, and custom header protection gaps across the full SA-SKL-CSRF family in 60 seconds.
Get your free audit