OpenClaude MCP OAuth Callback: State Check Bypass via error Param Leads to DoS
Description
# OAuth State Validation Bypass via error Parameter Causes Local Server DoS in MCP Auth Callback ---
Description
The OpenClaude MCP authentication flow starts a temporary local HTTP server to handle OAuth callbacks. To prevent CSRF attacks, the server validates a state parameter against an internally stored value. However, due to a logic flaw in the order of conditionals, an attacker can completely bypass this check and force the server to shut down — without knowing the state value at all.
The vulnerable code looks like this:
if (!error && state !== oauthState) {
rejectOnce(new Error('OAuth state mismatch - possible CSRF attack'))
return
}
if (error) {
cleanup()
rejectOnce(new Error(errorMessage))
return
}
When a request arrives with an error query parameter (e.g., ?error=anything), the first condition becomes false because !error evaluates to false. This means the CSRF check is never reached. Execution falls through to the second block, where cleanup() is called — shutting down the local server and terminating the user's active authentication session.
The attacker does not need to know the state value. Any request containing an error parameter is enough to trigger the shutdown.
---
Impact
- The user's OAuth flow is silently terminated mid-session
- The local callback server is shut down (Denial of Service)
- Can be triggered remotely via a malicious web page using a cross-origin request (CSRF)
- No authentication or prior knowledge of the
statevalue is required
---
Steps to
Reproduce
Save the following as poc.js and run with Node.js:
import { createServer } from 'http';
import { parse } from 'url';
const expectedState = "secure_state_abc123";
const server = createServer((req, res) => {
const parsedUrl = parse(req.url || '', true);
const { pathname, query } = parsedUrl;
const { state, error } = query;
if (pathname === '/callback') {
// Vulnerable: error param causes state check to be skipped entirely
if (!error && state !== expectedState) {
res.writeHead(400);
res.end('State mismatch');
console.log('[-] CSRF attempt blocked.');
return;
}
if (error) {
res.writeHead(200);
res.end(`Error: ${error}`);
console.log(`[!] Server shutting down. Triggered by: ${error}`);
server.close();
return;
}
}
});
server.listen(12345, '127.0.0.1', () => {
console.log('Listening on http://127.0.0.1:12345');
});
Terminal 1 — start the server: ``bash node poc.js ``
Terminal 2 — trigger the bypass: ``bash curl "http://127.0.0.1:12345/callback?error=triggered" ``
Expected result: Server shuts down immediately. The state value was never checked.
---
Root
Cause
The CSRF protection is conditioned on !error, meaning it is silently disabled whenever an error parameter is present. The two checks need to be decoupled — state validation must happen first, independently of any other parameters.
---
Fix
Move the state check before the error check, and remove the dependency on !error:
// Fixed
if (state !== oauthState) {
cleanup()
rejectOnce(new Error('OAuth state mismatch - possible CSRF attack'))
return
}
if (error) {
cleanup()
rejectOnce(new Error(errorMessage))
return
}
With this change, any request — whether it contains an error parameter or not — must first pass the state validation before any further processing occurs.
---
Credit: Xanlar Agamalizade
Affected packages
Versions sourced from the GitHub Security Advisory.
| Package | Affected versions | Patched versions |
|---|---|---|
@gitlawb/openclaudenpm | < 0.5.1 | 0.5.1 |
Patches
1739b8d1f40fdfix: enforce MCP OAuth callback state before errors (#775)
2 files changed · +171 −45
src/services/mcp/auth.test.ts+61 −0 added@@ -0,0 +1,61 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { validateOAuthCallbackParams } from './auth.js' + +test('OAuth callback rejects error parameters before state validation can be bypassed', () => { + const result = validateOAuthCallbackParams( + { + error: 'access_denied', + error_description: 'denied by provider', + }, + 'expected-state', + ) + + assert.deepEqual(result, { type: 'state_mismatch' }) +}) + +test('OAuth callback accepts provider errors only when state matches', () => { + const result = validateOAuthCallbackParams( + { + state: 'expected-state', + error: 'access_denied', + error_description: 'denied by provider', + error_uri: 'https://example.test/error', + }, + 'expected-state', + ) + + assert.deepEqual(result, { + type: 'error', + error: 'access_denied', + errorDescription: 'denied by provider', + errorUri: 'https://example.test/error', + message: + 'OAuth error: access_denied - denied by provider (See: https://example.test/error)', + }) +}) + +test('OAuth callback accepts authorization codes only when state matches', () => { + assert.deepEqual( + validateOAuthCallbackParams( + { + state: 'expected-state', + code: 'auth-code', + }, + 'expected-state', + ), + { type: 'code', code: 'auth-code' }, + ) + + assert.deepEqual( + validateOAuthCallbackParams( + { + state: 'wrong-state', + code: 'auth-code', + }, + 'expected-state', + ), + { type: 'state_mismatch' }, + ) +})
src/services/mcp/auth.ts+110 −45 modified@@ -124,6 +124,74 @@ function redactSensitiveUrlParams(url: string): string { } } +type OAuthCallbackParamValue = string | string[] | null | undefined + +type OAuthCallbackValidationResult = + | { type: 'code'; code: string } + | { + type: 'error' + error: string + errorDescription: string + errorUri: string + message: string + } + | { type: 'missing_result' } + | { type: 'state_mismatch' } + +function getFirstOAuthCallbackParam( + value: OAuthCallbackParamValue, +): string | undefined { + if (Array.isArray(value)) { + return value.find(item => item.length > 0) + } + return value && value.length > 0 ? value : undefined +} + +export function validateOAuthCallbackParams( + params: { + code?: OAuthCallbackParamValue + state?: OAuthCallbackParamValue + error?: OAuthCallbackParamValue + error_description?: OAuthCallbackParamValue + error_uri?: OAuthCallbackParamValue + }, + oauthState: string, +): OAuthCallbackValidationResult { + const code = getFirstOAuthCallbackParam(params.code) + const state = getFirstOAuthCallbackParam(params.state) + const error = getFirstOAuthCallbackParam(params.error) + const errorDescription = + getFirstOAuthCallbackParam(params.error_description) ?? '' + const errorUri = getFirstOAuthCallbackParam(params.error_uri) ?? '' + + if (state !== oauthState) { + return { type: 'state_mismatch' } + } + + if (error) { + let message = `OAuth error: ${error}` + if (errorDescription) { + message += ` - ${errorDescription}` + } + if (errorUri) { + message += ` (See: ${errorUri})` + } + return { + type: 'error', + error, + errorDescription, + errorUri, + message, + } + } + + if (code) { + return { type: 'code', code } + } + + return { type: 'missing_result' } +} + /** * Some OAuth servers (notably Slack) return HTTP 200 for all responses, * signaling errors via the JSON body instead. The SDK's executeTokenRequest @@ -1058,30 +1126,31 @@ export async function performMCPOAuthFlow( options.onWaitingForCallback((callbackUrl: string) => { try { const parsed = new URL(callbackUrl) - const code = parsed.searchParams.get('code') - const state = parsed.searchParams.get('state') - const error = parsed.searchParams.get('error') + const result = validateOAuthCallbackParams( + { + code: parsed.searchParams.get('code'), + state: parsed.searchParams.get('state'), + error: parsed.searchParams.get('error'), + error_description: + parsed.searchParams.get('error_description'), + error_uri: parsed.searchParams.get('error_uri'), + }, + oauthState, + ) - if (error) { - const errorDescription = - parsed.searchParams.get('error_description') || '' - cleanup() - rejectOnce( - new Error(`OAuth error: ${error} - ${errorDescription}`), - ) + if (result.type === 'state_mismatch') { + // Ignore so a stray or malicious URL cannot cancel an active flow. return } - if (!code) { - // Not a valid callback URL, ignore so the user can try again + if (result.type === 'missing_result') { + // Not a valid callback URL, ignore so the user can try again. return } - if (state !== oauthState) { + if (result.type === 'error') { cleanup() - rejectOnce( - new Error('OAuth state mismatch - possible CSRF attack'), - ) + rejectOnce(new Error(result.message)) return } @@ -1090,7 +1159,7 @@ export async function performMCPOAuthFlow( `Received auth code via manual callback URL`, ) cleanup() - resolveOnce(code) + resolveOnce(result.code) } catch { // Invalid URL, ignore so the user can try again } @@ -1101,53 +1170,49 @@ export async function performMCPOAuthFlow( const parsedUrl = parse(req.url || '', true) if (parsedUrl.pathname === '/callback') { - const code = parsedUrl.query.code as string - const state = parsedUrl.query.state as string - const error = parsedUrl.query.error - const errorDescription = parsedUrl.query.error_description as string - const errorUri = parsedUrl.query.error_uri as string + const result = validateOAuthCallbackParams( + parsedUrl.query, + oauthState, + ) // Validate OAuth state to prevent CSRF attacks - if (!error && state !== oauthState) { + if (result.type === 'state_mismatch') { res.writeHead(400, { 'Content-Type': 'text/html' }) res.end( `<h1>Authentication Error</h1><p>Invalid state parameter. Please try again.</p><p>You can close this window.</p>`, ) - cleanup() - rejectOnce(new Error('OAuth state mismatch - possible CSRF attack')) return } - if (error) { - res.writeHead(200, { 'Content-Type': 'text/html' }) - // Sanitize error messages to prevent XSS - const sanitizedError = xss(String(error)) - const sanitizedErrorDescription = errorDescription - ? xss(String(errorDescription)) - : '' + if (result.type === 'missing_result') { + res.writeHead(400, { 'Content-Type': 'text/html' }) res.end( - `<h1>Authentication Error</h1><p>${sanitizedError}: ${sanitizedErrorDescription}</p><p>You can close this window.</p>`, + `<h1>Authentication Error</h1><p>Missing OAuth result. Please try again.</p><p>You can close this window.</p>`, ) - cleanup() - let errorMessage = `OAuth error: ${error}` - if (errorDescription) { - errorMessage += ` - ${errorDescription}` - } - if (errorUri) { - errorMessage += ` (See: ${errorUri})` - } - rejectOnce(new Error(errorMessage)) return } - if (code) { + if (result.type === 'error') { res.writeHead(200, { 'Content-Type': 'text/html' }) + // Sanitize error messages to prevent XSS + const sanitizedError = xss(result.error) + const sanitizedErrorDescription = result.errorDescription + ? xss(result.errorDescription) + : '' res.end( - `<h1>Authentication Successful</h1><p>You can close this window. Return to Claude Code.</p>`, + `<h1>Authentication Error</h1><p>${sanitizedError}: ${sanitizedErrorDescription}</p><p>You can close this window.</p>`, ) cleanup() - resolveOnce(code) + rejectOnce(new Error(result.message)) + return } + + res.writeHead(200, { 'Content-Type': 'text/html' }) + res.end( + `<h1>Authentication Successful</h1><p>You can close this window. Return to Claude Code.</p>`, + ) + cleanup() + resolveOnce(result.code) } })
Vulnerability mechanics
AI mechanics synthesis has not run for this CVE yet.
References
4News mentions
0No linked articles in our index yet.