Claude MCP skill insecure random token generation and predictable reset codes — SA-SKL-CRYPTO3
Math.random() in JavaScript is not a cryptographically secure pseudorandom number generator. It uses a Xorshift128+ or similar PRNG seeded from the platform's entropy source, but once a few consecutive values are observed, the internal state can be recovered and future values predicted. Password reset tokens, email verification codes, session secrets, and invite tokens generated with Math.random() are therefore predictable by an attacker who can observe any output from the same process. Four SA-SKL-CRYPTO3 patterns cover the most common weak randomness vulnerabilities in MCP skill authentication flows, with fixes using Node.js's crypto module.
Math.random().toString(36).slice(2); Mersenne Twister or Xorshift128+ output; internal state recoverable from 3-4 observed tokens; attacker requests password resets for victim accounts and predicts the token before the victim clicks itMath.floor(Math.random() * 1000000); only 1 000 000 possible values; brute-forceable in under 100k guesses on average with no rate limit or attempt lockout on the verification endpointDate.now().toString(36) + userId.toString(36); both inputs are predictable for authenticated users who know their own userId and can estimate the server's clock; invite can be guessed for any pending invite in the same time windowos.hostname() + process.pid.toString(); hostname often appears in HTTP response headers or error pages; PID is discoverable via /proc or timing side-channels; HMAC on session cookies is predictableCRYPTO3-001 — Math.random() password reset token
V8's Math.random() uses Xorshift128+, a PRNG with 128 bits of internal state. While this produces numbers that pass statistical randomness tests, its state can be fully recovered by observing 3-4 consecutive output values using an algebraic attack on the linear recurrence. Once an attacker recovers the PRNG state, they can predict all future values generated by the same process — including the next password reset token for any account. The practical attack: request a reset for your own account, observe the token, recover the PRNG state, then request resets for victim accounts and predict their tokens before the victims act.
// VULNERABLE — CRYPTO3-001 (CRITICAL)
// Math.random() used for password reset token generation.
// Xorshift128+ state recoverable from ~4 observed values.
function generateResetToken(): string {
// VULNERABLE: Xorshift128+ — not a CSPRNG; state is recoverable
return Math.random().toString(36).slice(2) +
Math.random().toString(36).slice(2) +
Math.random().toString(36).slice(2);
// Output: ~24 chars base-36, ~125 bits apparent entropy, ~48 bits actual
}
router.post('/auth/reset-password', async (req, res) => {
const { email } = req.body;
const token = generateResetToken(); // predictable
const expires = Date.now() + 3600_000; // 1 hour
await db.run(
'UPDATE users SET reset_token = ?, reset_expires = ? WHERE email = ?',
token, expires, email
);
await sendResetEmail(email, token);
res.json({ ok: true });
});
// FIXED — CRYPTO3-001
// Use crypto.randomBytes(32) — 256 bits from OS CSPRNG (/dev/urandom on Linux).
// Store the token as a SHA-256 hash in the DB; compare via timingSafeEqual.
import crypto from 'crypto';
function generateResetToken(): { token: string; hash: string } {
// FIX: 32 bytes = 256 bits from OS CSPRNG — cryptographically unpredictable
const token = crypto.randomBytes(32).toString('hex');
const hash = crypto.createHash('sha256').update(token).digest('hex');
return { token, hash }; // send token to user; store only hash in DB
}
router.post('/auth/reset-password', async (req, res) => {
const { email } = req.body;
const { token, hash } = generateResetToken();
const expires = Math.floor(Date.now() / 1000) + 3600; // UTC unix seconds
await db.run(
'UPDATE users SET reset_token_hash = ?, reset_expires = ? WHERE email = ?',
hash, expires, email
);
await sendResetEmail(email, token); // user gets raw token
res.json({ ok: true });
});
router.post('/auth/reset-confirm', async (req, res) => {
const { token, newPassword } = req.body;
const hash = crypto.createHash('sha256').update(token).digest('hex');
const user = await db.get(
'SELECT * FROM users WHERE reset_token_hash = ? AND reset_expires > ?',
hash, Math.floor(Date.now() / 1000)
);
if (!user) return res.status(400).json({ error: 'Invalid or expired token' });
// proceed with password update and clear the token
});
CRYPTO3-002 — 6-digit Math.random() email verification code
A 6-digit numeric code generated with Math.floor(Math.random() * 1000000) has only 1 000 000 possible values. With no rate limiting or attempt lockout on the verification endpoint, an attacker can brute-force the correct code by trying values in sequence. At 1000 requests per second (easily achievable from a datacenter), the full space is exhausted in 1000 seconds (~17 minutes). With the expected 500k trials to reach the correct code, it takes about 8 minutes. Using a CSPRNG does not help if the code is short — the fix requires both switching to crypto.randomInt and enforcing a strict per-user attempt limit with lockout.
// VULNERABLE — CRYPTO3-002 (HIGH)
// 6-digit verification code from Math.random() — 1M possibilities.
// No attempt limit on the verification endpoint.
router.post('/auth/send-verification', authenticate, async (req, res) => {
// VULNERABLE: only 1M possibilities; Math.random() is not CSPRNG
const code = Math.floor(Math.random() * 1_000_000)
.toString()
.padStart(6, '0');
await db.run(
'UPDATE users SET verification_code = ?, code_expires = ? WHERE id = ?',
code, Date.now() + 600_000, req.user.id
);
await sendVerificationEmail(req.user.email, code);
res.json({ ok: true });
});
router.post('/auth/verify-email', authenticate, async (req, res) => {
const { code } = req.body;
// VULNERABLE: no attempt counter — attacker can try all 1M codes
const user = await db.get(
'SELECT * FROM users WHERE id = ? AND verification_code = ? AND code_expires > ?',
req.user.id, code, Date.now()
);
if (!user) return res.status(400).json({ error: 'Invalid code' });
await db.run('UPDATE users SET email_verified = 1 WHERE id = ?', req.user.id);
res.json({ ok: true });
});
// FIXED — CRYPTO3-002
// Use crypto.randomInt (CSPRNG) for the code.
// Enforce a 5-attempt lockout per code issuance.
import crypto from 'crypto';
router.post('/auth/send-verification', authenticate, async (req, res) => {
// FIX: crypto.randomInt is a CSPRNG (uses /dev/urandom)
const code = crypto.randomInt(100_000, 1_000_000).toString(); // 6 digits, no leading zero issue
const expires = Math.floor(Date.now() / 1000) + 600; // 10 min
await db.run(
'UPDATE users SET verification_code = ?, code_expires = ?, code_attempts = 0 WHERE id = ?',
code, expires, req.user.id
);
await sendVerificationEmail(req.user.email, code);
res.json({ ok: true });
});
router.post('/auth/verify-email', authenticate, async (req, res) => {
const { code } = req.body;
const user = await db.get(
'SELECT verification_code, code_expires, code_attempts FROM users WHERE id = ?',
req.user.id
);
// FIX: enforce attempt lockout
if (user.code_attempts >= 5) {
return res.status(429).json({ error: 'Too many attempts. Request a new code.' });
}
await db.run('UPDATE users SET code_attempts = code_attempts + 1 WHERE id = ?', req.user.id);
if (user.code_expires < Math.floor(Date.now() / 1000) || user.verification_code !== code) {
return res.status(400).json({ error: 'Invalid or expired code' });
}
await db.run(
'UPDATE users SET email_verified = 1, verification_code = NULL WHERE id = ?',
req.user.id
);
res.json({ ok: true });
});
CRYPTO3-003 — Date.now() XOR userId invite token
Invite tokens generated from deterministic inputs like Date.now() and userId are guessable by any authenticated user who knows their own userId and can estimate the server clock. XOR of two 64-bit integers is not a cryptographic construction — it leaks both operands if either is known. An attacker who observes one invite token they own can derive the timestamp component, subtract the known userId XOR bits, and enumerate other users' pending invite tokens by guessing plausible userIds and timestamp windows. This allows the attacker to accept invites for other users' accounts or enumerate valid invite tokens in the system.
// VULNERABLE — CRYPTO3-003 (HIGH)
// Invite token from Date.now() XOR userId. Deterministic and reversible.
// Attacker who knows their own userId can recover the timestamp component.
function generateInviteToken(userId: number): string {
// VULNERABLE: Date.now() and userId are both known or guessable
const timestamp = Date.now(); // milliseconds, predictable ±1s
return (BigInt(timestamp) ^ BigInt(userId)).toString(36);
}
router.post('/api/invites', authenticate, async (req, res) => {
const token = generateInviteToken(req.user.id); // predictable
await db.run(
'INSERT INTO invites (token, inviter_id, email, expires_at) VALUES (?, ?, ?, ?)',
token, req.user.id, req.body.email, Date.now() + 86400_000
);
await sendInviteEmail(req.body.email, token);
res.json({ ok: true });
});
// FIXED — CRYPTO3-003
// Use crypto.randomBytes(16) — 128 bits of CSPRNG entropy.
// Token has no relationship to userId or timestamp.
import crypto from 'crypto';
function generateInviteToken(): string {
// FIX: 16 random bytes = 128 bits from OS CSPRNG
return crypto.randomBytes(16).toString('hex');
}
router.post('/api/invites', authenticate, async (req, res) => {
const token = generateInviteToken(); // no deterministic inputs
await db.run(
'INSERT INTO invites (token, inviter_id, email, expires_at) VALUES (?, ?, ?, ?)',
token, req.user.id, req.body.email,
Math.floor(Date.now() / 1000) + 86400 // UTC unix seconds
);
await sendInviteEmail(req.body.email, token);
res.json({ ok: true });
});
CRYPTO3-004 — Session secret derived from hostname and process PID
Express session middleware requires a secret string used to HMAC-sign session cookies. If this secret is derived from predictable values like os.hostname() and process.pid, an attacker who can discover these values can forge valid session cookies for any userId. Hostnames often appear in HTTP Server headers, error stack traces, or cloud metadata. PIDs are bounded (typically 1-32768 on Linux), and are discoverable via /proc/self/stat if any file read primitive exists, or via timing side-channels comparing the number of open file descriptors. The fix is to generate a 32-byte random secret at deploy time and inject it as an environment variable.
// VULNERABLE — CRYPTO3-004 (HIGH)
// Session secret derived from hostname + PID. Both are discoverable.
// Attacker recovers secret → forges session cookie with arbitrary userId.
import os from 'os';
import session from 'express-session';
app.use(session({
// VULNERABLE: os.hostname() in HTTP headers; process.pid in /proc or error pages
secret: os.hostname() + process.pid.toString(),
resave: false,
saveUninitialized: false,
cookie: { secure: true, httpOnly: true },
}));
// FIXED — CRYPTO3-004
// SESSION_SECRET must be a 32+ byte random value set at deploy time.
// Validate at startup — crash fast rather than run with a weak secret.
import session from 'express-session';
const secret = process.env.SESSION_SECRET;
if (!secret || secret.length < 64) {
// 64 hex chars = 32 bytes = 256-bit secret
throw new Error(
'SESSION_SECRET must be at least 64 hex chars. ' +
'Generate with: node -e "console.log(require(\'crypto\').randomBytes(32).toString(\'hex\'))"'
);
}
app.use(session({
secret, // FIX: 256-bit secret from environment — not from process state
resave: false,
saveUninitialized: false,
cookie: { secure: true, httpOnly: true, sameSite: 'lax' },
}));
SkillAudit detection: SA-SKL-CRYPTO3 flags Math.random() calls in token generation functions (password reset, email verification, session nonce, invite), numeric codes with fewer than 10^8 possible values without a per-attempt lockout, token construction expressions involving Date.now() or user-identity fields (userId, email) without a CSPRNG component, and session secret initialization from os.hostname() or process.pid. Run a free audit at skillaudit.dev.
| Pattern | CVSS | Impact | Fix |
|---|---|---|---|
| CRYPTO3-001 Math.random() reset token | 9.3 Critical | Account takeover via predicted reset token | crypto.randomBytes(32).toString('hex'); store SHA-256 hash in DB |
| CRYPTO3-002 6-digit OTP brute-force | 7.5 High | Email verification bypassed in <17 minutes | crypto.randomInt(100000, 1000000) + 5-attempt lockout |
| CRYPTO3-003 Date.now XOR userId | 7.1 High | Invite token enumeration and account hijack | crypto.randomBytes(16).toString('hex') per invite |
| CRYPTO3-004 PID-derived session secret | 8.1 High | Session cookie forgery for any userId | 32+ random bytes in SESSION_SECRET env var; validate at startup |