Server side request forgery explained: when your own app knocks on internal doors
TL;DR
Difficulty: Intermediate
Server side request forgery (SSRF) tricks your own server into making a request on the attacker's behalf, from inside your network where nothing is checked.
- The classic prize is the cloud metadata endpoint at 169.254.169.254, which can hand out temporary credentials to your whole account.
- Any feature that fetches a URL the user supplied is a candidate: webhooks, image fetchers, link previews, PDF renderers, avatar imports.
- AI assistants write these fetch features confidently and almost never add the address checks, so the hole ships by default.
- I defend with an allowlist of destinations, hard blocks on private, loopback and link local ranges and the metadata IP, resolving the name myself and checking the real address, refusing redirects, and isolating the fetcher.
- Cucumber scenarios lock the defence in and a pen test with Burp Suite and the cloud exploitation tools proves it before release.
Most web apps have a feature that takes a web address from a user and fetches it: a webhook, an image importer, a link preview, a PDF renderer. It looks harmless, because the user only ever sees the picture or the preview that comes back. Server side request forgery is the attack that turns that feature inside out, so your own server reaches into your private network and reads things no outsider ever should. Here is how it works, what it is really after, and how I keep it out of the apps I build.
What server side request forgery actually is
Picture the front desk of an office. Visitors queue outside, show ID and get a pass that opens only a few doors. Now picture a visitor who cannot get past the desk, so instead they hand the receptionist a note: "please pop to the server room on the third floor, read the code taped to the cabinet and bring it back to me". The receptionist has keys to every door. She is trusted. She was never meant to run errands for strangers, but nobody told her not to.
Server side request forgery, almost always shortened to SSRF, is that note. The attacker cannot reach your internal systems directly, because a firewall sits in the way and the internal machines have no public address. So instead of attacking those systems, the attacker asks your application to fetch something for them. Your application sits inside the network, it is trusted, and it has the keys. When it makes the request the attacker chose, it does so from the inside, where the firewall waves it through and the internal services answer without asking who is calling.
The word forgery is the important part. The request looks completely genuine, because it genuinely came from your server. Nothing on the outside of your network ever sees it. Your logins, your firewall rules and your rate limits all face the outside world, and this request was born on the inside.
SSRF has been in the OWASP Top 10, the industry's standard list of the most serious web application risks, as its own category since 2021. It earned that place because the move to cloud hosting gave it a target so valuable that one successful request can hand over an entire account.
The feature that causes it
SSRF does not come from exotic code. It comes from a feature almost every useful app has: taking a web address from a user and fetching it on the server. Once you look for it, you see it everywhere.
- Webhooks. You let a customer type in a URL, and your app posts to it whenever something happens, an order paid, a form filled. Your server now sends requests to an address the customer controls.
- Image and avatar fetchers. "Import your photo from a URL." Your server downloads whatever address the user pasted.
- Link previews. Paste a link into a message and a little card appears with the title and picture. To build that card, your server fetched the link.
- PDF and HTML renderers. Turn this web page into a PDF, or render this HTML into an invoice. The renderer loads whatever addresses the document points at, including images and stylesheets.
- Import by URL. Pull a product feed, a spreadsheet or an XML document from an address the user gave you.
Every one of these is a legitimate feature a client asks for. Every one of them, built naively, lets a user decide where your server sends a request. That is the whole vulnerability. The attacker does not need to break in. They just need your server to be helpful.
How the attack works, step by step
Let me build it on one invented shop, which I will use for the rest of this article. Hartley Goods is an online kitchenware shop in Manchester (hartleygoods.example). It sells pans, knives and bakeware, runs on Ruby on Rails and Solidus, and is hosted on a cloud provider behind a managed database. Its developer is Nadia. The shop, Nadia and the code are made up. The attack is real and happens to shops like it every week.
Nadia adds a small, reasonable feature. When a supplier sends Hartley a new product, they can paste the address of a product photo and the shop fetches it, so the team does not have to download and upload images by hand. The code looks like this:
# app/services/image_importer.rb
require "open-uri"
class ImageImporter
def self.fetch(url)
URI.open(url).read
end
end
It works perfectly. Paste a photo address, the picture appears. It shipped on a Tuesday and nobody thought about it again.
Here is what a supplier is meant to send:
https://supplier.example/photos/copper-pan.jpg
Here is what an attacker sends instead, into the very same box:
http://169.254.169.254/latest/meta-data/
That second address is not on the public internet. It is a special address that only exists from inside a cloud server, and I will come to what lives there in a moment. The point for now is that the box asked for a URL, and a URL is exactly what it got. The code did not care that this one points inward. URI.open dutifully made the request from inside the network and handed back whatever answered.
The attacker does not even need the picture to display. If a bad address makes the page hang for five seconds, that tells them a service is listening there. If another returns at once, that one is closed. By trying a list of internal addresses and watching the timing, an attacker can map your private network from the outside, one guess at a time, using nothing but your image importer.
Example: Nadia maps what her own feature can reach
The honest way to understand the hole is to see it from the attacker's side on a safe setup, which is exactly what a pen test does. On a copy of the shop with no real data, Nadia pastes a few internal addresses into her own importer and watches what comes back:
http://127.0.0.1:5432reaches the database port on the server itself. Loopback, meaning the machine talking to itself, is normally invisible from outside. Her importer can see it.http://10.0.1.14:9200reaches a search service on a private address that has no route from the internet at all.http://169.254.169.254/latest/meta-data/returns a list of fields. This is the one that matters.
None of these should be reachable by a stranger. All of them are reachable by Hartley's own server, and the importer let a stranger drive it.
The crown jewel: the cloud metadata endpoint
That address, 169.254.169.254, deserves its own section, because it is why SSRF went from a nuisance to a top tier risk.
When you run a server on a cloud provider, the machine needs to know things about itself: its name, its region, its network, and above all its credentials, the temporary keys that let it talk to the rest of your cloud account to read files from storage, send mail, or reach the database. The provider delivers all of this through a metadata service that answers only on that one internal address. It is meant to be read by the machine, by nobody else, and it is never protected by a password, because the provider assumes that only trusted code on the machine would ever ask.
SSRF breaks that assumption. If your application can be tricked into fetching that address, it fetches the credentials and hands them to the attacker. Those credentials often carry wide permissions, because somebody set them up in a hurry and never trimmed them back. With them, the attacker is no longer poking at one shop. They can read every file in your storage buckets, including customer uploads and database backups, and in a bad case stand up new servers on your bill or delete everything you have.
This is not theory. The 2019 breach at a large American bank, which exposed the data of more than one hundred million people, began with an SSRF that reached exactly this metadata endpoint and pulled the credentials behind it. One misused fetch, a set of over permissioned keys, and a hundred million records.
Newer versions of the metadata service make this harder. They require the caller to ask for a short lived token first with a specific header, a scheme designed so that a simple blind fetch no longer works. It helps, and I insist on it. But plenty of servers still run the old scheme, and a determined SSRF can sometimes still satisfy the token step, so the metadata endpoint stays firmly on the block list no matter which version is running.
What the attacker is really after
SSRF is rarely the goal. It is the way in. What the attacker does once your server is running their errands depends on what your network holds, and the list is uncomfortable.
Cloud credentials and the keys to the account. As above, the metadata endpoint is the jackpot. Temporary keys lead to your storage, your backups and sometimes the ability to create and destroy infrastructure.
Internal services that trust the network. Most companies run internal tools, a search cluster, a cache, an admin dashboard, a metrics system, that have no login because they are "only reachable from inside". SSRF is precisely a way to reach them from inside. An unprotected admin API or a database with no password becomes a direct read of your customer data.
A map of your network. Even when nothing answers usefully, the timing and the error messages let an attacker learn which addresses and ports exist, which is the groundwork for the next attack.
A quiet place to launch from. Requests from your trusted server are more likely to be allowed and less likely to be logged as suspicious, so an attacker can use your app as a relay and make the traffic look like it came from you.
For a shop, the breach scenario is concrete. The importer reads the metadata endpoint, the credentials lead to the storage bucket, the bucket holds a nightly database backup, and the backup holds every customer's name, address and order history. The shop did nothing that felt like a security decision. It added a convenient way to import product photos.
Why AI has made this far more likely
A fetch a URL feature is exactly the kind of small, self contained task people now hand to an AI assistant. "Write me a Rails service that downloads an image from a URL the user provides." The assistant will produce clean, working code in seconds. It will almost never, unprompted, add a check on where that URL points. It gives you the happy path, because the happy path is what the request asked for and what the training data is full of.
That is the heart of the problem. The naive version and the safe version look almost identical. The difference is a dozen lines of address checking that an AI leaves out unless you know to ask, and if you did not know SSRF existed, you did not know to ask. The feature demos perfectly, so it ships.
The measured picture backs this up. Veracode's 2025 GenAI Code Security Report found that AI generated code contains 2.74 times more vulnerabilities than human written code. An Ox Security analysis of more than 300 repositories in 2025 found the same ten anti patterns in 80 to 100 per cent of AI generated code, the recurring blind spots a model has. Separate research found that 45 per cent of AI generated code introduces a vulnerability from the OWASP Top 10, the list SSRF sits on. And a 2026 study of more than 304,000 commits found that 24.2 per cent of the issues AI introduced were still unresolved later, because nobody understood the code well enough to spot them. The Georgetown CSET report on the cybersecurity risks of AI generated code in 2024 and CrowdStrike's 2025 research into AI code vulnerabilities point the same way.
There is a reason SSRF in particular slips through. It is not a visible bug. The code does what it says: it fetches the URL. It passes every functional test, because every functional test uses a real, friendly URL. There is nothing to see in a demo, no error, no crash. The vulnerability is entirely in what the code fails to refuse, and an AI that was asked to fetch a URL has no reason to refuse anything. When nobody on the team understands the fetch code well enough to ask "but where can this request actually go?", the hole is invisible until someone outside finds it.
How I defend against it
SSRF has no single switch. The defence is a short stack of checks, each one closing a gap the one before cannot. I apply all of them to any feature that fetches a user supplied address, and I treat the whole stack as the minimum, not a menu.
Validate and allowlist the destination
The strongest defence is to decide, in advance, the small set of places the feature is ever allowed to reach, and refuse everything else. This is an allowlist, and it is the opposite of trying to list all the bad addresses and hoping you caught them. Attackers are endlessly creative about writing the same bad address in new ways; you will never list them all. But the set of places your feature legitimately needs is usually tiny and known.
A webhook that only ever talks to one payment provider should be allowed to reach that provider's domains and nothing else. An importer that only pulls from known suppliers should hold those suppliers' domains and refuse the rest. Where an allowlist of domains is genuinely impossible, because the feature is a general link preview that must reach any public site, you fall back to the address blocking below as the primary line, and you make it strict.
Block the private, loopback, link local and metadata ranges
Wherever a strict allowlist is not possible, the rule is that your fetcher must refuse to connect to any address that lives inside your own infrastructure. In practice that means blocking, at minimum:
- loopback, the machine talking to itself: 127.0.0.0/8 and the IPv6 equivalent
- the private ranges that make up internal networks: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16
- the link local range 169.254.0.0/16, which contains the cloud metadata address 169.254.169.254
- unspecified and reserved addresses, and the IPv6 forms that map back onto all of the above
The metadata IP earns an explicit line of its own, because it is the single most valuable target and because people who block the private ranges sometimes forget that link local is separate. Block the range and name the address.
Resolve the name yourself, then check the real address
Here is the trap that catches naive blocklists. The attacker does not have to paste 169.254.169.254. They can register a normal looking domain, photos.attacker.example, and point it at 169.254.169.254 in DNS. Your check sees a friendly domain name, waves it through, and then the fetch resolves the name and connects to the metadata endpoint anyway. This is called a DNS rebinding style bypass.
The fix is to resolve the hostname to an actual IP address yourself, check that resolved address against the block list, and then connect to that exact address rather than letting the HTTP library resolve the name a second time. If the name resolves to a blocked range, you refuse before a single packet leaves the server. Resolving once and reusing the result also closes the window where a name is friendly on the first lookup and hostile on the second.
Do not follow redirects blindly
An attacker who cannot paste a bad address directly will paste a good one that redirects to a bad one. You allow https://supplier.example/photo, your server fetches it, and the supplier address answers with "go to 169.254.169.254 instead". A fetcher that follows redirects automatically walks straight through your front door check and into the very place you were guarding.
So I never follow redirects blindly on a user driven fetch. Either redirects are refused outright, or every hop is run back through the full address check before the next request is made. One friendly first hop is not permission to follow wherever it points.
Isolate the fetcher
Every check above can have a gap, so the last layer assumes one got through. The fetching code runs somewhere that cannot do much damage even if it is tricked: on a network path that physically cannot reach the metadata endpoint or the internal services, with its own narrow set of outbound firewall rules, and ideally as a separate small service rather than inside the main application. If a fetch does escape the checks, it escapes into a room with nothing worth stealing in it. On the cloud side this pairs with the newer metadata scheme that demands a token, and with credentials trimmed to the few permissions the server actually needs, so that even a leaked key opens very little.
Here is the shape of the defended fetcher
The naive version was three lines. The safe version is longer because refusing is the whole job. This is illustrative, not a library to paste, but it shows the order of the checks:
# app/services/safe_fetch.rb
require "resolv"
require "ipaddr"
class SafeFetch
ALLOWED_HOSTS = %w[supplier.example images.supplier.example].freeze
BLOCKED = [
IPAddr.new("127.0.0.0/8"), IPAddr.new("10.0.0.0/8"),
IPAddr.new("172.16.0.0/12"), IPAddr.new("192.168.0.0/16"),
IPAddr.new("169.254.0.0/16"), IPAddr.new("::1/128")
].freeze
def self.fetch(raw_url)
uri = URI.parse(raw_url)
raise "scheme not allowed" unless %w[http https].include?(uri.scheme)
raise "host not on the allowlist" unless ALLOWED_HOSTS.include?(uri.host)
address = Resolv.getaddress(uri.host)
ip = IPAddr.new(address)
raise "address is internal" if BLOCKED.any? { |range| range.include?(ip) }
# connect to the resolved address, with redirects refused and a timeout
HTTP.timeout(5).follow(max_hops: 0).get("#{uri.scheme}://#{address}")
end
end
Reading it in order: the scheme must be http or https, so nobody fetches a local file or some other protocol. The host must be on the allowlist. The name is resolved to a real address, which is checked against the blocked ranges, so a friendly domain pointing at the metadata IP is caught. Then the request is made to the resolved address with redirects refused and a timeout. Every raise is a door the note writer does not get through.
Lock the behaviour in with Cucumber
A check that is not tested is a check that quietly stops working the next time someone edits the file. So I write the refusals down as behaviour scenarios in Cucumber, where they read as plain English a client can follow:
Feature: The image importer only reaches allowed suppliers
Scenario: It refuses the cloud metadata endpoint
When a supplier submits the address "http://169.254.169.254/latest/meta-data/"
Then the import is refused
And no request leaves the server
Scenario: It refuses a domain that resolves to an internal address
Given "photos.attacker.example" resolves to "169.254.169.254"
When a supplier submits the address "http://photos.attacker.example/pan.jpg"
Then the import is refused
Scenario: It refuses a redirect into an internal address
Given "supplier.example" redirects to "http://127.0.0.1:5432"
When a supplier submits the address "https://supplier.example/pan.jpg"
Then the import is refused
These scenarios are the specification. They say, in words the shop owner can read and approve, that the importer will never touch the metadata endpoint, never be fooled by a rebinding domain, and never be walked through a redirect. They run on every change, and a red scenario stops the release. The day a well meaning edit removes the address check, these go red before the code reaches a customer.
Alongside the behaviour scenarios, Brakeman, the static analysis tool for Rails, flags the SSRF prone patterns automatically on every build, so an unsafe URI.open on user input never slips in quietly in the first place.
Pen test it with Kali before release
Tests prove that the cases I thought of are handled. A pen test looks for the cases I did not. Before a build with any URL fetching feature goes live, I run it from a Kali Linux setup, the standard toolkit for this work, and try to break my own defence.
Burp Suite and OWASP ZAP sit between a browser and the app and let me replay the fetch with crafted addresses: the metadata IP written in decimal and hexadecimal, addresses wrapped in rare URL forms, redirect chains, domains set up to rebind. There are purpose built tools for the metadata step in particular, which attempt exactly the credential theft described above against a safe target. The goal is simple and adversarial: can I, as the attacker, make the server fetch one thing it should refuse? If I can, the build does not ship, the gap becomes a new Cucumber scenario, and the fix comes before the release, not after a breach.
Why testing and pen testing make this insurable
Here is the business case, and it is the same one that runs through everything I build. SSRF is invisible to the normal eye. It does not crash, it does not error, it passes every demo, and it sails past a review that only reads what the code does rather than what it refuses. The only way to know a fetch feature is safe is to have tried to abuse it and to have the refusals written down and running.
That is why I build with owned, readable code rather than a black box. Every outbound fetch in an app I build has a named place where the address check lives, a set of Cucumber scenarios that state what it will and will not reach, and a pen test on record that someone tried to break it before release. When an insurer, an auditor or a client's own security team asks "how do you know your app cannot be turned against your network?", the answer is not "we are careful". It is a list of scenarios they can read and a test gate they can watch run. That is verifiable work, and verifiable work is what makes a claim like "this is secure" worth anything.
A vibe coded fetch feature, written by an assistant and understood by nobody, offers none of that. It works on the day, and what it refuses is whatever the model happened to leave in, which for SSRF is usually nothing.
A short honest close
Server side request forgery is not an exotic attack. It is the predictable result of a very ordinary feature, fetching a URL a user gave you, built without asking where that request can go. The fix is not clever either: decide where the feature is allowed to reach, refuse the private, loopback, link local and metadata addresses, resolve names yourself and recheck, never follow redirects blindly, isolate the fetcher, and then prove all of it with tests and a pen test before release.
If your app has a webhook, an image importer, a link preview or a PDF renderer, it has a place where this could already be open, and the odds are nobody has checked, especially if the feature was written quickly or by an assistant. If you would like a second pair of eyes on where your app's outbound requests can actually go, that is one of the things we do in the free workshop. We map every fetch together and write the first allowlist and its tests, no hard sell, and the first two weeks of work are on me.
