What SSRF is, in one paragraph
Server-side request forgery (SSRF) happens when an attacker makes your server request a URL of their choosing. If your code fetches http://169.254.169.254/latest/meta-data/ for them, you may hand over cloud credentials. If it fetches http://localhost:6379, you may let them poke an internal service. Any feature that fetches a URL, such as link previews, webhooks, importers or a website scanner, needs a guard.
I built one for the scanner inside my Freelance Growth Engine, which fetches the public websites of businesses. It is a single class, SafeUrlGuard, plus a fetcher that refuses to trust anything the guard has not just approved.
Step 1: be strict about the URL itself
Reject what you do not need before you resolve anything. The guard allows only http and https, ports 80 and 443, no embedded credentials, no control characters and a sane length:
$scheme = strtolower($p['scheme']);
if (! in_array($scheme, ['http', 'https'], true)) {
throw new UnsafeUrlException('Only http and https URLs are allowed.');
}
if (isset($p['user']) || isset($p['pass'])) {
throw new UnsafeUrlException('URLs with credentials are not allowed.');
}
$port = $p['port'] ?? ($scheme === 'https' ? 443 : 80);
if (! in_array($port, [80, 443], true)) {
throw new UnsafeUrlException('Only ports 80 and 443 are allowed.');
}
Hostnames get the same treatment: localhost, suffixes like .local, .internal and .lan, and anything that is not a well-formed domain are refused.
Step 2: resolve the host and require public IPs only
Checking the hostname string is not enough, because an attacker can register evil.example and point it at 10.0.0.5. Resolve it yourself (A and AAAA records) and check every address it returns:
foreach ($ips as $ip) {
if (! self::isPublicIp($ip)) {
throw new UnsafeUrlException('Host resolves to a non-public address.');
}
}
public static function isPublicIp(string $ip): bool
{
if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return false;
}
foreach (self::EXTRA_BLOCKED as $cidr) {
if (self::inCidr($ip, $cidr)) {
return false;
}
}
return true;
}
PHP's FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE does most of the work, but not all of it. I add an explicit list of ranges it does not reliably cover:
'100.64.0.0/10', // carrier-grade NAT
'::ffff:0:0/96', // IPv4-mapped IPv6
'64:ff9b::/96', // NAT64
'2002::/16', // 6to4
'fc00::/7', // unique local
'fe80::/10', // link-local
'224.0.0.0/4', 'ff00::/8', // multicast
The IPv4-mapped entry matters: http://[::ffff:127.0.0.1]/ is loopback wearing an IPv6 costume.
Step 3: pin the resolved IP so DNS cannot change its mind
There is still a gap. You resolved example.com to a public IP and approved it, then your HTTP client resolves it again to connect. A hostile DNS server can answer differently the second time (DNS rebinding) and send you to 127.0.0.1. The fix is to make the client connect to the IP you already checked. With cURL that is CURLOPT_RESOLVE:
$info = $this->guard->check($current); // returns host, port and the approved ip
$response = Http::withOptions([
'allow_redirects' => false,
'curl' => [CURLOPT_RESOLVE => ["{$info['host']}:{$info['port']}:{$info['ip']}"]],
])->timeout((int) config('scanner.timeout'))->get($current);
One practical gotcha from building this: do not set Guzzle's stream option. It switches to the stream handler, which cannot pin DNS, and the pinning silently stops working.
Step 4: follow redirects by hand
A public URL can answer with 302 Location: http://127.0.0.1/admin. That is why the code above sets allow_redirects to false. The fetcher follows redirects in its own loop, runs the full guard on every hop, and gives up after a configured number of hops:
for ($hop = 0; $hop <= (int) config('scanner.max_redirects'); $hop++) {
$info = $this->guard->check($current); // every hop is re-validated
// ... pinned request, capped download ...
// if the response is a redirect: resolve the Location, loop again
}
return new FetchResult($url, $current, error: 'connection', errorDetail: 'too_many_redirects');
Step 5: bound everything else
- Size: download into a capped sink so a multi-gigabyte response cannot fill memory or disk.
- Time: set both a connect timeout and a total timeout.
- Politeness: a per-host throttle, and respect
robots.txt. - Read-only: the scanner only issues GET requests and never submits forms.
Test the ugly cases
A guard is only as good as the inputs you tried to break it with. The unit test uses a Pest dataset of hostile URLs and asserts that each one throws:
it('blocks unsafe URLs', function (string $url) {
(new SafeUrlGuard(fn () => ['93.184.216.34']))->check($url);
})->throws(UnsafeUrlException::class)->with([
'file scheme' => 'file:///etc/passwd',
'credentials' => 'http://user:pass@example.com/',
'odd port' => 'http://example.com:8080/',
'metadata' => 'http://169.254.169.254/latest/meta-data/',
'cgnat' => 'http://100.64.0.1/',
'ipv6 loopback' => 'http://[::1]/',
'ipv4-mapped ipv6' => 'http://[::ffff:127.0.0.1]/',
'decimal ip' => 'http://2130706433/',
'newline injection' => "http://example.com/\r\nHost: evil",
]);
Note the resolver is injected as a closure, so the tests never touch real DNS. That keeps them fast and deterministic.
Checklist
- Allow-list schemes and ports; refuse credentials and control characters
- Resolve the host yourself and require every address to be public
- Block the ranges PHP's filter flags miss (CGNAT, IPv4-mapped, NAT64, 6to4)
- Pin the approved IP so DNS rebinding cannot swap it
- Follow redirects manually and re-validate each hop
- Cap download size and time, and test with a dataset of hostile URLs
This guard is part of a larger system, described in the Freelance Growth Engine case study. If you need features that fetch URLs built safely, see my Laravel development service.
Original article written by Saad Ali Khan. Code samples are illustrative and free to adapt in your own projects.