URL and Input Validation for SSRF Prevention
What you'll learn: How to validate and sanitize user-provided URLs to prevent attackers from exploiting your application to make unauthorized internal requests.
Why URL Validation Matters
Imagine you're a security guard at a corporate office. An attacker tries to trick you into delivering messages to restricted floors by giving you fake addresses. Without a strict checklist of allowed destinations, you might accidentally help them reach areas they shouldn't access. URL validation works the same way—it ensures your application only makes requests to safe, intended destinations.
The Core Defense: Allowlisting
Never trust user-supplied URLs directly. Instead, implement strict allowlists:
- Protocol allowlist: Only permit safe schemes like
https://andhttp://. Blockfile://,gopher://,dict://, and other dangerous protocols. - Domain allowlist: Maintain an explicit list of approved external domains your application should contact (e.g.,
api.trusted-partner.com). - IP range blocklist: Reject private IP ranges (
127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16) and cloud metadata endpoints (169.254.169.254).
Validation Steps
- Parse the URL using a reliable library to extract protocol, host, and path
- Check protocol against your allowlist
- Resolve the hostname to an IP address
- Validate the IP isn't in blocked ranges
- Compare domain against your allowlist
- Sanitize special characters that might bypass filters
Why This Matters
Without validation, an attacker can supply URLs like http://localhost:8080/admin or http://169.254.169.254/latest/meta-data/ to access internal systems through your application. Validation creates a controlled boundary around what external resources your application can reach.
Key Takeaway: Always validate URLs using allowlists for protocols and domains, resolve and check IP addresses against blocked ranges, and never trust user input before making outbound requests—validation is your first line of defense against SSRF attacks.