---
title: Protect Against SSRF Attacks
impact: MEDIUM
impactDescription: prevents internal network access from user input
tags: ssrf, url, network, internal, security, csharp
---

## Protect Against SSRF Attacks

Server-Side Request Forgery occurs when the server fetches a URL provided by the attacker.

**Incorrect (fetching user URL):**

```csharp
public async Task<string> FetchUrl(string url)
{
    using var client = new HttpClient();
    return await client.GetStringAsync(url); // Attacker can access internal metadata/localhost
}
```

**Correct (validation):**

```csharp
public async Task<string> SafeFetchUrl(string inputUrl)
{
    if (!Uri.TryCreate(inputUrl, UriKind.Absolute, out var uri))
        throw new ArgumentException("Invalid URL");

    if (uri.Scheme != "http" && uri.Scheme != "https")
        throw new ArgumentException("Invalid Scheme");

    // Block non-standard ports
    if (!uri.IsDefaultPort) throw new ArgumentException("Port not allowed");

    // Resolve IP and check blocklist (simplified)
    var ipAddresses = await Dns.GetHostAddressesAsync(uri.DnsSafeHost);
    foreach (var ip in ipAddresses)
    {
        if (IsPrivateIp(ip)) throw new Exception("SSRF Detected: Private IP");
    }

    using var client = new HttpClient();
    return await client.GetStringAsync(uri);
}

private bool IsPrivateIp(IPAddress ip)
{
    // Check for 127.0.0.1, 10.x.x.x, 192.168.x.x, etc.
    return IPAddress.IsLoopback(ip) || ip.ToString().StartsWith("10.") || ip.ToString().StartsWith("192.168.");
}
```

**Tools:** Security Code Scan, SonarQube
