Link Search Menu Expand Document

Server-Side Request Forgery in .NET

Play SecureFlag Play .NET Labs on this vulnerability with SecureFlag!

Vulnerable Example

The code snippet below is one example of how remote resources can be fetched from a Java web application:

private static string GetRemoteObject(string location) 
{
    using (var client = new WebClient()) {
        return client.DownloadString(location);
    }
}

However, this code has two vulnerabilities:

  1. The .NET WebClient allows more schemes than just HTTP, such as the file:// protocol, which could be used to fetch local files.
  2. There are no restrictions on which domains can be included or excluded, which could lead to internal resources being fetched, including those residing in localhost or the internal network.

Prevention

Fetching a user-provided URL is a sensitive operation, especially when the user can read the response. In such cases, it is advisable to use an allow-list approach, where only certain protocols, domains, paths, etc. are permitted to be requested, and all others are rejected.

To harden the code and only allow HTTP/S resources from specific subdomains, the following modifications can be made:

private static string GetRemoteObject(string location)
{
    Uri url = new Uri(location);
    
    if (!url.Host.EndsWith(".example.com") || 
        (!url.Scheme.Equals("http") &&
        !url.Scheme.Equals("https")))
    {
        throw new Exception("Forbidden remote source");
    }

    using (var client = new WebClient())
    {
        return client.DownloadString(location);
    }
}