From 15f9b9fbe57d48df8b733e7172ebf9d0f27caf68 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 13 Nov 2026 22:26:57 +0000 Subject: [PATCH] Passkeys: no permit without a live challenge; pin fact-to-credential binding, take-after-permit and separate budgets; docs and message corrections Co-Authored-By: Claude Sonnet 5.5 --- docs/passkeys.md | 7 +- .../Features/Passkeys/PasskeyCeremonies.cs | 5 +- .../Features/Passkeys/PasskeyRelyingParty.cs | 4 +- .../Features/Passkeys/PasskeyService.cs | 7 + .../Pages/Membership/LinkedAccounts.cshtml | 73 +++++----- tests/Bifrost.Web.Tests/PasskeyTests.cs | 130 +++++++++++++++++- 6 files changed, 182 insertions(+), 44 deletions(-) diff --git a/docs/passkeys.md b/docs/passkeys.md index 1519260..6a04d07 100644 --- a/docs/passkeys.md +++ b/docs/passkeys.md @@ -20,7 +20,7 @@ What was checked on 2026-11-13, against the package and the repository, not from | net8.0 | The 4.3.3 nuspec has a `net8.0` dependency group (and `net10.0`); it targets the framework this project targets. | | Packed attestation | `Src/Fido2/AttestationFormat/` holds `Packed`, `None`, `FidoU2f`, `Tpm`, `AndroidKey`, `AndroidSafetyNet`, `Apple`, `AppleAppAttest`. Bifrost asks for `none` attestation and does not use a metadata service, so it does not depend on any of them being trusted; a client that sends another format still has it parsed and its statement verified structurally by the library. | | What verification covers | Read in `AuthenticatorAssertionResponse.cs`: challenge, origin (against `Fido2Configuration.Origins`), `webauthn.get` type, RP ID hash, user-present and user-verified flags (when required), signature over `authData || SHA-256(clientDataJSON)` with the stored COSE key, user handle ownership, and the sign count (see "Sign count" below). Enrolment verifies the attestation, the credential id and the key. | -| Transitive weight | Heavier than the repository's other packages: `Microsoft.Extensions.Http` 9.0.0 pulls `Microsoft.Extensions.*` 9.0.0, so existing 8.x entries move to 9.0.0 (seven in `src/Bifrost.Web/packages.lock.json`; twelve `Microsoft.Extensions.*` entries plus `System.Diagnostics.DiagnosticSource` in the test project's lockfile, which sees them too; app-local on top of the net8 shared framework, a supported combination), and the lockfiles gain `Fido2`, `Fido2.Models`, `Microsoft.Bcl.Memory`, `Microsoft.Extensions.Http`, `Microsoft.Extensions.Diagnostics[.Abstractions]`, `Microsoft.Extensions.Configuration[.Binder]`, `Microsoft.Extensions.Options.ConfigurationExtensions`, `NSec.Cryptography`, `System.Formats.Cbor` and the native `libsodium` package. `Microsoft.IdentityModel.JsonWebTokens` is requested at 8.2.0 and already resolved to 8.19.2 (through OpenIddict) before this change; it still does (the Linux x64 glibc and musl binaries ship in the package's `runtimes/`). `packages.lock.json` in both projects is regenerated and committed. | +| Transitive weight | Heavier than the repository's other packages: `Microsoft.Extensions.Http` 9.0.0 pulls `Microsoft.Extensions.*` 9.0.0, so existing 8.x entries move to 9.0.0 (seven in `src/Bifrost.Web/packages.lock.json`; twelve `Microsoft.Extensions.*` entries plus `System.Diagnostics.DiagnosticSource` in the test project's lockfile, which sees them too; app-local on top of the net8 shared framework, a supported combination), and the lockfiles gain `Fido2`, `Fido2.Models`, `Microsoft.Bcl.Memory`, `Microsoft.Extensions.Http`, `Microsoft.Extensions.Diagnostics[.Abstractions]`, `Microsoft.Extensions.Configuration[.Binder]`, `System.Diagnostics.DiagnosticSource`, `Microsoft.Extensions.Options.ConfigurationExtensions`, `NSec.Cryptography`, `System.Formats.Cbor` and the native `libsodium` package (the Linux x64 glibc and musl binaries ship in the package's `runtimes/`). `Microsoft.IdentityModel.JsonWebTokens` is requested at 8.2.0 and already resolved to 8.19.2 (through OpenIddict) before this change; it still does. `packages.lock.json` in both projects is regenerated and committed. | | Alternatives | Not needed: the candidate passed. | Not verified: that the 9.0.0 `Microsoft.Extensions.*` assemblies behave on the live host's ASP.NET Core 8 runtime beyond the test host (the suite runs the real app under it); that `libsodium` loads on Yggdrasil (the EdDSA test loads it here, on Debian x64). @@ -33,7 +33,7 @@ The stored sign count is updated on every successful assertion, and the library ## Relying party -RP ID is the host of `Host:PublicBaseUrl`, the one origin is its scheme, host and port. They come from configuration and from nothing the browser sends. Passkeys are unavailable, with a warning logged once at start, when `Host:PublicBaseUrl` is not https or its host is not `Host:ExpectedHost`: the page offers none and every ceremony endpoint refuses (`passkeys_unavailable`). `PasskeyRelyingParty` is resolved at startup, so a misconfiguration is logged once at boot (not at the first ceremony). `Host:ExpectedHost` must be a bare host name: one written with a port (`host:443`) is reported as such and also makes passkeys unavailable, because it is not the RP ID's host. No new configuration key exists. +RP ID is the host of `Host:PublicBaseUrl`, the one origin is its scheme, host and port. They come from configuration and from nothing the browser sends. Passkeys are unavailable, with a warning logged once at start, when `Host:PublicBaseUrl` is not https or its host is not `Host:ExpectedHost`: the page offers none and every ceremony endpoint refuses (`passkeys_unavailable`). `PasskeyRelyingParty` is resolved at startup, so a misconfiguration is logged once at boot (not at the first ceremony). `Host:ExpectedHost` must be a bare host name: one with a port (`host:443`) or an IP address (`[::1]`, `127.0.0.1`) makes passkeys unavailable and is reported, because an IP address is not a valid RP ID and a port is not part of it. No new configuration key exists. If passkeys are unavailable while an account holds a strong passkey, the page shows no unlink form and says so: unlinking needs the passkey, the Google route stays closed (`passkey_required`), and the member can revoke their passkeys on the page (revoking does not need the relying party) to fall back to the Google proof, or wait for the operator to fix the server. This is a lockout until the operator or the member acts; it fails closed. @@ -51,7 +51,7 @@ If passkeys are unavailable while an account holds a strong passkey, the page sh A challenge kind has one live record per account: a newer one replaces the older. The table holds at most 2048 records and refuses past that. -A caller's own preconditions are checked before anything is spent. A registration needs the live ticket cookie (a session thief has none), a decodable body and room under the cap; an assertion needs a decodable body naming one of the session account's own strong, un-revoked credentials. Only then are the verification permit, the challenge and (for enrolment) the ticket taken. So junk posted by someone who holds only the session burns neither the member's ticket and challenge nor the 20 verification permits per 10 minutes. Asking for options spends a separate options budget (20 per 10 minutes), which a session holder can exhaust: that blocks new options for a while and nothing else. A session holder can also replace the member's pending challenge by asking for new options, which makes the member's assertion answer `passkey_expired` and the member tries again; that session can already revoke passkeys, so it is not a new capability. A thief who has read a credential id from the options can still post a bad signature for it and burn the challenge once; the member retries. +A caller's own preconditions are checked before anything is spent. A registration needs the live ticket cookie (a session thief has none), a decodable body and room under the cap; an assertion needs a decodable body naming one of the session account's own strong, un-revoked credentials. Only then are the verification permit, the challenge and (for enrolment) the ticket taken. An assertion also needs a live challenge for that account and identity before a permit is spent. So junk posted by someone who holds only the session, naming no credential of the account or arriving with no live challenge, spends nothing. Junk naming one of the account's own credentials (the id is in `allowCredentials`) spends one verification permit per challenge that was asked for, because the first such post takes the challenge; it cannot drain the 20 permits per 10 minutes in one go. It can still burn that challenge once, and a session holder who keeps asking for challenges (an options permit each) and posting junk can exhaust both budgets: a lockout the same session already has through revoking passkeys, not a bypass. A junk post naming no credential of the account costs two cheap database lookups and no permit; that is accepted rather than spending an options-style permit on it. Both budgets are per process: with more than one instance each has its own. Asking for options spends a separate options budget (20 per 10 minutes), which a session holder can exhaust: that blocks new options for a while and nothing else. A session holder can also replace the member's pending challenge by asking for new options, which makes the member's assertion answer `passkey_expired` and the member tries again; that session can already revoke passkeys, so it is not a new capability. The member whose challenge was burned retries with a new one. ## Enrolment @@ -118,6 +118,7 @@ Bifrost sends no `Content-Security-Policy` header (nothing in the application se - No native-only accounts (no Heimdall account, nothing to unlink). - No recovery without mail: a member who loses every passkey revokes them and falls back to the Google step-up if a Google login is linked, or waits for the mail gate (`docs/registration-gates.md`) and the email-code factor that follows it. The email code is not built. - Named limit and next hardening: enrolling a second passkey should require an assertion by an existing strong passkey, and enrolment should use a Google step-up when a Google login is held. Today enrolment needs only the fresh ordinary sign-in and the cooling-off, so an attacker who controls a provider session can add a key that becomes strong after 48 hours unless the member sees and revokes it. Not built; a follow-up is filed. +- A revoke between the completion's check and its unlink does not stop that unlink: the window is the few milliseconds of the two Heimdall calls and is inherent to checking before acting. - Revoking needs no strong proof, so a stolen session can revoke a member's passkeys and fall back to the Google proof: no weaker than the account was before it had a passkey. - A passkey synced through a cloud account the attacker also controls is a residual risk, as in the scoping note. - Heimdall cannot tell that a passkey was checked: `bifrost-passkey` is Bifrost's word, gated by the app secret and a live bearer (Heimdall `docs/app-profiles/bifrost.md`). diff --git a/src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs b/src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs index 3f8619f..ddbb36f 100644 --- a/src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs +++ b/src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs @@ -122,7 +122,10 @@ public sealed class PasskeyCeremonies(TimeProvider clock) /// The budgets on the passkey ceremonies, per Heimdall account, on the shared . Two separate /// ones: asking for options or starting an enrolment sign-in (anyone holding the session can do that), and verifying a /// registration or an assertion, which is spent only after the caller holds what the verification needs (a live ticket, or one of -/// the account's own strong credentials). So junk from a session thief cannot spend the permits a legitimate verification needs. +/// the account's own strong credentials and a live challenge). Junk from a session thief that names no credential of the account, or +/// arrives with no live challenge, spends nothing; junk naming one of the account's credentials spends one permit per challenge that +/// was asked for, because the first such post takes the challenge. A session holder can still exhaust both budgets by asking for +/// challenges over and over: a lockout the same session already has through revoking passkeys, not a bypass. Budgets are per process. /// public sealed class PasskeyRateLimit(TimeProvider clock) { diff --git a/src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs b/src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs index 94ae19c..38aae13 100644 --- a/src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs +++ b/src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs @@ -17,9 +17,9 @@ public sealed class PasskeyRelyingParty public PasskeyRelyingParty(IOptions hostOptions, ILogger logger) { var host = hostOptions.Value; - if (host.ExpectedHost.Contains(':')) + if (host.ExpectedHost.Contains(':') || System.Net.IPAddress.TryParse(host.ExpectedHost.Trim('[', ']'), out _)) { - logger.LogWarning("Passkeys are unavailable: Host:ExpectedHost must be a bare host name without a port (it is the RP ID's host); it was written with a port."); + logger.LogWarning("Passkeys are unavailable: Host:ExpectedHost must be a bare DNS host name, with no port and not an IP address (an IP address is not a valid RP ID)."); return; } diff --git a/src/Bifrost.Web/Features/Passkeys/PasskeyService.cs b/src/Bifrost.Web/Features/Passkeys/PasskeyService.cs index a25dca5..367d13c 100644 --- a/src/Bifrost.Web/Features/Passkeys/PasskeyService.cs +++ b/src/Bifrost.Web/Features/Passkeys/PasskeyService.cs @@ -339,6 +339,13 @@ public sealed class PasskeyService( return (HeimdallLinkOutcome.PasskeyFailed, null); } + // Without a live challenge for this account and identity nothing can verify, so no permit is spent either: junk naming the + // account's own credential spends at most one permit per challenge that was asked for (the first junk then takes it). + if (ceremonies.Peek(CeremonyKind.UnlinkChallenge, heimdallAccountId, identityId, null) is null) + { + return (HeimdallLinkOutcome.PasskeyExpired, null); + } + if (!rateLimit.TryAcquire(heimdallAccountId, verification: true)) { return (HeimdallLinkOutcome.RateLimited, null); diff --git a/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml b/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml index bad0da5..12790f3 100644 --- a/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml +++ b/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml @@ -129,47 +129,46 @@ {

Passkeys are not available on this server right now, so none can be added or used. You can still revoke the ones listed.

} - @if (Model.PasskeysAvailable) - { + @if (Model.PasskeysAvailable) + {

A passkey is the strong proof for unlinking a login: it stays on your device, and a site that is not Bifrost cannot use it. A new passkey is added only right after you sign in to Heimdall again, and it counts as strong proof 48 hours later, so someone who borrows your open browser cannot add one and use it at once. You can revoke a passkey here at any time.

- } - @if (Model.Passkeys.Count > 0) - { -
    - @foreach (var key in Model.Passkeys) - { -
  • - @key.Label - @if (key.IsStrong) - { - active - } - else - { - cooling off until @key.StrongFromUtc.UtcDateTime.ToString("dd MMM yyyy HH:mm") UTC; cannot unlink yet - } - added @key.CreatedUtc.UtcDateTime.ToString("dd MMM yyyy") UTC - @if (key.LastUsedUtc is { } used) - { - last used @used.UtcDateTime.ToString("dd MMM yyyy") UTC - } -
    - - -
    -
  • - } -
- } + } + @if (Model.Passkeys.Count > 0) + { +
    + @foreach (var key in Model.Passkeys) + { +
  • + @key.Label + @if (key.IsStrong) + { + active + } + else + { + cooling off until @key.StrongFromUtc.UtcDateTime.ToString("dd MMM yyyy HH:mm") UTC; cannot unlink yet + } + added @key.CreatedUtc.UtcDateTime.ToString("dd MMM yyyy") UTC + @if (key.LastUsedUtc is { } used) + { + last used @used.UtcDateTime.ToString("dd MMM yyyy") UTC + } +
    + + +
    +
  • + } +
+ } - @if (!Model.PasskeysAvailable) - { - } - else if (Model.PasskeyLimitReached) + @if (Model.PasskeysAvailable) + { + if (Model.PasskeyLimitReached) {

This is the most passkeys an account can hold. Revoke one to add another.

} @@ -196,8 +195,8 @@ {

Read your linked logins first; adding a passkey then asks you to sign in to Heimdall once more.

} - -

+ } +

@if (Model.Identities is not null) { diff --git a/tests/Bifrost.Web.Tests/PasskeyTests.cs b/tests/Bifrost.Web.Tests/PasskeyTests.cs index e81def8..9637fdd 100644 --- a/tests/Bifrost.Web.Tests/PasskeyTests.cs +++ b/tests/Bifrost.Web.Tests/PasskeyTests.cs @@ -951,7 +951,14 @@ public sealed class PasskeyTests Assert.False(party.IsAvailable); Assert.False(loud.IsAvailable); - Assert.Contains("without a port", Assert.Single(logs.Lines)); + foreach (var literal in new[] { "[::1]", "::1", "127.0.0.1" }) + { + Assert.False(new PasskeyRelyingParty( + Microsoft.Extensions.Options.Options.Create(new Bifrost.Web.Configuration.BifrostHostOptions { PublicBaseUrl = "https://localhost", ExpectedHost = literal }), + new Microsoft.Extensions.Logging.Abstractions.NullLogger()).IsAvailable); + } + + Assert.Contains("not an IP address", Assert.Single(logs.Lines)); Assert.True(fine.IsAvailable); Assert.Equal("https://localhost:8443", fine.Origin); Assert.Equal("localhost", fine.RpId); @@ -1021,4 +1028,125 @@ public sealed class PasskeyTests Assert.Equal(Page + "?result=passkey_added", Location(again)); Assert.Contains((await Credentials(host)), x => x.Label == "abc"); } + + // ---- delta: permits, challenges and the fact's credential ---- + + [Fact] + public async Task Junk_naming_the_accounts_own_credential_spends_one_permit_per_challenge_not_the_budget() + { + using var host = new HeimdallHost(realSessions: true); + var member = await NewMember(host); + var authenticator = new SoftwareAuthenticator(); + await AddPasskey(host, member, authenticator); + await CoolOff(host, member); + var (json, _) = await Challenge(host, member, member.Patreon); + var thief = new SoftwareAuthenticator(); + + // The credential id is public to the session (it is in allowCredentials): every junk post names it. + for (var i = 0; i < PasskeyRateLimit.Permits + 5; i++) + { + var junk = thief.Assert(json); + junk["id"] = junk["rawId"] = Microsoft.AspNetCore.WebUtilities.WebEncoders.Base64UrlEncode(authenticator.CredentialId); + var done = await PostAssertion(host, member, junk, member.Patreon); + Assert.Equal(Page + (i == 0 ? "?result=passkey_failed" : "?result=passkey_expired"), Location(done.Response)); + } + + var (fresh, _) = await Challenge(host, member, member.Patreon); + var real = await PostAssertion(host, member, authenticator.Assert(fresh), member.Patreon); + Assert.StartsWith("https://heimdall.test", Location(real.Response)); + } + + [Fact] + public async Task The_fact_is_bound_to_the_credential_it_was_made_with_not_to_some_strong_credential() + { + using var host = new HeimdallHost(realSessions: true); + var member = await NewMember(host); + var a = new SoftwareAuthenticator(); + var b = new SoftwareAuthenticator(); + await AddPasskey(host, member, a); + await AddPasskey(host, member, b); + await CoolOff(host, member); + var attempt = await Unlink(host, member, a, member.Patreon); + var aId = (await Credentials(host)).Single(x => x.CredentialId.SequenceEqual(a.CredentialId)).Id.ToString(); + await host.PostLinkedAccountsAsync(member.Session, "PasskeyRevoke", new Dictionary { ["credentialId"] = aId }); + + var done = await Finish(host, member, attempt); + + Assert.Equal(Page + "?result=passkey_failed", Location(done)); + Assert.Empty(host.Heimdall.StepUps); + Assert.Empty(host.Heimdall.Unlinks); + Assert.Single((await Credentials(host)), x => x.RevokedUtc is null); // B is still strong + } + + [Fact] + public async Task A_rate_limited_verification_spends_neither_the_ticket_nor_the_challenge() + { + using var host = new HeimdallHost(realSessions: true); + var member = await NewMember(host); + var authenticator = new SoftwareAuthenticator(); + var limit = host.Services.GetRequiredService(); + var ceremonies = host.Services.GetRequiredService(); + + // Enrolment. + var ticket = await SignInForEnrolment(host, member); + var options = await host.PostLinkedAccountsAsync(member.Session, "PasskeyEnrolOptions", extraCookies: Ticket(ticket)); + var registration = authenticator.Register(await JsonOf(options)); + for (var i = 0; i < PasskeyRateLimit.Permits; i++) + { + Assert.True(limit.TryAcquire(member.Account, verification: true)); + } + + var limited = await host.PostLinkedAccountsAsync(member.Session, "PasskeyEnrol", registration, extraCookies: Ticket(ticket)); + + Assert.Equal(Page + "?result=rate_limited", Location(limited.Response)); + Assert.NotNull(ceremonies.Peek(CeremonyKind.EnrolTicket, member.Account, null, ticket)); + Assert.NotNull(ceremonies.Peek(CeremonyKind.EnrolChallenge, member.Account, null, null)); + + // Assertion, for an account whose budget is fresh (the budgets time on the monotonic clock, which the test clock does not move). + var other = await NewMember(host); + var otherKey = new SoftwareAuthenticator(); + await AddPasskey(host, other, otherKey); + await CoolOff(host, other); + var (json, _) = await Challenge(host, other, other.Patreon); + while (limit.TryAcquire(other.Account, verification: true)) + { + } + + var assertion = await PostAssertion(host, other, otherKey.Assert(json), other.Patreon); + + Assert.Equal(Page + "?result=rate_limited", Location(assertion.Response)); + Assert.NotNull(ceremonies.Peek(CeremonyKind.UnlinkChallenge, other.Account, other.Patreon, null)); + } + + [Fact] + public async Task Options_and_verification_budgets_do_not_drain_each_other() + { + using var host = new HeimdallHost(realSessions: true); + var member = await NewMember(host); + var authenticator = new SoftwareAuthenticator(); + await AddPasskey(host, member, authenticator); + await CoolOff(host, member); + var limit = host.Services.GetRequiredService(); + var (json, _) = await Challenge(host, member, member.Patreon); + + // Options budget spent: a verification still goes through. + while (limit.TryAcquire(member.Account)) + { + } + + var real = await PostAssertion(host, member, authenticator.Assert(json), member.Patreon); + Assert.StartsWith("https://heimdall.test", Location(real.Response)); + + // And the other way round, for an account whose options budget is fresh: verification spent, options still answer. + var other = await NewMember(host); + await AddPasskey(host, other, new SoftwareAuthenticator()); + await CoolOff(host, other); + while (limit.TryAcquire(other.Account, verification: true)) + { + } + + var (again, call) = await Challenge(host, other, other.Patreon); + Assert.Equal(HttpStatusCode.OK, call.Response.StatusCode); + Assert.Contains("challenge", again); + } }