GuardAPI Logo
GuardAPI

Fix SSRF (Server Side Request Forgery) in Ktor

SSRF in Ktor manifests when the backend HttpClient processes user-controlled URLs to fetch resources. Without strict validation, an attacker can coerce the server into making requests to internal loopback interfaces, cloud metadata services (like 169.254.169.254), or non-public subnets. In a Ktor environment, this typically involves a route taking a 'url' parameter and passing it directly to an HttpClient instance.

The Vulnerable Pattern

get("/fetch") {
    val userUrl = call.parameters["url"] ?: return@get call.respond(HttpStatusCode.BadRequest)
    val client = HttpClient(CIO)
    // CRITICAL: No validation on userUrl. Attacker can pass http://localhost:8080/admin or http://169.254.169.254/latest/meta-data/
    val response: HttpResponse = client.get(userUrl)
    call.respond(response.bodyAsText())
}

The Secure Implementation

The fix involves three layers of defense. First, use a strict allowlist for domains to prevent arbitrary internet or intranet pivoting. Second, enforce the URI scheme to HTTPS to prevent protocol smuggling (e.g., file:// or gopher://). Third, perform URI parsing using a robust library rather than regex to avoid bypasses. For high-security environments, you should also resolve the hostname to an IP and verify it is not within a private range (RFC 1918) to mitigate DNS Rebinding attacks.

val ALLOWED_HOSTS = setOf("api.trusted-service.com", "cdn.trusted-service.com")

get(“/fetch”) { val userUrl = call.parameters[“url”] ?: return@get call.respond(HttpStatusCode.BadRequest) val uri = try { java.net.URI(userUrl) } catch (e: Exception) { null }

// 1. Validate Scheme (Force HTTPS)
// 2. Validate Host against an Allowlist
if (uri == null || uri.scheme != "https" || !ALLOWED_HOSTS.contains(uri.host)) {
    return@get call.respond(HttpStatusCode.Forbidden, "Invalid target host")
}

val client = HttpClient(CIO)
val response: HttpResponse = client.get(uri.toString())
call.respond(response.bodyAsText())

}

System Alert • ID: 7149
Target: Ktor API
Potential Vulnerability

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

74% of Ktor 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.