diff --git a/README.md b/README.md
index 2c161ea..87d98b2 100644
--- a/README.md
+++ b/README.md
@@ -275,6 +275,26 @@ GET /admin-api/geo which database is loaded and how old it is
GET /admin-api/state snapshot age, tracked sources, counts
```
+`redirectTo` on a block is the one field that ends up in a response header, and
+the shipped image used to accept any string in it — `POST /admin-api/blocks`
+answered 204 for all of these, and the next request from that source paid:
+
+| target written | what the blocked request answered |
+|---|---|
+| `https://example.com/ok` | `301 Location: https://example.com/ok` |
+| `http://bad target` | `301 Location: http://bad target` — unparseable |
+| `http://x.invalid/` + CRLF + `X-Injected: 1` | **`500 Internal Server Error`, `Content-Length: 0`** |
+| `javascript:alert(1)` | `301 Location: javascript:alert(1)` |
+| `not-a-url` | `301 Location: not-a-url` |
+
+The CRLF row is the one that makes this a defect rather than a wart: Kestrel
+refuses to write the header, so the operator's own block — accepted with 204 —
+turned that visitor's request into a server error. No header was injected, which
+is the only part of the old behaviour that was safe. `redirectTo` is now an
+absolute http(s) URL or a 400, and the decision point ignores a target it cannot
+send and answers the block's own default instead, for a row that arrived by a
+restored backup or a hand edit.
+
## Console
`GET /admin` serves a single page over those endpoints — mode and snapshot age,
diff --git a/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs b/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs
index b366f33..169d77b 100644
--- a/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs
+++ b/dotnet/OpenWaf.Domain/Engine/DecisionEngine.cs
@@ -85,7 +85,15 @@ public static class DecisionEngine
/// can read, while an operator can still send a scanner elsewhere.
private static (int Status, string? Location) BlockResponse(EdgePolicy policy, string? redirectTo, int defaultStatus)
{
- if (!string.IsNullOrWhiteSpace(redirectTo)) return (301, redirectTo);
+ // A per-entry redirect is honoured only if it can actually be sent.
+ // The shipped image used to write whatever string the entry held
+ // straight into Location: a CRLF in there made Kestrel refuse the
+ // header, and the blocked request came back as 500 with no body — the
+ // operator's own block, accepted with 204, turned into a server error
+ // for that visitor. Falling back to the kind's default status is the
+ // defined answer for a target that arrived by a route the API did not
+ // police (a restored row, a hand edit).
+ if (Security.RedirectTarget.IsSendable(redirectTo)) return (301, redirectTo);
// The last line of defence, and the only one that is not the operator's
// problem to fix. A status the wire cannot carry does not produce a bad
// answer, it produces no answer: measured on the shipped image,
diff --git a/dotnet/OpenWaf.Domain/Security/RedirectTarget.cs b/dotnet/OpenWaf.Domain/Security/RedirectTarget.cs
new file mode 100644
index 0000000..465b5a7
--- /dev/null
+++ b/dotnet/OpenWaf.Domain/Security/RedirectTarget.cs
@@ -0,0 +1,44 @@
+namespace OpenWaf.Domain.Security;
+
+///
+/// A per-entry redirect target, judged once.
+///
+/// This string is written straight into a Location header, and the
+/// shipped image used to accept any string at all: POST /admin-api/blocks
+/// answered 204 for every one of these, and the next request from that source
+/// then paid for it —
+///
+/// "https://example.com/ok" -> 301 Location: https://example.com/ok
+/// "http://bad target" -> 301 Location: http://bad target (unparseable)
+/// "http://x.invalid/\r\nX-Injected: 1"-> 500 Internal Server Error, Content-Length: 0
+/// "javascript:alert(1)" -> 301 Location: javascript:alert(1)
+/// "not-a-url" -> 301 Location: not-a-url
+///
+/// The CRLF one is the reason this type exists: Kestrel refuses to write the
+/// header, so the block that was supposed to protect the site turns into a 500
+/// for that visitor — the operator's own entry, accepted with 204, breaks the
+/// response. No header was injected (the server validates), which is the only
+/// part of this that went right.
+///
+/// http(s) only. javascript: and data: are absolute URIs and would
+/// be written into Location happily; a redirect is a navigation, and a
+/// navigation to a script: URL is an execution request made on the operator's
+/// behalf by a string somebody typed into a form.
+///
+public static class RedirectTarget
+{
+ public static bool IsSendable(string? target)
+ => target is not null && IsSendableUri(target);
+
+ private static bool IsSendableUri(string target)
+ {
+ if (string.IsNullOrWhiteSpace(target)) return false;
+ if (target.Trim() != target) return false;
+ foreach (var c in target)
+ {
+ if (c <= ' ' || c == '\u007f') return false;
+ }
+ if (!Uri.TryCreate(target, UriKind.Absolute, out var uri)) return false;
+ return uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps;
+ }
+}
diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs
index 740741c..f523b9f 100644
--- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs
+++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs
@@ -86,6 +86,12 @@ 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" });
+ // 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
+ // come back as 500 with no body — the block itself broke.
+ if (req.RedirectTo is not null && !RedirectTarget.IsSendable(req.RedirectTo))
+ return Results.BadRequest(new { error = $"redirectTo must be an absolute http(s) URL with no spaces or control characters; got \"{req.RedirectTo}\"" });
var (ok, error) = await store.AddOperatorAsync(req.Ip, req.Reason, req.RedirectTo, DateTimeOffset.UtcNow, ct);
return ok ? Results.NoContent() : Results.BadRequest(new { error });
});
@@ -311,7 +317,7 @@ internal static class AdminEndpoints
{
foreach (var target in req.DefaultRedirectTargets)
{
- if (!IsHttpUrl(target))
+ if (!RedirectTarget.IsSendable(target))
return $"redirectTargets must be absolute http(s) URLs; got \"{target}\"";
}
}
@@ -325,17 +331,6 @@ internal static class AdminEndpoints
&& range.Low >= PolicyBounds.ClassifiableStatusMin
&& range.High <= PolicyBounds.ClassifiableStatusMax;
- /// A redirect target goes into a Location header, so it has to be
- /// a URL: measured, "http://bad target" was stored and shipped as
- /// `Location: http://bad target`, which no client can follow.
- private static bool IsHttpUrl(string? value)
- => value is not null
- && !string.IsNullOrWhiteSpace(value)
- && value.Trim() == value
- && value.IndexOf(' ') < 0
- && Uri.TryCreate(value, UriKind.Absolute, out var uri)
- && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);
-
private static PolicyDto ToDto(EdgePolicy p) => new(
p.Mode.ToString(), p.StreakThreshold, p.StreakWindow.TotalMinutes, p.BanDuration.TotalMinutes,
p.RefusalRange.ToString(), p.ServerErrorRange.ToString(), p.Geo.ToString(), p.TrustProxyHeaders,
diff --git a/dotnet/OpenWaf.Tests.Integration/RedirectTargetTests.cs b/dotnet/OpenWaf.Tests.Integration/RedirectTargetTests.cs
new file mode 100644
index 0000000..44f34f7
--- /dev/null
+++ b/dotnet/OpenWaf.Tests.Integration/RedirectTargetTests.cs
@@ -0,0 +1,120 @@
+using System.Net;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using OpenWaf.Domain.Security;
+using OpenWaf.Infrastructure.Persistence;
+
+namespace OpenWaf.Tests.Integration;
+
+///
+/// The per-entry redirect is the one field on a block that ends up in a
+/// response header, and the shipped image accepted any string in it.
+///
+/// Measured on openwaf:ci before the fix — POST /admin-api/blocks answered 204
+/// for all of these, and the next request from that source then answered:
+/// "https://example.com/ok" 301 Location: https://example.com/ok
+/// "http://bad target" 301 Location: http://bad target
+/// "http://x.invalid/\r\nX-Injected: 1" 500 Internal Server Error, Content-Length: 0
+/// "javascript:alert(1)" 301 Location: javascript:alert(1)
+/// "not-a-url" 301 Location: not-a-url
+/// The CRLF row is the one that makes this a defect rather than a wart: the
+/// operator's own block, written with a 204, turned that visitor's request into
+/// a server error. No header was injected — Kestrel refused the write — which
+/// is the only part of the old behaviour that was safe.
+///
+public sealed class RedirectTargetTests
+{
+ private const string Blocked = "203.0.113.66";
+ private const string Bystander = "198.51.100.7";
+
+ private static async Task<(HttpStatusCode Status, string Body)> PostBlockAsync(EdgeFixture f, string json)
+ {
+ using var request = new HttpRequestMessage(new HttpMethod("POST"), "/admin-api/blocks")
+ {
+ 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<(HttpStatusCode Status, string? Location)> GetAsync(EdgeFixture f, string ip)
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Get, "/nope");
+ request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip);
+ var response = await f.Client.SendAsync(request);
+ return (response.StatusCode, response.Headers.Location?.ToString());
+ }
+
+ [Theory]
+ [InlineData("http://bad target", "http://bad target")]
+ [InlineData("http://x.invalid/\r\nX-Injected: 1", "X-Injected")]
+ [InlineData("javascript:alert(1)", "javascript:alert(1)")]
+ [InlineData("data:text/html,x", "data:text/html,x")]
+ [InlineData("not-a-url", "not-a-url")]
+ public async Task A_block_target_the_wire_cannot_carry_is_refused_at_the_api(string target, string echoFragment)
+ {
+ await using var f = new EdgeFixture();
+
+ var payload = System.Text.Json.JsonSerializer.Serialize(new { ip = Blocked, reason = "probe", redirectTo = target });
+ var (status, body) = await PostBlockAsync(f, payload);
+
+ Assert.Equal(HttpStatusCode.BadRequest, status);
+ Assert.Contains("redirectTo", body);
+ Assert.Contains("absolute http(s) URL", body);
+ Assert.Contains(echoFragment, body);
+
+ using var scope = f.Factory.Services.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ Assert.Empty(await db.Blocks.Where(b => b.SourceKey == Blocked).ToListAsync());
+ }
+
+ [Fact]
+ public async Task A_well_formed_target_is_stored_and_answered_as_a_redirect()
+ {
+ await using var f = new EdgeFixture();
+
+ var (status, _) = await PostBlockAsync(f,
+ "{\"ip\":\"" + Blocked + "\",\"reason\":\"confirmed scraper\",\"redirectTo\":\"https://honeypot.example.org/\"}");
+ Assert.Equal(HttpStatusCode.NoContent, status);
+
+ await f.Service().InvalidateAsync();
+ var (code, location) = await GetAsync(f, Blocked);
+ Assert.Equal(HttpStatusCode.MovedPermanently, code);
+ Assert.Equal("https://honeypot.example.org/", location);
+
+ var (bystanderCode, _) = await GetAsync(f, Bystander);
+ Assert.Equal(HttpStatusCode.NotFound, bystanderCode);
+ }
+
+ [Fact]
+ public async Task A_row_written_without_the_api_still_cannot_break_the_response()
+ {
+ await using var f = new EdgeFixture();
+
+ // Not through the API: a restored backup or a hand edit. The API guard
+ // cannot see this, so the decision point has to.
+ using (var scope = f.Factory.Services.CreateScope())
+ {
+ var db = scope.ServiceProvider.GetRequiredService();
+ db.Blocks.Add(new BlockEntry
+ {
+ SourceKey = Blocked,
+ Source = BlockSource.Operator,
+ CreatedAt = DateTimeOffset.UtcNow.AddMinutes(-1),
+ Reason = "operator: restored row with a CRLF target",
+ RedirectTo = "http://x.invalid/\r\nX-Injected: 1"
+ });
+ await db.SaveChangesAsync();
+ }
+
+ await f.Service().InvalidateAsync();
+ var (code, location) = await GetAsync(f, Blocked);
+
+ // Before the guard this was 500 with no body. Now it is the operator
+ // block's own defined answer: 301 to the honey-pot default.
+ Assert.Equal(HttpStatusCode.MovedPermanently, code);
+ Assert.Equal("https://www.iana.org/help/example-domains", location);
+ Assert.DoesNotContain("X-Injected", location ?? "");
+ }
+}
diff --git a/dotnet/OpenWaf.Tests.Unit/RedirectTargetTests.cs b/dotnet/OpenWaf.Tests.Unit/RedirectTargetTests.cs
new file mode 100644
index 0000000..c36b512
--- /dev/null
+++ b/dotnet/OpenWaf.Tests.Unit/RedirectTargetTests.cs
@@ -0,0 +1,111 @@
+using OpenWaf.Domain.Engine;
+using OpenWaf.Domain.Policy;
+using OpenWaf.Domain.Security;
+
+namespace OpenWaf.Tests.Unit;
+
+///
+/// A redirect target is written into a Location header, so "any string" is not
+/// a safe answer for it.
+///
+/// Measured on the shipped image before this existed: POST /admin-api/blocks
+/// answered 204 for every target below, and the next request from that source
+/// paid — "http://x.invalid/\r\nX-Injected: 1" came back as
+/// "500 Internal Server Error, Content-Length: 0" (Kestrel refused the header,
+/// so the operator's own block became a server error for that visitor),
+/// "javascript:alert(1)" was shipped as a Location, and "not-a-url" was a 301
+/// no client can follow.
+///
+public sealed class RedirectTargetTests
+{
+ private static readonly DateTimeOffset Now = new(2026, 10, 1, 12, 0, 0, TimeSpan.Zero);
+
+ [Theory]
+ [InlineData("https://example.com/ok", true)]
+ [InlineData("http://example.com/a?b=c#d", true)]
+ [InlineData("https://www.iana.org/help/example-domains", true)]
+ [InlineData("http://bad target", false)]
+ [InlineData("http://x.invalid/\r\nX-Injected: 1", false)]
+ [InlineData("http://x.invalid/\nX-Injected: 1", false)]
+ [InlineData("javascript:alert(1)", false)]
+ [InlineData("data:text/html,", false)]
+ [InlineData("not-a-url", false)]
+ [InlineData("/relative/path", false)]
+ [InlineData("", false)]
+ [InlineData(" ", false)]
+ [InlineData(" https://example.com/", false)]
+ public void Only_an_absolute_http_or_https_URL_can_be_sent_as_a_Location(string target, bool sendable)
+ => Assert.Equal(sendable, RedirectTarget.IsSendable(target));
+
+ [Fact]
+ public void A_null_target_is_not_a_redirect_at_all()
+ => Assert.False(RedirectTarget.IsSendable(null));
+
+ private static EdgeSnapshot Snapshot(EdgePolicy policy, BlockEntry entry, bool engine) => new()
+ {
+ GeneratedAt = Now,
+ Policy = policy,
+ EngineBans = engine
+ ? new Dictionary { [entry.SourceKey] = entry }
+ : new Dictionary(),
+ OperatorBlocks = engine
+ ? new Dictionary()
+ : new Dictionary { [entry.SourceKey] = entry }
+ };
+
+ private static BlockEntry Entry(string key, BlockSource source, string? redirect) => new()
+ {
+ SourceKey = key,
+ Source = source,
+ CreatedAt = Now.AddMinutes(-1),
+ ExpiresAt = Now.AddMinutes(30),
+ RedirectTo = redirect,
+ Reason = "3 consecutive refusals (400-499) within 5 min; last 404 /nope"
+ };
+
+ [Fact]
+ public void A_well_formed_target_is_the_redirect_the_operator_wrote()
+ {
+ var entry = Entry("203.0.113.7", BlockSource.Operator, "https://honeypot.example.org/");
+ var decision = DecisionEngine.Decide(
+ Snapshot(new EdgePolicy { Mode = EnforcementMode.Enforce }, entry, engine: false),
+ "203.0.113.7", "/nope", Now);
+
+ Assert.Equal(EdgeVerdict.BlockOperator, decision.Verdict);
+ Assert.Equal(301, decision.StatusCode);
+ Assert.Equal("https://honeypot.example.org/", decision.Location);
+ }
+
+ [Theory]
+ [InlineData("http://x.invalid/\r\nX-Injected: 1")]
+ [InlineData("javascript:alert(1)")]
+ [InlineData("not-a-url")]
+ [InlineData("http://bad target")]
+ public void An_unsendable_target_never_reaches_the_wire_and_the_block_still_answers_its_own_kind(string target)
+ {
+ var entry = Entry("203.0.113.7", BlockSource.Operator, target);
+ var decision = DecisionEngine.Decide(
+ Snapshot(new EdgePolicy { Mode = EnforcementMode.Enforce }, entry, engine: false),
+ "203.0.113.7", "/nope", Now);
+
+ Assert.Equal(EdgeVerdict.BlockOperator, decision.Verdict);
+ Assert.Equal(301, decision.StatusCode);
+ Assert.Equal("https://www.iana.org/help/example-domains", decision.Location);
+ Assert.NotEqual(target, decision.Location);
+ }
+
+ [Theory]
+ [InlineData("http://x.invalid/\r\nX-Injected: 1")]
+ [InlineData("javascript:alert(1)")]
+ public void An_engine_ban_with_a_broken_target_answers_the_engine_status_not_a_broken_redirect(string target)
+ {
+ var entry = Entry("203.0.113.7", BlockSource.Engine, target);
+ var decision = DecisionEngine.Decide(
+ Snapshot(new EdgePolicy { Mode = EnforcementMode.Enforce }, entry, engine: true),
+ "203.0.113.7", "/nope", Now);
+
+ Assert.Equal(EdgeVerdict.BlockEngine, decision.Verdict);
+ Assert.Equal(403, decision.StatusCode);
+ Assert.Null(decision.Location);
+ }
+}
diff --git a/scripts/ci-linux-rehearsal.sh b/scripts/ci-linux-rehearsal.sh
index 63dbb59..dcb2584 100755
--- a/scripts/ci-linux-rehearsal.sh
+++ b/scripts/ci-linux-rehearsal.sh
@@ -171,6 +171,8 @@ if [ "$STAGE" = all ] || [ "$STAGE" = console ]; then
# driver has to look at the same address, or the alert assertion checks
# nothing in particular.
SEED_ERROR=$(sed -n 's/^SEED_ERROR=//p' console-seed.env 2>/dev/null)
+ SEED_MARKUP_PATH=$(sed -n 's/^SEED_MARKUP_PATH=//p' console-seed.env 2>/dev/null)
+ SEED_MARKUP_BLOCK=$(sed -n 's/^SEED_MARKUP_BLOCK=//p' console-seed.env 2>/dev/null)
[ -n "$SEED_ERROR" ] || { echo 'console stage: no SEED_ERROR in console-seed.env' >&2; console_status=1; }
fi
@@ -181,6 +183,7 @@ if [ "$STAGE" = all ] || [ "$STAGE" = console ]; then
-e EDGE_URL="$HOST_EDGE" -e OPENWAF_ADMIN_TOKEN \
-e SEED_SOURCE=203.0.113.55 -e SEED_BLOCK=203.0.113.77 \
-e SEED_ERROR="$SEED_ERROR" \
+ -e SEED_MARKUP_PATH="$SEED_MARKUP_PATH" -e SEED_MARKUP_BLOCK="$SEED_MARKUP_BLOCK" \
-e SCREENSHOT=/tmp/console-linux.png \
-e CHECK="$PWD/scripts/console-check.cjs" \
-e PW_VERSION="$PLAYWRIGHT_VERSION" \
diff --git a/scripts/console-check.cjs b/scripts/console-check.cjs
index 2408efb..bd38037 100644
--- a/scripts/console-check.cjs
+++ b/scripts/console-check.cjs
@@ -17,6 +17,11 @@ const SCREENSHOT = process.env.SCREENSHOT
const SEED_SOURCE = process.env.SEED_SOURCE || '';
const SEED_BLOCK = process.env.SEED_BLOCK || '';
const SEED_ERROR = process.env.SEED_ERROR || '';
+// A path an anonymous visitor asked for, and a block reason somebody typed.
+// Both are API values that end up in a table cell; neither is authored by the
+// person reading this page.
+const SEED_MARKUP_PATH = process.env.SEED_MARKUP_PATH || '';
+const SEED_MARKUP_BLOCK = process.env.SEED_MARKUP_BLOCK || '';
let chromium;
try {
@@ -130,6 +135,32 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
warnCells.includes('server_error_streak'), JSON.stringify(warnCells));
check('the token never appears in the markup', !html.includes(TOKEN));
+
+ // esc() is the only thing between an anonymous request and the one browser in
+ // this system that holds the admin token. The path in an observation row is
+ // whatever a visitor asked for and the reason on a block is a form field, so
+ // the assertion is not "the page looks fine" — it is "nothing from the API
+ // became an element, and the markup is still visible as text".
+ if (SEED_MARKUP_PATH) {
+ const decoded = decodeURIComponent(SEED_MARKUP_PATH);
+ const title = await page.title();
+ check('a markup path from an anonymous visitor did not execute in the operator page',
+ !/XSS/.test(title), `title: ${JSON.stringify(title)}`);
+ const injected = await page.$$eval('#obs tbody, #blocks tbody, #streaks tbody',
+ (bodies) => bodies.reduce((n, b) => n + b.querySelectorAll('img,svg,script,iframe,object,embed').length, 0));
+ check('no element was created out of a value that came from the API',
+ injected === 0, `${injected} injected elements`);
+ const obsCells = await page.$$eval('#obs tbody tr', (rows) =>
+ rows.map((tr) => [...tr.children].map((td) => td.textContent)));
+ check('the markup path is printed as the text it is',
+ obsCells.some((r) => (r[4] || '').includes(decoded)),
+ JSON.stringify(obsCells.filter((r) => (r[4] || '').includes('xss-probe')).map((r) => r[4])));
+ }
+ if (SEED_MARKUP_BLOCK) {
+ check('a markup block reason is printed as text too',
+ blockRows.some((r) => r[0] === SEED_MARKUP_BLOCK && /