SSRF allows an attacker to force the server to send requests to internal services — AWS metadata, internal APIs, databases.
How SSRF works¶
Vulnerable code¶
@app.post(“/fetch-url”) async def fetch_url(url: str): response = requests.get(url) # Attacker: http://169.254.169.254/ return response.text
Prevention¶
import ipaddress from urllib.parse import urlparse BLOCKED = [ ipaddress.ip_network(‘10.0.0.0/8’), ipaddress.ip_network(‘172.16.0.0/12’), ipaddress.ip_network(‘192.168.0.0/16’), ipaddress.ip_network(‘169.254.0.0/16’), ] def is_safe_url(url: str) -> bool: parsed = urlparse(url) if parsed.scheme not in (‘http’, ‘https’): return False import socket for _, _, _, _, addr in socket.getaddrinfo(parsed.hostname, None): ip = ipaddress.ip_address(addr[0]) if any(ip in net for net in BLOCKED): return False return True
Cloud protection¶
- AWS: IMDSv2 (requires token)
- Network: Egress firewall
- Segmentation: App servers in a separate subnet
Key Takeaway¶
Validate URLs, block private IP ranges, use IMDSv2. SSRF is a gateway into internal infrastructure.