The Anatomy of a Production SSRF Blind Spot

Server-Side Request Forgery (SSRF) remains one of the most insidious vulnerabilities in modern backend architectures. When applications need to fetch remote webhooks, avatars, or previews, engineers frequently implement outbound HTTP clients. A naive implementation typically checks the target URL's hostname or IP address against a blocklist of private IP ranges (like 127.0.0.1, 10.0.0.0/8, or link-local addresses 169.254.169.254) before making the request.

However, production systems frequently fall victim to time-of-check to time-of-use (TOCTOU) flaws, specifically DNS Rebinding and unmonitored HTTP redirect chains. If your validation logic resolves the domain to an IP, verifies it is safe, and then hands the URL string over to an HTTP library (like Axios or Fetch), you have left the door wide open.

The Illusion of Safety: Naive Regex and Single-Point Resolution

Consider a standard backend snippet written in Node.js that attempts to block internal network access:

const { URL } = require('url');
const dns = require('dns').promises;

async function isSafeUrl(targetUrl) {
  const parsed = new URL(targetUrl);
  
  // Check protocol
  if (!['http:', 'https:'].includes(parsed.protocol)) return false;

  // Resolve hostname
  const resolvedIp = await dns.lookup(parsed.hostname);
  
  // Naive private IP check
  if (
    resolvedIp.address.startsWith('127.') || 
    resolvedIp.address.startsWith('10.') ||
    resolvedIp.address === '169.254.169.254'
  ) {
    return false;
  }
  return true;
}

This code suffers from two critical flaws. First, it only checks the first IP returned by dns.lookup and completely ignores IPv6 loopback or unique local addresses. Second, and more dangerously, it introduces a race condition. The attacker controls an authoritative DNS server with a low Time-To-Live (TTL). During the validation phase, the domain resolves to a benign public IP address. But by the time the actual HTTP client fires the TCP handshake milliseconds later, the DNS record has expired. The client re-resolves the domain—and this time, it points straight to 127.0.0.1 or cloud metadata endpoints.

The Danger of Unchecked Redirect Chains

Even if your initial IP check is airtight, HTTP redirects introduce another vector. Suppose your client successfully fetches https://example.com/image.png. If the remote server responds with a 302 Found pointing to http://169.254.169.254/latest/meta-data/, standard HTTP client libraries (like Node's native fetch or axios) will automatically follow the redirect by default.

Unless you explicitly intercept every redirect hop and run your security guardrails against the newly targeted destination URL and its resolved IP, the request will execute against your internal infrastructure.

The Production-Grade Fix: Custom Agents and Socket-Level IP Enforcement

To eliminate DNS rebinding and control redirect behavior, you must bypass high-level string validators and enforce security rules at the transport layer—specifically by intercepting the TCP connection phase using a custom Node.js http.Agent.

By overriding the lookup function inside a custom agent, you can guarantee that the IP address validated is the exact same IP address used to establish the TCP socket connection, completely eliminating the TOCTOU window.

const http = require('http');
const https = require('https');
const net = require('net');
const dns = require('dns');

function isPrivateIp(ip) {
  if (net.isIPv4(ip)) {
    // Check standard private ranges
    if (ip.startsWith('127.') || ip.startsWith('10.') || ip.startsWith('192.168.')) {
      return true;
    }
    // Check AWS/Cloud metadata IP
    if (ip === '169.254.169.254') {
      return true;
    }
    // Check 172.16.0.0/12 range
    const parts = ip.split('.').map(Number);
    if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) {
      return true;
    }
  } else if (net.isIPv6(ip)) {
    if (ip === '::1' || ip.toLowerCase().startsWith('fc00:') || ip.toLowerCase().startsWith('fe80:')) {
      return true;
    }
  }
  return false;
}

class SecureAgent extends http.Agent {
  constructor(options) {
    super(options);
  }

  createConnection(options, callback) {
    // Intercept DNS lookup during socket creation
    dns.lookup(options.hostname, { all: false }, (err, address, family) => {
      if (err) return callback(err);

      if (isPrivateIp(address)) {
        return callback(new Error(`Blocked SSRF attempt: Resolved to private IP ${address}`));
      }

      // Force the socket to connect directly to the validated IP, bypassing re-resolution
      options.host = address;
      super.createConnection(options, callback);
    });
  }
}

const secureAgent = new SecureAgent();
// Use this agent in your HTTP client configuration and disable automatic redirects

Key Takeaways

  • Never Trust DNS Resolution Timings: A domain that resolves to a public IP during validation can point to an internal network address seconds later via DNS rebinding.
  • Enforce Socket-Level Validation: Use custom network agents to validate and bind the exact IP address used in the TCP handshake.
  • Disable Automatic Redirects: Manually handle HTTP redirect status codes (3xx) so every downstream hop undergoes rigorous security inspection.
  • Cover IPv6 and Metadata Endpoints: Always account for IPv6 loopback addresses and link-local cloud metadata IPs (169.254.169.254).