Files
openwaf/dotnet/OpenWaf.Tests.Integration/ProvenanceAndLimitsTests.cs
T
Pavlo Ratushnyi 8fba8447e9 A misspelled provenance filter deleted the operator's own block list
ParseSource mapped any unrecognised string to BlockSource.Operator. Measured on
the shipped image (openwaf:ci), with two operator blocks and three engine bans
live:

  GET    /admin-api/blocks?source=enigne -> 200, the operator list, engine bans hidden
  DELETE /admin-api/blocks?source=enigne -> 200 {"deleted":1}, then operator=0 engine=3

The caller who mistyped "engine" while clearing automatic bans erased the
operator's hand-maintained list instead — the exact failure the comment above
that endpoint says the provenance parameter exists to prevent. A missing source
was already refused with 400; a misspelled one was not.

After the fix, same image, same script:

  GET    ?source=enigne   -> 400 source must be operator|engine|all; got "enigne"
  DELETE ?source=enigne   -> 400, counts unchanged (operator=2 engine=3)
  DELETE ?source=engine   -> 200 {"deleted":3}, then operator=2 engine=0

Two more of the same family, both measured on the image:

  expiresInMinutes: 0 and -5 -> 204 with expiresAt: null. Not "no expiry given",
    but a permanent allow entry — the one control that outranks every ban — from
    a field left at zero. Absent is now the only way to say never; present must
    be 1..5256000 or it is a 400. The console page refuses 0 in the field before
    the round trip, and the gate asserts both halves: 0 is refused, empty still
    means never.
  a 1 MB reason and a 1 MB note -> 204, and the listings then returned
    ~1,000,287 and ~1,000,722 bytes for a handful of rows. Operator notes are
    bounded at 512 characters, the budget the attacker-written path field
    already gets, so the two columns in the same table are the same size.

  unit 126/126 (unchanged), integration 62 -> 73 (+11), console 37 -> 39

Teeth, each measured by putting the old line back: old ParseSource -> exactly 5
integration tests fail; expiry guard off -> exactly 3; length guards off ->
exactly 1.
2026-10-02 01:21:20 +02:00

196 lines
9.2 KiB
C#

using System.Net;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
/// <summary>
/// Three more ways the admin API answered "yes" to something it did not mean.
/// All three were measured on the shipped image (openwaf:ci) before the fix.
///
/// 1. The provenance filter. <c>ParseSource</c> mapped any unrecognised string
/// to <c>BlockSource.Operator</c>. With two operator blocks and three engine
/// bans live:
/// GET /admin-api/blocks?source=enigne → 200, the operator list, engine bans hidden
/// DELETE /admin-api/blocks?source=enigne → 200 {"deleted":1}, then operator=0 engine=3
/// The caller who mistyped "engine" while clearing automatic bans erased the
/// operator's own list — the one thing the comment on that endpoint says the
/// provenance parameter exists to prevent. A missing source was already
/// refused; a misspelled one was not.
/// 2. <c>expiresInMinutes: 0</c> and <c>-5</c> → 204 with <c>expiresAt: null</c>:
/// a permanent allow entry, silently, on the control that outranks every ban.
/// 3. A 1 MB <c>reason</c> and a 1 MB <c>note</c> → 204, and the listings then
/// returned ~1,000,287 and ~1,000,722 bytes for a handful of rows.
/// </summary>
public sealed class ProvenanceAndLimitsTests
{
private const string OperatorBlocked = "203.0.113.66";
private const string Scanner = "203.0.113.88";
private static async Task<(HttpStatusCode Status, string Body)> SendAsync(
EdgeFixture f, HttpMethod method, string path, string? json = null)
{
using var request = new HttpRequestMessage(method, path);
if (json is not null)
request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
var response = await f.Client.SendAsync(request);
return (response.StatusCode, await response.Content.ReadAsStringAsync());
}
private static async Task GetAsync(EdgeFixture f, string ip)
{
using var request = new HttpRequestMessage(HttpMethod.Get, "/nope");
request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
await f.Client.SendAsync(request);
}
private static async Task<Dictionary<string, int>> CountsAsync(EdgeFixture f)
{
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
return (await db.Blocks.AsNoTracking().ToListAsync())
.GroupBy(b => b.Source.ToString())
.ToDictionary(g => g.Key, g => g.Count());
}
[Theory]
[InlineData("enigne")]
[InlineData("bogus")]
[InlineData("operatorz")]
[InlineData("оператор")]
public async Task A_misspelled_provenance_filter_is_refused_instead_of_answering_with_the_operator_list(string source)
{
await using var f = new EdgeFixture(threshold: 2);
await SendAsync(f, HttpMethod.Post, "/admin-api/blocks",
"{\"ip\":\"" + OperatorBlocked + "\",\"reason\":\"operator list\"}");
for (var i = 0; i < 2; i++) await GetAsync(f, Scanner);
var (status, body) = await SendAsync(f, HttpMethod.Get, "/admin-api/blocks?live=false&source=" + source);
Assert.Equal(HttpStatusCode.BadRequest, status);
Assert.Contains("source must be operator|engine|all", body);
Assert.Contains(source, body);
}
[Fact]
public async Task A_misspelled_source_on_a_delete_cannot_erase_the_operators_own_list()
{
await using var f = new EdgeFixture(threshold: 2);
await SendAsync(f, HttpMethod.Post, "/admin-api/blocks",
"{\"ip\":\"" + OperatorBlocked + "\",\"reason\":\"operator list\"}");
for (var i = 0; i < 2; i++) await GetAsync(f, Scanner);
var before = await CountsAsync(f);
Assert.Equal(1, before["Operator"]);
Assert.True(before["Engine"] >= 1);
// Measured before the fix: 200 {"deleted":1}, and afterwards the operator
// row was gone while the engine bans the caller meant to clear stayed.
var (status, body) = await SendAsync(f, HttpMethod.Delete, "/admin-api/blocks?source=enigne");
Assert.Equal(HttpStatusCode.BadRequest, status);
Assert.Contains("enigne", body);
var after = await CountsAsync(f);
Assert.Equal(before["Operator"], after["Operator"]);
Assert.Equal(before["Engine"], after["Engine"]);
}
[Fact]
public async Task The_documented_provenance_filter_still_works()
{
await using var f = new EdgeFixture(threshold: 2);
await SendAsync(f, HttpMethod.Post, "/admin-api/blocks",
"{\"ip\":\"" + OperatorBlocked + "\",\"reason\":\"operator list\"}");
for (var i = 0; i < 2; i++) await GetAsync(f, Scanner);
foreach (var source in new[] { "operator", "engine", "OPERATOR", " all ", "" })
{
var (status, _) = await SendAsync(f, HttpMethod.Get, "/admin-api/blocks?live=false&source=" + source);
Assert.Equal(HttpStatusCode.OK, status);
}
var (deleteStatus, deleteBody) = await SendAsync(f, HttpMethod.Delete, "/admin-api/blocks?source=engine");
Assert.Equal(HttpStatusCode.OK, deleteStatus);
Assert.True(JsonDocument.Parse(deleteBody).RootElement.GetProperty("deleted").GetInt32() >= 1);
Assert.Equal(0, (await CountsAsync(f)).TryGetValue("Engine", out var engine) ? engine : 0);
}
[Theory]
[InlineData(0)]
[InlineData(-5)]
[InlineData(5256001)]
public async Task An_expiry_that_cannot_mean_what_it_was_asked_is_refused_rather_than_becoming_never(int minutes)
{
await using var f = new EdgeFixture();
var (status, body) = await SendAsync(f, HttpMethod.Post, "/admin-api/allow",
"{\"match\":\"198.51.100.7\",\"note\":\"bounded\",\"expiresInMinutes\":" + minutes + "}");
Assert.Equal(HttpStatusCode.BadRequest, status);
Assert.Contains("expiresInMinutes", body);
Assert.Contains(minutes.ToString(), body);
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
Assert.Empty(await db.AllowEntries.Where(a => a.Match == "198.51.100.7").ToListAsync());
}
[Fact]
public async Task Leaving_the_expiry_out_is_the_only_way_to_ask_for_never()
{
await using var f = new EdgeFixture();
var (absentStatus, _) = await SendAsync(f, HttpMethod.Post, "/admin-api/allow",
"{\"match\":\"198.51.100.7\",\"note\":\"no expiry given\"}");
Assert.Equal(HttpStatusCode.NoContent, absentStatus);
var (oneStatus, _) = await SendAsync(f, HttpMethod.Post, "/admin-api/allow",
"{\"match\":\"198.51.100.8\",\"note\":\"one minute\",\"expiresInMinutes\":1}");
Assert.Equal(HttpStatusCode.NoContent, oneStatus);
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var entries = await db.AllowEntries.AsNoTracking().ToListAsync();
var never = entries.Single(a => a.Match == "198.51.100.7");
var bounded = entries.Single(a => a.Match == "198.51.100.8");
Assert.Null(never.ExpiresAt);
Assert.NotNull(bounded.ExpiresAt);
Assert.InRange(bounded.ExpiresAt!.Value, DateTimeOffset.UtcNow.AddSeconds(50), DateTimeOffset.UtcNow.AddMinutes(2));
}
[Fact]
public async Task An_operator_note_is_bounded_the_way_the_attacker_written_fields_already_are()
{
await using var f = new EdgeFixture();
var tooLong = new string('R', EntryLimits.NoteMaxLength + 1);
var fits = new string('R', EntryLimits.NoteMaxLength);
var (reasonStatus, reasonBody) = await SendAsync(f, HttpMethod.Post, "/admin-api/blocks",
JsonSerializer.Serialize(new { ip = OperatorBlocked, reason = tooLong }));
Assert.Equal(HttpStatusCode.BadRequest, reasonStatus);
Assert.Contains("reason must be at most 512 characters", reasonBody);
var (noteStatus, noteBody) = await SendAsync(f, HttpMethod.Post, "/admin-api/allow",
JsonSerializer.Serialize(new { match = "198.51.100.9", note = tooLong }));
Assert.Equal(HttpStatusCode.BadRequest, noteStatus);
Assert.Contains("note must be at most 512 characters", noteBody);
var (okReason, _) = await SendAsync(f, HttpMethod.Post, "/admin-api/blocks",
JsonSerializer.Serialize(new { ip = OperatorBlocked, reason = fits }));
Assert.Equal(HttpStatusCode.NoContent, okReason);
var (okNote, _) = await SendAsync(f, HttpMethod.Post, "/admin-api/allow",
JsonSerializer.Serialize(new { match = "198.51.100.9", note = fits }));
Assert.Equal(HttpStatusCode.NoContent, okNote);
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
Assert.Single(await db.Blocks.Where(b => b.SourceKey == OperatorBlocked).ToListAsync());
Assert.Single(await db.AllowEntries.Where(a => a.Match == "198.51.100.9").ToListAsync());
}
}