fix(security): Phase 4 edge hardening + SSRF egress guard
Backend security fixes from the Phase 1 register / Phase 2 roadmap (PR1 + V-01): - V-01 SSRF: new SafeHttpGuard validates outbound unsubscribe URLs (scheme allowlist + DNS-resolve-and-block private/loopback/link-local/ULA/metadata ranges), wired into UnsubscribeService; the "unsubscribe" HttpClient now disables auto-redirect so a validated external URL can't 3xx into an internal target. +33 unit tests. - V-04: session cookie SecurePolicy=Always in non-dev (SameAsRequest in dev). - V-06: UseExceptionHandler/ProblemDetails in prod; Cleanup/Unsubscribe no longer echo ex.Message to clients (logged server-side, generic message returned). - V-08: ForwardedHeaders trusted only from configurable KnownNetworks (default private ranges) + ForwardLimit, instead of trusting any client. New ForwardedHeaders config. - V-09: returnUrl validated with Url.IsLocalUrl (no open redirect via OAuth flow). - V-10: SearchService clamps Page/PageSize (<=200); Analytics clamps take/days. - V-11: baseline security headers (nosniff, X-Frame-Options DENY, Referrer-Policy, COOP) + HSTS in prod. - V-13: /app/info discloses only devMode to anonymous callers unless dev mode is on. - V-12: API container runs as non-root 'app' user (keys dir pre-owned). - V-03: Postgres + API ports bound to 127.0.0.1; POSTGRES_PASSWORD now required (no weak default fallback). API compatibility preserved (clamps not rejections; error-body shape changes only on failure paths). No DB migrations. Build + all 33 unit tests green. V-15 (MailKit NU1902) persists across versions and the SMTP path is default-off — tracked, not bumped. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -100,8 +100,9 @@ public class CleanupService : ICleanupService
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Cleanup action {Action} failed for user {UserId}", request.Action, userId);
|
||||
errors.Add(ex.Message);
|
||||
return Result<CleanupResultDto>.Failure(ex.Message);
|
||||
// V-06: do not echo internal exception detail to the client.
|
||||
errors.Add("The cleanup action could not be completed.");
|
||||
return Result<CleanupResultDto>.Failure("The cleanup action could not be completed.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ using InboxIntel.Domain.Entities;
|
||||
using InboxIntel.Domain.Enums;
|
||||
using InboxIntel.Infrastructure.Gmail;
|
||||
using InboxIntel.Infrastructure.Persistence;
|
||||
using InboxIntel.Infrastructure.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
@@ -120,13 +121,17 @@ public class UnsubscribeService : IUnsubscribeService
|
||||
switch (item.Method)
|
||||
{
|
||||
case UnsubscribeMethod.OneClickPost:
|
||||
var post = await http.PostAsync(item.UnsubscribeTarget,
|
||||
// V-01: the target comes from an attacker-authored email header.
|
||||
// Validate against SSRF (scheme + private/metadata ranges) before fetching.
|
||||
var postUri = await SafeHttpGuard.ValidateAsync(item.UnsubscribeTarget, ct);
|
||||
var post = await http.PostAsync(postUri,
|
||||
new StringContent("List-Unsubscribe=One-Click"), ct);
|
||||
SetResult(item, post.IsSuccessStatusCode);
|
||||
if (post.IsSuccessStatusCode) ok++; else fail++;
|
||||
break;
|
||||
case UnsubscribeMethod.HttpLink:
|
||||
var get = await http.GetAsync(item.UnsubscribeTarget, ct);
|
||||
var getUri = await SafeHttpGuard.ValidateAsync(item.UnsubscribeTarget, ct);
|
||||
var get = await http.GetAsync(getUri, ct);
|
||||
SetResult(item, get.IsSuccessStatusCode);
|
||||
if (get.IsSuccessStatusCode) ok++; else fail++;
|
||||
break;
|
||||
@@ -140,12 +145,24 @@ public class UnsubscribeService : IUnsubscribeService
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
catch (SsrfBlockedException ex)
|
||||
{
|
||||
// Blocked target (e.g. points at an internal/metadata address). Log
|
||||
// server-side; surface only a generic reason to the client.
|
||||
fail++;
|
||||
item.Status = UnsubscribeStatus.Failed;
|
||||
item.ResultMessage = ex.Message;
|
||||
errors.Add($"{item.UnsubscribeTarget}: {ex.Message}");
|
||||
item.ResultMessage = "Unsubscribe link was blocked for safety.";
|
||||
_logger.LogWarning(ex, "Blocked unsubscribe target for user {UserId}", userId);
|
||||
errors.Add("An unsubscribe link was blocked for safety.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// V-06: log detail, return a generic message.
|
||||
fail++;
|
||||
item.Status = UnsubscribeStatus.Failed;
|
||||
item.ResultMessage = "Unsubscribe request failed.";
|
||||
_logger.LogWarning(ex, "Unsubscribe request failed for user {UserId}", userId);
|
||||
errors.Add("An unsubscribe request failed.");
|
||||
}
|
||||
}
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
@@ -60,7 +60,10 @@ public static class DependencyInjection
|
||||
services.AddHostedService<DigestWorker>();
|
||||
|
||||
// HTTP clients
|
||||
services.AddHttpClient("unsubscribe", c => c.Timeout = TimeSpan.FromSeconds(15));
|
||||
// V-01: do NOT follow redirects — a validated external URL must not be able to
|
||||
// 3xx-redirect into an internal target after SafeHttpGuard has checked it.
|
||||
services.AddHttpClient("unsubscribe", c => c.Timeout = TimeSpan.FromSeconds(15))
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
|
||||
services.AddHttpClient("ollama");
|
||||
services.AddHttpClient("openai");
|
||||
|
||||
|
||||
@@ -17,8 +17,17 @@ public class SearchService : ISearchService
|
||||
private readonly AppDbContext _db;
|
||||
public SearchService(AppDbContext db) => _db = db;
|
||||
|
||||
/// <summary>Hard upper bound on a user-facing page of results (V-10: DoS via huge pageSize).</summary>
|
||||
public const int MaxPageSize = 200;
|
||||
|
||||
public async Task<PagedResult<EmailSummaryDto>> SearchAsync(Guid userId, SearchRequestDto r, CancellationToken ct = default)
|
||||
{
|
||||
// V-10: clamp pagination at the user-facing chokepoint (covers both the GET
|
||||
// query-string path and the POST body path) so a caller cannot request an
|
||||
// unbounded materialisation. Internal callers (e.g. cleanup target resolution)
|
||||
// do not go through this service, so their larger pages are unaffected.
|
||||
r = r with { Page = Math.Max(1, r.Page), PageSize = Math.Clamp(r.PageSize, 1, MaxPageSize) };
|
||||
|
||||
var q = _db.Emails.AsNoTracking().Where(e => e.UserId == userId);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(r.Sender))
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace InboxIntel.Infrastructure.Security;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class SafeHttpGuard
|
||||
{
|
||||
/// <summary>
|
||||
/// Throws <see cref="SsrfBlockedException"/> if the URL is unsafe to fetch.
|
||||
/// Returns the validated absolute Uri otherwise.
|
||||
/// </summary>
|
||||
public static async Task<Uri> 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;
|
||||
}
|
||||
|
||||
/// <summary>True if the address is in a range we must never fetch server-side.</summary>
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Raised when an outbound URL is rejected by <see cref="SafeHttpGuard"/>.</summary>
|
||||
public class SsrfBlockedException : Exception
|
||||
{
|
||||
public SsrfBlockedException(string message) : base(message) { }
|
||||
}
|
||||
Reference in New Issue
Block a user