Validate, whitelist, and isolate any user‑supplied URL before the server fetches it. Combine input sanitization with network‑level egress controls to eliminate SSRF.
Remediation steps
1. Reject non‑HTTP/HTTPS schemes – allow only http and https.
2. Parse and normalize the URL with urllib.parse.urlparse; reject if netloc is empty.
3. Whitelist domains/IPs – compare netloc against a static allow‑list (e.g., example.com, api.trusted.io).
4. Enforce DNS resolution limits – resolve the host with socket.getaddrinfo and ensure the returned IP is in the whitelist or private‑range blocklist.
5. Make the request with strict timeouts and redirects disabled.
import socket, urllib.parse, requests
def safe_fetch(user_url, whitelist):
parsed = urllib.parse.urlparse(user_url)
if parsed.scheme not in ("http", "https") or not parsed.netloc:
raise ValueError("Invalid scheme or host")
host = parsed.hostname
# DNS resolution check
for family, _, _, _, sockaddr in socket.getaddrinfo(host, None):
ip = sockaddr[0]
if ip.startswith(("10.", "172.", "192.168.", "fd00::")):
raise ValueError("Private IP not allowed")
if ip not in whitelist:
raise ValueError("Host not whitelisted")
resp = requests.get(user_url, timeout=3, allow_redirects=False)
return resp.content6. Network‑level egress filtering – configure a firewall or cloud security group to allow outbound traffic only to the whitelisted IP ranges (e.g., AWS Security Group rule Destination: 203.0.113.0/24 on port 80/443).
7. Log and monitor every outbound request, flagging any attempt to reach non‑whitelisted hosts.
Technique comparison
| Technique | Pros | Cons |
|--------------------------|-----------------------------------|--------------------------|
| Input validation only | Easy to add | Bypassed by DNS rebinding|
| Network egress controls | Guarantees isolation | Requires infra changes |
| Sandbox/sidecar fetcher | Full containment | Higher latency, complexity|
Gotcha: DNS rebinding can make a whitelisted domain resolve to an internal IP after the initial check; always re‑resolve or enforce IP allow‑list at the firewall level.