← Blog

Claude skill distributed rate limit bypass via IP rotation and header manipulation — SA-SKL-RATELIMIT4

Rate limiting keyed on client IP address is the most common implementation in Express-based MCP skills — and the most easily bypassed. An attacker who controls the IP value used as the rate limit key (via header injection) or who distributes requests across a large IP pool (via Cloudflare proxied mode) can effectively nullify any per-IP limit. SA-SKL-RATELIMIT4 covers four bypass patterns: X-Forwarded-For header injection via broad trustProxy, Cloudflare egress IP rotation, unprotected authentication endpoints, and fixed-window boundary double-burst.

By SkillAudit  |  6 Nov 2026

RATELIMIT4-001 — X-Forwarded-For header injection via broad trustProxy setting

Express's app.set('trust proxy', true) (or the equivalent app.set('trust proxy', 1) in many tutorials) instructs Express to read req.ip from the leftmost X-Forwarded-For header value rather than from the socket's remote address. When this setting is applied too broadly, an attacker directly connecting to the application (bypassing the proxy entirely, e.g. via the server's direct IP if it is reachable) can supply any value in X-Forwarded-For: 1.2.3.4 and have that value used as the rate limit key. By rotating the header value across different IP addresses, the attacker cycles through the per-IP allowance indefinitely without ever hitting a limit. Even when the server sits behind a load balancer, misconfigured proxy trust trusts all X-Forwarded-For entries in the chain rather than only the last N hops from known proxy IPs.

// VULNERABLE — RATELIMIT4-001
// app.js (Express + express-rate-limit)
import express from 'express';
import rateLimit from 'express-rate-limit';

const app = express();

// DANGEROUS: trusts ALL proxy headers — the leftmost XFF value is attacker-controlled
app.set('trust proxy', true); // or app.set('trust proxy', 1) in many tutorials

const limiter = rateLimit({
  windowMs: 60 * 1000, // 1 minute
  max: 60,             // 60 requests per minute per IP
  keyGenerator: (req) => req.ip, // req.ip = leftmost XFF value — attacker controls this
});

app.use('/api/', limiter);
// Attacker: curl -H 'X-Forwarded-For: 1.1.1.1' https://skill.example.com/api/scan
//   then:  curl -H 'X-Forwarded-For: 1.1.1.2' https://skill.example.com/api/scan
// Each request uses a different "IP" — rate limit is never hit
// FIXED — RATELIMIT4-001
// Trust only the last N hops from known upstream proxy IPs (not all XFF entries)
// For a skill behind a single Cloudflare / load balancer hop:
app.set('trust proxy', 1); // Trust only 1 upstream proxy hop — the nearest load balancer

// Or, for maximum safety, trust only specific known proxy CIDRs:
// app.set('trust proxy', ['loopback', '10.0.0.0/8', '172.16.0.0/12']);

// For authenticated endpoints, rate-limit by user ID rather than IP:
const authenticatedLimiter = rateLimit({
  windowMs: 60 * 1000,
  max: 100,
  keyGenerator: (req) => {
    // Use the authenticated user's ID — cannot be spoofed via headers
    return req.user?.id ?? req.ip; // Fall back to IP only for unauthenticated requests
  },
  skip: (req) => !req.user, // Let the IP limiter handle unauthenticated requests
});
HIGH
SA-SKL-RATELIMIT4-001 — Express app.set('trust proxy', true) or over-broad proxy trust causes req.ip to be sourced from the attacker-controlled X-Forwarded-For header leftmost value, allowing unlimited IP rotation that bypasses per-IP rate limits; fix by trusting only the exact number of upstream proxy hops (typically 1) or by using authenticated user ID as the rate limit key on protected endpoints. Detection: SkillAudit flags app.set('trust proxy', true) combined with any rate limiter using req.ip as the key.

RATELIMIT4-002 — Cloudflare IP rotation distributes hits across the egress range

Cloudflare's proxied mode routes traffic through a large pool of anycast edge IPs. When an attacker uses Cloudflare Workers, Cloudflare Tunnels, or simply routes their own site's traffic through Cloudflare's proxy network, their requests arrive at the origin from different Cloudflare egress IPs. Cloudflare's egress IP space spans millions of addresses across hundreds of prefixes. A per-IP rate limiter with a 60-request-per-minute limit effectively sees each request as coming from a unique IP when the attacker controls or rotates the Cloudflare egress path. The same pattern applies to any large proxy network (Tor exit nodes, residential proxy services, AWS NAT gateways in multi-region deployments). The root fix is to rate-limit authenticated requests by user ID rather than IP — a user ID cannot be rotated by routing through different proxies.

// VULNERABLE — RATELIMIT4-002
// IP-based rate limiting fails against requests routed through large proxy networks
const limiter = rateLimit({
  windowMs: 60 * 1000,
  max: 60,
  keyGenerator: (req) => req.ip, // Different IP on each Cloudflare-proxied request
  // The attacker uses Cloudflare Workers to issue requests from thousands of edge IPs
  // Each unique edge IP has its own fresh 60-request bucket
});

app.use('/api/scan', requireAuth, limiter);
// 60 requests × (number of distinct Cloudflare IPs used) = effective no-limit
// FIXED — RATELIMIT4-002
// Use user ID as the primary key for authenticated endpoints
// IP-based limiting remains only as a secondary limit for unauthenticated access
const scanLimiter = rateLimit({
  windowMs: 60 * 1000,
  max: 20, // 20 scans per minute per user
  keyGenerator: (req) => `user:${req.user.id}`, // User ID — cannot be rotated via IP
  handler: (req, res) => {
    res.status(429).json({
      error: 'Too many requests',
      retryAfter: Math.ceil(req.rateLimit.resetTime / 1000)
    });
  },
  standardHeaders: true,
  legacyHeaders: false,
});

// Also cap at the IP level for defense-in-depth (protects against unauthenticated abuse)
const ipLimiter = rateLimit({
  windowMs: 60 * 1000,
  max: 100, // Higher IP limit — user limit is the operative control
  keyGenerator: (req) => req.ip,
});

app.use('/api/scan', requireAuth, ipLimiter, scanLimiter);
HIGH
SA-SKL-RATELIMIT4-002 — Rate limiters keyed exclusively on req.ip are bypassed by attackers routing requests through large proxy networks (Cloudflare, residential proxies, Tor exit nodes) where each request arrives from a distinct IP; fix by keying rate limits on authenticated user ID for all endpoints that require authentication, reserving IP-keyed limits for unauthenticated routes. Detection: SkillAudit flags authenticated route handlers where the only rate limiter uses req.ip as the key, with no supplemental user-ID-keyed limiter.

RATELIMIT4-003 — Missing rate limit on password reset and magic link endpoints

Authentication endpoints that accept an email address and send a password reset link or magic login link are commonly omitted from rate limiting configurations. Developers apply express-rate-limit to /api/* but forget to include /auth/* routes. An attacker who finds an unprotected POST /auth/reset endpoint can flood it with email addresses to: (1) enumerate valid accounts — the response time or body differs between existing and non-existent email addresses even when both return generic messages; (2) trigger email bombing — sending thousands of password reset emails to a victim's address; (3) exhaust the email service API rate limit — causing legitimate reset emails to fail. The rate limit for auth endpoints should be tighter than the general API limit and must be keyed on the submitted email address (not IP) to prevent distributed email enumeration.

// VULNERABLE — RATELIMIT4-003
import express from 'express';
import rateLimit from 'express-rate-limit';

const app = express();
const apiLimiter = rateLimit({ windowMs: 60000, max: 100 });
app.use('/api/', apiLimiter); // Rate limits /api/* routes

// /auth/* routes are NOT rate limited — attacker can send unlimited requests
app.post('/auth/reset', async (req, res) => {
  const { email } = req.body;
  const user = await db.users.findByEmail(email);
  if (!user) return res.json({ message: 'If that email exists, we sent a reset link.' });
  await sendResetEmail(user.email, generateResetToken(user.id));
  res.json({ message: 'If that email exists, we sent a reset link.' });
  // No rate limit → attacker sends 10k requests per minute to enumerate emails
  // AND flood victim's inbox with reset emails
});
// FIXED — RATELIMIT4-003
// Separate, stricter rate limiters for auth endpoints
// Key on email address (normalized) — not IP — to prevent distributed enumeration
import { createHash } from 'crypto';

const authEmailLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15-minute window
  max: 5,                    // 5 reset requests per email per 15 minutes
  keyGenerator: (req) => {
    // Normalize email (lowercase + trim) then hash — avoids storing PII in rate limit store
    const email = (req.body?.email ?? '').toLowerCase().trim();
    return 'auth-email:' + createHash('sha256').update(email).digest('hex');
  },
  message: { error: 'Too many password reset requests. Please wait 15 minutes.' },
  standardHeaders: true,
});

const authIpLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 20, // 20 auth requests per IP per 15 minutes (defense-in-depth)
  keyGenerator: (req) => `auth-ip:${req.ip}`,
});

app.post('/auth/reset', authIpLimiter, authEmailLimiter, async (req, res) => {
  // Constant-time response — always respond after the same delay regardless of email existence
  const user = await db.users.findByEmail(req.body.email);
  if (user) await sendResetEmail(user.email, generateResetToken(user.id));
  // Always the same response — prevents timing-based email enumeration
  res.json({ message: 'If that email exists, we sent a reset link.' });
});
HIGH
SA-SKL-RATELIMIT4-003 — Password reset, magic link, and OTP auth endpoints without rate limiting allow attackers to enumerate valid email addresses via response timing, trigger email bombing, and exhaust the email service API quota; fix by applying a separate, stricter rate limiter on all /auth/* routes keyed on the submitted email address (normalized + hashed) in addition to IP, and enforce constant-time responses. Detection: SkillAudit flags POST /auth/* and POST /password* route handlers with no rate-limiting middleware in the middleware chain.

RATELIMIT4-004 — Fixed-window counter reset at exact UTC second boundary

Fixed-window rate limiting increments a counter during a window (e.g. 1 minute), resets it at the window boundary, and enforces a maximum count per window. The boundary vulnerability: an attacker sends N requests at time T-0.001 (just before the boundary) and N requests at time T+0.001 (just after the boundary). Both bursts fall in different windows, so the counter never exceeds N — but the actual request rate is 2N over a 2-millisecond span. For a 60-request-per-minute limit with 1-second resolution, the effective burst rate near the boundary is 120 requests per second. This is particularly significant for compute-intensive endpoints like scan initiations, where even 2× the nominal rate can cause resource exhaustion. Sliding window algorithms (time-based rolling bucket or token bucket) eliminate boundary bursting because the window moves continuously rather than resetting at discrete boundaries.

// VULNERABLE — RATELIMIT4-004: fixed-window boundary double-burst
// express-rate-limit default uses a fixed-window counter (MemoryStore)
const limiter = rateLimit({
  windowMs: 60 * 1000, // 60-second fixed window
  max: 60,             // 60 requests per window
  // Window resets at exactly :00, :01, :02 ... — boundary is predictable
  // At window boundary T: attacker sends 60 requests at T-0.001 + 60 at T+0.001
  // Both batches have counter < 60 — total 120 requests pass in ~2ms
});

// Impact on scan endpoint: 120 simultaneous scan initiations can saturate the
// scan worker pool, causing resource exhaustion for other users
// FIXED — RATELIMIT4-004: use sliding window via rate-limiter-flexible
import { RateLimiterMemory } from 'rate-limiter-flexible';

// Sliding window — no fixed boundary, window moves continuously with each request
const slidingLimiter = new RateLimiterMemory({
  points: 60,       // 60 requests
  duration: 60,     // per 60 seconds
  // 'sliding' is the default window type in rate-limiter-flexible
  // The window for each key slides forward with each consume() call
  // A burst of 60 at T-0.001 sets the window; requests at T+0.001 hit the same window
  // — no boundary double-burst is possible
});

// Express middleware adapter
const slidingRateLimit = async (req, res, next) => {
  try {
    await slidingLimiter.consume(req.user?.id ?? req.ip);
    next();
  } catch {
    res.status(429).json({ error: 'Rate limit exceeded', retryAfter: 60 });
  }
};

app.use('/api/scan', requireAuth, slidingRateLimit);
MEDIUM
SA-SKL-RATELIMIT4-004 — Fixed-window rate limiters with predictable reset boundaries allow attackers to burst 2× the nominal limit by splitting requests across the window boundary; fix by using a sliding window algorithm (token bucket or rolling time bucket via rate-limiter-flexible with duration-based windows) that moves continuously rather than resetting at discrete boundaries. Detection: SkillAudit flags express-rate-limit usage with the default MemoryStore (fixed-window) on compute-intensive endpoints where boundary bursting would cause resource exhaustion.

Detection summary

ID Severity Pattern Fix
RATELIMIT4-001 HIGH app.set('trust proxy', true) + req.ip key — attacker rotates X-Forwarded-For header Trust only N known proxy hops; use user ID as key for authenticated endpoints
RATELIMIT4-002 HIGH IP-only key on authenticated routes — bypassed by Cloudflare/proxy IP pool rotation Key authenticated rate limiters on req.user.id, not req.ip
RATELIMIT4-003 HIGH No rate limit on /auth/reset, /auth/magic — email enumeration + bombing Separate auth limiter keyed on hashed email + IP; constant-time response
RATELIMIT4-004 MEDIUM Fixed-window counter reset at UTC boundary — 2× burst at boundary second Sliding window via rate-limiter-flexible with duration windows

Related patterns: SA-SKL-RATELIMIT3 covers in-process memory rate limiter reset on restart and Redis rate limit TTL race conditions. SA-SKL-TIMEOUT covers request timeout absence and unbounded body size — the resource exhaustion scenarios that rate limiting is designed to prevent. SA-SKL-SSRF5 covers blind SSRF via fire-and-forget fetch, which also benefits from per-user rate limiting on external URL fetch endpoints.