SSRF: Allow-Lists and Cloud Metadata
Many applications fetch URLs on the user's behalf: link previews, "import from URL", webhooks, PDF renderers that load images, avatar uploads by URL. The fetch happens from the server, which usually sits inside a network the user can't reach: admin panels on internal hosts, databases, other microservices, and in the cloud a metadata service at 169.254.169.254 that hands out the server's own credentials. If the application fetches whatever URL it is given, the attacker borrows the server's network position. That is server-side request forgery (SSRF, CWE-918). It had its own category in the OWASP Top 10 2021; the 2025 edition folds it into A01 Broken Access Control, and the API Security Top 10 2023 lists it as API7. This lesson builds a vulnerable link-preview service in your sandbox, with a fake internal admin service and a fake metadata service, all on 127.0.0.1, then fixes it with an allow-list and safe redirect handling.
Definitions
- SSRF: making a server send a request to a destination the attacker chooses. Basic SSRF returns the response to the attacker; blind SSRF only triggers the request (detectable by timing or by a callback to a listener the tester controls).
- Cloud instance metadata service (IMDS): a link-local HTTP service (
169.254.169.254on AWS, Azure, GCP and others) that returns instance information and temporary credentials for the instance's role. AWS IMDSv2 requires a session token obtained with aPUTrequest and a custom header, which plain SSRF through aGETcan't do; GCP and Azure require aMetadata-Flavor: Google/Metadata: trueheader. - Allow-list vs deny-list: allow-lists name the destinations that are permitted; deny-lists try to name the dangerous ones (private ranges, loopback, link-local) and are notoriously bypassable.
- Bypass tricks for deny-lists: other spellings of an address (
127.1,2130706433,0x7f000001,[::ffff:127.0.0.1]), DNS names that resolve to internal addresses, DNS rebinding (the name resolves differently at check time and fetch time), and redirects from an allowed host to an internal one.
A link-preview service, attacked and fixed
Four servers run in the sandbox, all on loopback: the preview app on port 8000, a "partner" content server on 9100 (the only legitimate destination), a fake internal admin service on 9001 and a fake metadata service on 9002 that returns lab credentials (clearly fake; real IMDS paths are mimicked so the request pattern is recognisable). The vulnerable app fetches any url parameter and follows redirects; the fixed one accepts only the partner's exact scheme, host and port and doesn't follow redirects.
cat > servers.py <<'PY'
import json, sys, threading
from wsgiref.simple_server import make_server, WSGIRequestHandler
class Quiet(WSGIRequestHandler):
def log_message(self, *args):
pass
def internal_admin(environ, sr):
sr("200 OK", [("Content-Type", "text/plain")]); return [b"INTERNAL ADMIN: 3 users, delete button here\n"]
def metadata(environ, sr):
if environ["PATH_INFO"] == "/latest/meta-data/iam/security-credentials/lab-role":
sr("200 OK", [("Content-Type", "application/json")])
return [json.dumps({"AccessKeyId": "LAB-NOT-A-REAL-KEY", "SecretAccessKey": "lab-fake-secret"}).encode() + b"\n"]
sr("200 OK", [("Content-Type", "text/plain")]); return [b"iam/\n"]
def partner(environ, sr):
if environ["PATH_INFO"] == "/redirect":
sr("302 Found", [("Location", "http://127.0.0.1:9002/latest/meta-data/iam/security-credentials/lab-role")])
return [b""]
sr("200 OK", [("Content-Type", "text/plain")]); return [b"<title>Partner article</title>\n"]
for port, app in [(9001, internal_admin), (9002, metadata), (9100, partner)]:
threading.Thread(target=make_server("127.0.0.1", port, app, handler_class=Quiet).serve_forever, daemon=True).start()
threading.Event().wait()
PY
cat > preview.py <<'PY'
import sys, urllib.error, urllib.parse, urllib.request
from wsgiref.simple_server import make_server, WSGIRequestHandler
FIXED = sys.argv[1] == "fixed"
ALLOWED = {("http", "127.0.0.1", 9100)} # stands for ("https", "partner.lab.test", 443)
class NoRedirects(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None # a 3xx is returned as an error, not followed
plain = urllib.request.build_opener(urllib.request.ProxyHandler({}))
strict = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirects())
class Quiet(WSGIRequestHandler):
def log_message(self, *args):
pass
def app(environ, start_response):
url = urllib.parse.parse_qs(environ.get("QUERY_STRING", "")).get("url", [""])[0]
with open("egress.log", "a") as log:
log.write(f"preview requested {url}\n")
status, body = "200 OK", ""
try:
if FIXED:
u = urllib.parse.urlsplit(url)
if (u.scheme, u.hostname, u.port) not in ALLOWED:
raise PermissionError("destination not on the allow-list")
body = strict.open(url, timeout=3).read(200).decode()
else:
body = plain.open(url, timeout=3).read(200).decode()
except PermissionError as e:
status, body = "403 Forbidden", f"refused: {e}\n"
except urllib.error.HTTPError as e:
status, body = "502 Bad Gateway", f"upstream answered {e.code}, not followed\n"
except Exception as e:
status, body = "502 Bad Gateway", f"fetch failed ({type(e).__name__})\n"
start_response(status, [("Content-Type", "text/plain")])
return [body.encode()]
make_server("127.0.0.1", 8000, app, handler_class=Quiet).serve_forever()
PY
python3 servers.py &
for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:9100/ && break; sleep 0.1; done
ask() { printf ' %-74s -> ' "$1"; curl -s -G --data-urlencode "url=$1" -w ' [%{http_code}]' http://127.0.0.1:8000/preview | tr -d '\n'; echo; }
for mode in vulnerable fixed; do
: > egress.log
python3 preview.py $mode &
for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8000/ && break; sleep 0.1; done
echo "=== $mode"
ask 'http://127.0.0.1:9100/article'
ask 'http://127.0.0.1:9001/'
ask 'http://127.0.0.1:9002/latest/meta-data/iam/security-credentials/lab-role'
ask 'http://127.0.0.1:9100/redirect'
ask 'file:///etc/hostname'
kill %2; wait %2 2>/dev/null
done
kill %1=== vulnerable
http://127.0.0.1:9100/article -> <title>Partner article</title> [200]
http://127.0.0.1:9001/ -> INTERNAL ADMIN: 3 users, delete button here [200]
http://127.0.0.1:9002/latest/meta-data/iam/security-credentials/lab-role -> {"AccessKeyId": "LAB-NOT-A-REAL-KEY", "SecretAccessKey": "lab-fake-secret"} [200]
http://127.0.0.1:9100/redirect -> {"AccessKeyId": "LAB-NOT-A-REAL-KEY", "SecretAccessKey": "lab-fake-secret"} [200]
file:///etc/hostname -> tad [200]
=== fixed
http://127.0.0.1:9100/article -> <title>Partner article</title> [200]
http://127.0.0.1:9001/ -> refused: destination not on the allow-list [403]
http://127.0.0.1:9002/latest/meta-data/iam/security-credentials/lab-role -> refused: destination not on the allow-list [403]
http://127.0.0.1:9100/redirect -> upstream answered 302, not followed [502]
file:///etc/hostname -> refused: destination not on the allow-list [403]
The vulnerable preview service did everything asked of it: it showed the internal admin page, returned the (fake) metadata credentials, followed the partner's redirect straight into the metadata service, and even read a local file through file://, a scheme urllib supports by default. In a cloud deployment the credentials response alone would hand the attacker the instance role. The fixed service compared the parsed scheme, host and port with the allow-list before connecting, refused everything else with 403, and returned the partner's redirect as an error instead of following it.
When an allow-list isn't possible
Some features must fetch arbitrary public URLs (link previews of any site, webhooks to customer endpoints). Then the defence is a careful deny check on the resolved address, done at connection time, plus network isolation. The check below shows why parsing matters: ipaddress alone can't read legacy forms such as 127.1 or 0x7f000001, which many HTTP clients still accept, so the example normalises them with socket.inet_aton first.
import ipaddress, socket
def resolve_literal(host):
try:
return ipaddress.ip_address(host.strip("[]"))
except ValueError:
pass
try:
return ipaddress.ip_address(socket.inet_aton(host)) # 127.1, 0x7f000001, 2130706433, 0177.0.0.1
except OSError:
return None # a DNS name: resolve it, then check every address
def is_forbidden(addr):
if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped:
addr = addr.ipv4_mapped
return (addr.is_private or addr.is_loopback or addr.is_link_local or addr.is_multicast
or addr.is_reserved or addr.is_unspecified)
for host in ["203.0.113.10", "10.10.0.5", "169.254.169.254", "127.0.0.1", "127.1", "0x7f000001",
"2130706433", "[::1]", "[::ffff:127.0.0.1]", "[fd00::1]", "0.0.0.0", "partner.lab.test"]:
addr = resolve_literal(host)
verdict = "needs DNS, check after resolving" if addr is None else ("BLOCK" if is_forbidden(addr) else "allow")
print(f"{host:22} {str(addr):18} {verdict}")203.0.113.10 203.0.113.10 BLOCK
10.10.0.5 10.10.0.5 BLOCK
169.254.169.254 169.254.169.254 BLOCK
127.0.0.1 127.0.0.1 BLOCK
127.1 127.0.0.1 BLOCK
0x7f000001 127.0.0.1 BLOCK
2130706433 127.0.0.1 BLOCK
[::1] ::1 BLOCK
[::ffff:127.0.0.1] ::ffff:127.0.0.1 BLOCK
[fd00::1] fd00::1 BLOCK
0.0.0.0 0.0.0.0 BLOCK
partner.lab.test None needs DNS, check after resolving
Even 203.0.113.10 is blocked: it is an RFC 5737 documentation address, and Python's is_private follows the IANA special-purpose address registry, which marks the documentation ranges as not globally reachable, so the lab has no address that would pass (a real public address would). Older Python versions classify some of these ranges differently, so pin your own list of forbidden networks rather than relying on one library's flags. Every spelling of loopback is caught once normalised. A DNS name must be resolved, every returned address checked, and the connection made to the checked address (not by resolving the name again, which would allow DNS rebinding). Libraries and egress proxies built for this exist (for example Stripe's Smokescreen); prefer them to hand-written checks.
How SSRF is detected
- Testing (in scope): every parameter that holds a URL, host name or file path (
url=,callback=,webhook=,image=,feed=, XML and SVG uploads, PDF generators): point it at a listener you control in the lab and see whether the server connects; then at loopback, the lab's internal ranges and the metadata address; try alternate spellings, redirects and other schemes (file:,gopher:,dict:). - Egress monitoring (the strongest signal): application servers connecting to
169.254.169.254, to internal admin ports, or to destinations outside their usual set. The sandbox app'segress.logstands for proxy or firewall logs. Cloud providers log metadata-credential use; credentials used from outside the instance are an alarm (AWS GuardDuty'sUnauthorizedAccess:IAMUser/InstanceCredentialExfiltrationfindings,.OutsideAWSand.InsideAWS, exist for exactly this). - Code review: user input reaching
requests.get,urllib.request.urlopen,fetch,HttpClient,curl_exec, image libraries or headless browsers; redirects followed by default.
How it is fixed
- Allow-list destinations by parsed scheme, host and port when the feature permits.
- Otherwise resolve, check every address against private, loopback, link-local and reserved ranges, and connect to the checked address; disable redirects or re-check each hop; allow only
http/https. - Network controls: run fetchers in an isolated network segment or behind an egress proxy that enforces the policy; block the metadata address for workloads that don't need it.
- Harden the metadata service: require IMDSv2 (session tokens, hop limit 1) on AWS; on Kubernetes, block pod access to node metadata.
- Don't return raw responses to the user when a preview only needs a title; blind SSRF is harder to exploit than basic SSRF.
Pitfalls
- Checking the URL string (
if "169.254" in url) instead of the parsed, resolved address. - Checking before redirects and not after: the allowed host can redirect anywhere.
- Forgetting other URL consumers: XML parsers fetching external entities (XXE), SVG and PDF renderers, webhooks, OAuth
jkuheaders (JWT pitfalls).
Practice
1. A deny-list blocks 127.0.0.1 and localhost. Give three inputs that may still reach loopback.
http://127.1/, http://2130706433/ (or 0x7f000001), http://[::ffff:127.0.0.1]/, or a DNS name that resolves to 127.0.0.1. Normalise and resolve, then check the address.
2. Why does requiring IMDSv2 defeat most SSRF against AWS metadata?
IMDSv2 needs a PUT request with a X-aws-ec2-metadata-token-ttl-seconds header to get a session token, then the token in a header on every read. A typical SSRF can only make the server send GETs with attacker-chosen URLs, not custom methods and headers; and a hop limit of 1 stops containers behind the instance from reaching it.
Test yourself
What makes SSRF dangerous?
- It crashes the server
- The attacker borrows the server's network position: internal services and metadata the attacker can't reach directly
- It steals cookies
- It needs JavaScript
In the session, how did the vulnerable app reach the metadata service through the allowed partner?
- By guessing
- It followed the partner's redirect to the metadata URL
- Through a cookie
- Through CORS
Why is if '127.0.0.1' in url a poor SSRF check?
- It is slow
- Loopback has many spellings (127.1, 0x7f000001, ::ffff:127.0.0.1) and DNS names can resolve to it
- It blocks too much
- URLs can't contain IPs
Which monitoring signal is the strongest for SSRF?
- CSP reports
- Egress connections from application servers to metadata or internal addresses they don't normally contact
- 404 counts
- Login failures