From 00f6dd9513288eb98d2b967e9dc86a8ead1ad8c8 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 2 Oct 2026 00:34:35 +0200 Subject: [PATCH] A block's redirect target went into a header unchecked, and one of them turned the block into a 500 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Measured on the shipped image (openwaf:ci). POST /admin-api/blocks answered 204 for every one of these, and the next request from that source paid for it: "https://example.com/ok" 301 Location: https://example.com/ok "http://bad target" 301 Location: http://bad target "http://x.invalid/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 defect rather than the wart: Kestrel refuses to write the header, so the operator's own block — written with a 204 — became a server error for that visitor. Nothing was injected; the server validated the header, which is the only part of the old behaviour that was safe. javascript: and data: are absolute URIs too, and a redirect is a navigation, so those are an execution request made on the operator's behalf by a string somebody typed into a form. RedirectTarget.IsSendable is now the one judge: absolute, http(s), no control characters or surrounding whitespace. The API answers 400 naming the field, and DecisionEngine 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, where the API guard never ran. The console gate also asserts the other half of the same boundary: every value that came from the API is rendered through esc(), and two of those values are not authored by the person reading the page — the path in an observation row is whatever an anonymous visitor asked for, and a block reason is a form field. The seed now sends a percent-encoded path carrying and an operator block whose reason carries , and the page must show both as text and create no elements from them. unit 105 -> 126 (+21: the target table, and the decision point's fallback) integration 55 -> 62 (+7: 400 by name for five targets, a valid target reaching the wire as 301, and a hand-written row with CRLF answering 301 to the default target instead of the 500 it used to answer) console 33 -> 37 assertions Teeth, each measured by removing the thing: esc() reduced to identity in the shipped page makes the console gate go red with 6 failures, and the page title becomes "XSS" — the anonymous visitor's path executed script in the operator's browser. Dropping the API guard fails exactly 5 integration tests; dropping the decision-point guard fails exactly 6 unit tests and the 1 hand-written-row test. --- README.md | 20 +++ .../OpenWaf.Domain/Engine/DecisionEngine.cs | 10 +- .../OpenWaf.Domain/Security/RedirectTarget.cs | 44 +++++++ dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs | 19 +-- .../RedirectTargetTests.cs | 120 ++++++++++++++++++ .../OpenWaf.Tests.Unit/RedirectTargetTests.cs | 111 ++++++++++++++++ scripts/ci-linux-rehearsal.sh | 3 + scripts/console-check.cjs | 31 +++++ scripts/console-smoke.sh | 21 ++- 9 files changed, 363 insertions(+), 16 deletions(-) create mode 100644 dotnet/OpenWaf.Domain/Security/RedirectTarget.cs create mode 100644 dotnet/OpenWaf.Tests.Integration/RedirectTargetTests.cs create mode 100644 dotnet/OpenWaf.Tests.Unit/RedirectTargetTests.cs 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 && / [r[0], r[2]]))); + } check('the page threw no javascript', jsProblems.length === 0, jsProblems.join(' | ')); // The read side of the page is one thing; the write side is the part that can diff --git a/scripts/console-smoke.sh b/scripts/console-smoke.sh index a0a6fa7..3d3ab5f 100755 --- a/scripts/console-smoke.sh +++ b/scripts/console-smoke.sh @@ -22,7 +22,7 @@ SEED_BLOCK=203.0.113.77 # `compose down`, so a fixed address here would let last week's alert satisfy the # assertion. A fresh one makes the check about this run. SEED_ERROR="203.0.113.$(( 140 + RANDOM % 60 ))" -export EDGE_URL="$EDGE" SEED_SOURCE SEED_BLOCK SEED_ERROR +export EDGE_URL="$EDGE" SEED_SOURCE SEED_BLOCK SEED_ERROR SEED_MARKUP_PATH SEED_MARKUP_BLOCK admin() { curl -s -m 10 -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$@"; } @@ -66,6 +66,21 @@ curl -s -o /dev/null -H 'X-Forwarded-For: 8.8.8.8' "$EDGE/no-such-page" admin -X POST -H 'Content-Type: application/json' \ -d "{\"ip\":\"$SEED_BLOCK\",\"reason\":\"console gate: operator block\"}" "$EDGE/admin-api/blocks" >/dev/null +# Markup in a path an anonymous visitor sends, and markup in a reason the +# operator types. Both end up in a table cell. The page renders every API value +# through esc(), and this is the assertion that keeps it that way: the only +# browser in this system holding the admin token is the one that renders them, +# so an unescaped cell is a stored XSS against the operator. The path is +# percent-encoded on the wire and arrives decoded — that is what the edge +# stores as lastPath and what the table then prints. +SEED_MARKUP_SOURCE="203.0.113.$(( 180 + RANDOM % 30 ))" +SEED_MARKUP_BLOCK="203.0.113.$(( 215 + RANDOM % 30 ))" +SEED_MARKUP_PATH="/xss-probe-$(( RANDOM % 32768 ))/%3Cimg%20src%3D1%20alt%3Dprobe%20onerror%3D%22document.title%3D%27XSS%27%22%3E" +curl -s -o /dev/null -H "X-Forwarded-For: $SEED_MARKUP_SOURCE" "$EDGE$SEED_MARKUP_PATH" +admin -X POST -H 'Content-Type: application/json' \ + -d "{\"ip\":\"$SEED_MARKUP_BLOCK\",\"reason\":\" probe\"}" \ + "$EDGE/admin-api/blocks" >/dev/null + # An alert the page must show. /boom answers 502 (deploy/upstream.conf), and this # gate already set the threshold to 3, so four of them from one address write # server_error_streak rows. The alert is written after the response is, hence the @@ -87,8 +102,8 @@ if [ "${SEED_ONLY:-0}" = 1 ]; then # page in a browser image), so it cannot inherit these values. Writing them out # is what keeps the alert assertion honest: SEED_ERROR is chosen per run, and an # empty one on the driver side would silently weaken the check to "any alert". - printf 'EDGE_URL=%s\nSEED_SOURCE=%s\nSEED_BLOCK=%s\nSEED_ERROR=%s\n' \ - "$EDGE" "$SEED_SOURCE" "$SEED_BLOCK" "$SEED_ERROR" > "${SEED_FILE:-console-seed.env}" + printf 'EDGE_URL=%s\nSEED_SOURCE=%s\nSEED_BLOCK=%s\nSEED_ERROR=%s\nSEED_MARKUP_PATH=%s\nSEED_MARKUP_BLOCK=%s\n' \ + "$EDGE" "$SEED_SOURCE" "$SEED_BLOCK" "$SEED_ERROR" "$SEED_MARKUP_PATH" "$SEED_MARKUP_BLOCK" > "${SEED_FILE:-console-seed.env}" echo "- SEED_ONLY=1: stack is up and seeded at $EDGE; seed values in ${SEED_FILE:-console-seed.env}" trap - EXIT exit 0