Server-side request forgery (SSRF)

Server-side request forgery (SSRF)

Description

Server-side request forgery occurs when user input directly controls the URL or host of an outbound server request. An attacker can make the server request loopback addresses such as 127.0.0.1, metadata endpoints, private IP addresses or services that should not be externally accessible. Depending on the destination, this may bypass access controls, reveal internal information or enable port scanning.

Potential impact

  • Users may send requests through the server to private APIs, administration consoles or other internal services, potentially exploiting additional vulnerabilities there.
  • Requests to metadata or configuration services may expose tokens, credentials or settings.
  • Using the application server as a proxy may bypass network controls that block direct external access.
  • Repeated requests to slow destinations or large responses may exhaust resources and disrupt service.

Remediation

  1. Let callers select an identifier such as users and map it to a fixed server-owned URL. If callers supply a path or query value, restrict its format and encode it for that position.
  2. If destinations must be dynamic, allow only approved hosts or domains, http or https schemes, and required ports. Resolve the hostname with LookupIP. Check the IPv4 or IPv6 address you will use against your policy for loopback, private, link-local and metadata addresses. To prevent DNS rebinding, have a custom DialContext connect directly to that checked IP.
  3. Trust the DNS and services for your destinations, and restrict outbound network access. Set timeouts, a redirect policy, and a response-size limit. Test the restrictions and monitor unexpected outbound requests.

Examples

Before

go
package main

import (
    "io"
    "log"
    "net/http"
)

// Before: an unsafe SSRF example
func proxyHandler(w http.ResponseWriter, r *http.Request) {
    // Accept the complete URL directly from user input
    target := r.URL.Query().Get("url")
    if target == "" {
        http.Error(w, "missing url", http.StatusBadRequest)
        return
    }

    // Unsafe: the server requests the user-supplied URL
    // Example: http://myserver/proxy?url=http://169.254.169.254/latest/meta-data/
    resp, err := http.Get(target)
    if err != nil {
        http.Error(w, "request failed", http.StatusBadGateway)
        return
    }
    defer resp.Body.Close()

    // Relay the response directly
    w.WriteHeader(resp.StatusCode)
    if _, err := io.Copy(w, resp.Body); err != nil {
        log.Println("write response error:", err)
    }
}

func main() {
    http.HandleFunc("/proxy", proxyHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

After

go
package main

import (
    "io"
    "log"
    "net/http"
    "time"
)

var outboundClient = &http.Client{
    Timeout: 5 * time.Second,
    CheckRedirect: func(req *http.Request, via []*http.Request) error {
        // Do not follow redirects from the allowed host to internal addresses or other hosts.
        return http.ErrUseLastResponse
    },
}

func safeProxyHandler(w http.ResponseWriter, r *http.Request) {
    endpointID := r.URL.Query().Get("endpoint")
    var target string
    // Input selects only a fixed server-managed endpoint, not an arbitrary URL.
    switch endpointID {
    case "users":
        target = "https://api.example.com/v1/users"
    case "status":
        target = "https://status.example.com/api/status"
    default:
        http.Error(w, "unknown endpoint", http.StatusBadRequest)
        return
    }

    req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, target, nil)
    if err != nil {
        http.Error(w, "request build failed", http.StatusInternalServerError)
        return
    }

    resp, err := outboundClient.Do(req)
    if err != nil {
        http.Error(w, "request failed", http.StatusBadGateway)
        return
    }
    defer resp.Body.Close()

    w.Header().Set("Content-Type", "application/octet-stream")
    w.Header().Set("X-Content-Type-Options", "nosniff")
    w.WriteHeader(resp.StatusCode)
    const maxResponseBytes = 1024 * 1024
    if _, err := io.Copy(w, io.LimitReader(resp.Body, maxResponseBytes)); err != nil {
        log.Println("write response error:", err)
    }
}

func main() {
    http.HandleFunc("/proxy", safeProxyHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

users and status each select a fixed URL. CheckRedirect stops redirects, the client has a five-second timeout, and the handler forwards up to 1 MiB. application/octet-stream and nosniff keep the browser from treating the response as HTML from your site.

References