diff --git a/dotnet/OpenWaf.Domain/Security/EntryLimits.cs b/dotnet/OpenWaf.Domain/Security/EntryLimits.cs
new file mode 100644
index 0000000..34f3147
--- /dev/null
+++ b/dotnet/OpenWaf.Domain/Security/EntryLimits.cs
@@ -0,0 +1,35 @@
+namespace OpenWaf.Domain.Security;
+
+///
+/// How long an operator-authored note may be, and how long an exemption may
+/// last. Said once, next to the reason.
+///
+/// The fields the attacker writes are already bounded — the path an observation
+/// keeps is truncated to 512 and the User-Agent to 256 — while the fields the
+/// operator writes were not bounded at all: a 1 MB reason and a 1 MB note were
+/// both accepted with 204, and the listings then returned ~1,000,287 and
+/// ~1,000,722 bytes for a handful of rows. The console renders every reason into
+/// a table cell, so "unbounded" there means a page that cannot be read.
+///
+/// The expiry bound is the same class of mistake with sharper edges. The old
+/// shape — `is > 0 ? UtcNow.AddMinutes(n) : null` — made `expiresInMinutes: 0`
+/// and `expiresInMinutes: -5` mean "never expires", silently, on the one control
+/// that outranks every ban in the system. A form that sends 0 for an empty field
+/// does not create a short exemption; it creates a permanent one.
+///
+public static class EntryLimits
+{
+ /// An operator's note about why a source is blocked or allowlisted.
+ /// 512 is the budget the attacker-controlled path field already gets, so the
+ /// two columns in the same table are the same size.
+ public const int NoteMaxLength = 512;
+
+ /// 10 years. Long enough that "until this contract ends" is
+ /// expressible; short enough that a permanent exemption is a thing you have
+ /// to say on purpose by leaving the field out.
+ public const int ExpiresInMinutesMin = 1, ExpiresInMinutesMax = 5_256_000;
+
+ public static bool NoteOk(string? value) => value is null || value.Length <= NoteMaxLength;
+ public static bool ExpiresInMinutesOk(int value) =>
+ value >= ExpiresInMinutesMin && value <= ExpiresInMinutesMax;
+}
diff --git a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs
index 1e108fa..65b0897 100644
--- a/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs
+++ b/dotnet/OpenWaf.Edge/Admin/AdminConsole.cs
@@ -302,10 +302,23 @@ el('addBlock').onclick = async () => {
el('addAllow').onclick = async () => {
const match = el('allowMatch').value.trim();
if (!match) { note('an address or CIDR first', true); return; }
- const ttl = parseInt(el('allowTtl').value, 10);
+ // A TTL of 0 used to fall through to null, and null is how this API says
+ // "never expires" — the one exemption that outranks every ban, arriving from a
+ // field left at zero. The API refuses that now; the page says so before the
+ // round trip. Empty is still the way to ask for never, on purpose.
+ const rawTtl = el('allowTtl').value.trim();
+ let ttl = null;
+ if (rawTtl !== '') {
+ const parsed = Number(rawTtl);
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 5256000) {
+ note('a TTL in minutes (1..5256000), or leave it empty for never', true);
+ return;
+ }
+ ttl = parsed;
+ }
if (await postJson('/admin-api/allow', { match,
note: el('allowNote').value.trim() || 'allowlisted from the console',
- expiresInMinutes: Number.isFinite(ttl) && ttl > 0 ? ttl : null })) {
+ expiresInMinutes: ttl })) {
el('allowMatch').value = ''; el('allowNote').value = ''; el('allowTtl').value = '';
note('allowlisted ' + match, false);
load();
diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs
index f523b9f..7b70a66 100644
--- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs
+++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs
@@ -71,11 +71,12 @@ internal static class AdminEndpoints
group.MapGet("/blocks", async (string? source, bool? live, int? limit, int? offset, BlockStore store, HttpContext ctx, CancellationToken ct) =>
{
+ if (!TryParseSource(source, out var wanted)) return BadSource(source);
var now = DateTimeOffset.UtcNow;
var take = Math.Clamp(limit ?? BlockStore.ListDefaultLimit, 1, BlockStore.ListMaxLimit);
var skip = Math.Max(0, offset ?? 0);
- var rows = await store.ListAsync(ParseSource(source), live ?? true, now, take, skip, ct);
- var total = await store.CountAsync(ParseSource(source), live ?? true, now, ct);
+ var rows = await store.ListAsync(wanted, live ?? true, now, take, skip, ct);
+ var total = await store.CountAsync(wanted, live ?? true, now, ct);
// The listing is capped; the header is what stops a page of 500
// reading like a complete answer.
ctx.Response.Headers["X-Total-Count"] = total.ToString();
@@ -86,6 +87,8 @@ internal static class AdminEndpoints
group.MapPost("/blocks", async (NewBlockRequest req, BlockStore store, CancellationToken ct) =>
{
if (string.IsNullOrWhiteSpace(req.Ip)) return Results.BadRequest(new { error = "ip is required" });
+ if (!EntryLimits.NoteOk(req.Reason))
+ return Results.BadRequest(new { error = $"reason must be at most {EntryLimits.NoteMaxLength} characters; got {req.Reason!.Length}" });
// The target goes into a Location header on the next request from
// this source. Measured on the shipped image, POST answered 204 for
// every string, and a redirectTo holding CRLF made that next request
@@ -100,7 +103,7 @@ internal static class AdminEndpoints
// automatic bans" must never be able to erase an operator's list.
group.MapDelete("/blocks", async (string? source, string? key, BlockStore store, CancellationToken ct) =>
{
- var parsed = ParseSource(source);
+ if (!TryParseSource(source, out var parsed)) return BadSource(source);
if (parsed is null && string.IsNullOrWhiteSpace(key))
return Results.BadRequest(new { error = "refusing to delete every block: pass source=operator|engine or key=..." });
var n = await store.DeleteAsync(parsed, key, ct);
@@ -115,6 +118,13 @@ internal static class AdminEndpoints
if (string.IsNullOrWhiteSpace(req.Match) || !IsValidMatch(req.Match))
return Results.BadRequest(new { error = "match must be an address or CIDR" });
+ if (!EntryLimits.NoteOk(req.Note))
+ return Results.BadRequest(new { error = $"note must be at most {EntryLimits.NoteMaxLength} characters; got {req.Note!.Length}" });
+ // Present but out of range is a 400. Absent is the only way to say
+ // "never expires" — it used to be what 0 and -5 said as well.
+ if (req.ExpiresInMinutes is { } minutes && !EntryLimits.ExpiresInMinutesOk(minutes))
+ return Results.BadRequest(new { error = $"expiresInMinutes must be {EntryLimits.ExpiresInMinutesMin}..{EntryLimits.ExpiresInMinutesMax} to expire, or left out to never expire; got {minutes}" });
+
var existing = await db.AllowEntries.FirstOrDefaultAsync(a => a.Match == req.Match, ct);
if (existing is not null) return Results.Conflict(new { error = "already allowlisted" });
@@ -122,7 +132,7 @@ internal static class AdminEndpoints
{
Match = req.Match.Trim(),
Note = req.Note,
- ExpiresAt = req.ExpiresInMinutes is > 0 ? DateTimeOffset.UtcNow.AddMinutes(req.ExpiresInMinutes.Value) : null
+ ExpiresAt = req.ExpiresInMinutes is { } expiry ? DateTimeOffset.UtcNow.AddMinutes(expiry) : null
});
await db.SaveChangesAsync(ct);
await state.InvalidateAsync(ct);
@@ -337,13 +347,30 @@ internal static class AdminEndpoints
p.MaxTrackedSources, p.Ipv4KeyPrefixLength, p.Ipv6KeyPrefixLength, p.EngineBlockStatus,
p.OperatorBlockStatus, p.DefaultRedirectTargets);
- private static BlockSource? ParseSource(string? source) => source?.Trim().ToLowerInvariant() switch
+ ///
+ /// The provenance filter, parsed honestly. The old shape mapped any unrecognised
+ /// string to BlockSource.Operator, measured on the shipped image: with two
+ /// operator blocks and three engine bans live, GET ?source=enigne returned
+ /// the operator list and hid the engine bans, and
+ /// DELETE ?source=enigne answered {"deleted":1} and left
+ /// operator=0 engine=3 — the caller who mistyped "engine" while clearing
+ /// automatic bans erased the operator's own list instead, which is the exact
+ /// failure the comment above that endpoint says this API exists to prevent. A
+ /// missing source is still "all"; a misspelled one is a 400.
+ ///
+ private static bool TryParseSource(string? source, out BlockSource? parsed)
{
- "operator" => BlockSource.Operator,
- "engine" => BlockSource.Engine,
- "all" or "" or null => null,
- _ => BlockSource.Operator
- };
+ switch (source?.Trim().ToLowerInvariant())
+ {
+ case null or "" or "all": parsed = null; return true;
+ case "operator": parsed = BlockSource.Operator; return true;
+ case "engine": parsed = BlockSource.Engine; return true;
+ default: parsed = null; return false;
+ }
+ }
+
+ private static IResult BadSource(string? source)
+ => Results.BadRequest(new { error = $"source must be operator|engine|all; got \"{source}\"" });
private static bool FixedTimeEquals(string a, string b)
{
diff --git a/dotnet/OpenWaf.Tests.Integration/ProvenanceAndLimitsTests.cs b/dotnet/OpenWaf.Tests.Integration/ProvenanceAndLimitsTests.cs
new file mode 100644
index 0000000..a67a1f3
--- /dev/null
+++ b/dotnet/OpenWaf.Tests.Integration/ProvenanceAndLimitsTests.cs
@@ -0,0 +1,195 @@
+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;
+
+///
+/// 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. ParseSource mapped any unrecognised string
+/// to BlockSource.Operator. 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. expiresInMinutes: 0 and -5 → 204 with expiresAt: null:
+/// a permanent allow entry, silently, on the control that outranks every ban.
+/// 3. 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.
+///
+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> CountsAsync(EdgeFixture f)
+ {
+ using var scope = f.Factory.Services.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ 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();
+ 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();
+ 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();
+ 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());
+ }
+}
diff --git a/scripts/console-check.cjs b/scripts/console-check.cjs
index bd38037..123bd55 100644
--- a/scripts/console-check.cjs
+++ b/scripts/console-check.cjs
@@ -237,6 +237,37 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
(await page.$$eval('#allow tbody tr', (r) => r.map((tr) => tr.children[0].textContent))).indexOf(WRITE_CIDR) === -1,
JSON.stringify(await page.$$eval('#allow tbody tr', (r) => r.map((tr) => tr.children[0].textContent))));
+ // The other quiet failure on this form: a TTL of 0. It used to fall through to
+ // null, and null is how the API says "never expires" — so a field left at zero
+ // bought the one exemption that outranks every ban. The API refuses it now, and
+ // the page refuses it before the round trip; empty is still "never", on purpose.
+ await page.fill('#allowMatch', WRITE_CIDR);
+ await page.fill('#allowNote', 'console gate: zero ttl');
+ await page.fill('#allowTtl', '0');
+ await page.click('#addAllow');
+ await page.waitForFunction(
+ () => /TTL in minutes/.test(document.getElementById('status').textContent),
+ null, { timeout: 5000 }).catch(() => {});
+ const ttlStatus = (await page.textContent('#status')).trim();
+ const rowsAfterZero = await page.$$eval('#allow tbody tr', (r) => r.map((tr) => tr.children[0].textContent));
+ check('a TTL of 0 is refused by the page instead of becoming a permanent exemption',
+ /TTL in minutes/.test(ttlStatus) && !rowsAfterZero.includes(WRITE_CIDR),
+ `${JSON.stringify(ttlStatus)} rows=${JSON.stringify(rowsAfterZero)}`);
+
+ await page.fill('#allowTtl', '');
+ await page.click('#addAllow');
+ await page.waitForFunction(
+ (cidr) => [...document.querySelectorAll('#allow tbody tr')].some((tr) => tr.children[0].textContent === cidr),
+ WRITE_CIDR, { timeout: 15000 }).catch(() => {});
+ const neverRows = await cells('#allow tbody tr');
+ check('leaving the TTL empty is still the way to ask for never',
+ neverRows.some((r) => r[0] === WRITE_CIDR && /never/.test(r[2] || '')),
+ JSON.stringify(neverRows.map((r) => [r[0], r[2]])));
+ await page.click('#allow tbody button[data-act="delallow"]');
+ await page.waitForFunction(
+ (cidr) => ![...document.querySelectorAll('#allow tbody tr')].some((tr) => tr.children[0].textContent === cidr),
+ WRITE_CIDR, { timeout: 15000 }).catch(() => {});
+
// The failure mode worth asserting on a write form is the quiet one: the
// operator believes they blocked an address and did not. A typo in the field
// must come back as the API's own error, not as a status line that says