Back to Blog
medium SEVERITY8 min read

Defending Against Rate Limit Bypass: Securing Express Applications from IP Spoofing

A critical rate limiting vulnerability in an Express.js application allowed attackers to bypass API throttling through IP rotation and header manipulation. This fix demonstrates how improperly configured rate limiters can be circumvented through proxy networks, VPNs, and forged X-Forwarded-For headers, potentially enabling brute force attacks, credential stuffing, and resource exhaustion.

O
By Orbis AppSec
•Technically reviewed by Anupam Mediratta•Published March 19, 2026•Reviewed June 3, 2026

Answer Summary

Rate limit bypass in Express.js occurs when applications trust untrusted X-Forwarded-For headers without proper validation, allowing attackers to rotate IPs and circumvent throttling. The vulnerability is related to CWE-345 (Insufficient Verification of Data Authenticity) and CWE-636 (Not Controlling Generation of Code). The fix involves properly configuring Express's trust proxy setting, validating IP sources, and implementing a whitelist of trusted proxies rather than blindly trusting forwarded headers.

Vulnerability at a Glance

cweCWE-345 (Insufficient Verification of Data Authenticity), CWE-636 (Not Controlling Generation of Code)
fixImplement explicit trust proxy configuration, validate IP sources against a whitelist of trusted proxies, and use secure rate limiting middleware with proper IP identification
riskAttackers can bypass API rate limiting through IP rotation, enabling brute force attacks, credential stuffing, and resource exhaustion
languageJavaScript (Node.js/Express.js)
root causeImproper trust of X-Forwarded-For headers without validating proxy authenticity or implementing strict IP validation
vulnerabilityRate Limit Bypass via IP Header Spoofing

Introduction

Rate limiting is one of the most fundamental security controls in modern web applications. It protects your APIs from abuse, prevents brute force attacks, and ensures fair resource allocation among users. However, as with many security mechanisms, implementation details matter—a lot.

The vulnerability we're discussing today affects an Express.js authentication controller that implemented rate limiting but left the door open for determined attackers to bypass these protections entirely. While the vulnerability was classified as medium severity, the potential impact on authentication endpoints could be severe, enabling credential stuffing attacks, account enumeration, and denial of service.

The Vulnerability Explained

What Went Wrong?

The application used the popular express-rate-limit middleware to throttle requests, but it suffered from two critical weaknesses:

  1. IP Rotation Vulnerability: The rate limiter tracked requests by IP address, but attackers could easily rotate through different IPs using proxy networks, VPNs, or botnets, effectively resetting their rate limit counter with each new IP.

  2. Header Manipulation: The application trusted X-Forwarded-For headers without proper validation. This header is commonly used by reverse proxies to pass the original client IP, but it can be trivially spoofed by attackers.

Technical Deep Dive

When you deploy an Express application behind a reverse proxy (like NGINX or a load balancer), the actual client IP is often lost. The proxy adds headers like X-Forwarded-For to preserve this information:

X-Forwarded-For: 203.0.113.45, 198.51.100.67

A naive rate limiter configuration might look like this:

// VULNERABLE CODE
const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 5, // 5 requests per window
  // Trusts X-Forwarded-For without validation
  standardHeaders: true,
  legacyHeaders: false,
});

app.use('/api/auth/login', limiter, authController.login);

How Could It Be Exploited?

Scenario 1: Header Spoofing Attack

An attacker can send requests with forged X-Forwarded-For headers:

# Request 1
curl -H "X-Forwarded-For: 192.168.1.1" https://api.example.com/auth/login

# Request 2 (bypasses rate limit)
curl -H "X-Forwarded-For: 192.168.1.2" https://api.example.com/auth/login

# Request 3 (bypasses rate limit)
curl -H "X-Forwarded-For: 192.168.1.3" https://api.example.com/auth/login

Each request appears to come from a different IP, bypassing the rate limiter entirely.

Scenario 2: Distributed Attack via Proxy Networks

Attackers can route requests through:
- Residential proxy networks: Services that route traffic through thousands of legitimate residential IPs
- VPN networks: Rotating through different VPN exit nodes
- Botnets: Using compromised devices distributed across the internet
- Cloud infrastructure: Spinning up multiple cloud instances with different IPs

Real-World Impact

This vulnerability enables several dangerous attack vectors:

  1. Credential Stuffing: Attackers can test millions of username/password combinations from data breaches without being throttled
  2. Account Enumeration: Bypassing rate limits allows attackers to discover valid usernames by testing different accounts
  3. Brute Force Attacks: Password guessing attacks become feasible when rate limits can be circumvented
  4. Resource Exhaustion: Unlimited requests can overwhelm backend services and databases
  5. API Abuse: Scraping, data harvesting, or other automated abuse becomes trivial

Attack Scenario Example

Imagine an e-commerce platform with this vulnerability on its login endpoint:

1. Attacker obtains 10 million email/password pairs from a data breach
2. They use a residential proxy network with 100,000 unique IPs
3. Rate limiter allows 5 login attempts per 15 minutes per IP
4. Attacker can attempt: 100,000 IPs × 5 attempts = 500,000 login attempts every 15 minutes
5. In 24 hours: 48 million login attempts possible
6. Result: Thousands of compromised accounts, potential data breach

The Fix

Implementing Robust Rate Limiting

The proper fix involves multiple layers of defense:

1. Configure Trust Proxy Correctly

// SECURE CODE
const express = require('express');
const app = express();

// Only trust proxy headers from known proxy servers
app.set('trust proxy', ['loopback', 'linklocal', '172.31.0.0/16']);
// Or specify exact proxy IP
// app.set('trust proxy', '172.31.0.1');

2. Use Multiple Rate Limiting Keys

const rateLimit = require('express-rate-limit');

// Combine IP-based and user-based rate limiting
const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 5,
  standardHeaders: true,
  legacyHeaders: false,

  // Custom key generator for better tracking
  keyGenerator: (req) => {
    // Use the rightmost trusted IP from X-Forwarded-For
    return req.ip;
  },

  // Custom handler for rate limit exceeded
  handler: (req, res) => {
    res.status(429).json({
      error: 'Too many login attempts. Please try again later.',
      retryAfter: req.rateLimit.resetTime
    });
  }
});

// Additional user-specific rate limiting
const userLimiter = rateLimit({
  windowMs: 60 * 60 * 1000, // 1 hour
  max: 10,
  keyGenerator: (req) => {
    // Rate limit by username/email
    return req.body.email || req.body.username || req.ip;
  },
  skipSuccessfulRequests: true // Only count failed attempts
});

app.use('/api/auth/login', loginLimiter, userLimiter, authController.login);

3. Implement Additional Security Layers

const { RateLimiterMemory, RateLimiterRedis } = require('rate-limiter-flexible');

// More sophisticated rate limiting with Redis
const rateLimiter = new RateLimiterRedis({
  storeClient: redisClient,
  points: 5, // Number of points
  duration: 900, // Per 15 minutes
  blockDuration: 900, // Block for 15 minutes if exceeded

  // Track by multiple factors
  keyPrefix: 'login_attempt',
});

const rateLimitMiddleware = async (req, res, next) => {
  try {
    // Combine IP and user identifier
    const key = `${req.ip}_${req.body.email || 'anonymous'}`;

    await rateLimiter.consume(key);
    next();
  } catch (rejRes) {
    res.status(429).json({
      error: 'Too many requests',
      retryAfter: Math.ceil(rejRes.msBeforeNext / 1000)
    });
  }
};

4. Add CAPTCHA for Suspicious Activity

const suspiciousActivityDetector = async (req, res, next) => {
  const failedAttempts = await getFailedLoginAttempts(req.ip);

  if (failedAttempts > 3 && !req.body.captchaToken) {
    return res.status(400).json({
      error: 'CAPTCHA verification required',
      requiresCaptcha: true
    });
  }

  if (req.body.captchaToken) {
    const isValid = await verifyCaptcha(req.body.captchaToken);
    if (!isValid) {
      return res.status(400).json({ error: 'Invalid CAPTCHA' });
    }
  }

  next();
};

How This Solves the Problem

The comprehensive fix addresses the vulnerability through:

  1. Proper Proxy Configuration: Only trusts proxy headers from verified sources
  2. Multi-Factor Rate Limiting: Tracks both IP addresses and user identifiers
  3. Distributed Storage: Uses Redis for rate limiting across multiple application instances
  4. Progressive Challenges: Introduces CAPTCHA after detecting suspicious patterns
  5. Granular Control: Different limits for different scenarios (per-IP, per-user, per-endpoint)

Conclusion

Rate limiting is a critical security control, but its effectiveness depends entirely on proper implementation. As this vulnerability demonstrates, a rate limiter that can be easily bypassed provides a false sense of security—perhaps worse than having no rate limiting at all.

The key takeaways:

  1. Never trust client-provided headers without proper validation and proxy configuration
  2. Implement multiple layers of protection rather than relying on a single mechanism
  3. Use distributed rate limiting for applications running across multiple instances
  4. Monitor and test your rate limiting implementation regularly
  5. Consider the full attack surface, including IP rotation, header manipulation, and distributed attacks

Security is not a checkbox—it's an ongoing process of identifying weaknesses, implementing defenses, and continuously improving. By understanding vulnerabilities like this one and implementing robust fixes, we build more resilient applications that protect both our users and our infrastructure.

Remember: in security, the details matter. A small configuration oversight can undermine an entire security mechanism. Stay vigilant, test thoroughly, and always assume attackers will try to bypass your defenses.

Stay secure, and happy coding!


Have you encountered rate limiting bypass attempts in your applications? Share your experiences and solutions in the comments below.

Prevention and further reading

Related Articles

medium

path-to-regexp 0.1.12 DoS: Catastrophic Backtracking on Malformed URL

path-to-regexp version 0.1.12 contains a regular expression engine vulnerability where maliciously crafted URL parameters trigger exponential backtracking, causing CPU exhaustion and service unavailability. Upgrading to version 0.1.13 eliminates the vulnerable pattern from the parsing logic.

critical

CVE-2026-59873: node-tar 7.5.11 DoS via Crafted Gzip Bomb

node-tar versions 7.5.11 through 7.5.18 are vulnerable to a denial-of-service attack through maliciously crafted gzip archives that decompress to disproportionately large sizes. An attacker can exploit this to exhaust memory and CPU resources by submitting a small, highly compressed archive that expands beyond configured limits during extraction.

high

MapManager.get() Race Condition Duplicates API Requests

The MapManager's `get(mapUid, cache)` method used a check-then-act pattern that permitted multiple concurrent requests to pass the cache miss check simultaneously, triggering redundant API calls and risking cache corruption. The fix introduces a `_pending` promise map to deduplicate in-flight fetches for identical map UIDs.

critical

Lampa Desktop Auto-Update Heuristic Bypass: Execution of Unverified

Lampa Desktop's auto-update mechanism downloaded JavaScript and CSS from `raw.githubusercontent.com` using only heuristic validation—file size thresholds and string pattern matching—that attackers could trivially satisfy. The fix introduces cryptographic integrity verification by cross-referencing Git blob hashes from the GitHub Contents API, ensuring downloaded code matches the repository's authoritative state before execution.

high

adm-zip 0.6.0 Preserves SUID Bits From ZIPs: CVE-2026-102282

The `adm-zip` dependency resolved to 0.6.0 in this project's dependency tree, a version affected by CVE-2026-102282: during extraction it applies the Unix permission bits stored in each ZIP entry's external file attributes verbatim, including the setuid (`04000`), setgid (`02000`), and sticky bits. An attacker who controls an archive passed to `extractAllTo()` or `extractEntryTo()` can therefore have the extractor create a setuid binary owned by whatever user the extraction process runs as. The

high

requestInput() Type Confusion: NaN and Object Bypass in JavaScript

The `requestInput()` utility function lacked validation on its `type` parameter and failed to handle `NaN` results from float conversions, creating a type confusion weakness. An attacker could supply malformed inputs that propagate unhandled `NaN` values or unexpected object types through the type system. The fix adds explicit guards against `NaN` type parameters and rejects non-primitive type values.