Claude skill Redis cache poisoning and key collision via user-controlled input — SA-SKL-MEMCACHE3
Redis caching is universal in MCP skills that need to avoid redundant external API calls, store session state, or implement rate limiting. Each of these uses introduces a distinct class of vulnerability when the cache key is not carefully constructed, the TTL policy is incomplete, the atomic operation is non-atomic, or the connection is unencrypted. SA-SKL-MEMCACHE3 covers four patterns: user-controlled cache key collision, missing negative entry TTL, Redis INCR race for rate limiting, and unencrypted Redis in-transit data exposure.
MEMCACHE3-001 — Cache key collision via user-controlled input without normalization
MCP skills that cache external API responses or audit results often construct the Redis cache key directly from the inbound request path, query string, or body values. When the key is built without normalizing the input, an attacker can craft a request whose key is identical to a legitimate user's cached response, then read that response back through the cache. The collision can be achieved by exploiting URL percent-encoding equivalences (%2F vs /), case variation (GitHub.com vs github.com), trailing slash differences (/repo/ vs /repo), or Unicode normalization forms (é vs é). If the cached value contains a user-specific audit report or API response with tokens, the attacker obtains another user's data without authentication. Beyond data theft, an attacker can also poison the cache by submitting a crafted value that gets stored under a key that future legitimate requests will hit.
// VULNERABLE — MEMCACHE3-001
// skill-audit.js — cache key built directly from user-supplied URL
import { createClient } from 'redis';
const redis = createClient();
async function getAuditResult(repoUrl) {
const cacheKey = `audit:${repoUrl}`; // DANGEROUS: user-controlled, not normalized
const cached = await redis.get(cacheKey);
if (cached) return JSON.parse(cached);
const result = await runAudit(repoUrl);
await redis.setEx(cacheKey, 3600, JSON.stringify(result));
return result;
}
// User A requests: audit:https://github.com/user/repo
// Attacker requests: audit:https://GitHub.com/user/repo ← different key — no collision yet
// But: audit:https://github.com/user/repo/ ← trailing slash: same repo, different key
// Or attacker's repo URL happens to match user A's key via encoding tricks
// FIXED — MEMCACHE3-001
// Normalize the cache key: lowercase hostname, remove trailing slash, decode percent-encoding
import { URL } from 'url';
import { createHash } from 'crypto';
function normalizeCacheKey(prefix, rawUrl) {
let parsed;
try { parsed = new URL(rawUrl); } catch { return null; }
// Normalize: lowercase host, sort query params, strip trailing slash from pathname
parsed.hostname = parsed.hostname.toLowerCase();
parsed.pathname = parsed.pathname.replace(/\/+$/, '') || '/';
parsed.searchParams.sort(); // deterministic query param order
// Hash the normalized URL to prevent key-length issues and avoid special chars
const normalized = parsed.toString();
const hash = createHash('sha256').update(normalized).digest('hex').slice(0, 32);
return `${prefix}:${hash}`;
}
async function getAuditResult(repoUrl) {
const cacheKey = normalizeCacheKey('audit', repoUrl);
if (!cacheKey) throw new Error('Invalid URL');
const cached = await redis.get(cacheKey);
if (cached) return JSON.parse(cached);
const result = await runAudit(repoUrl);
await redis.setEx(cacheKey, 3600, JSON.stringify(result));
return result;
}
redis.get(cacheKey) or redis.setEx(cacheKey, ...) calls where cacheKey is built by string concatenation with req.params, req.query, or req.body values without a normalization step.MEMCACHE3-002 — Missing TTL on negative cache entries blocks legitimate resource creation
The cache-aside pattern — check cache, on miss fetch from origin, store in cache — is straightforward for positive responses. The error case is frequently mishandled: when the origin returns a 404 (resource not found), many implementations either do not cache the response at all (causing repeated origin hammering for genuinely absent resources) or cache it with the same TTL as a positive response (which can be hours). Caching a 404 with a long TTL means that if a resource is created after the negative entry was written, all subsequent requests hit the stale cached 404 until it expires — the resource appears non-existent to the application even though it now exists at the origin. In an MCP skill context, this can manifest as a package or repo that was just published being permanently "not found" for an hour because a pre-publication availability check cached a negative result. The fix is a separate, shorter TTL for negative entries — typically 30–60 seconds — so stale negatives expire quickly while valid positive results cache for the full window.
// VULNERABLE — MEMCACHE3-002
// npm-metadata.js — negative cache entries get the same TTL as positive
async function getNpmPackageMeta(packageName) {
const key = `npm:${packageName}`;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const res = await fetch(`https://registry.npmjs.org/${packageName}`);
if (!res.ok) {
// BUG: caches a 404 for 1 hour — if the package is published in the meantime,
// all requests return the cached null for up to 60 minutes
await redis.setEx(key, 3600, JSON.stringify(null));
return null;
}
const data = await res.json();
await redis.setEx(key, 3600, JSON.stringify(data)); // 1-hour positive TTL
return data;
}
// FIXED — MEMCACHE3-002
// Use a short TTL for negative entries so they expire quickly after resource creation
async function getNpmPackageMeta(packageName) {
const key = `npm:${packageName}`;
const cached = await redis.get(key);
if (cached !== null) {
const parsed = JSON.parse(cached);
return parsed; // null means "cached 404" — still return it for the brief TTL
}
const res = await fetch(`https://registry.npmjs.org/${packageName}`);
if (!res.ok) {
// Short TTL for negative entries: 60 seconds instead of 3600
// Package published moments ago will be visible within a minute
await redis.setEx(key, 60, JSON.stringify(null));
return null;
}
const data = await res.json();
await redis.setEx(key, 3600, JSON.stringify(data)); // positive: 1 hour
return data;
}
// Alternative: use a sentinel value to distinguish "explicitly cached null" from "not in cache"
const NEGATIVE_SENTINEL = '__NOT_FOUND__';
async function getNpmPackageMetaSentinel(packageName) {
const key = `npm:${packageName}`;
const raw = await redis.get(key);
if (raw === NEGATIVE_SENTINEL) return null; // cached 404
if (raw !== null) return JSON.parse(raw); // cached hit
// cache miss — fetch from origin
const res = await fetch(`https://registry.npmjs.org/${packageName}`);
if (!res.ok) {
await redis.setEx(key, 60, NEGATIVE_SENTINEL); // 60s negative TTL
return null;
}
const data = await res.json();
await redis.setEx(key, 3600, JSON.stringify(data));
return data;
}
redis.setEx(key, ttl, ...) calls inside a !res.ok or 404 branch that share the same ttl constant as the positive-result branch.MEMCACHE3-003 — Redis INCR race condition for rate limit counter
A common DIY rate-limiting pattern uses Redis INCR to increment a per-user or per-IP counter, checks the returned value against a limit, and applies a TTL with a separate EXPIRE command on the first increment. This two-step implementation — INCR then conditional EXPIRE — is non-atomic. Under concurrent load, multiple requests can all execute INCR before any of them executes EXPIRE. If the key does not exist yet (counter is 0), all concurrent requests return 1 from INCR (the first request sets it to 1; the others do too because the key was not yet created when they checked). More critically, if the first request's EXPIRE never executes (network error, process crash, Node event loop starvation), the counter key has no TTL and persists forever — permanently locking a user. The correct implementation uses a Lua script that atomically checks, increments, and sets the TTL in a single Redis round-trip.
// VULNERABLE — MEMCACHE3-003
// rate-limit.js — non-atomic INCR + EXPIRE race
async function checkRateLimit(userId, limit, windowSeconds) {
const key = `rl:${userId}`;
const count = await redis.incr(key); // Step 1: increment
if (count === 1) {
// RACE: between incr and expire, another request also sees count=1
// If this EXPIRE never executes (crash/error), key persists forever — user locked out
await redis.expire(key, windowSeconds); // Step 2: set TTL (not atomic with Step 1)
}
return count <= limit; // true = allowed, false = rate limited
}
// Concurrent scenario:
// Request A: INCR → returns 1 (key created, no TTL yet)
// Request B: INCR → returns 2 (count=2, still no TTL if A's EXPIRE hasn't run)
// Request A: EXPIRE 60 → TTL set
// Request B: sees count=2 → might be blocked when it shouldn't be on first window
// FIXED — MEMCACHE3-003
// Atomic increment-and-expire via Lua script — single round-trip, no race
const RATE_LIMIT_SCRIPT = `
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local current = redis.call('INCR', key)
if current == 1 then
redis.call('EXPIRE', key, window)
end
return current
`;
async function checkRateLimit(userId, limit, windowSeconds) {
const key = `rl:${userId}`;
// evalsha is preferred for performance once the script is loaded
const count = await redis.eval(RATE_LIMIT_SCRIPT, 1, key, limit, windowSeconds);
return Number(count) <= limit; // true = request allowed
}
// Alternative: use rate-limiter-flexible with RedisStore — it uses the same atomic Lua approach
import { RateLimiterRedis } from 'rate-limiter-flexible';
const rateLimiter = new RateLimiterRedis({
storeClient: redis,
keyPrefix: 'rl',
points: 60, // requests allowed
duration: 60, // per 60-second window
// Uses Lua script internally — always atomic
});
rate-limiter-flexible with a Redis store (which uses this Lua approach internally). Detection: SkillAudit flags redis.incr(key) followed by a conditional redis.expire(key, ...) that is not wrapped in a Lua script or pipeline.MEMCACHE3-004 — Unencrypted Redis connection exposes session and JWT data
Redis connections inside a Kubernetes cluster or VPC are frequently left unencrypted on the assumption that the internal network is trusted. This assumption fails in several real-world scenarios: a compromised sidecar container or pod in the same namespace, a misconfigured network policy that allows cross-namespace traffic, an attacker with access to any node's network namespace (via container escape), or a rogue process on a shared VPS. Redis in its default configuration transmits commands and responses as plaintext on the wire. For an MCP skill that stores session tokens, JWT access tokens, audit results, or user email addresses in Redis, a passive MITM on the internal network segment can read all of this data without authentication. Redis also has no access control by default — a process that can reach the port can issue any command, including FLUSHALL (delete all data) or CONFIG SET dir /etc (overwrite server files via SAVE). The fix is Redis TLS (tls configuration in ioredis), requirepass in redis.conf, and rename-command FLUSHALL "" to disable dangerous commands.
// VULNERABLE — MEMCACHE3-004
// redis-client.js — plaintext connection with no authentication
import { createClient } from 'redis';
// Connects to Redis at default localhost:6379 without TLS or auth
// All data (sessions, JWTs, audit results) transmitted in plaintext
const redis = createClient({
url: 'redis://localhost:6379', // No TLS (rediss://), no password
});
await redis.connect();
// Everything this client writes is readable by any process that can reach the port:
// SET session:abc123 '{"userId":42,"role":"admin","jwt":"eyJhbGciOiJIUzI1NiJ9..."}'
// GET session:abc123 ← any process on the network can issue this
// FIXED — MEMCACHE3-004
// Use TLS (rediss://), requirepass, and disable dangerous commands
// 1. redis.conf additions:
// requirepass YourStrongPassphrase
// rename-command FLUSHALL ""
// rename-command FLUSHDB ""
// rename-command CONFIG "__CONFIG_SECRET__"
// rename-command DEBUG ""
// tls-port 6380
// tls-cert-file /etc/redis/tls/redis.crt
// tls-key-file /etc/redis/tls/redis.key
// tls-ca-cert-file /etc/redis/tls/ca.crt
// 2. ioredis TLS client:
import Redis from 'ioredis';
import { readFileSync } from 'fs';
const redis = new Redis({
host: process.env.REDIS_HOST,
port: 6380,
password: process.env.REDIS_PASSWORD,
tls: {
cert: readFileSync('/etc/redis/tls/client.crt'),
key: readFileSync('/etc/redis/tls/client.key'),
ca: readFileSync('/etc/redis/tls/ca.crt'),
// Reject connections with invalid certificates
rejectUnauthorized: true,
},
lazyConnect: true,
});
// 3. ACL (Redis 6+) — scope to only the commands the skill actually needs:
// ACL SETUSER skill-service on >SkillPass ~audit:* ~rl:* ~session:* +GET +SET +SETEX +DEL +INCR +EXPIRE +EVAL
rediss:// URI or ioredis tls option), setting requirepass in redis.conf, and using Redis ACL to restrict commands to only those the skill needs. Detection: SkillAudit flags redis:// (not rediss://) connection strings or ioredis constructors without a tls key when the Redis instance stores session or authentication data.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| MEMCACHE3-001 | HIGH | Cache key from user-controlled URL without normalization — collision via encoding/case/trailing slash | Normalize (lowercase, decode, strip slash) then hash before using as key |
| MEMCACHE3-002 | MEDIUM | Same TTL for negative (404) and positive cache entries — stale 404 blocks created resources | Short TTL (30–60 s) for negative entries; full TTL for positive |
| MEMCACHE3-003 | HIGH | INCR + conditional EXPIRE in two commands — race allows bypass; crash creates persistent key | Lua script atomic increment-and-expire, or rate-limiter-flexible Redis store |
| MEMCACHE3-004 | HIGH | Plaintext Redis connection — session, JWT, audit data readable by internal network MITM | Redis TLS (rediss://), requirepass, ACL command restrictions |
Related patterns: SA-SKL-ASYNCRACE3 covers async race conditions including the concurrent quota check race that Redis Lua scripts also fix. SA-SKL-RATELIMIT4 covers distributed rate limit bypass at the HTTP layer — the Redis INCR pattern here is the backing store for those limiters. SA-SKL-SESSION2 covers session fixation and JWT expiry — the same session tokens exposed by MEMCACHE3-004.