SSRF

Example 1 (Java)

Vulnerable Code:

import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class SSRFVulnerable {
    public static String fetchUrl(String urlString) throws Exception {
        URL url = new URL(urlString);
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuilder content = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            content.append(line);
        }
        reader.close();
        return content.toString();
    }
}

Reason for Vulnerability:

This code allows an attacker to specify any URL, potentially accessing internal resources or making requests to unintended destinations.

Fixed Code:

Reason for Fix:

The fixed code implements a whitelist of allowed hosts and checks if the provided URL's host is in this list. It also prevents access to loopback and local addresses, mitigating the risk of SSRF attacks.

Example 2 (Java)

Vulnerable Code:

Reason for Vulnerability:

This endpoint allows an attacker to specify any URL, potentially accessing internal resources or making requests to unintended destinations.

Fixed Code:

Reason for Fix:

The fixed code implements URL validation using a regex pattern and restricts requests to a specific allowed domain. This prevents attackers from accessing internal resources or making requests to unintended destinations.

Example 3 (Python)

Vulnerable Code:

Reason for Vulnerability:

This Flask application creates a proxy endpoint that makes requests to any URL provided as a query parameter, allowing potential SSRF attacks.

Fixed Code:

Reason for Fix:

The fixed code implements several security measures:

  1. It checks if the URL's domain is in the allowed list.

  2. It validates that the URL uses either HTTP or HTTPS protocols.

  3. If the hostname is an IP address, it ensures it's a valid public IP address.

  4. It disables redirects to prevent potential bypass techniques. These measures significantly reduce the risk of SSRF attacks while still allowing the proxy functionality for legitimate use cases.


Example 1: Java

Vulnerable Code:

Reason for vulnerability: User-controlled URL can lead to SSRF attacks.

Fixed Code:

Reason for fix: Validate the URL to prevent SSRF attacks.

Example 2: Python

Vulnerable Code:

Reason for vulnerability: User-controlled URL can lead to SSRF attacks.

Fixed Code:

Reason for fix: Validate the URL to prevent SSRF attacks.

Last updated