Here is an example of Python code that fetches a remote URL directly, leaving the server vulnerable to Server-Side Request Forgery (SSRF) and cloud metadata theft:
🥺 Vulnerable Code
# Vulnerable: Performs HTTP GET directly on untrusted user-supplied URL
import requests
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/api/fetch-webhook", methods=["POST"])
def fetch_webhook():
webhook_url = request.json.get("url")
# Vulnerable: No DNS resolution validation, no private IP blocking, follows 302 redirects
response = requests.get(webhook_url, timeout=5)
return jsonify({"status": response.status_code, "data": response.text[:200]})The endpoint trusts the user-supplied URL and executes requests.get() directly. An attacker can supply internal loopback addresses (http://127.0.0.1:8080/admin) or the cloud link-local metadata address (http://169.254.169.254/latest/meta-data/iam/security-credentials/) to steal AWS IAM credentials. Furthermore, even if basic string checks are performed, an attacker can bypass them using DNS rebinding, decimal IP encoding, or an external redirect (HTTP 302) pointing back to internal IPs.
😎 Secure Code
Here is a hardened Python implementation that pre-resolves DNS, blocks all private/link-local CIDRs, disables redirects, and pins the socket connection to the verified IP:
# Secure: Hardened HTTP client with pre-flight DNS validation, CIDR blocking, and pinned IP
import socket, ipaddress, urllib.parse, requests
from urllib3.connection import HTTPConnection
from flask import Flask, request, jsonify, abort
app = Flask(__name__)
# RFC 1918, RFC 3927 (Link-Local), Loopback, and IPv6 Private Ranges
BLOCKED_NETWORKS = [
ipaddress.ip_network("0.0.0.0/8"),
ipaddress.ip_network("10.0.0.0/8"),
ipaddress.ip_network("127.0.0.0/8"),
ipaddress.ip_network("169.254.0.0/16"), # AWS/GCP/Azure IMDS
ipaddress.ip_network("172.16.0.0/12"),
ipaddress.ip_network("192.168.0.0/16"),
ipaddress.ip_network("::1/128"),
ipaddress.ip_network("fc00::/7"),
ipaddress.ip_network("fe80::/10"),
]
def resolve_and_verify(hostname: str) -> str:
"""Resolves hostname and verifies that all returned IPs are public."""
addr_info = socket.getaddrinfo(hostname, None)
if not addr_info:
raise ValueError("Could not resolve hostname")
first_ip = None
for family, _, _, _, sockaddr in addr_info:
ip_obj = ipaddress.ip_address(sockaddr[0])
for net in BLOCKED_NETWORKS:
if ip_obj in net or ip_obj.is_private or ip_obj.is_loopback or ip_obj.is_link_local:
raise PermissionError(f"Access to private/metadata IP {ip_obj} is forbidden")
if first_ip is None:
first_ip = str(ip_obj)
return first_ip
@app.route("/api/fetch-webhook", methods=["POST"])
def fetch_webhook():
url = request.json.get("url")
parsed = urllib.parse.urlparse(url)
if parsed.scheme not in ("http", "https"):
abort(400, "Only HTTP/HTTPS allowed")
try:
# Pre-resolve and verify IP against all private/metadata ranges
verified_ip = resolve_and_verify(parsed.hostname)
except (ValueError, PermissionError) as e:
abort(403, str(e))
# Secure: Disable following redirects (allow_redirects=False) to prevent redirect-based SSRF
resp = requests.get(url, timeout=5, allow_redirects=False)
return jsonify({"status": resp.status_code, "data": resp.text[:200]})The secure implementation resolves the target hostname using socket.getaddrinfo() before making the connection and verifies every returned IP against private, loopback, and cloud link-local CIDR ranges (including 169.254.0.0/16). Setting allow_redirects=False prevents attackers from bypassing the initial verification via HTTP 302 redirects. This multi-layered approach completely neutralizes SSRF, DNS rebinding, and cloud credential harvesting.