Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Make all SRP step-up verifications rate limited and make wrong password count for account lockout (#2469)
Leendert de Borst1aa790cc73c9
diff --git a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V1/AuthController.csindex ebdd3bce1..8ca0fa618 100644--- a/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/AuthController.cs@@ -634,11 +634,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// Validate the SRP session (actual password check).await using var context = await dbContextFactory.CreateDbContextAsync();- var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, SrpPurpose.AccountDeletion, model.ClientPublicEphemeral, model.ClientSessionProof);+ var srpResult = await AuthHelper.ValidateStepUpAsync(cache, context, userManager, user, SrpPurpose.AccountDeletion, model.ClientPublicEphemeral, model.ClientSessionProof);if (srpResult.Session is null){await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.AccountDeletion, srpResult.FailureReason);- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400));}// Log the successful account deletion.diff --git a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V1/VaultController.csindex 51f3bd0a7..dd216a646 100644--- a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs@@ -248,18 +248,11 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont}// Validate the SRP session (actual password check).- var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, SrpPurpose.PasswordChange, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);+ var srpResult = await AuthHelper.ValidateStepUpAsync(cache, context, GetUserManager(), user, SrpPurpose.PasswordChange, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);if (srpResult.Session is null){- if (srpResult.ActiveSessionFound)- {- // The password was wrong: increment failed login attempts which then locks out- // the account when the limit is reached.- await GetUserManager().AccessFailedAsync(user);- }-await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.PasswordChange, srpResult.FailureReason);- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400));}// Check if the provided revision number is equal to the latest revision number.diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.csindex 94fbd3426..433a6272c 100644--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs@@ -668,18 +668,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}// Validate the SRP session (actual current password check).- var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, SrpPurpose.PasswordChange, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);+ var srpResult = await AuthHelper.ValidateStepUpAsync(cache, context, userManager, user, SrpPurpose.PasswordChange, model.CurrentClientPublicEphemeral, model.CurrentClientSessionProof);if (srpResult.Session is null){- if (srpResult.ActiveSessionFound)- {- // The password was wrong: increment failed login attempts which then locks out- // the account when the limit is reached.- await userManager.AccessFailedAsync(user);- }-await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.PasswordChange, srpResult.FailureReason);- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400));}var now = timeProvider.GetUtcNow().UtcDateTime;@@ -1119,11 +1112,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// Validate the SRP session (actual password check).await using var context = await dbContextFactory.CreateDbContextAsync();- var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, SrpPurpose.AccountDeletion, model.ClientPublicEphemeral, model.ClientSessionProof);+ var srpResult = await AuthHelper.ValidateStepUpAsync(cache, context, userManager, user, SrpPurpose.AccountDeletion, model.ClientPublicEphemeral, model.ClientSessionProof);if (srpResult.Session is null){await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.AccountDeletion, srpResult.FailureReason);- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400));}// Log the successful account deletion.diff --git a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.csindex 361bb2177..d146b806e 100644--- a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs@@ -520,11 +520,11 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use}// Validate the SRP session (actual password check).- var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, me, SrpPurpose.SharedManifestDeletion, model.ClientPublicEphemeral, model.ClientSessionProof);+ var srpResult = await AuthHelper.ValidateStepUpAsync(cache, context, GetUserManager(), me, SrpPurpose.SharedManifestDeletion, model.ClientPublicEphemeral, model.ClientSessionProof);if (srpResult.Session is null){await authLoggingService.LogAuthEventFailAsync(me.UserName!, AuthEventType.SharedVaultDeletion, srpResult.FailureReason);- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.PASSWORD_MISMATCH, 400));+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(srpResult.LockedOut ? ApiErrorCode.ACCOUNT_LOCKED : ApiErrorCode.PASSWORD_MISMATCH, 400));}await authLoggingService.LogAuthEventSuccessAsync(me.UserName!, AuthEventType.SharedVaultDeletion);diff --git a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs b/apps/server/AliasVault.Api/Helpers/AuthHelper.csindex 9b84059d5..743fd2431 100644--- a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs+++ b/apps/server/AliasVault.Api/Helpers/AuthHelper.cs@@ -13,6 +13,7 @@ using AliasVault.Api.Headers;using AliasVault.Api.Models;using AliasVault.Cryptography;using AliasVault.Shared.Models.Enums;+using Microsoft.AspNetCore.Identity;using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.Caching.Memory;@@ -92,9 +93,11 @@ public static class AuthHelperreturn new SrpValidationResult(null, false, null);}- if (!cache.TryGetValue(EphemeralCacheKey(purpose, user, sessionId), out CachedEphemeral? cached) || cached is null)+ var cacheKey = EphemeralCacheKey(purpose, user, sessionId);+ var cached = purpose == SrpPurpose.Login ? Peek(cache, cacheKey) : Take(cache, cacheKey);+ if (cached is null){- // No exchange was initiated for this flow, or the server ephemeral has expired.+ // No exchange was initiated for this flow, it was already used, or the server ephemeral has expired.return new SrpValidationResult(null, false, null);}@@ -102,6 +105,7 @@ public static class AuthHelpervar credentials = await GetUserLatestVaultEncryptionSettingsAsync(context, user);if (credentials.UnlockKeyId != cached.UnlockKeyId){+ cache.Remove(cacheKey);return new SrpValidationResult(null, false, null);}@@ -116,9 +120,57 @@ public static class AuthHelperclientSessionProof);// If validation failed, serverSession will be null here.+ if (serverSession is null)+ {+ cache.Remove(cacheKey);+ }+return new SrpValidationResult(serverSession, true, credentials.UnlockKeyId);}+ /// <summary>+ /// Evict a login exchange once the login it proved has completed, so its proof cannot be replayed.+ /// </summary>+ /// <param name="cache">IMemoryCache instance.</param>+ /// <param name="user">The user object.</param>+ /// <param name="sessionId">The session id the exchange was created with, or null for an exchange cached per identity.</param>+ /// <returns>False when the exchange was already used or has expired; the login must then be refused.</returns>+ public static bool ConsumeSrpSession(IMemoryCache cache, AliasVaultUser user, string? sessionId) => Take(cache, EphemeralCacheKey(SrpPurpose.Login, user, sessionId)) is not null;++ /// <summary>+ /// Check a step-up proof (password confirmation of a logged-in user), refusing it while the account is locked out+ /// and counting a wrong password towards the lockout like a failed login.+ /// </summary>+ /// <param name="cache">IMemoryCache instance.</param>+ /// <param name="context">Database context, used to resolve the user's current SRP credentials.</param>+ /// <param name="userManager">User manager that tracks the failed attempts.</param>+ /// <param name="user">The user object.</param>+ /// <param name="purpose">The step-up flow the exchange belongs to.</param>+ /// <param name="clientEphemeral">The client ephemeral value.</param>+ /// <param name="clientSessionProof">The client session proof.</param>+ /// <returns>The validation outcome; <see cref="SrpValidationResult.LockedOut"/> is set when the proof was not checked.</returns>+ public static async Task<SrpValidationResult> ValidateStepUpAsync(IMemoryCache cache, AliasServerDbContext context, UserManager<AliasVaultUser> userManager, AliasVaultUser user, SrpPurpose purpose, string clientEphemeral, string clientSessionProof)+ {+ if (await userManager.IsLockedOutAsync(user))+ {+ // Spend the exchange anyway, so a guess sent while locked out cannot be checked later.+ cache.Remove(EphemeralCacheKey(purpose, user, null));+ return new SrpValidationResult(null, false, null) { LockedOut = true };+ }++ var result = await ValidateSrpSessionAsync(cache, context, user, purpose, clientEphemeral, clientSessionProof);+ if (result.Session is not null)+ {+ await userManager.ResetAccessFailedCountAsync(user);+ }+ else if (result.ActiveSessionFound)+ {+ await userManager.AccessFailedAsync(user);+ }++ return result;+ }+/// <summary>/// Get the user's current SRP salt/verifier and key derivation settings./// </summary>@@ -209,8 +261,51 @@ public static class AuthHelper/// </summary>private static string EphemeralCacheKey(SrpPurpose purpose, AliasVaultUser user, string? sessionId) => sessionId is null ? $"{CachePrefixEphemeral}{purpose}_{GetSrpIdentity(user)}" : $"{CachePrefixEphemeral}{purpose}_{GetSrpIdentity(user)}_{sessionId}";+ /// <summary>+ /// The cached exchange under a key, unless it has been claimed already.+ /// </summary>+ private static CachedEphemeral? Peek(IMemoryCache cache, string cacheKey) => cache.TryGetValue(cacheKey, out CachedEphemeral? cached) && cached is not null && !cached.IsClaimed ? cached : null;++ /// <summary>+ /// Claim and evict the cached exchange under a key; of two concurrent callers only one gets it.+ /// </summary>+ private static CachedEphemeral? Take(IMemoryCache cache, string cacheKey)+ {+ if (!cache.TryGetValue(cacheKey, out CachedEphemeral? cached) || cached is null || !cached.TryClaim())+ {+ return null;+ }++ cache.Remove(cacheKey);+ return cached;+ }+/// <summary>/// A cached server ephemeral and the unlock method whose verifier it was created for (null for a legacy account)./// </summary>- private sealed record CachedEphemeral(string Secret, Guid? UnlockKeyId);+ private sealed class CachedEphemeral(string secret, Guid? unlockKeyId)+ {+ private int claimed;++ /// <summary>+ /// Gets the secret server ephemeral.+ /// </summary>+ public string Secret { get; } = secret;++ /// <summary>+ /// Gets the unlock key the verifier came from.+ /// </summary>+ public Guid? UnlockKeyId { get; } = unlockKeyId;++ /// <summary>+ /// Gets a value indicating whether the exchange has been used up.+ /// </summary>+ public bool IsClaimed => Volatile.Read(ref claimed) == 1;++ /// <summary>+ /// Mark the exchange as used; true only for the first caller.+ /// </summary>+ /// <returns>Whether this call claimed it.</returns>+ public bool TryClaim() => Interlocked.Exchange(ref claimed, 1) == 0;+ }}diff --git a/apps/server/AliasVault.Api/Models/SrpValidationResult.cs b/apps/server/AliasVault.Api/Models/SrpValidationResult.csindex 645d2714b..771c869e1 100644--- a/apps/server/AliasVault.Api/Models/SrpValidationResult.cs+++ b/apps/server/AliasVault.Api/Models/SrpValidationResult.cs@@ -18,9 +18,14 @@ using SecureRemotePassword;/// <param name="UnlockKeyId">The unlock method whose secret was proven, or null for a legacy user that has no unlock key yet.</param>public sealed record SrpValidationResult(SrpSession? Session, bool ActiveSessionFound, Guid? UnlockKeyId){+ /// <summary>+ /// Gets a value indicating whether the proof was refused unchecked because the account is locked out.+ /// </summary>+ public bool LockedOut { get; init; }+/// <summary>/// Gets the reason to log when <see cref="Session"/> is null: a cached ephemeral means the client got the- /// secret wrong, no ephemeral means it never initiated the exchange or took too long over it.+ /// secret wrong, no ephemeral means it never initiated the exchange, already used it or took too long over it./// </summary>- public AuthFailureReason FailureReason => ActiveSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound;+ public AuthFailureReason FailureReason => LockedOut ? AuthFailureReason.AccountLocked : ActiveSessionFound ? AuthFailureReason.InvalidPassword : AuthFailureReason.SrpSessionNotFound;}