Course contentsShow
← Security
Lesson 897 of 3,05218. Web Security - CSRF and Request ForgeryFree lesson

DNS Rebinding and TOCTOU Protections

Resolve URLs once and validate IP before connection; prevent attackers from exploiting DNS resolution timing to bypass filters.

DNS Rebinding and TOCTOU Protections

You'll learn how to prevent attackers from exploiting the timing gap between DNS lookups and actual connections to bypass SSRF filters.

The Problem: Time-of-Check vs Time-of-Use

Imagine a security guard who checks your ID at the gate but doesn't follow you into the building. You could hand your ID to someone else after the check! DNS rebinding exploits a similar timing gap.

When your application fetches a URL:

  1. Time-of-Check: DNS resolves evil.com to a safe IP like 203.0.113.5
  2. Your SSRF filter validates this IP and approves the request
  3. Time-of-Use: The attacker rapidly changes evil.com's DNS to point to 127.0.0.1
  4. Your application connects to localhost instead of the validated IP

This Time-of-Check, Time-of-Use (TOCTOU) race condition bypasses your IP-based filters completely.

The Defense: Resolve Once, Validate Once, Connect Once

The key protection is eliminating the timing gap:

  1. Resolve the URL to an IP address first
  2. Validate that resolved IP against your whitelist/blacklist
  3. Connect directly to that validated IP, not the hostname

Never re-resolve the DNS between validation and connection. Think of it like checking an ID and then escorting the person yourself — no opportunity for a switch.

Additional Hardening

  • Cache DNS results for the duration of the request
  • Set minimum DNS TTL values to prevent rapid changes
  • Use IP addresses directly when possible instead of hostnames
  • Monitor for suspiciously low DNS TTL values (under 60 seconds)

Key Takeaway: Prevent DNS rebinding by resolving hostnames once, validating the resulting IP address, and connecting directly to that validated IP without re-resolving — eliminating the TOCTOU window attackers exploit.