Search by

securized / laravel-ssrf

securized

SSRF prevention for Laravel. Protect Http::, Guzzle, and validate user-supplied URLs against server-side request forgery.

Package info

github.com/securized/laravel-ssrf

pkg:composer/securized/laravel-ssrf

Statistics

Installs: 7 446

Dependents: 0

Suggesters: 0

Stars: 16

Open Issues: 0

1.2.0 2026-11-25 00:10 UTC

README

Latest Version on Packagist Tests Quality Total Downloads

SSRF (Server-Side Request Forgery) prevention for Laravel. Protect Http::, raw Guzzle, and user-supplied URLs from being weaponised to reach internal infrastructure, cloud metadata endpoints, or private networks.

The problem

Fetching a user-supplied URL is a normal thing to do. Webhooks, link previews, avatar imports, "import from URL" buttons. The code usually looks like this:

$response = Http::get($request->input('webhook_url'));

Your server will happily fetch whatever it's pointed at, from a network position your users don't have. So an attacker submits:

http://169.254.169.254/latest/meta-data/iam/security-credentials/

On unpatched EC2 (IMDSv1), that returns your instance's IAM credentials. The same trick reaches http://localhost:6379 (Redis), your internal admin panel, or a Kubernetes API on a private subnet. Anything your server can route to but the internet can't.

Blocking this properly is harder than it looks. 127.0.0.1 is also http://0177.0.0.1/, http://2130706433/, and http://[::1]/. A hostname that resolves to a public IP when you check it can resolve to 127.0.0.1 a second later when Guzzle connects. This package handles those cases and validates every URL before the request leaves your application.

Installation

composer require securized/laravel-ssrf

Publish the config file:

php artisan vendor:publish --tag="ssrf-config"

Quick Start

use Illuminate\Support\Facades\Http;

// Wrap any Http:: call with ->ssrf() to enable protection
Http::ssrf()->get($userSuppliedUrl);
Http::ssrf()->post($webhookUrl, $payload);

That's it. Requests to private IPs, localhost, link-local addresses (including cloud metadata endpoints), and non-HTTP(S) schemes are blocked out of the box.

Features

  • Laravel HTTP Client macro: Http::ssrf() and Http::withSsrfProtection()
  • Raw Guzzle middleware: drop into any HandlerStack
  • Validation rule: new SsrfSafeUrl() for form/API input validation
  • Facade: Ssrf::validate($url), Ssrf::isSafe($url), Ssrf::safeUrl($url)
  • IPv4 + IPv6: blocks private ranges for both address families
  • DNS pinning: prevents DNS rebinding attacks
  • Configurable: whitelist/blacklist for IPs, ports, domains, and schemes
  • Immutable options: safe in long-running processes (Octane, RoadRunner)

Usage

Laravel HTTP Client

The ssrf() and withSsrfProtection() macros return a PendingRequest and chain normally with all other HTTP client methods:

use Illuminate\Support\Facades\Http;

// Protect a single request
$response = Http::ssrf()->get($userUrl);

// Chain with other options
$response = Http::ssrf()
    ->withHeaders(['Accept' => 'application/json'])
    ->timeout(10)
    ->get($userUrl);

// Both macros are identical
Http::withSsrfProtection()->post($webhookUrl, $data);

Blocked requests throw a \GuzzleHttp\Exception\RequestException (the same exception Guzzle throws for failed requests), so your existing error handling works without changes.

Global Protection

To protect every outgoing Http:: request automatically, set auto_protect in your .env:

SSRF_AUTO_PROTECT=true

Or in config/ssrf.php:

'auto_protect' => true,

Raw Guzzle

Use the static factory to add SSRF protection to any Guzzle client without the Laravel container:

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Securized\Ssrf\Http\Middleware\SsrfProtectionMiddleware;

$stack = HandlerStack::create();
$stack->push(SsrfProtectionMiddleware::make());

$client = new Client(['handler' => $stack]);
$response = $client->get($userUrl);

Validation Rule

Validate user-supplied URLs in form requests or controllers:

use Securized\Ssrf\Rules\SsrfSafeUrl;

$request->validate([
    'webhook_url' => ['required', 'url', new SsrfSafeUrl()],
    'preview_url' => ['required', 'url', new SsrfSafeUrl()],
]);

The validation error message deliberately does not expose internal network details to end users.

Facade

use Securized\Ssrf\Facades\Ssrf;

// Returns array{url: string, host: string, ips: list<string>, pinned: bool}
// Throws SsrfException on failure.
$result = Ssrf::validate($url);

// Returns the validated URL string.
// When pin_dns is enabled, the host is replaced with the resolved IP.
// Always use this value for the actual request, not the original $url.
// Throws SsrfException on failure.
$safeUrl = Ssrf::safeUrl($url);

// Returns true/false, never throws.
if (!Ssrf::isSafe($url)) {
    abort(422, 'URL is not permitted.');
}

Configuration

After publishing, edit config/ssrf.php:

return [

    // Apply SSRF protection to all Http:: requests globally.
    'auto_protect' => env('SSRF_AUTO_PROTECT', false),

    // Allow credentials (user:pass@host) in URLs. Disabled by default.
    'send_credentials' => false,

    // Connect to the validated IP via CURLOPT_RESOLVE, keeping the hostname.
    // Prevents DNS rebinding attacks. See "DNS Pinning" below.
    'pin_dns' => false,

    'whitelist' => [
        'ips'     => [],               // CIDR ranges or exact IPs
        'ports'   => [80, 443, 8080],  // Allowed ports (empty = allow all)
        'domains' => [],               // Regex patterns (empty = allow all)
        'schemes' => ['http', 'https'],
    ],

    'blacklist' => [
        'ips' => [
            // RFC 1918 private ranges
            '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16',
            // Loopback
            '127.0.0.0/8',
            // Link-local (cloud metadata: AWS, GCP, Azure)
            '169.254.0.0/16',
            // ... and more (see config/ssrf.php for the full list)
        ],
        'ports'   => [],
        'domains' => [],
        'schemes' => [],
    ],
];

Whitelist semantics

An empty whitelist for a type means "allow all" (subject to the blacklist). A non-empty whitelist means only the listed values are permitted. The blacklist always takes precedence.

A hostname can resolve to several addresses. With an IP whitelist, every one of them must be whitelisted, since curl is free to connect to any of them. The exception is a request that is actually pinned: with pin_dns on, the HTTP middleware and Ssrf::safeUrl() accept a host with at least one whitelisted address and connect only to the whitelisted ones. Ssrf::isSafe(), Ssrf::validate() and the validation rule pin nothing, so they always require all of them.

Domain patterns

Domain entries are literal hostnames with * as a wildcard, matched case-insensitively:

'whitelist' => [
    'domains' => [
        'api.example.com',      // exact host
        '*.trusted.com',        // any subdomain (not the bare apex)
    ],
],

Dots are literal, so a pattern never matches more hosts than it appears to. api.example.com matches that host and nothing else. Regex syntax is not supported; characters like . and ( are matched literally.

IP ranges

IP entries support CIDR notation for both IPv4 and IPv6:

'blacklist' => [
    'ips' => [
        '10.0.0.0/8',   // IPv4 range
        'fc00::/7',     // IPv6 unique local
    ],
],

IPv6 addresses that carry an IPv4 address

Several IPv6 forms exist only to reach an IPv4 address, and a gateway or tunnel on the network forwards them there: 64:ff9b::a9fe:a9fe is 169.254.169.254 behind a NAT64 gateway. The validator unwraps these and checks the IPv4 address against the same IP lists as the address itself, so an IPv4 blacklist entry covers every wrapping of it. The forms it unwraps are IPv4-compatible, IPv4-mapped, IPv4-translated, 6to4, Teredo (server and client), ISATAP and NAT64.

The transition prefixes nobody should be fetching from are also in the default blacklist as whole ranges. NAT64 is the exception: on an IPv6-only network with DNS64, every IPv4-only host resolves into the NAT64 prefix, so its addresses are only judged by the IPv4 address they carry. The well-known prefix 64:ff9b::/96 is handled out of the box. If your gateway uses its own prefix, list it so its addresses are unwrapped too:

'nat64_prefixes' => ['64:ff9b::/96', '2001:db8:64::/96'],

A prefix must be IPv6 with one of the RFC 6052 lengths (/32, /40, /48, /56, /64, /96); anything else throws when the options are built. An address in a listed prefix is judged by the IPv4 address it carries and not by the default blacklist ranges around it, so a gateway on 64:ff9b:1::/96 or a unique-local prefix works. A range you add to the blacklist yourself still applies to the address, so adding 64:ff9b::/96 blocks NAT64 outright. The well-known prefix is always unwrapped, whatever the list holds.

An IP whitelist entry admits the NAT64 address that forwards to it: whitelisting 93.184.216.0/24 also allows 64:ff9b::5db8:d822. That only holds for a well-formed NAT64 address, with nothing set after the embedded IPv4. The other forms are never whitelisted by the IPv4 address they carry, because they can appear in an address the attacker controls.

Hostnames

The host is validated under the name curl will actually look up, so the domain lists, DNS and the pin all see the same thing:

  • IDN hosts are converted to punycode (bücher.example becomes xn--bcher-kva.example, and a full-width example.com becomes example.com). This needs the intl extension; without it non-ASCII hosts are rejected.
  • One trailing dot is dropped (example.com. is example.com).
  • After that, a hostname may only contain letters, digits, ., - and _, and may not start with - or .. curl percent-decodes the host before resolving it, so %61.example.com would otherwise be validated under one name and fetched as a.example.com.
  • A bracketed host must be a valid IPv6 address.

Anything else throws InvalidUrlException.

Numeric hosts

A host whose last label is numeric is an IPv4 address, never a DNS name, as no top-level domain is all-numeric. It is accepted only in dotted-decimal form. Octal, hex, integer and shorthand forms (0177.0.0.1, 0x7f000001, 2130706433, 127.1, 127.0.0.1.) throw InvalidUrlException before any DNS lookup.

They are rejected and not converted because PHP, libc and curl read them differently from one build to the next, so no conversion here could be trusted to match what curl then connects to. Looking them up is worse: a resolver that answers for one would get the URL approved while curl connects to the address it encodes. This is the same rule as the WHATWG URL Standard's "ends in a number" check.

Per-Request Options

Override the global config for a single request using SsrfOptions:

use Securized\Ssrf\SsrfOptions;

// Build from config and customise
$options = SsrfOptions::fromConfig(config('ssrf'))
    ->withPinDns()
    ->withWhitelistSchemes(['https'])  // HTTPS only for this request
    ->addBlacklistIp('203.0.113.0/24');

Http::ssrf($options)->get($url);

// Also works with the validation rule
new SsrfSafeUrl($options)

SsrfOptions is immutable. Each method returns a new instance, so customising per-request never affects shared state.

DNS Pinning

DNS rebinding is an attack where a hostname initially resolves to a public IP (passing validation) but then re-resolves to a private IP for the actual request. Enabling pin_dns prevents this by resolving the hostname once, validating the IP, and then telling curl to connect to exactly that IP through CURLOPT_RESOLVE. The URL itself is left alone, so the Host header, TLS SNI and certificate validation all keep using the original hostname.

// In config/ssrf.php
'pin_dns' => true,

// Or per-request
Http::ssrf(SsrfOptions::fromConfig(config('ssrf'))->withPinDns())->get($url);

Every validated address is pinned, so curl can still fail over between them. With an IP whitelist, only the whitelisted addresses are pinned. Pins expire with curl's DNS cache instead of staying on a reused handle (libcurl 7.75+).

CURLOPT_RESOLVE is not consulted in every setup, so the middleware pins another way where it has to:

  • HTTPS through a proxy: the proxy does the DNS lookup, so the request uses CURLOPT_CONNECT_TO to tunnel to the validated IP. TLS still uses the hostname.
  • HTTP through a proxy, the stream option, or no curl extension: the hostname in the URL is replaced with the IP and the Host header is set. HTTPS certificate validation may fail for stream requests and without curl. Plain HTTP through a proxy is rewritten instead of tunnelled because CURLOPT_CONNECT_TO makes curl send CONNECT, which proxies commonly refuse for port 80.
  • IDN and trailing-dot hostnames: the request is sent under the normalised name (see "Hostnames"), which is what curl matches pin entries against.

Proxy detection is deliberately broad. A request counts as proxied when the Guzzle proxy option, CURLOPT_PROXY, CURLOPT_PRE_PROXY, or one of the proxy environment variables curl reads (http_proxy, https_proxy, all_proxy) applies to its scheme. Treating a direct request as proxied still pins it, whereas missing a proxy would lose the pin.

A host exempted by no_proxy is pinned as a direct request. The no key applies to a proxy set through the Guzzle proxy option, and the no_proxy environment variable to any proxy curl is handed, matching what Guzzle and curl do themselves. For such a host the middleware switches the proxy off for that request explicitly so the exemption still holds once the request is pinned.

A non-curl handler (a StreamHandler, a coroutine handler) ignores curl options. When such a handler sits directly below the middleware, the middleware sees it and pins by rewriting the URL. It cannot see a handler wrapped in further middleware pushed after it, and Guzzle's default handler is opaque, so in that case tell it to rewrite explicitly:

use Securized\Ssrf\Http\Middleware\SsrfProtectionMiddleware;

new Client([
    'handler' => $stackWithYourHandler,
    SsrfProtectionMiddleware::REWRITE_OPTION => true,
]);

HTTPS certificate validation may fail in that mode, as the URL carries the IP.

If a request sets CURLOPT_DNS_CACHE_TIMEOUT to 0, its pin is added as a permanent entry, because an expiring one would be discarded before curl used it. That entry stays on the curl handle for as long as the handle is reused.

Ssrf::safeUrl() and Ssrf::validate() have no request to attach curl options to, so with pin_dns enabled they still return the URL with the IP substituted for the hostname.

What this does not protect against

Worth knowing before you rely on it:

  • Second-order requests are your responsibility. Redirects are covered, as Guzzle re-enters the middleware for each hop, so a 302 to http://169.254.169.254/ is blocked (there are tests for this). But if you fetch a page, parse a URL out of the body, and request it yourself, that second request needs its own validation.
  • TOCTOU without DNS pinning. With pin_dns disabled, the hostname is resolved once for validation and again by Guzzle when it connects. An attacker controlling the DNS response can return a public IP for the first lookup and a private one for the second. Enable pin_dns to close this.
  • Blocked hosts are still distinguishable. Timing and error differences let an attacker infer which internal hosts exist. This is a port scan with a very narrow oracle, not data exfiltration, but it is not nothing.
  • The blacklist covers documented ranges, not your network. If your internal services live on public IPs, add them to the blacklist yourself, nothing here can infer that.

Exception Hierarchy

All SSRF exceptions extend \Securized\Ssrf\Exceptions\SsrfException (itself a RuntimeException):

SsrfException
└── InvalidUrlException      - URL cannot be parsed, is empty, or contains credentials
    ├── InvalidSchemeException  - scheme not permitted (e.g. file://, gopher://)
    ├── InvalidPortException    - port not permitted
    ├── InvalidDomainException  - hostname not permitted or does not resolve
    └── InvalidIpException      - resolved IP matches a blacklisted range

Catch SsrfException to handle any SSRF failure, or catch specific subclasses for fine-grained handling:

use Securized\Ssrf\Exceptions\InvalidIpException;
use Securized\Ssrf\Exceptions\SsrfException;
use Securized\Ssrf\Facades\Ssrf;

try {
    $safeUrl = Ssrf::safeUrl($userUrl);
} catch (InvalidIpException $e) {
    // Resolved to a private IP
} catch (SsrfException $e) {
    // Any other validation failure
}

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Credits

The threat model and much of the test suite structure come from SSRF vs. Developers: A Study of SSRF-Defenses in PHP Applications (USENIX Security '24) by Malte Wessels, Simon Koch, Giancarlo Pellegrino and Martin Johns, of TU Braunschweig and CISPA Helmholtz Center for Information Security.

Their Table 2 enumerates the three ways a URL validation layer gets evaded, and this package defends against each:

Evasion Fix Here
URL parser confusion Well-established, hardened parser Guzzle's PSR-7 Uri, plus parser differential tests
DNS rebinding IP pinning pin_dns
Redirects Recheck on each redirect Middleware runs per hop

The paper describes IP pinning as "the only reliable defense against attacks targeting local resources without unduly restricting the versatility of the SSR feature".

Security Vulnerabilities

If you find a security issue in this package, please email root@securized.dev rather than opening a public issue.

License

The MIT License (MIT). Please see License File for more information.