---
title: Protect Against SSRF Attacks
impact: CRITICAL
impactDescription: prevents attackers from making requests to internal infrastructure or cloud metadata endpoints via the server
tags: ssrf, url, network, internal, security, kotlin
---

## Protect Against SSRF Attacks

Server-Side Request Forgery (SSRF) allows an attacker to force the server to make HTTP requests to an arbitrary domain. This is often used to scan internal networks, access private local services (e.g., Redis, DBs), or steal credentials from Cloud Metadata services (AWS/GCP/Azure metadata endpoints).

**Incorrect (trusting user-provided URLs):**

```kotlin
// VULNERABLE: Direct use of user input in a network client
@GetMapping("/proxy")
fun fetchUrl(@RequestParam url: String): String {
    val client = HttpClient.newHttpClient()
    val request = HttpRequest.newBuilder().uri(URI.create(url)).build()
    return client.send(request, BodyHandlers.ofString()).body()
}
// Attacker: /proxy?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/
```

**Correct (strict validation and allow-listing):**

```kotlin
import java.net.InetAddress
import java.net.URI

private val ALLOWED_DOMAINS = setOf("trusted-api.com", "cdn.com")

fun safeFetch(targetUrl: String): String {
    val uri = URI(targetUrl)
    
    // 1. Protocol Whitelist
    if (uri.scheme != "http" && uri.scheme != "https") {
        throw SecurityException("Protocol not allowed")
    }

    // 2. Domain Whitelist (Recommended)
    if (!ALLOWED_DOMAINS.contains(uri.host)) {
        throw SecurityException("Domain not authorized")
    }

    // 3. IP Check (preventing local/private IP access)
    val address = InetAddress.getByName(uri.host)
    if (address.isLoopbackAddress || address.isSiteLocalAddress || address.isLinkLocalAddress) {
        throw SecurityException("Internal network access forbidden")
    }

    // 4. Disable Redirects or manually validate them
    val client = HttpClient.newBuilder()
        .followRedirects(HttpClient.Redirect.NEVER)
        .build()
        
    // Execute request...
    return "" 
}
```

**SSRF Prevention Guidelines:**
- **Whitelisting:** Only allow requests to a predefined list of trusted domains.
- **Protocol Restriction:** Only allow `http` and `https`. Block `file://`, `gopher://`, `dict://`, etc.
- **Internal Network Blocking:** Block access to `localhost`, `127.0.0.1`, and private IP ranges (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`).
- **Cloud Metadata Blocking:** Explicitly block `169.254.169.254`.
- **DNS Resolution:** Perform validation on the resolved IP address, not just the hostname.

**Tools:** SonarQube (S5144), Semgrep, OWASP SSRF Prevention Cheat Sheet
