GuardAPI Logo
GuardAPI

Fix SSRF (Server Side Request Forgery) in Laravel

SSRF in Laravel occurs when user-controlled input is passed directly to the HTTP client (Guzzle or Laravel's Http Facade) without rigorous validation. This allows an attacker to force the server to proxy requests to internal-only services, cloud metadata endpoints (like 169.254.169.254), or scan the internal network behind the firewall.

The Vulnerable Pattern

public function fetchExternalData(Request $request) {
    $url = $request->input('url');
    // VULNERABLE: No validation on the URL. Attacker can pass 'http://localhost:8080/admin' or 'http://169.254.169.254/latest/meta-data/'
    return Http::get($url)->body();
}

The Secure Implementation

The secure implementation follows a defense-in-depth approach. First, it enforces a strict whitelist of domains and requires the HTTPS protocol. Second, it resolves the hostname to an IP address and uses PHP's filter_var with flags to ensure the IP does not belong to private or reserved ranges (preventing access to 127.0.0.1, 10.0.0.0/8, etc.). Finally, it disables HTTP redirects; this is critical because an attacker could provide a URL that points to a benign domain they control, which then issues a 302 redirect to an internal resource, bypassing the initial domain check.

public function fetchExternalData(Request $request) {
    $url = $request->input('url');
    $allowed_domains = ['trusted-api.com', 'cdn.partner.org'];
$parsedUrl = parse_url($url);
$host = $parsedUrl['host'] ?? null;
$scheme = $parsedUrl['scheme'] ?? null;

// 1. Enforce HTTPS and Whitelist
if ($scheme !== 'https' || !in_array($host, $allowed_domains)) {
    abort(403, 'Invalid target host');
}

// 2. Prevent DNS Rebinding / Private IP access
$ip = gethostbyname($host);
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
    abort(403, 'Internal IP access prohibited');
}

// 3. Disable redirects to prevent bypasses
return Http::timeout(5)->withOptions([
    'allow_redirects' => false,
    'connect_timeout' => 2
])->get($url)->body();

}

System Alert • ID: 9626
Target: Laravel API
Potential Vulnerability

Your Laravel API might be exposed to SSRF (Server Side Request Forgery)

74% of Laravel apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.