Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Bind refresh token to generated access tokens for future revocation and bind SRP ephemeral session to unique ID (#2469)
Leendert de Borsta0e91f9040f1
diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.csindex e802e5c39..e18a9cafa 100644--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs@@ -60,6 +60,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM/// </summary>private const int AccessTokenValiditySeconds = 600;+ /// <summary>+ /// Access token claim with the id of the refresh token it was issued with.+ /// </summary>+ private const string RefreshTokenIdClaim = "rtid";+/// <summary>/// Maximum accepted length of a password salt./// </summary>@@ -125,9 +130,10 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMvar srpIdentity = AuthHelper.GetSrpIdentity(user);- var serverEphemeral = AuthHelper.CreateSrpEphemeral(cache, user, SrpPurpose.Login, latestVaultEncryptionSettings);+ var loginSessionId = AuthHelper.CreateSrpSessionId();+ var serverEphemeral = AuthHelper.CreateSrpEphemeral(cache, user, SrpPurpose.Login, latestVaultEncryptionSettings, loginSessionId);- return Ok(new LoginInitiateResponse(latestVaultEncryptionSettings.Salt, serverEphemeral, latestVaultEncryptionSettings.EncryptionType, latestVaultEncryptionSettings.EncryptionSettings, srpIdentity));+ return Ok(new LoginInitiateResponse(latestVaultEncryptionSettings.Salt, serverEphemeral, latestVaultEncryptionSettings.EncryptionType, latestVaultEncryptionSettings.EncryptionSettings, srpIdentity, loginSessionId));}/// <summary>@@ -338,7 +344,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMif (refreshTokenEntry == null){- // Token doesn't exist - could already be revoked or never existed.+ // Token doesn't exist: could already be revoked or never existed.// Return success to avoid leaking information about token validity.return Ok();}@@ -645,7 +651,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMvar now = timeProvider.GetUtcNow().UtcDateTime;var settings = await settingsService.GetAllSettingsAsync();- var deviceIdentifier = AuthHelper.GenerateDeviceIdentifier(Request);+ var currentRefreshTokenId = Guid.TryParse(User.FindFirstValue(RefreshTokenIdClaim), out var tokenId) ? tokenId : Guid.Empty;var newMetadata = VaultKeyMetadata.Parse(unlockKey.Metadata);newMetadata.Salt = model.NewPasswordSalt;@@ -672,8 +678,8 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// Update the password last changed at timestamp for user.await writeContext.AliasVaultUsers.Where(x => x.Id == user.Id).ExecuteUpdateAsync(s => s.SetProperty(x => x.PasswordChangedAt, now));- // Force revoke all logged-in sessions except the current one so other clients re-authenticate with the new password.- await writeContext.AliasVaultUserRefreshTokens.Where(x => x.UserId == user.Id && x.DeviceIdentifier != deviceIdentifier).ExecuteDeleteAsync();+ // Revoke every session except the caller's own refresh token; an access token without that claim keeps none.+ await writeContext.AliasVaultUserRefreshTokens.Where(x => x.UserId == user.Id && x.Id != currentRefreshTokenId).ExecuteDeleteAsync();await transaction.CommitAsync();});@@ -882,7 +888,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM}// One-time use: an approved request is handed out once, and only shortly after the approval.- if (loginRequest.RetrievedAt != null || loginRequest.EncryptedUnlockKey == null || MobileLoginRequestHelper.IsRetrievalWindowClosed(loginRequest, timeProvider.GetUtcNow().UtcDateTime))+ if (loginRequest.RetrievedAt != null || loginRequest.EncryptedAccountKey == null || MobileLoginRequestHelper.IsRetrievalWindowClosed(loginRequest, timeProvider.GetUtcNow().UtcDateTime)){return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));}@@ -911,11 +917,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// Claim the request and clear its key material in one transaction.var clientPublicKey = loginRequest.ClientPublicKey;- var encryptedUnlockKey = loginRequest.EncryptedUnlockKey;+ var encryptedAccountKey = loginRequest.EncryptedAccountKey;var retrievedAt = timeProvider.GetUtcNow().UtcDateTime;var claimed = await context.MobileLoginRequests.Where(r => r.Id == loginRequest.Id && r.RetrievedAt == null)- .ExecuteUpdateAsync(u => u.SetProperty(r => r.RetrievedAt, retrievedAt).SetProperty(r => r.ClientPublicKey, string.Empty).SetProperty(r => r.EncryptedUnlockKey, (string?)null));+ .ExecuteUpdateAsync(u => u.SetProperty(r => r.RetrievedAt, retrievedAt).SetProperty(r => r.ClientPublicKey, string.Empty).SetProperty(r => r.EncryptedAccountKey, (string?)null));if (claimed != 1){return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));@@ -946,7 +952,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMStatus = MobileLoginStatus.Approved,EncryptedSymmetricKey = encryptedSymmetricKey,EncryptedPayload = encryptedPayload,- EncryptedUnlockKey = encryptedUnlockKey,+ EncryptedAccountKey = encryptedAccountKey,});}@@ -1014,7 +1020,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMvar mobileIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);var updated = await context.MobileLoginRequests.Where(r => r.Id == loginRequest.Id && r.FulfilledAt == null && r.DeclinedAt == null)- .ExecuteUpdateAsync(u => u.SetProperty(r => r.EncryptedUnlockKey, model.EncryptedUnlockKey).SetProperty(r => r.UserId, user.Id).SetProperty(r => r.FulfilledAt, fulfilledAt).SetProperty(r => r.MobileIpAddress, mobileIpAddress));+ .ExecuteUpdateAsync(u => u.SetProperty(r => r.EncryptedAccountKey, model.EncryptedAccountKey).SetProperty(r => r.UserId, user.Id).SetProperty(r => r.FulfilledAt, fulfilledAt).SetProperty(r => r.MobileIpAddress, mobileIpAddress));if (updated != 1){return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_ALREADY_FULFILLED, 400));@@ -1343,7 +1349,7 @@ 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.Login, model.ClientPublicEphemeral, model.ClientSessionProof);+ var srpResult = await AuthHelper.ValidateSrpSessionAsync(cache, context, user, SrpPurpose.Login, model.ClientPublicEphemeral, model.ClientSessionProof, model.LoginSessionId);if (srpResult.Session is null){if (srpResult.ActiveSessionFound)@@ -1404,14 +1410,16 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM/// when this access token expires./// </summary>/// <param name="user">The user to generate the Jwt access token for.</param>+ /// <param name="refreshTokenId">The id of the refresh token issued with this access token.</param>/// <returns>Access token as string.</returns>- private string GenerateJwtToken(AliasVaultUser user)+ private string GenerateJwtToken(AliasVaultUser user, Guid refreshTokenId){var claims = new List<Claim>{new(ClaimTypes.NameIdentifier, user.Id),new(ClaimTypes.Name, user.UserName ?? string.Empty),new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),+ new(RefreshTokenIdClaim, refreshTokenId.ToString()),};var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetJwtKey()));@@ -1481,7 +1489,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM{// A new token was already generated for the current token in the last 30 seconds.// Return the already generated new token.- var accessToken = GenerateJwtToken(user);+ var accessToken = GenerateJwtToken(user, existingTokenReuse.Id);return new TokenModel { Token = accessToken, RefreshToken = existingTokenReuse.Value };}@@ -1524,14 +1532,15 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM{await using var context = await dbContextFactory.CreateDbContextAsync();- // Generate device identifier- var accessToken = GenerateJwtToken(user);+ var refreshTokenId = Guid.NewGuid();+ var accessToken = GenerateJwtToken(user, refreshTokenId);var refreshToken = GenerateRefreshToken();var deviceIdentifier = AuthHelper.GenerateDeviceIdentifier(Request);// Add new refresh token.context.AliasVaultUserRefreshTokens.Add(new AliasVaultUserRefreshToken{+ Id = refreshTokenId,UserId = user.Id,DeviceIdentifier = deviceIdentifier,IpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled),@@ -1554,6 +1563,6 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM{// Always generate a new ephemeral, as this is also done for existing users.var fakeEphemeral = Srp.GenerateEphemeralServer(profile.Verifier);- return Ok(new LoginInitiateResponse(profile.Salt, fakeEphemeral.Public, Defaults.EncryptionType, Defaults.EncryptionSettings, profile.SrpIdentity));+ return Ok(new LoginInitiateResponse(profile.Salt, fakeEphemeral.Public, Defaults.EncryptionType, Defaults.EncryptionSettings, profile.SrpIdentity, AuthHelper.CreateSrpSessionId()));}}diff --git a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs b/apps/server/AliasVault.Api/Helpers/AuthHelper.csindex ab9a5383b..9b84059d5 100644--- a/apps/server/AliasVault.Api/Helpers/AuthHelper.cs+++ b/apps/server/AliasVault.Api/Helpers/AuthHelper.cs@@ -7,6 +7,7 @@namespace AliasVault.Api.Helpers;+using System.Security.Cryptography;using AliasServerDb;using AliasVault.Api.Headers;using AliasVault.Api.Models;@@ -25,6 +26,11 @@ public static class AuthHelper/// </summary>private const string CachePrefixEphemeral = "SrpEphemeral_";+ /// <summary>+ /// Length of an SRP session id in hex characters.+ /// </summary>+ private const int SrpSessionIdLength = 32;+/// <summary>/// How long a client has to answer a server ephemeral./// </summary>@@ -53,14 +59,21 @@ public static class AuthHelper/// <param name="user">The user object.</param>/// <param name="purpose">The flow the exchange belongs to.</param>/// <param name="credentials">The credentials the client has to prove, as returned by <see cref="GetUserLatestVaultEncryptionSettingsAsync"/>.</param>+ /// <param name="sessionId">The session id from <see cref="CreateSrpSessionId"/> the exchange is cached under, so a new exchange cannot replace it; null caches it per identity.</param>/// <returns>The public server ephemeral to send to the client.</returns>- public static string CreateSrpEphemeral(IMemoryCache cache, AliasVaultUser user, SrpPurpose purpose, UserSrpCredentials credentials)+ public static string CreateSrpEphemeral(IMemoryCache cache, AliasVaultUser user, SrpPurpose purpose, UserSrpCredentials credentials, string? sessionId = null){var ephemeral = Srp.GenerateEphemeralServer(credentials.Verifier);- cache.Set(EphemeralCacheKey(purpose, user), new CachedEphemeral(ephemeral.Secret, credentials.UnlockKeyId), EphemeralLifetime);+ cache.Set(EphemeralCacheKey(purpose, user, sessionId), new CachedEphemeral(ephemeral.Secret, credentials.UnlockKeyId), EphemeralLifetime);return ephemeral.Public;}+ /// <summary>+ /// Create a random id for one SRP exchange.+ /// </summary>+ /// <returns>32 lowercase hex characters.</returns>+ public static string CreateSrpSessionId() => RandomNumberGenerator.GetHexString(SrpSessionIdLength, lowercase: true);+/// <summary>/// Validate a client's SRP proof against the ephemeral cached by <see cref="CreateSrpEphemeral"/> for the same flow./// </summary>@@ -70,10 +83,16 @@ public static class AuthHelper/// <param name="purpose">The flow the exchange belongs to.</param>/// <param name="clientEphemeral">The client ephemeral value.</param>/// <param name="clientSessionProof">The client session proof.</param>+ /// <param name="sessionId">The session id the exchange was created with, or null for an exchange cached per identity.</param>/// <returns>The validation outcome, carrying the unlock method whose secret was proven.</returns>- public static async Task<SrpValidationResult> ValidateSrpSessionAsync(IMemoryCache cache, AliasServerDbContext context, AliasVaultUser user, SrpPurpose purpose, string clientEphemeral, string clientSessionProof)+ public static async Task<SrpValidationResult> ValidateSrpSessionAsync(IMemoryCache cache, AliasServerDbContext context, AliasVaultUser user, SrpPurpose purpose, string clientEphemeral, string clientSessionProof, string? sessionId = null){- if (!cache.TryGetValue(EphemeralCacheKey(purpose, user), out CachedEphemeral? cached) || cached is null)+ if (sessionId is not null && sessionId.Length != SrpSessionIdLength)+ {+ return new SrpValidationResult(null, false, null);+ }++ if (!cache.TryGetValue(EphemeralCacheKey(purpose, user, sessionId), out CachedEphemeral? cached) || cached is null){// No exchange was initiated for this flow, or the server ephemeral has expired.return new SrpValidationResult(null, false, null);@@ -186,9 +205,9 @@ public static class AuthHelper}/// <summary>- /// The cache key of the server ephemeral of one flow for one user.+ /// The cache key of the server ephemeral of one flow for one user, and of one exchange when a session id is given./// </summary>- private static string EphemeralCacheKey(SrpPurpose purpose, AliasVaultUser user) => $"{CachePrefixEphemeral}{purpose}_{GetSrpIdentity(user)}";+ private static string EphemeralCacheKey(SrpPurpose purpose, AliasVaultUser user, string? sessionId) => sessionId is null ? $"{CachePrefixEphemeral}{purpose}_{GetSrpIdentity(user)}" : $"{CachePrefixEphemeral}{purpose}_{GetSrpIdentity(user)}_{sessionId}";/// <summary>/// A cached server ephemeral and the unlock method whose verifier it was created for (null for a legacy account).diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/LoginInitiateResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/LoginInitiateResponse.csindex 0150d8d15..95ae59590 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/LoginInitiateResponse.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/LoginInitiateResponse.cs@@ -22,13 +22,15 @@ public class LoginInitiateResponse/// <param name="encryptionType">Encryption type.</param>/// <param name="encryptionSettings">Encryption settings.</param>/// <param name="srpIdentity">The SRP identity.</param>- public LoginInitiateResponse(string salt, string serverEphemeral, string encryptionType, string encryptionSettings, string srpIdentity)+ /// <param name="loginSessionId">The login session id, only set for a login.</param>+ public LoginInitiateResponse(string salt, string serverEphemeral, string encryptionType, string encryptionSettings, string srpIdentity, string? loginSessionId = null){Salt = salt;ServerEphemeral = serverEphemeral;EncryptionType = encryptionType;EncryptionSettings = encryptionSettings;SrpIdentity = srpIdentity;+ LoginSessionId = loginSessionId;}/// <summary>@@ -62,4 +64,11 @@ public class LoginInitiateResponse/// </summary>[JsonPropertyName("srpIdentity")]public string SrpIdentity { get; set; }++ /// <summary>+ /// Gets or sets the id of this login exchange, which the client sends back with its proof.+ /// </summary>+ [JsonPropertyName("loginSessionId")]+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]+ public string? LoginSessionId { get; set; }}diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/ValidateLoginRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/ValidateLoginRequest.csindex f16332604..87e530d00 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/ValidateLoginRequest.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/ValidateLoginRequest.cs@@ -47,6 +47,11 @@ public class ValidateLoginRequest/// </summary>public string ClientSessionProof { get; }+ /// <summary>+ /// Gets or sets the login session id from the initiate response.+ /// </summary>+ public required string LoginSessionId { get; set; }+/// <summary>/// Gets or sets the upgrade of a legacy verifier, which the server stores once the login completes./// TODO: remove once no legacy verifiers are left.diff --git a/core/client/src/auth/SrpLoginService.ts b/core/client/src/auth/SrpLoginService.tsindex f86678e97..5310f751d 100644--- a/core/client/src/auth/SrpLoginService.ts+++ b/core/client/src/auth/SrpLoginService.ts@@ -78,7 +78,7 @@ export class SrpLoginService {public async validateLogin(username: string, credentials: LoginCredentials, rememberMe: boolean, loginResponse: LoginResponse): Promise<ValidateLoginResponse> {const normalizedUsername = SrpAuthService.normalizeUsername(username);const session = await SrpAuthService.deriveLoginSession(loginResponse, normalizedUsername, credentials.passwordHashString);- const model: ValidateLoginRequest = { username: normalizedUsername, rememberMe, ...session.proof, legacyVerifierUpgrade: credentials.legacyVerifierUpgrade };+ const model: ValidateLoginRequest = this.validateModel(normalizedUsername, rememberMe, session, credentials, loginResponse);return this.verifiedLoginResponse(session, await this.post('Auth/validate', model));}@@ -94,7 +94,7 @@ export class SrpLoginService {public async validateLogin2Fa(username: string, credentials: LoginCredentials, rememberMe: boolean, loginResponse: LoginResponse, code2Fa: number): Promise<ValidateLoginResponse> {const normalizedUsername = SrpAuthService.normalizeUsername(username);const session = await SrpAuthService.deriveLoginSession(loginResponse, normalizedUsername, credentials.passwordHashString);- const model: ValidateLoginRequest2Fa = { username: normalizedUsername, rememberMe, ...session.proof, legacyVerifierUpgrade: credentials.legacyVerifierUpgrade, code2Fa };+ const model: ValidateLoginRequest2Fa = { ...this.validateModel(normalizedUsername, rememberMe, session, credentials, loginResponse), code2Fa };return this.verifiedLoginResponse(session, await this.post('Auth/validate-2fa', model));}@@ -110,10 +110,23 @@ export class SrpLoginService {public async validateLoginRecoveryCode(username: string, credentials: LoginCredentials, rememberMe: boolean, loginResponse: LoginResponse, recoveryCode: string): Promise<ValidateLoginResponse> {const normalizedUsername = SrpAuthService.normalizeUsername(username);const session = await SrpAuthService.deriveLoginSession(loginResponse, normalizedUsername, credentials.passwordHashString);- const model: ValidateLoginRequestRecoveryCode = { username: normalizedUsername, rememberMe, ...session.proof, legacyVerifierUpgrade: credentials.legacyVerifierUpgrade, recoveryCode };+ const model: ValidateLoginRequestRecoveryCode = { ...this.validateModel(normalizedUsername, rememberMe, session, credentials, loginResponse), recoveryCode };return this.verifiedLoginResponse(session, await this.post('Auth/validate-recovery-code', model));}+ /**+ * Build the fields every validate request carries.+ * @param username - The normalized username+ * @param rememberMe - Whether to request an extended token lifetime+ * @param session - The client session+ * @param credentials - The SRP password hash and, for a legacy verifier, its upgrade+ * @param loginResponse - The initiate response+ * @returns The validate request+ */+ private validateModel(username: string, rememberMe: boolean, session: SrpClientSession, credentials: LoginCredentials, loginResponse: LoginResponse): ValidateLoginRequest {+ return { username, rememberMe, ...session.proof, loginSessionId: loginResponse.loginSessionId, legacyVerifierUpgrade: credentials.legacyVerifierUpgrade };+ }+/*** Parse a validate response and, once it carries tokens, check the server's session proof.* @param session - The client session the request was sent with