GuardAPI Logo
GuardAPI
Automated Security Protocol

How to fix SSRF (Server Side Request Forgery)
in Vapor (Swift)

Executive Summary

SSRF in Vapor is a critical vulnerability where an attacker forces the server to make unauthorized requests to internal or external resources. In Swift-based backends, this typically occurs when the 'req.client' service is used with unvalidated user input. This can lead to internal port scanning, cloud metadata theft (IMDSv2), or bypassing firewalls.

The Vulnerable Pattern

VULNERABLE CODE
app.get("fetch") { req -> EventLoopFuture in
    let userUrl = req.query["url"] ?? ""
    // VULNERABLE: Direct use of user-controlled string in client request
    return req.client.get(URI(string: userUrl))
}

The Secure Implementation

The secure implementation follows the principle of 'Default Deny'. First, we parse the raw string into a Vapor URI object to extract the host and scheme safely. We enforce HTTPS to prevent protocol smuggling (e.g., file:// or gopher://). Most importantly, we validate the host against a strict allowlist. This prevents attackers from targeting loopback addresses (127.0.0.1) or cloud provider metadata endpoints (169.254.169.254) which are common targets in SSRF attacks.

SECURE CODE
app.get("fetch") { req -> EventLoopFuture in
    guard let urlString = req.query["url"],
          let uri = URI(string: urlString),
          let host = uri.host else {
        throw Abort(.badRequest)
    }
// 1. Protocol Enforcement (HTTPS only)
guard uri.scheme == "https" else {
    throw Abort(.forbidden, reason: "Insecure protocol.")
}

// 2. Strict Allowlisting
let allowedHosts = ["api.trusted-partner.com", "cdn.myapp.com"]
guard allowedHosts.contains(host) else {
    throw Abort(.forbidden, reason: "Target host not authorized.")
}

return req.client.get(uri)

}

System Alert • ID: 7131
Target: Vapor (Swift) API
Potential Vulnerability

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

74% of Vapor (Swift) 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.