Claude MCP skill insecure deserialization — session management and authentication token handling — SA-SKL-DESER11
Session management and authentication token handling are the most sensitive deserialization surfaces in an MCP skill registry: they determine who the server believes a user is on every request. SA-SKL-DESER11 covers four insecure deserialization patterns in these surfaces — a MessagePack Redis session restored without schema validation that allows an attacker with Redis write access to inject isAdmin: true, a JWT payload merged via Object.assign that achieves process-wide prototype pollution, a base64 remember-me cookie that lets any user self-upgrade their role to admin, and an OAuth2 state parameter whose Object.assign merge creates a CSRF-triggerable prototype pollution vector.
msgpack.decode() without schema validation — attacker with Redis write access injects isAdmin: true into the session object, gaining admin access on the next request by any user whose session is targetedJSON.parse + Object.assign — attacker crafts a JWT with a __proto__ own property, achieving prototype pollution on session merge and setting Object.prototype.isAdmin = true process-wide for all subsequent requestsbase64(JSON.stringify(userData)) and decoded via JSON.parse + Object.assign — attacker modifies cookie value to inject role: 'admin', bypassing all authorization checks that read req.user.roleJSON.parse + Object.assign into the session — attacker crafts a state parameter with a __proto__ property and forces a victim to complete an OAuth flow via CSRF, polluting the victim's session object prototypeBackground: deserialization in session and token pipelines
Session management and authentication token pipelines are uniquely dangerous deserialization surfaces because they execute on every authenticated request and because their output — the req.user or req.session object — is trusted by all downstream middleware and route handlers. A single deserialization vulnerability in a session restoration path grants persistent elevated access for as long as the manipulated session or token remains valid.
DESER11-001 targets the session store layer: MessagePack provides compact binary serialization but no type safety. When session data is decoded without schema validation, any property that an attacker can write to the session's Redis key is restored verbatim into the session object. DESER11-002 is a JavaScript-specific pattern where Object.assign(target, JSON.parse(payload)) allows a crafted payload containing the string key "__proto__" to overwrite Object.prototype — a process-wide effect that persists across all requests until the Node.js process restarts.
DESER11-003 demonstrates the client-side session anti-pattern: storing session state in a client-controlled cookie without signing or encryption. Even when the token is base64-encoded (which provides no security), the content is under attacker control. DESER11-004 compounds OAuth state handling with prototype pollution: the state parameter is designed to carry cross-request context through a third-party redirect, making it an external-input surface that most developers assume is safe.
Related patterns: SA-SKL-DESER10 (task queue deserialization), SA-SKL-INJECTION15 (CI/CD injection), SA-SKL-PRIVESC8 (RBAC enforcement privilege escalation).
DESER11-001 — HIGH — MessagePack Redis session decoded without schema validation allows isAdmin injection
Session data is serialized to MessagePack and stored in Redis under the session key. On each request, the session middleware retrieves the binary blob from Redis and decodes it via msgpack.decode(). The decoded object is assigned directly to req.session without any schema validation or property allowlisting. MessagePack faithfully reproduces the type and structure of whatever was stored — if an attacker can write arbitrary data to the Redis key for a target session, they can inject any property they choose.
An attacker with Redis write access (via a Redis injection vulnerability, compromised Redis credentials, or a misconfigured Redis instance accessible from the internal network) retrieves the target session's binary blob, decodes it, appends isAdmin: true, re-encodes it to MessagePack, and writes it back to Redis. On the next request by the session owner, the session middleware decodes the modified blob and sets req.session.isAdmin = true. Any route handler that checks if (req.session.isAdmin) now grants admin access.
The fix requires two layers. First, schema validation must be applied after decoding — only known, expected properties should be permitted in a session object. Second, privileged flags such as isAdmin should not be stored in the session at all; they should be re-fetched from the database on each request (or on first access with a short-lived cache) rather than trusting the session store value.
// VULNERABLE — DESER11-001
// middleware/session.js
const msgpack = require('msgpack5')();
const redis = require('./redis');
async function restoreSession(req, res, next) {
const sessionId = req.cookies.sessionId;
if (!sessionId) return next();
const raw = await redis.getBuffer(`session:${sessionId}`);
if (!raw) return next();
// BUG: msgpack.decode() restores whatever was stored — no schema validation
// Attacker with Redis write access modifies the blob to include isAdmin:true
// msgpack faithfully decodes all properties including injected ones
const sessionData = msgpack.decode(raw);
// BUG: blindly assigns decoded data — isAdmin:true from Redis now on req.session
req.session = sessionData;
next();
}
// In route handlers:
app.get('/api/admin/users', (req, res) => {
// BUG: trusts req.session.isAdmin which came from the potentially-tampered session store
if (!req.session.isAdmin) return res.status(403).json({ error: 'Forbidden' });
// ... serve admin user list ...
});
// FIXED — DESER11-001
// middleware/session.js
const msgpack = require('msgpack5')();
const redis = require('./redis');
// Define the exact set of allowed session properties and their types
const SESSION_SCHEMA = {
userId: 'string',
email: 'string',
createdAt: 'number',
expiresAt: 'number',
csrfToken: 'string',
// isAdmin is intentionally NOT in the session schema — re-fetch from DB each request
};
function validateSessionSchema(data) {
const validated = {};
for (const [key, expectedType] of Object.entries(SESSION_SCHEMA)) {
if (data[key] !== undefined && typeof data[key] === expectedType) {
validated[key] = data[key];
}
}
// Reject any keys not in the schema (e.g., injected isAdmin, role, etc.)
return validated;
}
async function restoreSession(req, res, next) {
const sessionId = req.cookies.sessionId;
if (!sessionId) return next();
const raw = await redis.getBuffer(`session:${sessionId}`);
if (!raw) return next();
let sessionData;
try {
sessionData = msgpack.decode(raw);
} catch (err) {
logger.warn('DESER11-001: failed to decode session blob', { sessionId });
return next(); // treat as unauthenticated
}
// Validate against allowlist schema — strips any injected properties
req.session = validateSessionSchema(sessionData);
if (req.session.userId) {
// Re-fetch authorization state from DB — never trust session store for privileges
req.sessionUser = await User.findById(req.session.userId)
.select('id email isAdmin role')
.lean();
}
next();
}
// In route handlers — read isAdmin from DB-sourced user, not from session:
app.get('/api/admin/users', requireAuth, (req, res) => {
if (!req.sessionUser?.isAdmin) return res.status(403).json({ error: 'Forbidden' });
// ... serve admin user list ...
});
DESER11-001 impact: An attacker with Redis write access can inject arbitrary properties into any user's session, granting themselves or any victim escalated privileges on their next request. The attack does not require knowledge of the application's signing key or the user's password — it operates entirely at the data store layer. Privilege flags like isAdmin stored in the session store are a persistent anti-pattern: the session store should contain only identity claims (userId, email) with authorization state re-fetched from the authoritative database on each request. SkillAudit detects this by identifying session restoration paths that call binary or structured decode functions and assign the result directly to the session object without schema validation, and by flagging session objects that contain authorization flags such as isAdmin, role, or permissions.
DESER11-002 — CRITICAL — JWT Object.assign prototype pollution grants process-wide admin access
When a JWT token is verified, its payload is decoded from base64 JSON. The application then merges the payload into the user context object using Object.assign(req.user, JSON.parse(jwtPayload)). JSON.parse in JavaScript creates plain objects whose property "__proto__" — if present as a string key in the JSON — does not trigger prototype chain lookup; it is treated as an own property of the parsed object. When this object is passed to Object.assign as the source, the assignment engine sees a property named "__proto__" and writes it onto the target's prototype chain — this is prototype pollution.
An attacker crafts a JWT with a payload containing {"userId":"attacker","__proto__":{"isAdmin":true}}. The JWT is signed with the attacker's own token (which the server verifies successfully, since the attacker is a legitimate user). The JSON.parse call returns an object with an own property __proto__ whose value is {"isAdmin":true}. When Object.assign(req.user, parsed) executes, it sets Object.prototype.isAdmin = true. This mutation is process-wide and persistent: every subsequent object in the Node.js process that checks obj.isAdmin will find true via prototype lookup, granting admin access to all users on all subsequent requests until the process restarts.
The fix requires using a null-prototype target for the merge (eliminating the prototype chain) and explicitly allowlisting which JWT claims are trusted. JWT libraries that return decoded payloads as plain objects with Object.create(null) provide an additional layer of protection, but the application-level merge must still avoid Object.assign with untrusted sources.
// VULNERABLE — DESER11-002
// middleware/auth.js
const jwt = require('jsonwebtoken');
function authenticateJWT(req, res, next) {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) return res.status(401).json({ error: 'No token' });
let decoded;
try {
// jwt.verify returns the payload — but the raw payload is also re-parsed below
decoded = jwt.verify(token, process.env.JWT_SECRET);
} catch (err) {
return res.status(401).json({ error: 'Invalid token' });
}
// BUG: Object.assign with decoded JWT payload — prototype pollution via __proto__
// Attacker payload: {"userId":"x","__proto__":{"isAdmin":true}}
// After this line, Object.prototype.isAdmin === true for all objects in process
req.user = {};
Object.assign(req.user, decoded); // BUG: merges __proto__ own property
next();
}
// In route handlers — this check passes for ALL users after one malicious JWT:
app.get('/api/admin/keys', authenticateJWT, (req, res) => {
if (!req.user.isAdmin) return res.status(403).json({ error: 'Forbidden' });
// After prototype pollution: req.user.isAdmin is true for every user
// ...
});
// FIXED — DESER11-002
// middleware/auth.js
const jwt = require('jsonwebtoken');
// Allowlist of claims to extract from JWT payload
const ALLOWED_JWT_CLAIMS = ['userId', 'email', 'sessionId', 'iat', 'exp'];
function extractSafeClaims(decoded) {
// Use Object.create(null) — no prototype chain, no prototype pollution possible
const safe = Object.create(null);
for (const claim of ALLOWED_JWT_CLAIMS) {
if (decoded[claim] !== undefined) {
safe[claim] = decoded[claim];
}
}
return safe;
}
function authenticateJWT(req, res, next) {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) return res.status(401).json({ error: 'No token' });
let decoded;
try {
decoded = jwt.verify(token, process.env.JWT_SECRET, {
algorithms: ['HS256'], // pin algorithm — prevent alg:none attack
});
} catch (err) {
return res.status(401).json({ error: 'Invalid token' });
}
// Extract only allowlisted claims into a null-prototype object
// __proto__ key in decoded will not be in ALLOWED_JWT_CLAIMS — safely discarded
const claims = extractSafeClaims(decoded);
if (!claims.userId) return res.status(401).json({ error: 'Missing userId claim' });
// Re-fetch authorization state from DB — JWT claims never carry isAdmin
req.user = claims;
req.authPromise = User.findById(claims.userId).select('id email isAdmin role').lean();
next();
}
// requireAdmin middleware re-fetches from DB
async function requireAdmin(req, res, next) {
const user = await req.authPromise;
if (!user?.isAdmin) return res.status(403).json({ error: 'Forbidden' });
req.dbUser = user;
next();
}
app.get('/api/admin/keys', authenticateJWT, requireAdmin, (req, res) => {
// req.dbUser.isAdmin is true only for real admins from the database
// ...
});
DESER11-002 impact: A single request from any legitimate authenticated user (attacker or not) with a crafted JWT payload permanently sets Object.prototype.isAdmin = true for the entire Node.js process. Every subsequent request by any user — including unauthenticated requests if the admin check is applied before authentication — passes the if (req.user.isAdmin) check. The pollution persists until the process restarts, potentially affecting thousands of requests. SkillAudit detects this by identifying Object.assign calls where the source is a parsed JWT payload or any other externally-supplied object, flagging them as prototype pollution vectors regardless of the specific property being assigned.
DESER11-003 — HIGH — Unsigned base64 remember-me cookie allows role injection via JSON.parse + Object.assign
The application implements remember-me functionality by storing the user's data as base64(JSON.stringify(userData)) in a long-lived cookie. On subsequent visits, the cookie is decoded via Buffer.from(cookie, 'base64').toString() and parsed with JSON.parse, then merged into the session user object via Object.assign(req.user, parsed). Because the cookie is not signed, any user can modify its base64-encoded content in their browser's cookie store.
An attacker decodes the legitimate cookie: {"userId":"123","email":"user@example.com","role":"user"}. They modify the payload to {"userId":"123","email":"user@example.com","role":"admin"}, re-encodes it to base64, and writes the modified value back to their cookie jar. On the next request, the application decodes and parses the cookie, then executes Object.assign(req.user, { userId: '123', email: 'user@example.com', role: 'admin' }). The req.user.role is now 'admin'. Any route that checks if (req.user.role === 'admin') grants the attacker admin access.
The fix is to never store session state in unsigned client-controlled cookies. Remember-me tokens must be opaque random values stored in the server-side session store, with the server looking up the associated user record on each request. If the application must store data in the cookie itself (a client-side session), the cookie must be signed with an HMAC and encrypted, using a library such as iron-session or cookie-session with a strong secret — and even then, privilege fields must not be included in the cookie payload.
// VULNERABLE — DESER11-003
// middleware/rememberMe.js
function restoreRememberMe(req, res, next) {
const rememberToken = req.cookies.remember_me;
if (!rememberToken || req.session.userId) return next();
let userData;
try {
// BUG: base64 decode + JSON.parse on attacker-controlled cookie value
// Attacker modifies cookie to inject role:'admin' or isAdmin:true
const raw = Buffer.from(rememberToken, 'base64').toString('utf8');
userData = JSON.parse(raw);
} catch (err) {
return next();
}
// BUG: Object.assign merges attacker-controlled data onto req.user
// Any property in the cookie payload is trusted, including role and isAdmin
req.user = {};
Object.assign(req.user, userData); // BUG: role:'admin' from cookie trusted
next();
}
// Route handler trusts req.user.role set from cookie:
app.delete('/api/users/:id', restoreRememberMe, (req, res) => {
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
// Attacker reaches here with role:'admin' from modified cookie
// ...
});
// FIXED — DESER11-003
// middleware/rememberMe.js
const crypto = require('crypto');
async function restoreRememberMe(req, res, next) {
const rememberToken = req.cookies.remember_me;
if (!rememberToken || req.session?.userId) return next();
// remember_me cookie is an opaque random token — look it up in the DB
// No session data is stored client-side; the token is a lookup key only
let session;
try {
// Hash the token before lookup to prevent timing attacks on the raw value
const tokenHash = crypto
.createHash('sha256')
.update(rememberToken)
.digest('hex');
session = await RememberMeSession.findOne({
tokenHash,
expiresAt: { $gt: new Date() },
});
} catch (err) {
logger.error('DESER11-003: remember-me lookup failed', { err });
return next();
}
if (!session) {
// Clear the invalid/expired cookie
res.clearCookie('remember_me');
return next();
}
// Re-fetch user from database — no data from cookie is trusted
const user = await User.findById(session.userId)
.select('id email role isAdmin')
.lean();
if (!user) {
await RememberMeSession.deleteOne({ _id: session._id });
res.clearCookie('remember_me');
return next();
}
// Rotate the remember-me token on use (token binding)
const newToken = crypto.randomBytes(32).toString('hex');
const newTokenHash = crypto.createHash('sha256').update(newToken).digest('hex');
await RememberMeSession.updateOne(
{ _id: session._id },
{ tokenHash: newTokenHash, updatedAt: new Date() }
);
res.cookie('remember_me', newToken, {
httpOnly: true,
secure: true,
sameSite: 'lax',
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
});
// Set req.user from DB — role and isAdmin come from the authoritative source
req.user = user;
next();
}
DESER11-003 impact: Any user can self-escalate to admin by modifying the base64-encoded remember-me cookie in their browser's cookie jar. The attack requires no server-side access, no knowledge of other users' credentials, and no network interception. The only barrier is that the user must know which properties to inject — but since role: 'admin' and isAdmin: true are common patterns, trial and error quickly succeeds. SkillAudit detects this by identifying base64-decode + JSON.parse + Object.assign chains that operate on cookie values, and by flagging any cookie-to-session assignment path that does not verify an HMAC signature before trusting the decoded content.
DESER11-004 — HIGH — OAuth2 state parameter Object.assign prototype pollution via CSRF-forced flow
The OAuth2 login flow stores application-specific state in the OAuth2 state parameter as base64(JSON.stringify(stateObj)). When the OAuth provider redirects back to the application's callback URL, the application decodes the state parameter and merges it into the session via Object.assign(req.session, JSON.parse(decodedState)). The state parameter is a string that travels through the OAuth provider's redirect URI and arrives at the callback handler as a query parameter — entirely under attacker control if the attacker can craft the initial OAuth authorization URL.
An attacker crafts an OAuth2 authorization URL whose state parameter is base64(JSON.stringify({"returnTo":"/","__proto__":{"isAdmin":true}})). The attacker then forces the victim to visit this URL using a CSRF attack (embedding the URL in an img src, an iframe, or a Fetch with no-cors mode). The victim's browser follows the OAuth flow, and the provider redirects back to /auth/callback?code=...&state=BASE64_PAYLOAD. The callback handler decodes the state, calls Object.assign(req.session, parsed), and writes isAdmin: true onto Object.prototype — or directly onto the victim's session object, depending on whether a plain-object or prototype-chain assignment is used.
The fix requires validating the OAuth2 state parameter against a server-side nonce before processing it. The state must contain only an opaque random token (the CSRF nonce); any application state (such as return URL) must be stored server-side keyed by the nonce and looked up after validation. No JSON payload from the state parameter should be merged into the session.
// VULNERABLE — DESER11-004
// routes/auth.js
app.get('/auth/github/callback', async (req, res) => {
const { code, state } = req.query;
if (!state) return res.status(400).send('Missing state');
// BUG: decode and parse attacker-controlled state parameter
// Attacker crafts state with __proto__:{"isAdmin":true}
let stateData;
try {
stateData = JSON.parse(Buffer.from(state, 'base64').toString('utf8'));
} catch (err) {
return res.status(400).send('Invalid state');
}
// BUG: Object.assign merges __proto__ own property from stateData onto req.session
// Attacker's CSRF-forced flow pollutes victim's session object prototype
Object.assign(req.session, stateData); // BUG: prototype pollution vector
// Exchange code for token and log user in
const accessToken = await exchangeOAuthCode(code);
const profile = await getGitHubProfile(accessToken);
const user = await User.findOrCreate({ githubId: profile.id, email: profile.email });
req.session.userId = user.id;
// Redirect to returnTo from state — also allows open redirect if not validated
res.redirect(stateData.returnTo || '/dashboard');
});
// FIXED — DESER11-004
// routes/auth.js
const crypto = require('crypto');
// When initiating OAuth flow, generate a CSRF nonce and store return URL server-side
app.get('/auth/github', (req, res) => {
const nonce = crypto.randomBytes(32).toString('hex');
const returnTo = req.query.returnTo || '/dashboard';
// Validate returnTo is a relative path (open redirect guard)
const safeReturnTo = returnTo.startsWith('/') && !returnTo.startsWith('//')
? returnTo
: '/dashboard';
// Store state server-side keyed by nonce — nothing sensitive in the OAuth state param
req.session.oauthNonce = nonce;
req.session.oauthReturnTo = safeReturnTo;
const params = new URLSearchParams({
client_id: process.env.GITHUB_CLIENT_ID,
redirect_uri: process.env.GITHUB_CALLBACK_URL,
scope: 'user:email',
state: nonce, // opaque nonce only — no JSON payload
});
res.redirect(`https://github.com/login/oauth/authorize?${params}`);
});
app.get('/auth/github/callback', async (req, res) => {
const { code, state } = req.query;
// Validate state is the expected nonce — CSRF protection
if (!state || !req.session.oauthNonce) {
return res.status(400).send('Missing OAuth state');
}
if (!crypto.timingSafeEqual(
Buffer.from(state),
Buffer.from(req.session.oauthNonce)
)) {
logger.warn('DESER11-004: OAuth state mismatch — potential CSRF', { state });
return res.status(403).send('Invalid OAuth state');
}
// Retrieve return URL from session (server-side) — not from the state parameter
const returnTo = req.session.oauthReturnTo || '/dashboard';
// Clear nonce and returnTo from session before proceeding
delete req.session.oauthNonce;
delete req.session.oauthReturnTo;
// Exchange code for token and log user in
const accessToken = await exchangeOAuthCode(code);
const profile = await getGitHubProfile(accessToken);
const user = await User.findOrCreate({ githubId: profile.id, email: profile.email });
// Set only the userId in the session — no Object.assign with external data
req.session.userId = user.id;
req.session.createdAt = Date.now();
res.redirect(returnTo);
});
DESER11-004 impact: An attacker can force a victim to complete an OAuth flow with a crafted state parameter via a CSRF attack, polluting the victim's session object prototype with arbitrary properties including isAdmin: true. Because Object.assign with a JSON-parsed __proto__ key operates on the prototype chain, the pollution affects the victim's Object.prototype — meaning every object in that session context (and potentially process-wide) will find isAdmin: true via prototype lookup. The attack requires only that the victim can be induced to visit the attacker's OAuth initiation URL while authenticated. SkillAudit detects this by identifying OAuth callback handlers that call Object.assign or spread (...) with the parsed state parameter as a source, and by flagging any OAuth flow where the state parameter contains a JSON payload rather than an opaque nonce.
Detection with SkillAudit
SkillAudit's static analysis scans session management and authentication token pipelines for all four SA-SKL-DESER11 patterns. For DESER11-001 it identifies binary decode functions (msgpack, cbor, protobuf) used in session restoration paths and flags those that assign the decoded result to the session object without schema validation, and separately flags session objects containing authorization properties. For DESER11-002 it identifies Object.assign and spread assignment calls where the source is any parsed external token payload, flagging them as prototype pollution vectors. For DESER11-003 it identifies base64-decode + JSON.parse chains that operate on cookie values and are not followed by HMAC verification. For DESER11-004 it identifies OAuth callback handlers that parse the state query parameter as JSON and merge it into the session, and flags those that do not perform nonce validation before the merge.
| Finding | Severity | Root cause | Fix |
|---|---|---|---|
| DESER11-001 | HIGH | MessagePack session decoded without schema validation; Redis write access injects isAdmin:true property | Schema allowlist post-decode; store only identity claims in session; re-fetch authorization from DB |
| DESER11-002 | CRITICAL | Object.assign with JWT payload allows __proto__ prototype pollution; process-wide isAdmin:true for all users | Allowlist JWT claims; use null-prototype target; never use Object.assign with external sources |
| DESER11-003 | HIGH | Unsigned base64 remember-me cookie decoded and merged; attacker injects role:admin into req.user | Opaque random token in cookie; server-side token lookup; re-fetch user from DB; rotate token on use |
| DESER11-004 | HIGH | OAuth2 state JSON parsed and Object.assigned into session; CSRF-forced flow pollutes session prototype | Store only opaque nonce in state; validate nonce before processing; keep return URL server-side |
Related findings: SA-SKL-DESER10 (task queue deserialization), SA-SKL-INJECTION15 (CI/CD injection), SA-SKL-PRIVESC8 (RBAC enforcement privilege escalation).
SkillAudit scans your MCP skill registry for all SA-SKL-DESER11 patterns — schema-less binary session decoding, Object.assign prototype pollution via JWT payloads, unsigned client-side session cookies, and OAuth state parameter injection — and delivers a prioritized fix report in minutes.
Join the waitlist →