Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Refactor legacyVerifierUpgrade (#2469)

Leendert de Borst3707888604f7
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
index b595737e3..974b9cea3 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
@@ -7,14 +7,13 @@ import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreOperationCallback
import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreProvider
import net.aliasvault.app.vaultstore.storageprovider.StorageProvider
import org.json.JSONObject
-import uniffi.aliasvault_core.srpDerivePrivateKey
-import uniffi.aliasvault_core.srpDeriveSession
-import uniffi.aliasvault_core.srpGenerateEphemeral
+import uniffi.aliasvault_core.KeyChainException
import java.math.BigInteger
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
+import uniffi.aliasvault_core.openAccountKeyChain as rustOpenAccountKeyChain
/**
* Handles encryption, decryption, and key management for the vault.
@@ -75,8 +74,8 @@ class VaultCrypto(
}
/**
- * The unlock key. The one secret the unlocked session holds in memory, and the key the
- * unlock methods (keystore, PIN) protect. Every other key is derived from it and the cached account key chain.
+ * The stored key: the one secret the unlocked session holds in memory, and the key the unlock methods (keystore,
+ * PIN) protect. Every other key is derived from it and the cached account key chain.
*/
internal var unlockKey: ByteArray? = null
@@ -93,13 +92,15 @@ class VaultCrypto(
get() = sessionKeys()?.accountPrivateKey
/**
- * What the unlock key opens in the cached account key chain.
+ * What the stored key opens in the cached account key chain. A session that still holds an unlock key while the
+ * account has a chain (a sync accepted one created on another device) keeps the Account Key from now on; the
+ * keystore copy converts at the next biometric unlock (see [LegacyKeyConversion]), so this never prompts.
*/
@Suppress("SwallowedException")
private fun sessionKeys(): SessionKeys? {
val key = unlockKey ?: return null
return try {
- openAccountKeyChain(key)
+ openAccountKeyChain(key).also { if (!it.accountKey.contentEquals(key)) unlockKey = it.accountKey }
} catch (e: Exception) {
null
}
@@ -116,7 +117,8 @@ class VaultCrypto(
encryptionType: String,
encryptionSettings: String,
): ByteArray {
- require(encryptionType == "Argon2Id") { "Unsupported encryption type: $encryptionType" }
+ // Both types derive the unlock key with Argon2id; they differ only in how the SRP input is made from it.
+ require(encryptionType == "Argon2Id" || encryptionType == "Argon2IdHkdf") { "Unsupported encryption type: $encryptionType" }
return uniffi.aliasvault_core.argon2DeriveKey(password, salt, encryptionSettings)
}
@@ -143,7 +145,7 @@ class VaultCrypto(
var error: Exception? = null
keystoreProvider.storeKey(
- key = base64UnlockKey,
+ key = Base64.encodeToString(unlockKey, Base64.NO_WRAP),
object : KeystoreOperationCallback {
override fun onSuccess(result: String) {
Log.d(TAG, "Encryption key stored successfully with biometric protection")
@@ -202,26 +204,27 @@ class VaultCrypto(
}
/**
- * Store the account-key chain the native password unlock unwraps: JSON with the Account Key wrapped by the
- * unlock key ("encryptedAccountKey") and the VEK wrapped by the Account Key ("encryptedVek").
- * Null means a legacy account whose KEK encrypts the vault directly.
+ * Store the account-key chain the native unlock opens: JSON with the Account Key wrapped by the
+ * KEK derived from the unlock key ("encryptedAccountKey") and the VEK wrapped by the Account Key ("encryptedVek").
+ * Null until the account is upgraded; its unlock key encrypts the vault directly.
*/
fun storeAccountKeyChain(chainJson: String?) {
storageProvider.setAccountKeyChain(chainJson?.takeIf { it.isNotEmpty() })
}
/**
- * The stored account-key chain JSON, or null for a legacy account.
+ * The stored account-key chain JSON, or null until the account is upgraded.
*/
fun getAccountKeyChain(): String? {
return storageProvider.getAccountKeyChain()
}
/*
- * The unlock key is the one secret a session holds; keystore and PIN only protect
- * that same key. It opens the cached account key chain as the server returned it: KEK > Account Key > vault key
- * and account private key, which are derived on demand and never stored. A legacy account has no chain and its
- * KEK is the vault key.
+ * The stored key is the one secret a session holds; keystore and PIN only protect that same key. It is the Account
+ * Key, so it does not depend on the password: a typed password yields an unlock key (its Argon2id output), which
+ * opening the chain turns into the Account Key before anything stores it. A key stored before the account had a
+ * chain is an unlock key; it still opens the chain and is replaced by the Account Key on the next open. The
+ * Account Key opens the vault key and account private key, which are derived on demand and never stored.
*/
/**
@@ -229,48 +232,38 @@ class VaultCrypto(
*
* @property vaultEncryptionKey The key that encrypts and decrypts the vault
* @property accountPrivateKey The account private key (JWK), null when the account has no keypair
+ * @property accountKey The key to store for later unlocks, in place of the key the chain was opened with
*/
- class SessionKeys(val vaultEncryptionKey: ByteArray, val accountPrivateKey: String?)
+ class SessionKeys(val vaultEncryptionKey: ByteArray, val accountPrivateKey: String?, val accountKey: ByteArray)
/**
- * Open the cached account key chain with the KEK. Without a chain (legacy account) the KEK is the vault key.
+ * Open the cached account key chain with the stored key: the Account Key, or an unlock key that `accountKey` then
+ * replaces (Rust `openAccountKeyChain`). Without a chain (account not yet upgraded) the unlock key is the vault key.
*/
- @Suppress("SwallowedException")
- fun openAccountKeyChain(derivedKey: ByteArray): SessionKeys {
- val chainJson = getAccountKeyChain() ?: return SessionKeys(derivedKey, null)
+ fun openAccountKeyChain(storedKey: ByteArray): SessionKeys {
+ val chainJson = getAccountKeyChain() ?: return SessionKeys(storedKey, null, storedKey)
val chain = JSONObject(chainJson)
- val encryptedAccountKey = chain.optString("encryptedAccountKey").takeIf { it.isNotEmpty() } ?: return SessionKeys(derivedKey, null)
+ val encryptedAccountKey = chain.optString("encryptedAccountKey").takeIf { it.isNotEmpty() } ?: return SessionKeys(storedKey, null, storedKey)
val encryptedVek = chain.optString("encryptedVek").takeIf { it.isNotEmpty() } ?: error("Account key chain is missing the encrypted VEK")
+ // A private key that does not open must not fail the unlock; grants stay closed until the next login.
+ val encryptedPrivateKey = chain.optString("encryptedAccountPrivateKey").takeIf { it.isNotEmpty() }
- val accountKey = try {
- decrypt(Base64.decode(encryptedAccountKey, Base64.NO_WRAP), derivedKey)
- } catch (e: Exception) {
+ val keys = try {
+ rustOpenAccountKeyChain(storedKey, encryptedAccountKey, encryptedVek, encryptedPrivateKey)
+ } catch (e: KeyChainException.UnlockKeyRejected) {
throw AppError.UnlockKeyRejected(cause = e)
- }
- // The account key opened, so a failure here is a damaged chain and never a wrong password.
- val vaultEncryptionKey = try {
- decrypt(Base64.decode(encryptedVek, Base64.NO_WRAP), accountKey)
- } catch (e: Exception) {
+ } catch (e: KeyChainException.KeyChainUnreadable) {
+ // The account key opened, so this is a damaged chain and never a wrong password.
throw AppError.KeyChainUnreadable(e.message ?: "decrypt failed", e)
}
-
- // A private key that does not open must not fail the unlock; grants stay closed until the next login.
- val accountPrivateKey = chain.optString("encryptedAccountPrivateKey").takeIf { it.isNotEmpty() }?.let {
- try {
- String(decrypt(Base64.decode(it, Base64.NO_WRAP), accountKey), Charsets.UTF_8)
- } catch (e: Exception) {
- null
- }
- }
- return SessionKeys(vaultEncryptionKey, accountPrivateKey)
+ return SessionKeys(keys.vaultEncryptionKey, keys.accountPrivateKey, keys.accountKey)
}
/**
- * Open a session with the unlock key, after checking that it opens the cached account key chain.
+ * Open a session with a key that opens the cached account key chain; the session keeps the Account Key it yields.
*/
fun openSession(unlockKey: ByteArray) {
- openAccountKeyChain(unlockKey)
- this.unlockKey = unlockKey
+ this.unlockKey = openAccountKeyChain(unlockKey).accountKey
}
/**
@@ -294,33 +287,6 @@ class VaultCrypto(
withSession(callback, authMethods) { unlockKey }
}
- /**
- * Answer a server's SRP challenge with the available unlock key.
- */
- fun deriveSrpProof(salt: String, srpIdentity: String, serverEphemeral: String, callback: CryptoOperationCallback, authMethods: String) {
- withSession(
- object : CryptoOperationCallback {
- override fun onSuccess(result: String) {
- try {
- val passwordHash = Base64.decode(result, Base64.NO_WRAP).joinToString("") { "%02X".format(it) }
- val ephemeral = srpGenerateEphemeral()
- val privateKey = srpDerivePrivateKey(salt, srpIdentity, passwordHash)
- val session = srpDeriveSession(ephemeral.secret, serverEphemeral, salt, srpIdentity, privateKey)
- callback.onSuccess(JSONObject().put("clientPublicEphemeral", ephemeral.public).put("clientSessionProof", session.proof).toString())
- } catch (e: Exception) {
- Log.e(TAG, "Could not derive the SRP proof from the unlock key", e)
- callback.onError(e)
- }
- }
-
- override fun onError(e: Exception) {
- callback.onError(e)
- }
- },
- authMethods,
- ) { unlockKey }
- }
-
/**
* Hand one of the session keys to the callback, opening the session from the keystore behind a biometric prompt
* when none is open.
@@ -336,7 +302,9 @@ class VaultCrypto(
object : KeystoreOperationCallback {
override fun onSuccess(result: String) {
try {
- openSession(Base64.decode(result, Base64.NO_WRAP))
+ val keystoreKey = Base64.decode(result, Base64.NO_WRAP)
+ openSession(keystoreKey)
+ unlockKey?.let { LegacyKeyConversion.convertKeystoreKey(keystoreProvider, keystoreKey, it) }
callback.onSuccess(Base64.encodeToString(key(), Base64.NO_WRAP))
} catch (e: AppError) {
Log.e(TAG, "The unlock key from the keystore does not open the account key chain", e)
diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
index 2430a506f..6bdc6d906 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
@@ -144,7 +144,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
[HttpPost("validate")]
public async Task<IActionResult> Validate([FromBody] ValidateLoginRequest model)
{
- var (user, serverSession, error) = await ValidateUserAndPassword(model);
+ var (user, serverSession, unlockKeyId, error) = await ValidateUserAndPassword(model);
if (error is not null)
{
// Error occured during validation, return the error.
@@ -161,6 +161,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
// Reset failed login attempts.
await userManager.ResetAccessFailedCountAsync(user);
await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.Login);
+ await UpgradeLegacySrpVerifierAsync(unlockKeyId, model);
var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: model.RememberMe);
return Ok(new ValidateLoginResponse(false, serverSession!.Proof, tokenModel));
@@ -174,7 +175,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
[HttpPost("validate-2fa")]
public async Task<IActionResult> Validate2Fa([FromBody] ValidateLoginRequest2Fa model)
{
- var (user, serverSession, error) = await ValidateUserAndPassword(model);
+ var (user, serverSession, unlockKeyId, error) = await ValidateUserAndPassword(model);
if (error is not null)
{
// Error occured during validation, return the error.
@@ -201,6 +202,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
// Validation of 2-FA token is successful, user is authenticated.
await userManager.ResetAccessFailedCountAsync(user);
await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.TwoFactorAuthentication);
+ await UpgradeLegacySrpVerifierAsync(unlockKeyId, model);
// Generate and return the JWT token.
var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: model.RememberMe);
@@ -215,7 +217,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
[HttpPost("validate-recovery-code")]
public async Task<IActionResult> ValidateRecoveryCode([FromBody] ValidateLoginRequestRecoveryCode model)
{
- var (user, serverSession, error) = await ValidateUserAndPassword(model);
+ var (user, serverSession, unlockKeyId, error) = await ValidateUserAndPassword(model);
if (error is not null)
{
// Error occured during validation, return the error.
@@ -246,6 +248,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
// Recovery code is valid, user is authenticated.
await userManager.ResetAccessFailedCountAsync(user);
await authLoggingService.LogAuthEventSuccessAsync(model.Username, AuthEventType.TwoFactorAuthentication);
+ await UpgradeLegacySrpVerifierAsync(unlockKeyId, model);
// Generate and return the JWT token.
var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: model.RememberMe);
@@ -1328,28 +1331,28 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
/// action result is returned with the appropriate error message. If everything is valid nothing is returned.
/// </summary>
/// <param name="model">ValidateLoginRequest model.</param>
- /// <returns>User and SrpSession object if validation succeeded, IActionResult as error on error.</returns>
- private async Task<(AliasVaultUser? User, SrpSession? ServerSession, IActionResult? Error)> ValidateUserAndPassword(ValidateLoginRequest model)
+ /// <returns>User, SrpSession and the proven unlock key if validation succeeded, IActionResult as error on error.</returns>
+ private async Task<(AliasVaultUser? User, SrpSession? ServerSession, Guid? UnlockKeyId, IActionResult? Error)> ValidateUserAndPassword(ValidateLoginRequest model)
{
var user = await userManager.FindByNameAsync(model.Username);
if (user == null)
{
await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.InvalidUsername);
- return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
+ return (null, null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
}
// Check if the account is locked out.
if (await userManager.IsLockedOutAsync(user))
{
await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.TwoFactorAuthentication, AuthFailureReason.AccountLocked);
- return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400)));
+ return (null, null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400)));
}
// Check if the account is blocked.
if (user.Blocked)
{
await authLoggingService.LogAuthEventFailAsync(model.Username, AuthEventType.Login, AuthFailureReason.AccountBlocked);
- return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 400)));
+ return (null, null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ACCOUNT_BLOCKED, 400)));
}
// Validate the SRP session (actual password check).
@@ -1365,13 +1368,48 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
}
await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.Login, srpResult.FailureReason);
- return (null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
+ return (null, null, null, BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.USER_NOT_FOUND, 400)));
}
// Record usage of this unlock method for statistics purposes.
await AuthHelper.TouchUnlockKeyLastUsedAsync(context, srpResult.UnlockKeyId, timeProvider.GetUtcNow().UtcDateTime);
- return (user, srpResult.Session, null);
+ return (user, srpResult.Session, srpResult.UnlockKeyId, null);
+ }
+
+ /// <summary>
+ /// Replace the legacy verifier of the unlock key a completed login proved with the upgraded one the client sent.
+ /// </summary>
+ /// <param name="unlockKeyId">The unlock key the login proved; null for a legacy account, which keeps its verifier.</param>
+ /// <param name="model">The validate request carrying the upgraded verifier.</param>
+ /// <returns>Task.</returns>
+ private async Task UpgradeLegacySrpVerifierAsync(Guid? unlockKeyId, ValidateLoginRequest model)
+ {
+ /*
+ * Only after the whole login (2FA included): the proof shows the client holds the password, and the upgraded
+ * verifier keeps that same password and salt, so this is no password change. A legacy account (no unlock key
+ * row) is skipped on purpose: v1 clients can still sign in to it and only know the legacy verifier.
+ */
+ var upgrade = model.LegacyVerifierUpgrade;
+ if (unlockKeyId is null || upgrade is null || upgrade.EncryptionType != Defaults.EncryptionType || string.IsNullOrEmpty(upgrade.SrpVerifier) || upgrade.SrpVerifier.Length > MaxVerifierLength)
+ {
+ return;
+ }
+
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var unlockKey = await context.UserUnlockKeys.FirstOrDefaultAsync(x => x.Id == unlockKeyId.Value);
+ var metadata = VaultKeyMetadata.Parse(unlockKey?.Metadata);
+ if (unlockKey is null || metadata.EncryptionType != Defaults.LegacyEncryptionType)
+ {
+ return;
+ }
+
+ metadata.SrpVerifier = upgrade.SrpVerifier;
+ metadata.EncryptionType = Defaults.EncryptionType;
+ var newMetadataJson = metadata.ToJson();
+
+ // Conditional on the row being unchanged since it was read (a password change bumps UpdatedAt), so a concurrent change wins.
+ await context.UserUnlockKeys.Where(x => x.Id == unlockKey.Id && x.UpdatedAt == unlockKey.UpdatedAt).ExecuteUpdateAsync(s => s.SetProperty(x => x.Metadata, newMetadataJson));
}
/// <summary>
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/LegacySrpVerifierUpgrade.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/LegacySrpVerifierUpgrade.cs
new file mode 100644
index 000000000..262ceb503
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/LegacySrpVerifierUpgrade.cs
@@ -0,0 +1,25 @@
+//-----------------------------------------------------------------------
+// <copyright file="LegacySrpVerifierUpgrade.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Shared.Models.WebApi.V2.Auth;
+
+/// <summary>
+/// The verifier of the same password and salt under the current encryption type, sent once with a login that answered
+/// a legacy (pre-0.31.0, <c>Argon2Id</c>) verifier. TODO: remove once no legacy verifiers are left and/or we stop supporting pre-0.31.0 accounts.
+/// </summary>
+public class LegacySrpVerifierUpgrade
+{
+ /// <summary>
+ /// Gets or sets the upgraded SRP verifier.
+ /// </summary>
+ public string SrpVerifier { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the encryption type <see cref="SrpVerifier"/> was made with.
+ /// </summary>
+ public string EncryptionType { get; set; } = string.Empty;
+}
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.cs
index 434895018..f16332604 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
@@ -46,4 +46,10 @@ public class ValidateLoginRequest
/// Gets the client's session proof.
/// </summary>
public string ClientSessionProof { get; }
+
+ /// <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.
+ /// </summary>
+ public LegacySrpVerifierUpgrade? LegacyVerifierUpgrade { get; set; }
}
diff --git a/apps/server/Utilities/AliasVault.Cryptography/Defaults.cs b/apps/server/Utilities/AliasVault.Cryptography/Defaults.cs
index e8f9cf220..3d804613e 100644
--- a/apps/server/Utilities/AliasVault.Cryptography/Defaults.cs
+++ b/apps/server/Utilities/AliasVault.Cryptography/Defaults.cs
@@ -13,9 +13,16 @@ namespace AliasVault.Cryptography;
public static class Defaults
{
/// <summary>
- /// Gets the default encryption type.
+ /// Gets the encryption type of new verifiers: Argon2id, with the SRP input and the KEK each derived from its output
+ /// with HKDF. Every v2 registration and password change uses it.
/// </summary>
- public static string EncryptionType { get; } = "Argon2Id";
+ public static string EncryptionType { get; } = "Argon2IdHkdf";
+
+ /// <summary>
+ /// Gets the encryption type of verifiers made from the Argon2id output itself, created before the SRP input was
+ /// split off. A v2 password login upgrades them to <see cref="EncryptionType"/>; v1 clients only know this one.
+ /// </summary>
+ public static string LegacyEncryptionType { get; } = "Argon2Id";
/// <summary>
/// Gets the default degree of parallelism for Argon2id.
diff --git a/apps/web/src/utils/MasterPasswordCheck.ts b/apps/web/src/utils/MasterPasswordCheck.ts
index 7377c547d..973300084 100644
--- a/apps/web/src/utils/MasterPasswordCheck.ts
+++ b/apps/web/src/utils/MasterPasswordCheck.ts
@@ -15,7 +15,7 @@ export async function verifyMasterPassword(password: string): Promise<boolean> {
throw new Error('No local key chain to verify the master password against');
}
- const prepared = await SrpAuthService.prepareCredentials(password, params.salt, params.encryptionSettings);
+ const prepared = await SrpAuthService.prepareCredentials(password, params.salt, params.encryptionType, params.encryptionSettings);
try {
await VaultKeyService.verifyUnlockKey(prepared.passwordHashBase64);
return true;
diff --git a/core/client/src/auth/SrpAuthService.ts b/core/client/src/auth/SrpAuthService.ts
index 2dcb2a866..06fac563c 100644
--- a/core/client/src/auth/SrpAuthService.ts
+++ b/core/client/src/auth/SrpAuthService.ts
@@ -4,7 +4,7 @@ import { rustCore } from '../rust/RustCore';
import { bytesToBase64 } from '../utilities/Base64';
import type { SrpEphemeral, SrpSession } from '../rust/RustCoreTypes';
-import type { LoginResponse } from '@aliasvault/models/webapi';
+import type { LegacySrpVerifierUpgrade, LoginResponse } from '@aliasvault/models/webapi';
/**
* Register request type for creating a new user.
@@ -48,26 +48,40 @@ export type SrpClientSession = {
* Login credentials prepared from password derivation.
*/
export type PreparedCredentials = {
+ /** The SRP password hash (uppercase hex) for the account's encryption type. */
passwordHashString: string;
+ /** The unlock key (base64): the Argon2id output of the password. */
passwordHashBase64: string;
+ /** Set when the account still has a legacy verifier, see {@link LegacySrpVerifierUpgrade}. */
+ legacyVerifierUpgrade?: LegacySrpVerifierUpgrade;
};
/**
- * What a new master password needs on both sides: what the server stores to verify it, and the KEK it derives.
+ * What a login proof is made from: the SRP password hash and, for a legacy verifier, its upgrade.
+ */
+export type LoginCredentials = Pick<PreparedCredentials, 'passwordHashString' | 'legacyVerifierUpgrade'>;
+
+/**
+ * What a new master password needs on both sides: what the server stores to verify it, and the unlock key it derives.
*/
export type NewPasswordMaterial = {
salt: string;
verifier: string;
encryptionType: string;
encryptionSettings: string;
- kekBase64: string;
+ unlockKeyBase64: string;
};
/**
- * Default Argon2Id settings for a newly derived KEK.
+ * The encryption type of a verifier made from the unlock key itself, created before the SRP input was split off.
+ */
+export const LEGACY_ENCRYPTION_TYPE = 'Argon2Id';
+
+/**
+ * Default Argon2Id settings for a newly derived unlock key. The type derives the SRP input and the KEK from it with HKDF.
*/
export const DEFAULT_ENCRYPTION = {
- type: 'Argon2Id',
+ type: 'Argon2IdHkdf',
settings: JSON.stringify({
DegreeOfParallelism: 1,
MemorySize: 65536,
@@ -106,19 +120,6 @@ export class SrpAuthService {
return rustCore().srpGenerateSalt();
}
- /**
- * Converts a Uint8Array to an uppercase hex string.
- *
- * @param bytes - The byte array to convert
- * @returns Uppercase hex string
- */
- public static bytesToHexString(bytes: Uint8Array): string {
- return Array.from(bytes)
- .map((b) => b.toString(16).padStart(2, '0'))
- .join('')
- .toUpperCase();
- }
-
/**
* Derives an SRP private key from credentials using Rust WASM.
*
@@ -252,29 +253,67 @@ export class SrpAuthService {
}
/**
- * Prepares login credentials by deriving the password hash.
- *
- * This method derives the encryption key from the password using the
- * encryption parameters from the login initiate response.
+ * Derive the unlock key from the password and the SRP password hash the account's encryption type makes from it.
*
* @param password - The user's password
- * @param salt - The salt from login initiate response
- * @param encryptionType - The encryption type (e.g., 'Argon2Id')
+ * @param salt - The salt from the server's challenge
+ * @param encryptionType - The encryption type from the server's challenge
* @param encryptionSettings - The encryption settings JSON string
- * @returns Prepared credentials with hash in both hex and base64 formats
+ * @returns The SRP password hash (hex) and the unlock key (base64)
*/
- public static async prepareCredentials(
- password: string,
- salt: string,
- encryptionSettings: string
- ): Promise<PreparedCredentials> {
- // Derive key from password using Argon2Id
- const passwordHash = await EncryptionUtility.deriveKeyFromPassword(password, salt, encryptionSettings);
-
+ public static async prepareCredentials(password: string, salt: string, encryptionType: string, encryptionSettings: string): Promise<PreparedCredentials> {
+ const unlockKey = bytesToBase64(await EncryptionUtility.deriveKeyFromPassword(password, salt, encryptionSettings));
return {
- passwordHashString: SrpAuthService.bytesToHexString(passwordHash),
- passwordHashBase64: bytesToBase64(passwordHash),
+ passwordHashString: await SrpAuthService.srpPasswordHash(unlockKey, encryptionType),
+ passwordHashBase64: unlockKey,
+ };
+ }
+
+ /**
+ * The SRP password hash (uppercase hex) an account's encryption type makes from an unlock key.
+ *
+ * @param unlockKeyBase64 - The unlock key (base64), the Argon2id output of the password
+ * @param encryptionType - The encryption type from the server's challenge
+ * @returns The SRP password hash
+ */
+ public static async srpPasswordHash(unlockKeyBase64: string, encryptionType: string): Promise<string> {
+ return rustCore().deriveSrpPasswordHash(unlockKeyBase64, encryptionType);
+ }
+
+ /**
+ * {@link prepareCredentials} for a login: an account that still has a legacy verifier also gets its upgrade.
+ *
+ * @param password - The user's password
+ * @param loginResponse - The login initiate response
+ * @param username - The username typed by the user, used as SRP identity fallback on older servers
+ * @returns The credentials to log in with
+ */
+ public static async prepareLoginCredentials(password: string, loginResponse: LoginResponse, username: string): Promise<PreparedCredentials> {
+ const unlockKey = bytesToBase64(await EncryptionUtility.deriveKeyFromPassword(password, loginResponse.salt, loginResponse.encryptionSettings));
+ return SrpAuthService.loginCredentials(unlockKey, loginResponse, username);
+ }
+
+ /**
+ * The login credentials of an unlock key derived elsewhere (natively on mobile), see {@link prepareLoginCredentials}.
+ *
+ * @param unlockKeyBase64 - The unlock key (base64), the Argon2id output of the password
+ * @param loginResponse - The login initiate response
+ * @param username - The username typed by the user, used as SRP identity fallback on older servers
+ * @returns The credentials to log in with
+ */
+ public static async loginCredentials(unlockKeyBase64: string, loginResponse: LoginResponse, username: string): Promise<PreparedCredentials> {
+ const credentials: PreparedCredentials = {
+ passwordHashString: await SrpAuthService.srpPasswordHash(unlockKeyBase64, loginResponse.encryptionType),
+ passwordHashBase64: unlockKeyBase64,
};
+ if (loginResponse.encryptionType !== LEGACY_ENCRYPTION_TYPE) {
+ return credentials;
+ }
+
+ const srpIdentity = loginResponse.srpIdentity ?? SrpAuthService.normalizeUsername(username);
+ const upgradedHash = await SrpAuthService.srpPasswordHash(unlockKeyBase64, DEFAULT_ENCRYPTION.type);
+ const srpVerifier = await SrpAuthService.deriveVerifier(await SrpAuthService.derivePrivateKey(loginResponse.salt, srpIdentity, upgradedHash));
+ return { ...credentials, legacyVerifierUpgrade: { srpVerifier, encryptionType: DEFAULT_ENCRYPTION.type } };
}
/**
@@ -287,17 +326,17 @@ export class SrpAuthService {
}
/**
- * Derive what a new master password needs: a fresh salt, the SRP verifier the server stores, and the KEK the
- * client wraps its key material with. Uses the default Argon2Id settings.
+ * Derive what a new master password needs: a fresh salt, the SRP verifier the server stores, and the unlock key
+ * whose derived KEK wraps the client's key material. Uses the default Argon2Id settings.
* @param password - the new master password
* @param srpIdentity - the account's SRP identity the verifier is bound to
*/
public static async prepareNewPassword(password: string, srpIdentity: string): Promise<NewPasswordMaterial> {
const salt = await SrpAuthService.generateSalt();
- const credentials = await SrpAuthService.prepareCredentials(password, salt, DEFAULT_ENCRYPTION.settings);
+ const credentials = await SrpAuthService.prepareCredentials(password, salt, DEFAULT_ENCRYPTION.type, DEFAULT_ENCRYPTION.settings);
const privateKey = await SrpAuthService.derivePrivateKey(salt, srpIdentity, credentials.passwordHashString);
const verifier = await SrpAuthService.deriveVerifier(privateKey);
- return { salt, verifier, encryptionType: DEFAULT_ENCRYPTION.type, encryptionSettings: DEFAULT_ENCRYPTION.settings, kekBase64: credentials.passwordHashBase64 };
+ return { salt, verifier, encryptionType: DEFAULT_ENCRYPTION.type, encryptionSettings: DEFAULT_ENCRYPTION.settings, unlockKeyBase64: credentials.passwordHashBase64 };
}
/**
@@ -319,7 +358,7 @@ export class SrpAuthService {
const normalizedUsername = SrpAuthService.normalizeUsername(username);
const srpIdentity = SrpAuthService.generateSrpIdentity();
const material = await SrpAuthService.prepareNewPassword(password, srpIdentity);
- const hierarchy = await createAccountKeyHierarchy(material.kekBase64);
+ const hierarchy = await createAccountKeyHierarchy(material.unlockKeyBase64);
return {
request: {
@@ -332,7 +371,7 @@ export class SrpAuthService {
...hierarchy.accountKeys,
},
keys: hierarchy,
- derivedKey: material.kekBase64,
+ derivedKey: material.unlockKeyBase64,
};
}
}
diff --git a/core/client/src/auth/SrpLoginService.ts b/core/client/src/auth/SrpLoginService.ts
index 209447810..f86678e97 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, ...credentials.srpUpgrade };
+ const model: ValidateLoginRequest = { username: normalizedUsername, rememberMe, ...session.proof, legacyVerifierUpgrade: credentials.legacyVerifierUpgrade };
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, ...credentials.srpUpgrade, code2Fa };
+ const model: ValidateLoginRequest2Fa = { username: normalizedUsername, rememberMe, ...session.proof, legacyVerifierUpgrade: credentials.legacyVerifierUpgrade, code2Fa };
return this.verifiedLoginResponse(session, await this.post('Auth/validate-2fa', model));
}
@@ -110,7 +110,7 @@ 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, ...credentials.srpUpgrade, recoveryCode };
+ const model: ValidateLoginRequestRecoveryCode = { username: normalizedUsername, rememberMe, ...session.proof, legacyVerifierUpgrade: credentials.legacyVerifierUpgrade, recoveryCode };
return this.verifiedLoginResponse(session, await this.post('Auth/validate-recovery-code', model));
}
diff --git a/core/models/src/webapi/ValidateLogin.ts b/core/models/src/webapi/ValidateLogin.ts
index 81360c9a2..f36a65422 100644
--- a/core/models/src/webapi/ValidateLogin.ts
+++ b/core/models/src/webapi/ValidateLogin.ts
@@ -1,3 +1,12 @@
+/**
+ * The verifier of the same password and salt under the current encryption type, sent once with a login that answered
+ * a legacy (pre-0.31.0, Argon2Id) verifier. TODO: remove once no legacy verifiers are left.
+ */
+export type LegacySrpVerifierUpgrade = {
+ srpVerifier: string;
+ encryptionType: string;
+}
+
/**
* Validate login request type.
*/
@@ -6,6 +15,7 @@ export type ValidateLoginRequest = {
rememberMe: boolean;
clientPublicEphemeral: string;
clientSessionProof: string;
+ legacyVerifierUpgrade?: LegacySrpVerifierUpgrade;
}
/**
@@ -17,6 +27,7 @@ export type ValidateLoginRequest2Fa = {
rememberMe: boolean;
clientPublicEphemeral: string;
clientSessionProof: string;
+ legacyVerifierUpgrade?: LegacySrpVerifierUpgrade;
}
/**