using System.Net;
using System.Net.Sockets;
namespace InboxIntel.Infrastructure.Security;
///
/// Validates outbound request URLs before the server fetches them, to prevent
/// SSRF (V-01). Used by the unsubscribe processor (URLs come from attacker-authored
/// List-Unsubscribe headers) and intended for any future server-initiated fetch
/// (AI/breach providers). Enforces an http/https scheme allowlist and rejects hosts
/// that resolve to loopback / private / link-local / unique-local / multicast ranges
/// or the cloud metadata address. DNS is resolved and EVERY resolved address is
/// checked, defeating DNS-rebinding to an external name that points at an internal IP.
///
/// Pair this with an HttpClient configured with AllowAutoRedirect = false so a
/// permitted external URL cannot 3xx-redirect into an internal target post-validation.
///
public static class SafeHttpGuard
{
///
/// Throws if the URL is unsafe to fetch.
/// Returns the validated absolute Uri otherwise.
///
public static async Task ValidateAsync(string? url, CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(url) || !Uri.TryCreate(url, UriKind.Absolute, out var uri))
throw new SsrfBlockedException("Unsubscribe target is not a valid absolute URL.");
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
throw new SsrfBlockedException($"Disallowed URL scheme '{uri.Scheme}'.");
// Resolve the host; if it's already a literal IP, GetHostAddressesAsync returns it.
IPAddress[] addresses;
try
{
addresses = await Dns.GetHostAddressesAsync(uri.DnsSafeHost, ct);
}
catch (Exception ex) when (ex is SocketException or ArgumentException)
{
throw new SsrfBlockedException("Unsubscribe target host could not be resolved.");
}
if (addresses.Length == 0)
throw new SsrfBlockedException("Unsubscribe target host did not resolve to any address.");
foreach (var ip in addresses)
if (IsBlocked(ip))
throw new SsrfBlockedException($"Unsubscribe target resolves to a disallowed address ({ip}).");
return uri;
}
/// True if the address is in a range we must never fetch server-side.
public static bool IsBlocked(IPAddress ip)
{
if (IPAddress.IsLoopback(ip)) return true;
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
var b = ip.GetAddressBytes(); // big-endian
// 0.0.0.0/8 (this host), 10/8, 100.64/10 (CGNAT), 127/8, 169.254/16 (link-local + metadata),
// 172.16/12, 192.0.0/24, 192.168/16, 255.255.255.255
if (b[0] == 0) return true;
if (b[0] == 10) return true;
if (b[0] == 100 && b[1] >= 64 && b[1] <= 127) return true;
if (b[0] == 127) return true;
if (b[0] == 169 && b[1] == 254) return true; // includes 169.254.169.254 metadata
if (b[0] == 172 && b[1] >= 16 && b[1] <= 31) return true;
if (b[0] == 192 && b[1] == 168) return true;
if (ip.Equals(IPAddress.Broadcast)) return true;
if (b[0] >= 224) return true; // multicast / reserved
return false;
}
if (ip.AddressFamily == AddressFamily.InterNetworkV6)
{
if (ip.IsIPv6LinkLocal || ip.IsIPv6SiteLocal || ip.IsIPv6Multicast) return true;
// IPv4-mapped (::ffff:a.b.c.d) — re-check the embedded v4 address.
if (ip.IsIPv4MappedToIPv6) return IsBlocked(ip.MapToIPv4());
var b = ip.GetAddressBytes();
// Unique-local fc00::/7
if ((b[0] & 0xFE) == 0xFC) return true;
return false;
}
return true; // unknown family — fail closed
}
}
/// Raised when an outbound URL is rejected by .
public class SsrfBlockedException : Exception
{
public SsrfBlockedException(string message) : base(message) { }
}