Claude skill CORS policy on WebSocket upgrade requests — SA-SKL-CORS7
WebSocket upgrades do not go through the standard CORS preflight mechanism — the browser sends the upgrade request directly with an Origin header, and it is the server's responsibility to validate that header before accepting the connection. MCP skill WebSocket servers that skip the Origin check allow any web page — including attacker-controlled pages — to open an authenticated WebSocket connection using the user's session cookie. SA-SKL-CORS7 covers four Origin-validation failures on WebSocket upgrades: missing check, wildcard acceptance, SameSite-Lax cookie forwarding, and CDN Origin header stripping.
Why WebSocket upgrades bypass the standard CORS preflight mechanism
Standard HTTP cross-origin requests are gated by the browser's CORS preflight: for non-simple requests, the browser sends OPTIONS before the real request and checks that the server allows the origin. WebSocket upgrades are not gated by this mechanism. The browser sends the HTTP Upgrade request directly — no preflight OPTIONS — with the Origin header set to the page's origin. The WebSocket specification requires that browsers always set the Origin header on upgrade requests, regardless of whether the request is same-origin or cross-origin. Because the upgrade is not blocked by the browser pre-flight, the server must perform origin validation itself in the upgrade handler before accepting the connection. If the server does not check Origin, any page can open a WebSocket to the skill's server.
The practical consequence: if a user is logged into the skill's web app (with a session cookie), and the user visits an attacker's page, that page can call new WebSocket('wss://app.skillaudit.dev/ws'). The browser sends the upgrade request with the user's session cookie (subject to SameSite policy — see CORS7-003). If the server does not validate the Origin header, it accepts the connection and the attacker's page can now read and write on the user's authenticated WebSocket channel — subscribing to real-time audit results, sending commands, or reading sensitive data.
SA-SKL-CORS7 in scope: CORS7-001 (WebSocket upgrade handler does not check request.headers.origin), CORS7-002 (wildcard or missing origin check allows any origin to subscribe to real-time audit data), CORS7-003 (session cookies with SameSite=Lax are forwarded on WS upgrade from cross-origin navigation context), CORS7-004 (CDN or reverse proxy strips Origin on WS upgrade — skill treats null/missing Origin as trusted). Each pattern includes SkillAudit detection rules and correct fixes.
CORS7-001 — WebSocket upgrade handler does not check Origin header
An MCP skill's real-time audit progress feed is delivered via WebSocket. The Node.js ws library accepts upgrade connections by default without any origin check. The developer adds authentication by verifying the session cookie in the upgrade event, but does not add an Origin check. An attacker page can open a WebSocket connection to wss://app.skillaudit.dev/ws/audits/{id} — the browser sends the user's session cookie, the server validates it successfully, and the attacker's page receives the real-time audit progress stream of another user. The fix is to validate request.headers.origin against the allowlist before accepting the upgrade.
// VULNERABLE — WebSocket upgrade validates auth but not Origin
import { WebSocketServer } from 'ws';
import { verifySessionCookie } from './auth';
const wss = new WebSocketServer({ noServer: true });
server.on('upgrade', async (request, socket, head) => {
// Authenticates the connection — but does not check the Origin header
const user = await verifySessionCookie(request.headers.cookie);
if (!user) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
// Attacker page at https://attacker.com can reach here:
// new WebSocket('wss://app.skillaudit.dev/ws') with user's cookie
// request.headers.origin = 'https://attacker.com' — never checked
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request, user);
});
});
// FIXED — validate Origin header before accepting the WebSocket upgrade
import { WebSocketServer } from 'ws';
import { verifySessionCookie } from './auth';
const wss = new WebSocketServer({ noServer: true });
const ALLOWED_WS_ORIGINS = new Set([
'https://app.skillaudit.dev',
'https://skillaudit.dev',
// During development only — remove before production:
// 'http://localhost:3000',
]);
server.on('upgrade', async (request, socket, head) => {
const origin = request.headers.origin;
// Check Origin FIRST — before authentication — so unauthenticated upgrade attempts
// from non-allowed origins are rejected with minimal processing
if (!origin || !ALLOWED_WS_ORIGINS.has(origin)) {
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
return;
}
// Then authenticate the user
const user = await verifySessionCookie(request.headers.cookie);
if (!user) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request, user);
});
});
request.headers.origin allow cross-origin pages to open authenticated WebSocket connections using the logged-in user's cookie; the browser always sends Origin on WS upgrades and there is no CORS preflight — origin validation must be performed in the upgrade handler; fix by checking origin against an explicit allowlist before wss.handleUpgrade(). Detection: SkillAudit flags server.on('upgrade', ...) handlers that call handleUpgrade() without an intervening request.headers.origin allowlist check.CORS7-002 — Wildcard or missing origin check allows any origin to read real-time audit data
Some developers add an Origin check to the WebSocket upgrade handler but implement it in a way that accepts any origin — for example, by checking that origin !== undefined (which is true for any request that includes the header) rather than checking against a specific allowlist. Others use a broad regex that matches all subdomains including attacker-controlled subdomains via subdomain takeover. When the WebSocket channel delivers real-time audit results — including partial scan findings, internal service URLs discovered, and credentials found in the repository — any origin that passes the too-permissive check can subscribe to this data stream.
// VULNERABLE — Origin check that accepts any non-null origin value
server.on('upgrade', (request, socket, head) => {
const origin = request.headers.origin;
// Checks that Origin is present — but accepts any origin value
if (!origin) {
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
return;
}
// "Any origin is fine as long as it's set" — this is not an allowlist check
// Attacker at https://attacker.com passes this check trivially
// Another common mistake: a regex that accepts all subdomains
// if (!origin.endsWith('.skillaudit.dev')) — bypassed by https://evil.skillaudit.dev
// via subdomain takeover
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
});
// FIXED — strict Set-based allowlist, not a truthy check or broad regex
const ALLOWED_WS_ORIGINS = new Set([
'https://app.skillaudit.dev',
'https://skillaudit.dev',
]);
server.on('upgrade', async (request, socket, head) => {
const origin = request.headers.origin;
// Exact match against an explicit Set — no regex, no prefix/suffix checks
// A Set lookup is O(1) and immune to regex bypass via subdomain takeover
if (!ALLOWED_WS_ORIGINS.has(origin ?? '')) {
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
return;
}
// Authenticate user (token-based preferred for WS — see CORS7-003 on cookie risk)
const token = extractBearerToken(request.url ?? '');
const user = await verifyAccessToken(token);
if (!user) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request, user);
});
});
endsWith() / regex matching instead of exact Set membership, allow attacker-controlled origins (or origins obtained via subdomain takeover) to subscribe to real-time audit data streams; fix by using an exact-match Set allowlist containing only the production origins, with no wildcard or substring matching. Detection: SkillAudit flags WebSocket upgrade handlers where the origin check uses endsWith(), includes(), regex, or truthy checks rather than exact Set.has() membership.CORS7-003 — Session cookies with SameSite=Lax forwarded on cross-origin WebSocket upgrade
Cookies set with SameSite=Lax are sent on top-level cross-origin navigations (GET requests that change the page URL) but not on subresource requests from cross-origin frames. The key edge case for WebSocket: if a cross-origin page triggers a WebSocket upgrade within a navigation-equivalent context (for example, by opening a new window that immediately upgrades to WS), the browser may send SameSite=Lax cookies on that upgrade request. SameSite=Strict cookies are never sent on cross-origin requests of any kind. The practical consequence is that skill session cookies set with SameSite=Lax are potentially forwarded on WS upgrades from cross-origin pages, making the Origin check the primary (and sometimes only) CSRF protection for WebSocket channels. Using SameSite=Strict for session cookies adds a second layer of protection — but the Origin check remains mandatory because Strict breaks OAuth and email link authentication flows that use cross-origin navigation.
// UNDERSTANDING cookie SameSite behavior on WebSocket upgrade requests
// session cookie set with SameSite=Lax:
res.cookie('session', token, {
httpOnly: true,
secure: true,
sameSite: 'lax', // Sent on top-level cross-origin GET navigations
// For WebSocket: browsers differ on whether WS upgrade counts as a "navigation"
// Chrome treats it as a subresource (not sent cross-origin)
// Some older browsers and certain upgrade contexts send it cross-origin
});
// session cookie set with SameSite=Strict:
res.cookie('session', token, {
httpOnly: true,
secure: true,
sameSite: 'strict', // Never sent on cross-origin requests of any kind
// Trade-off: breaks OAuth flows, email login links, and any cross-domain redirect
// that lands on the app expecting to be authenticated
});
// RECOMMENDED: Use token-based authentication in the WebSocket URL for real-time channels
// This avoids SameSite ambiguity entirely — cookies are not involved in WS auth
// Server: generate a short-lived WebSocket access token from the session
app.get('/api/ws-token', requireAuth, (req, res) => {
// Generate a one-time token tied to the session — expires in 60 seconds
const wsToken = generateShortLivedToken(req.user.id, { expiresIn: 60 });
res.json({ wsToken });
});
// Client: include the token in the WebSocket URL (query param or subprotocol)
// const { wsToken } = await fetchWsToken();
// const ws = new WebSocket(`wss://app.skillaudit.dev/ws?token=${wsToken}`);
// Server: extract and validate token from URL query parameter
server.on('upgrade', async (request, socket, head) => {
// Always check Origin first
if (!ALLOWED_WS_ORIGINS.has(request.headers.origin ?? '')) {
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
return;
}
// Validate token from query parameter — not from cookie
const url = new URL(request.url ?? '/', 'wss://app.skillaudit.dev');
const token = url.searchParams.get('token');
if (!token) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
const user = await verifyShortLivedToken(token);
if (!user) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request, user);
});
});
SameSite=Lax may be forwarded by browsers on WebSocket upgrade requests from cross-origin pages in navigation-equivalent contexts, making the Origin check in the upgrade handler the primary CSRF protection for the WebSocket channel; use SameSite=Strict as a second layer (while accepting OAuth flow breakage), or authenticate WebSocket connections with a short-lived URL token rather than session cookies. Detection: SkillAudit flags WebSocket upgrade handlers that read the session cookie for authentication where that cookie is set with SameSite=Lax and no Origin check is present in the handler.CORS7-004 — Reverse proxy strips Origin on WebSocket upgrade; skill accepts null origin
Some reverse proxies and CDNs (nginx in certain configurations, some AWS CloudFront behaviors, legacy HAProxy setups) rewrite or drop the Origin header when proxying WebSocket upgrade requests. When the skill's WebSocket server receives an upgrade request with no Origin header, it has three choices: reject the connection (safe), accept the connection treating the absence of Origin as a same-origin signal (unsafe), or fall back to a less strict check (also unsafe). The safe choice is to always reject upgrade requests where Origin is absent — a legitimate browser WebSocket connection always sends Origin. If the proxy is stripping the header, the fix is at the proxy configuration level, not at the application level.
// VULNERABLE — treats missing Origin as a same-origin signal and accepts the connection
server.on('upgrade', async (request, socket, head) => {
const origin = request.headers.origin;
if (origin) {
// If Origin is present, check the allowlist
if (!ALLOWED_WS_ORIGINS.has(origin)) {
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
return;
}
}
// If Origin is MISSING, we fall through and accept the connection
// Assumption: "No Origin header means it's a same-origin server-to-server connection"
// Reality: CDN or attacker-controlled proxy stripped the Origin header
// Now any WebSocket client that can strip the Origin header bypasses all CORS checks
const user = await verifySessionCookie(request.headers.cookie);
if (!user) { socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); socket.destroy(); return; }
wss.handleUpgrade(request, socket, head, (ws) => { wss.emit('connection', ws, request, user); });
});
// FIXED — reject ALL WebSocket upgrades where Origin is absent or not in the allowlist
const ALLOWED_WS_ORIGINS = new Set([
'https://app.skillaudit.dev',
'https://skillaudit.dev',
]);
server.on('upgrade', async (request, socket, head) => {
const origin = request.headers.origin;
// Reject if Origin is absent (possible CDN stripping) or not in the allowlist
// A legitimate browser WS connection ALWAYS includes Origin — treat absence as untrusted
if (!origin || !ALLOWED_WS_ORIGINS.has(origin)) {
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
return;
}
const user = await verifySessionCookie(request.headers.cookie);
if (!user) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request, user);
});
});
// Reverse proxy fix (nginx) — preserve the Origin header on WS proxy:
// location /ws {
// proxy_pass http://backend;
// proxy_http_version 1.1;
// proxy_set_header Upgrade $http_upgrade;
// proxy_set_header Connection "Upgrade";
// proxy_set_header Host $host;
// proxy_set_header Origin $http_origin; // ← Explicitly forward the Origin header
// }
//
// Without proxy_set_header Origin, nginx may strip or not forward the Origin
// depending on its proxy_hide_header and proxy_pass_header configuration
Origin header are vulnerable to bypasses from reverse proxies or CDNs that strip the Origin header, allowing any WebSocket client behind such a proxy to connect without origin validation; fix by rejecting all upgrade requests where Origin is absent (legitimate browser WS always sends Origin) and by configuring the reverse proxy to explicitly forward the Origin header. Detection: SkillAudit flags WebSocket upgrade handlers that only validate Origin when it is present, or that fall through to accept the connection when Origin is absent.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| CORS7-001 | CRITICAL | WS upgrade handler authenticates but never checks request.headers.origin — any cross-origin page opens authenticated WS |
Check origin against ALLOWED_WS_ORIGINS.has(origin) before handleUpgrade() |
| CORS7-002 | CRITICAL | Wildcard or truthy origin check on WS upgrade — attacker-controlled origin or subdomain takeover passes | Use exact-match Set.has() for allowed WS origins; no regex or suffix matching |
| CORS7-003 | HIGH | SameSite=Lax cookies forwarded on WS upgrade in navigation contexts — Origin check is sole CSRF protection |
Use short-lived URL token for WS auth (avoids SameSite ambiguity); or SameSite=Strict |
| CORS7-004 | HIGH | CDN/proxy strips Origin header on WS upgrade — skill accepts null origin as trusted | Reject all upgrades with absent Origin; fix proxy to forward Origin: $http_origin |
Related patterns: SA-SKL-CORS6 covers CORS preflight caching misconfigurations on HTTP endpoints. SA-SKL-CORS5 covers credentialed cross-origin requests and advanced CORS bypass patterns. WebSocket connection security covers WebSocket message validation, rate limiting, and authentication token handling on the WS channel itself.