What Is SSRF? Server-Side Request Forgery Examples & How to Prevent SSRF Attacks
What is SSRF? See real server-side request forgery examples, a worked lab test, and how to prevent SSRF attacks with allowlists, IMDSv2 and egress controls.
When the Server Becomes Your Proxy
A web app lets you fetch a URL to preview a link. You enter http://169.254.169.254/latest/meta-data/ — the cloud metadata endpoint that should only be accessible from inside the server. The server fetches it and returns your cloud provider's access keys. This is Server-Side Request Forgery (SSRF): the attacker tricks the server into making requests to internal services, cloud metadata, or systems behind firewalls that should never be exposed.
Prerequisites
Before studying SSRF, you should understand:
What Is SSRF?
Server-Side Request Forgery (SSRF) is a web security vulnerability that lets an attacker control the destination of a request your server makes, turning the server into a proxy into its own internal network. The attacker never connects to the internal service directly — the application server does it for them, with all the trust and network access that position carries.
SSRF was added to the OWASP Top 10 in 2021 as A10, after practitioners ranked it first in the community survey even though the underlying data showed a relatively low incidence rate (2.72% across 385 mapped CVEs). In the OWASP Top 10 2025 edition it was folded into A01 Broken Access Control, where it is listed as a notable weakness (CWE-918) — a reclassification that is accurate, because at its heart SSRF is an access-control failure where the network was the only access control. SSRF still matters in 2026 because API-heavy architectures keep adding features that fetch URLs on a user's behalf — webhooks, link previews, image proxies, PDF generators — and every one of them is a potential SSRF sink. In October 2025, Oracle disclosed CVE-2025-61882, a critical SSRF vulnerability in Oracle E-Business Suite versions 12.2.3 through 12.2.14, a reminder that the flaw still shows up in major enterprise software.
How SSRF Works
Applications that fetch remote resources are vulnerable when user input controls the URL. Common functionality includes webhooks, image processing, proxy functionality, API integrations, URL preview generators, PDF generators, and RSS feed parsers. The attack follows a simple flow:
http://127.0.0.1:6379/, http://169.254.169.254/latest/meta-data/, or file:///etc/passwd.The danger comes from implicit trust. Internal services — a Redis instance, an admin panel, a cloud metadata service — assume that any request arriving from inside the network is legitimate, because firewalls block outsiders. SSRF breaks that assumption: the request does arrive from inside, but it was chosen by an outsider.
Basic SSRF Example
import requests
@app.route('/fetch-avatar')
def fetch_avatar():
url = request.args.get('url')
response = requests.get(url)
return response.content
An attacker exploits this to access internal services:
GET /fetch-avatar?url=http://169.254.169.254/latest/meta-data/ HTTP/1.1
Host: vulnerable-app.com
The server dutifully fetches the cloud metadata endpoint and returns the response — including, on an EC2 instance, the IAM credentials attached to that server.
How to Prevent SSRF Attacks
No single control stops SSRF. The OWASP SSRF Prevention Cheat Sheet is blunt about this: deny-lists are bypass-prone, so prefer allow-lists, and layer controls at the application and the network. Work through these seven layers in order.
1. Allowlist Destinations
The strongest defense is also the simplest: do not accept arbitrary URLs at all. If your feature integrates with a known set of services, let the user pick an identifier and build the URL yourself.
ALLOWED_DOMAINS = {'api.trusted-service.com', 'cdn.trusted.com'}
def is_allowed_url(url):
from urllib.parse import urlparse
parsed = urlparse(url)
return parsed.hostname in ALLOWED_DOMAINS
An allowlist fails closed: any destination you did not explicitly approve is blocked by default. A denylist fails open: you must enumerate every private range, every metadata address, every odd IP encoding — and missing one creates a bypass.
2. Validate the Resolved IP and Pin It
When any URL must be allowed, do not trust the hostname string. Resolve the hostname, validate the IP address it resolves to, and then connect to that validated IP — not to the hostname again. Validation and fetching must use the same resolved address, or DNS rebinding defeats the check: the attacker registers a domain that first resolves to a safe IP (passing validation) and then, seconds later, resolves to 169.254.169.254 when the server actually fetches the URL.
import socket
from urllib.parse import urlparse
BLOCKED = [
'127.0.0.0/8', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16',
'169.254.0.0/16', '::1/128', 'fc00::/7', 'fe80::/10',
]
def resolve_and_validate(url):
host = urlparse(url).hostname
ip = socket.getaddrinfo(host, None)[0][4][0]
# Reject the IP if it falls inside any blocked range, then
# connect to the validated IP directly so a later DNS
# change cannot redirect the request.
return ip
Validate IPv4 and IPv6 addresses, including IPv4-mapped IPv6 forms such as ::ffff:127.0.0.1. Reject private, loopback, link-local, and reserved ranges, and reject the cloud metadata addresses explicitly.
3. Disable Redirects or Re-validate Each One
An attacker can pass validation with a safe URL that redirects (HTTP 301/302) to an internal IP. Disable automatic redirect following in your HTTP library, or re-validate the URL after every redirect against the same allowlist and resolved-IP checks. This is the single most commonly missed SSRF control: the initial URL is checked, the redirect target is not.
response = requests.get(url, allow_redirects=False)
if response.status_code in (301, 302, 307, 308):
target = response.headers['Location']
# Re-run the full validation on the redirect target
# before following it.
4. Restrict URL Schemes
Most applications only need http and https. Block everything else — file:// (local file reads such as /etc/passwd), gopher:// (talking raw protocols to internal services), dict://, ftp://, and smb:// — at the input-validation layer, before any request is made.
from urllib.parse import urlparse
ALLOWED_SCHEMES = {'https'}
def safe_fetch(url):
parsed = urlparse(url)
if parsed.scheme not in ALLOWED_SCHEMES:
raise ValueError("Scheme not allowed")
return requests.get(url, allow_redirects=False)
5. Restrict Egress at the Network Layer
Code-level checks can have bugs, so the network should also refuse to let the application reach places it never needs. Put outbound-fetching services in a separate network segment or behind an egress proxy with deny-by-default rules, and log allowed and blocked flows.
# Only root may reach the metadata service; the app runs as www-data
sudo iptables -A OUTPUT -d 169.254.169.254 -m owner --uid-owner www-data -j REJECT
sudo iptables -A OUTPUT -d 127.0.0.0/8 -j DROP
sudo iptables -A OUTPUT -d 10.0.0.0/8 -j DROP
sudo iptables -A OUTPUT -d 172.16.0.0/12 -j DROP
sudo iptables -A OUTPUT -d 192.168.0.0/16 -j DROP
In Kubernetes, an egress NetworkPolicy can restrict the pod to the proxy and the services it truly needs.
6. Harden Cloud Metadata
On AWS, require IMDSv2: it forces a session token obtained with a PUT request and a special header before metadata can be read, so a basic SSRF that can only make simple GET requests cannot steal credentials. Set the response hop limit to 1 so the token cannot be used through an extra network hop, such as from a container.
# Require IMDSv2 on an existing instance
aws ec2 modify-instance-metadata-options \
--instance-id i-0123456789abcdef0 \
--http-tokens required \
--http-put-response-hop-limit 1
As of November 2026, IMDSv2-only is the default for Amazon Linux 2023, for console Quick Start launches since November 2023, and for EC2 instance types released since mid-2024. GCP requires the Metadata-Flavor: Google header for its metadata service, and Azure requires the Metadata: true header — both stop the simplest metadata probes, but neither replaces allowlisting and egress controls.
7. Shrink the IAM Role and Monitor
Limit the blast radius when earlier layers fail: give the fetching service the smallest IAM role it needs, use Pod Identity or IRSA in EKS, and monitor outbound traffic. Log every outbound request — especially blocked ones — and alert on requests to metadata or internal ranges. Do not return raw upstream responses to the user: that turns a full-read SSRF into a blind one, which is still dangerous but leaks less.
Worked Example: Testing SSRF in a Local Lab
Build the lab on your own machine. You need a vulnerable app and an internal service — both on 127.0.0.1, both yours. Never point these payloads at a real application you do not own.
Create a tiny vulnerable Flask app that fetches a user-supplied URL, and a second service listening on port 6379 that stands in for an internal service:
# vulnerable_app.py — a deliberately vulnerable avatar fetcher
from flask import Flask, request
import requests
app = Flask(__name__)
@app.route('/fetch-avatar')
def fetch_avatar():
url = request.args.get('url')
response = requests.get(url, timeout=5)
return response.content, response.status_code
app.run(host='127.0.0.1', port=5000)
# Terminal 1: start the vulnerable app
python3 vulnerable_app.py
# Terminal 2: start a fake internal service on 6379
python3 -m http.server 6379 --bind 127.0.0.1
Step 1 — confirm the feature works normally:
curl "http://127.0.0.1:5000/fetch-avatar?url=http://example.com/logo.png"
Step 2 — probe the loopback interface. If the app returns the internal service's response, the SSRF is confirmed:
curl "http://127.0.0.1:5000/fetch-avatar?url=http://127.0.0.1:6379/"
Step 3 — probe the cloud metadata address. On your laptop there is no metadata service, so you will get a connection error — but on a cloud VM this same request returns IAM credentials:
curl "http://127.0.0.1:5000/fetch-avatar?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/"
Step 4 — confirm a blind SSRF with a callback. Start a listener, then ask the app to fetch a URL pointing at it. A connection on your listener proves the server made the request, even when the response is never shown to you:
# Terminal 3: start a listener
nc -lvnp 4444
# Terminal 4: trigger the callback
curl "http://127.0.0.1:5000/fetch-avatar?url=http://127.0.0.1:4444/ping"
All outputs above are illustrative — your exact responses depend on your local setup. The pattern is what matters: normal fetch, loopback probe, metadata probe, blind confirmation. For guided practice, use the PortSwigger Web Security Academy SSRF labs or OWASP Juice Shop, which are built for exactly this.
Types of SSRF
Basic SSRF
The application fetches from user-controlled URLs without restrictions, and returns the response to the attacker. This is the most damaging form: the attacker reads internal services and cloud metadata directly.
Blind SSRF
The attacker cannot see the response but can observe side effects like timing differences, DNS lookups, or HTTP callbacks to a listener they control. Detection is harder because there is no direct data exfiltration, but attackers can still trigger internal requests, cause denial of service, or use out-of-band techniques to extract information.
Partial SSRF
Some validation exists but is insufficient — attackers use protocol confusion, URL parsing tricks, or redirect chains to slip past it. Partial SSRF is the most common form in real applications, because most apps have some validation; it is just not complete.
SSRF Attack Vectors
Cloud Metadata Endpoints
# AWS metadata
http://169.254.169.254/latest/meta-data/
http://169.254.169.254/latest/meta-data/iam/security-credentials/
# GCP metadata (needs the Metadata-Flavor: Google header)
http://metadata.google.internal/computeMetadata/v1/
# Azure metadata (needs the Metadata: true header)
http://169.254.169.254/metadata/instance?api-version=2021-02-01
Cloud metadata endpoints are the most valuable SSRF target: they return temporary IAM credentials to anything that asks from inside the instance. The widely reported 2019 Capital One breach involved an SSRF-style request to the EC2 instance metadata service to obtain credentials — one reason AWS introduced IMDSv2.
Internal Service Access
http://localhost:6379/ # Redis
http://localhost:9200/ # Elasticsearch
http://localhost:27017/ # MongoDB
http://localhost:8080/admin # Internal admin panel
Internal services assume that traffic from inside the network is legitimate. SSRF hands the attacker that trusted position, letting them reach admin panels, databases, and message queues that no firewall would ever expose to the internet.
File Protocol Access
file:///etc/passwd
file:///proc/self/environ
file:///app/config/database.yml
When the server-side fetcher supports file://, SSRF becomes local file read. The fix is scheme restriction: only http and https should ever be fetchable.
Port Scanning Through SSRF
An attacker can sweep internal ports by watching response timing and error messages: an open port answers quickly, a closed port refuses the connection, a filtered port times out. Blind SSRF still leaks this information through timing alone.
DNS Rebinding
DNS rebinding switches a domain's DNS resolution from a safe IP to a malicious one after hostname validation passes. An attacker registers a domain that first resolves to a safe IP (passing validation), then changes to 169.254.169.254 when the server fetches the URL. This bypasses hostname-based allowlists because validation and fetching happen at different times — which is why you must validate the resolved IP and connect to that pinned address.
SSRF Bypass Techniques
Every bypass below has a defense. The point of studying them is to see why shallow validation fails.
| Bypass | Example | Why a string check misses it | Defense that stops it |
|---|---|---|---|
| Decimal IP encoding | http://2130706433/ | 2130706433 is 127.0.0.1 as a decimal number | Validate the resolved IP, not the string |
| Hex IP encoding | http://0x7f.0.0.1/ | Hex form of 127.0.0.1 | Validate the resolved IP, not the string |
| Octal IP encoding | http://0177.0.0.1/ | Octal form of 127.0.0.1 | Validate the resolved IP, not the string |
| IPv6 loopback | http://[::1]/ | A different spelling of localhost | Validate IPv6 and IPv4-mapped forms too |
| IPv4-mapped IPv6 | http://[::ffff:127.0.0.1]/ | Looks like IPv6, resolves to 127.0.0.1 | Normalize and validate the resolved address |
| Short forms | http://0.0.0.0/, http://127.1/ | Parsers accept abbreviated IPs | Validate the resolved IP, not the string |
| User-info trick | http://trusted.com@169.254.169.254/ | The real host is after the @ | Parse the URL properly; never split on strings |
| Redirect chain | Safe URL → 302 → http://169.254.169.254/ | The first URL passes validation | Re-validate every redirect target |
| DNS rebinding | Domain resolves safe, then internal | Validation and fetch see different IPs | Pin the validated resolved IP |
| URL parser differentials | http://127.0.0.1%09@example.com/ | Two parsers read the same URL differently | Use one parser; validate after parsing |
| Open-redirect chaining | Your own /redirect?url=... endpoint | A trusted endpoint forwards to an internal host | Validate the final destination, not the first hop |
Preventing SSRF in Your Language
The controls are the same in every stack; only the APIs differ. In every case: allowlist where possible, validate the resolved IP, disable redirects or re-validate them, and restrict schemes.
Python
import socket
from urllib.parse import urlparse
import requests
def safe_get(url, allowed_hosts):
parsed = urlparse(url)
if parsed.scheme != 'https':
raise ValueError('Only https is allowed')
if parsed.hostname not in allowed_hosts:
raise ValueError('Host not allowlisted')
ip = socket.getaddrinfo(parsed.hostname, 443)[0][4][0]
# Check the resolved IP against your blocked ranges here,
# then fetch with redirects disabled.
return requests.get(url, allow_redirects=False, timeout=5)
Node.js
Use undici or the built-in http/https modules with a custom lookup that resolves the hostname first and validates the address before connecting. Disable redirect following (or re-validate each redirect target) and reject any scheme other than http/https. If your fetcher accepts a lookup option, validate inside it; otherwise resolve with dns.lookup and connect to the validated IP.
Java
Use HttpClient with redirects set to NEVER, resolve the hostname with InetAddress.getByName, check the resolved address against your blocked ranges, and only then build the request. For older code using HttpURLConnection, call setInstanceFollowRedirects(false) and validate each Location header manually.
C#
Use HttpClient with an HttpClientHandler that sets AllowAutoRedirect to false. Resolve the host with Dns.GetHostAddresses, validate every returned address against your blocked ranges, and reject schemes other than http/https before sending.
PHP
Use parse_url to extract the host, filter_var with FILTER_VALIDATE_URL as a first pass, gethostbyname to resolve the host, and filter_var with FILTER_VALIDATE_IP plus FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE to reject private and reserved addresses. Disable redirects in cURL with CURLOPT_FOLLOWLOCATION => false.
SSRF vs CSRF vs XSS
The three are confused constantly. The difference is who makes the forged request, and where it goes.
| SSRF | CSRF | XSS | |
|---|---|---|---|
| Target | The server | The victim's browser | The victim's browser |
| Forged request made by | The application server | The victim's browser | The victim's browser (running attacker script) |
| Attacker controls | The URL the server fetches | A request the browser sends | Script executed in the victim's page |
| Typical impact | Internal services, cloud metadata, file read | Unwanted state-changing actions as the victim | Session theft, defacement, account takeover |
| Primary defense | Allowlist + resolved-IP validation + egress controls | Unpredictable tokens + SameSite cookies | Output encoding + Content Security Policy |
| OWASP Top 10 2021 | A10 | — (part of A01 in 2025) | A03 Injection (2021) / A03 (2025) |
SSRF and CSRF are opposites in one useful way: CSRF tricks the browser into attacking the server, while SSRF tricks the server into attacking itself and its own network.
Testing for SSRF
Manual Workflow
http://127.0.0.1/ and http://localhost/ — a different response from a public URL confirms the server is fetching.http://169.254.169.254/latest/meta-data/ — on a cloud VM this is the critical test.nc -lvnp) and watch for the connection.Tools
SSRF Cheat Sheet
Attack Payloads
| Goal | Payload |
|---|---|
| AWS metadata | http://169.254.169.254/latest/meta-data/iam/security-credentials/ |
| GCP metadata | http://metadata.google.internal/computeMetadata/v1/ |
| Azure metadata | http://169.254.169.254/metadata/instance?api-version=2021-02-01 |
| Redis | http://127.0.0.1:6379/ |
| Elasticsearch | http://127.0.0.1:9200/ |
| Local file | file:///etc/passwd |
| Decimal loopback | http://2130706433/ |
| Hex loopback | http://0x7f.0.0.1/ |
| IPv6 loopback | http://[::1]/ |
| Blind confirmation | http://YOUR-LISTENER:4444/ping |
Prevention Checklist
| Layer | Control |
|---|---|
| Design | Do not accept arbitrary URLs; use identifiers + allowlist |
| Validation | Validate the resolved IP; pin it; validate IPv4 + IPv6 |
| Redirects | Disable auto-redirects or re-validate every target |
| Schemes | Allow only http/https |
| Network | Egress proxy, deny-by-default, block metadata ranges |
| Cloud | IMDSv2 required, hop limit 1, least-privilege IAM |
| Monitoring | Log outbound requests; alert on metadata/internal targets |
| Response | Never return raw upstream responses to the user |
Troubleshooting SSRF Problems
| Problem | Likely cause | Fix |
|---|---|---|
| Payload returns 400 | Your URL is malformed or the fetcher rejects the scheme | Check the scheme and encoding; try a plain http:// URL first |
| Metadata probe returns 403 | IMDSv2 is enforced or the header is missing | On your own lab instance, add the IMDSv2 token flow; the 403 proves the control works |
| Redirect is not followed | The library disables redirects by default | That is the secure default; re-validate and follow manually if the feature needs it |
| DNS rebinding does not work | The resolver caches the first answer | Use a short-TTL rebinding domain and a fresh lookup per request |
| Blind SSRF shows no callback | Outbound traffic is blocked or the listener is unreachable | Check the listener is public, the port is open, and no egress firewall drops it |
| WAF blocks the payload | A WAF rule matches the metadata IP or file:// | Encode the payload differently for testing, or test in a lab without the WAF |
| IPv6 payload fails | The fetcher or network has no IPv6 | Test the IPv4 equivalents; note the gap in your report |
| Fix breaks legitimate webhooks | The allowlist is too narrow | Add the real webhook hosts to the allowlist instead of loosening validation |
Common Mistakes
127.0.0.1 but forgetting IPv6 ::1, or blocking AWS metadata but not GCP or Azure equivalents. Use an allowlist instead.Host header or the URL string — The string trusted.com@169.254.169.254 has a real host of 169.254.169.254. Parse properly.Best Practices
http/https.Is SSRF Testing Legal?
Testing for SSRF is legal only on systems you own or have written permission to test. Probing a live application's fetch features without authorization is unlawful in most jurisdictions, even if you only read a metadata endpoint. Practice in the PortSwigger Web Security Academy SSRF labs or OWASP Juice Shop, both built for exactly this, and keep every test inside a lab you control. If you find SSRF in a real application, report it through the vendor's responsible-disclosure channel and do not access internal data beyond what is needed to prove the issue.
Keep Learning
Summary
SSRF allows attackers to turn your server into a proxy to access internal resources. The most effective defense is using an allowlist of trusted domains and validating at both the application and network level. Cloud environments are particularly vulnerable due to accessible metadata endpoints — require IMDSv2, restrict egress, and shrink IAM roles. Remember the pattern that catches most real SSRF: the initial URL is validated, but the redirect, the resolved IP, or the second DNS answer is not. Validate the resolved IP, pin it, re-validate every redirect, and log what your servers fetch.
Knowledge Check
Answers: 1. SSRF tricks the server into making requests to unintended locations; CSRF tricks a user's browser into making requests. 2. It exposes IAM credentials, instance identity, and security configuration to anything that can reach it from inside the instance. 3. DNS rebinding switches a domain's resolution from a safe IP to a malicious one after validation passes, so the fetch goes somewhere the check never approved. 4. A denylist must block every possible internal range and encoding, and missing one creates a bypass; an allowlist blocks everything unknown by default. 5. The attacker passes validation with a safe URL that redirects (301/302) to an internal IP, and the application follows it without re-validating. 6. IMDSv2 requires a session token obtained with a PUT request and a special header, so a simple GET-only SSRF cannot read metadata. 7. Point the fetcher at a listener you control (Burp Collaborator or netcat) and watch for the incoming connection, or measure timing and DNS side effects. 8. Because hostnames can resolve to different IPs at validation time and fetch time, and because decimal, hex, and IPv6 spellings of the same IP look different as strings.
Frequently Asked Questions
Continue Learning
What Is IDOR? Insecure Direct Object Reference Examples & How to Prevent IDOR Attacks
What is IDOR? See real insecure direct object reference examples, a worked lab test with Burp Suite, and how to prevent IDOR with server-side checks.
Web Security · IntermediateWhat Is CSRF? Cross-Site Request Forgery Examples & How to Prevent CSRF Attacks
What is CSRF? Learn how cross-site request forgery tricks your browser into unwanted actions, see real examples and a DVWA worked test, and follow 7 steps to prevent CSRF attacks with tokens, SameSite cookies and framework protection.
Web Security · IntermediateWhat Is SQL Injection? Types, Examples & How to Prevent SQL Injection Attacks
What is SQL injection? See real SQL injection examples, a worked DVWA lab test, and how to prevent SQL injection with parameterized queries.
Web Security · BeginnerOWASP Top 10 2025: All 10 Risks Explained With Examples & How to Test Them
OWASP Top 10 2025 explained: all 10 risks with real examples, what changed from 2021, and how to test each one in Kali Linux, plus a cheat sheet.
Related Security Tools
Burp Suite
Burp Suite is the industry-standard web application security testing platform from PortSwigger, free as Community Edition on Kali Linux. Learn how to use Burp Suite: install it, route your browser through its proxy, intercept your first request, and test it with Repeater and Intruder.
Web ApplicationSQLMap
SQLMap is an open-source penetration testing tool that automates SQL injection detection and exploitation. It supports six SQL injection techniques (boolean-based blind, time-based blind, error-based, UNION query-based, stacked queries, and out-of-band) and over 30 database backends including MySQL, Oracle, PostgreSQL, Microsoft SQL Server, and many more.
Vulnerability AnalysisNikto
Learn how to use Nikto, an open-source web server scanner written in Perl and pre-installed on Kali Linux, to audit servers you own or have written permission to test. Its 6700+ checks for potentially dangerous files and programs, plus tests for outdated software and misconfigurations, highlight issues that need verification.
Web SecuritySecurity Headers Checker
Check HTTP security headers (CSP, HSTS, X-Frame-Options, X-XSS-Protection, Referrer-Policy, and more) with security scoring.