Registration form: text browsers without fetch metadata pass when sessionless; keep a challenge only while live
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
d47f1d5e9d
commit
7bd26e9239
4 changed files with 119 additions and 5 deletions
|
|
@ -85,6 +85,20 @@ public sealed class RegistrationChallengeService(
|
|||
public bool TryConsumeWaited(string? challenge) =>
|
||||
WaitRemaining(challenge) == TimeSpan.Zero && Open(challenge) is { } open && Spend(open);
|
||||
|
||||
/// <summary>True when the token is ours, unexpired and not yet spent, so a form may carry it into its next attempt.</summary>
|
||||
public bool IsLive(string? challenge)
|
||||
{
|
||||
if (Open(challenge) is not { } open)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (gate)
|
||||
{
|
||||
return !consumed.Contains(open.Id);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record OpenChallenge(string Id, int Difficulty, DateTimeOffset ExpiresAt, DateTimeOffset IssuedAt);
|
||||
|
||||
/// <summary>The payload of a challenge that we protected and that has not expired; null otherwise.</summary>
|
||||
|
|
|
|||
|
|
@ -26,4 +26,16 @@ public static class RequestOriginGuard
|
|||
var fetchSite = request.Headers["Sec-Fetch-Site"];
|
||||
return fetchSite.Count == 1 && string.Equals(fetchSite[0], "same-origin", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// For the no-script sign-up form only. Text browsers (Lynx, w3m, Links) send neither Origin nor Sec-Fetch-Site, so a
|
||||
/// request with neither is let through when it carries no Bifrost session cookie: there is no session to replace.
|
||||
/// Any Origin or Sec-Fetch-Site present is judged exactly as <see cref="Allows"/> judges it, and a headerless request
|
||||
/// that does carry a session cookie is refused.
|
||||
/// </summary>
|
||||
public static bool AllowsFormWithoutFetchMetadata(HttpRequest request, BifrostHostOptions host) =>
|
||||
Allows(request, host) ||
|
||||
(!request.Headers.ContainsKey("Origin") &&
|
||||
!request.Headers.ContainsKey("Sec-Fetch-Site") &&
|
||||
!request.Cookies.Keys.Any(name => name.StartsWith(BifrostCookies.Session, StringComparison.Ordinal)));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -441,7 +441,8 @@ app.MapGet("/auth/bifrost/register", (
|
|||
}).AllowAnonymous();
|
||||
|
||||
// No antiforgery token or cookie exists for an anonymous visitor, so a cross-site post is refused by origin instead
|
||||
// (RequestOriginGuard, the same Fetch Metadata check as the vote page). Without it a foreign page could post here with
|
||||
// (RequestOriginGuard, the same Fetch Metadata check as the vote page, except that a request with no Origin and no
|
||||
// Sec-Fetch-Site and no session cookie passes: text browsers send neither, and there is no session to replace). Without it a foreign page could post here with
|
||||
// a challenge of its own and replace the visitor's session cookie with an empty account holding a forged consent.
|
||||
// Order: origin, then the general address budget, then the body cap, then the form; a refusal sets no cookie.
|
||||
app.MapPost("/auth/bifrost/register/form", async (
|
||||
|
|
@ -453,7 +454,7 @@ app.MapPost("/auth/bifrost/register/form", async (
|
|||
IOptions<RegistrationOptions> registrationOptions,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
if (!RequestOriginGuard.Allows(httpContext.Request, hostOptions.Value))
|
||||
if (!RequestOriginGuard.AllowsFormWithoutFetchMetadata(httpContext.Request, hostOptions.Value))
|
||||
{
|
||||
return Results.Text("Cross-site registration is refused.", statusCode: StatusCodes.Status403Forbidden);
|
||||
}
|
||||
|
|
@ -530,7 +531,7 @@ app.MapPost("/auth/bifrost/register/form", async (
|
|||
challenges,
|
||||
options,
|
||||
new RegistrationPageModel(returnPath.Value, "", 0, options.Captcha.FallbackWaitSeconds, Truncate(identity), Truncate(displayName), outcome.Message, outcome.Field),
|
||||
outcome.KeepChallenge ? challenge : null,
|
||||
outcome.KeepChallenge && challenges.IsLive(challenge) ? challenge : null,
|
||||
outcome.Status);
|
||||
|
||||
static string Truncate(string text) => text.Length <= 256 ? text : text[..256];
|
||||
|
|
|
|||
|
|
@ -457,8 +457,7 @@ public sealed class RegistrationFormTests(RegistrationFormFactory factory) : ICl
|
|||
{ "https://localhost.evil.example", null },
|
||||
{ null, "cross-site" },
|
||||
{ null, "same-site" },
|
||||
{ null, "none" },
|
||||
{ null, null }
|
||||
{ null, "none" }
|
||||
};
|
||||
|
||||
[Theory]
|
||||
|
|
@ -494,6 +493,94 @@ public sealed class RegistrationFormTests(RegistrationFormFactory factory) : ICl
|
|||
Assert.Equal(HttpStatusCode.SeeOther, ok.StatusCode);
|
||||
}
|
||||
|
||||
private async Task<HttpResponseMessage> PostWithAsync(HttpClient client, string html, string identity, string? origin, string? fetchSite, string? cookie)
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/register/form")
|
||||
{
|
||||
Content = new FormUrlEncodedContent(FormKit.Fields(html, identity, nonce: FormKit.Solved(html)))
|
||||
};
|
||||
if (origin is not null) request.Headers.Add("Origin", origin);
|
||||
if (fetchSite is not null) request.Headers.Add("Sec-Fetch-Site", fetchSite);
|
||||
if (cookie is not null) request.Headers.Add("Cookie", cookie);
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_text_browser_sending_neither_header_is_accepted_only_without_a_session_cookie()
|
||||
{
|
||||
const string session = "__Host-bifrost_session=abc";
|
||||
using var client = Client();
|
||||
|
||||
var html = await FormKit.PageAsync(client);
|
||||
var plain = NewIdentity();
|
||||
using (var ok = await PostWithAsync(client, html, plain, null, null, null))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.SeeOther, ok.StatusCode);
|
||||
Assert.Equal((true, true), Created(plain));
|
||||
}
|
||||
|
||||
var second = await FormKit.PageAsync(client);
|
||||
var withSession = NewIdentity();
|
||||
using (var refused = await PostWithAsync(client, second, withSession, null, null, session))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, refused.StatusCode);
|
||||
Assert.False(refused.Headers.Contains("Set-Cookie"));
|
||||
Assert.False(Exists(withSession));
|
||||
}
|
||||
|
||||
// Any header present is judged as before, cookie or not; same-origin with a session passes.
|
||||
using (var crossNoCookie = await PostWithAsync(client, second, withSession, null, "cross-site", null))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, crossNoCookie.StatusCode);
|
||||
}
|
||||
|
||||
using var sameOrigin = await PostWithAsync(client, second, withSession, FormKit.SiteOrigin, null, session);
|
||||
Assert.Equal(HttpStatusCode.SeeOther, sameOrigin.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_identity_error_carries_the_challenge_on_only_while_it_is_live()
|
||||
{
|
||||
using var client = Client();
|
||||
var html = await FormKit.PageAsync(client);
|
||||
var live = FormKit.Hidden(html, "challenge");
|
||||
|
||||
// Live: kept.
|
||||
using (var kept = await FormKit.PostAsync(client, FormKit.Fields(html, "a!", nonce: "1")))
|
||||
{
|
||||
Assert.Equal(live, FormKit.Hidden(await kept.Content.ReadAsStringAsync(), "challenge"));
|
||||
}
|
||||
|
||||
// Garbage: replaced by a fresh live one, never echoed.
|
||||
var garbage = FormKit.Fields(html, "a!", nonce: "1");
|
||||
garbage["challenge"] = "garbage-token";
|
||||
using (var replaced = await FormKit.PostAsync(client, garbage))
|
||||
{
|
||||
var page = await replaced.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("garbage-token", page);
|
||||
Assert.True(factory.Services.GetRequiredService<RegistrationChallengeService>().IsLive(FormKit.Hidden(page, "challenge")));
|
||||
}
|
||||
|
||||
// Spent: replaced.
|
||||
var spentPage = await FormKit.PageAsync(client);
|
||||
using (var spend = await FormKit.PostAsync(client, FormKit.Fields(spentPage, NewIdentity(), nonce: FormKit.Solved(spentPage))))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.SeeOther, spend.StatusCode);
|
||||
}
|
||||
|
||||
using (var afterSpend = await FormKit.PostAsync(client, FormKit.Fields(spentPage, "a!", nonce: "1")))
|
||||
{
|
||||
Assert.NotEqual(FormKit.Hidden(spentPage, "challenge"), FormKit.Hidden(await afterSpend.Content.ReadAsStringAsync(), "challenge"));
|
||||
}
|
||||
|
||||
// Expired: replaced.
|
||||
factory.Time.Advance(RegistrationChallengeService.Lifetime + TimeSpan.FromSeconds(1));
|
||||
using var afterExpiry = await FormKit.PostAsync(client, FormKit.Fields(html, "a!", nonce: "1"));
|
||||
var expiredPage = await afterExpiry.Content.ReadAsStringAsync();
|
||||
Assert.NotEqual(live, FormKit.Hidden(expiredPage, "challenge"));
|
||||
Assert.True(factory.Services.GetRequiredService<RegistrationChallengeService>().IsLive(FormKit.Hidden(expiredPage, "challenge")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_same_origin_post_without_an_Origin_header_is_accepted_on_Sec_Fetch_Site()
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue