Web Security

SSRF Prevention Guide

8 min read

Server-Side Request Forgery (SSRF) tricks servers into making requests to unintended locations, often targeting internal services or cloud metadata endpoints.

SSRF Targets

Attack Example

# Vulnerable endpoint
GET /fetch?url=http://example.com/image.jpg

# SSRF attack - AWS metadata
GET /fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/

# SSRF attack - Internal service
GET /fetch?url=http://localhost:8080/admin

Prevention

# Python - URL validation
from urllib.parse import urlparse
import ipaddress

def is_safe_url(url):
    parsed = urlparse(url)
    
    # Only allow HTTPS
    if parsed.scheme != 'https':
        return False
    
    # Block internal IPs
    try:
        ip = ipaddress.ip_address(parsed.hostname)
        if ip.is_private or ip.is_loopback:
            return False
    except ValueError:
        pass  # Hostname, not IP
    
    # Allowlist domains
    allowed_domains = ['trusted.com', 'api.example.com']
    if parsed.hostname not in allowed_domains:
        return False
    
    return True
Cloud Risk

SSRF to cloud metadata endpoints (AWS, GCP, Azure) can expose IAM credentials that lead to full cloud account takeover.

Defense Checklist

December 2024