Skip to content

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

Raise Argon2id defaults (#2445)

Leendert de Borstaf91cba9d296
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 7e35acaec..75e8bc058 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -34,10 +34,13 @@ To derive a key from the master password, AliasVault uses the Argon2id key deriv
key derivation function which allows for controlling the execution time, memory required and degree of parallelism.
This makes it resilient against brute-force attacks and makes it one of the best choices for deriving keys from passwords.
-AliasVault uses Argon2id with the following default parameters:
+AliasVault uses Argon2id with the following default parameters for new accounts and password changes:
- Degree of parallelism: 1
-- Memory size: 19456 KB
-- Iterations: 2
+- Memory size: 65536 KiB (64 MiB)
+- Iterations: 5
+
+This is well above the [OWASP minimum](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html)
+(19 MiB, 2 iterations) and above the 64 MiB, 3 iterations of [RFC 9106](https://www.rfc-editor.org/rfc/rfc9106.html#section-4).
More information about Argon2id can be found on the [Argon2](https://en.wikipedia.org/wiki/Argon2) Wikipedia page.
diff --git a/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/TestConfiguration.kt b/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/TestConfiguration.kt
index eef44d59b..48d4cb954 100644
--- a/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/TestConfiguration.kt
+++ b/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/TestConfiguration.kt
@@ -39,8 +39,8 @@ object TestConfiguration {
*/
object EncryptionDefaults {
const val TYPE = "Argon2Id"
- const val ITERATIONS = 2
- const val MEMORY_SIZE = 19456
+ const val ITERATIONS = 5
+ const val MEMORY_SIZE = 65536
const val PARALLELISM = 1
val settingsJson: String
diff --git a/apps/mobile-app/ios/AliasVaultUITests/TestUserRegistration.swift b/apps/mobile-app/ios/AliasVaultUITests/TestUserRegistration.swift
index 14207da4b..bf0496c61 100644
--- a/apps/mobile-app/ios/AliasVaultUITests/TestUserRegistration.swift
+++ b/apps/mobile-app/ios/AliasVaultUITests/TestUserRegistration.swift
@@ -31,8 +31,8 @@ struct ApiError: Codable {
/// These match the server defaults in apps/server/Utilities/AliasVault.Cryptography/Defaults.cs
enum EncryptionDefaults {
static let type = "Argon2Id"
- static let iterations: UInt32 = 2
- static let memorySize: UInt32 = 19456
+ static let iterations: UInt32 = 5
+ static let memorySize: UInt32 = 65536
static let parallelism: UInt32 = 1
static var settingsJson: String {
diff --git a/apps/mobile-app/utils/EncryptionUtility.ts b/apps/mobile-app/utils/EncryptionUtility.ts
index 68febb37d..e95896070 100644
--- a/apps/mobile-app/utils/EncryptionUtility.ts
+++ b/apps/mobile-app/utils/EncryptionUtility.ts
@@ -40,8 +40,8 @@ class EncryptionUtility {
public static async deriveKeyFromPassword(
password: string,
salt: string,
- encryptionType: string = 'Argon2Id',
- encryptionSettings: string = '{"Iterations":2,"MemorySize":19456,"DegreeOfParallelism":1}'
+ encryptionType: string,
+ encryptionSettings: string
): Promise<Uint8Array> {
try {
// Call the native method to derive the key via Argon2id
diff --git a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
index 8ad5c90ef..2e1ba7c3e 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
@@ -15,7 +15,6 @@ using AliasVault.Api.Services;
using AliasVault.Api.Vault;
using AliasVault.Api.Vault.RetentionRules;
using AliasVault.Auth;
-using AliasVault.Cryptography;
using AliasVault.Shared.Models.Enums;
using AliasVault.Shared.Models.WebApi;
using AliasVault.Shared.Models.WebApi.V1.PasswordChange;
@@ -288,8 +287,6 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont
currentManifest.FileSize = FileHelper.Base64StringToKilobytes(model.Blob);
currentManifest.Salt = model.NewPasswordSalt;
currentManifest.Verifier = model.NewPasswordVerifier;
- currentManifest.EncryptionType = Defaults.EncryptionType;
- currentManifest.EncryptionSettings = Defaults.EncryptionSettings;
currentManifest.Client = ClientHeader;
currentManifest.UpdatedByUserId = user.Id;
currentManifest.CreatedAt = timeProvider.GetUtcNow().UtcDateTime;
diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
index 09dbd0ac4..e9fd40ba1 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
@@ -430,6 +430,11 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_ERROR, 400));
}
+ if (!IsValidKekDerivationParams(model.EncryptionType, model.EncryptionSettings))
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.INVALID_ENCRYPTION_PARAMETERS, 400));
+ }
+
var user = new AliasVaultUser
{
UserName = UsernameHelper.NormalizeUsername(model.Username),
@@ -1084,7 +1089,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
}
/// <summary>
- /// Whether the KDF parameters a client derived its new KEK with are Argon2id at or above the current defaults.
+ /// Whether the KDF parameters a client derived its new KEK with are Argon2id at or above the accepted minimum.
/// </summary>
/// <param name="encryptionType">The KDF type.</param>
/// <param name="encryptionSettings">The KDF settings JSON.</param>
@@ -1115,7 +1120,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
}
// Check if any parameter is less than the allowed minimum, return false.
- if (parallelismValue < Defaults.Argon2IdDegreeOfParallelism || memorySizeValue < Defaults.Argon2IdMemorySize || iterationsValue < Defaults.Argon2IdIterations)
+ if (parallelismValue < Defaults.MinimumArgon2IdDegreeOfParallelism || memorySizeValue < Defaults.MinimumArgon2IdMemorySize || iterationsValue < Defaults.MinimumArgon2IdIterations)
{
return false;
}
diff --git a/apps/server/Utilities/AliasVault.Cryptography/Defaults.cs b/apps/server/Utilities/AliasVault.Cryptography/Defaults.cs
index 8727db378..e8f9cf220 100644
--- a/apps/server/Utilities/AliasVault.Cryptography/Defaults.cs
+++ b/apps/server/Utilities/AliasVault.Cryptography/Defaults.cs
@@ -23,17 +23,38 @@ public static class Defaults
public static int Argon2IdDegreeOfParallelism { get; } = 1;
/// <summary>
- /// Gets the default memory size for Argon2id (in KB).
+ /// Gets the default memory size for Argon2id (in KiB).
/// </summary>
- public static int Argon2IdMemorySize { get; } = 19456;
+ public static int Argon2IdMemorySize { get; } = 65536;
/// <summary>
/// Gets the default number of iterations for Argon2id.
/// </summary>
- public static int Argon2IdIterations { get; } = 2;
+ public static int Argon2IdIterations { get; } = 5;
/// <summary>
/// Gets the default encryption settings.
/// </summary>
public static string EncryptionSettings { get; } = $"{{\"DegreeOfParallelism\":{Argon2IdDegreeOfParallelism},\"MemorySize\":{Argon2IdMemorySize},\"Iterations\":{Argon2IdIterations}}}";
+
+ /*
+ * The lowest Argon2id parameters the server accepts for a new KEK: the pre-0.31.0 defaults, so clients built before
+ * the defaults were raised can still register and change passwords for one more release with the old parameters.
+ * TODO: remove in 0.32.0+ and enforce the current defaults (Argon2Id* above) as the minimum instead.
+ */
+
+ /// <summary>
+ /// Gets the minimum accepted degree of parallelism for Argon2id.
+ /// </summary>
+ public static int MinimumArgon2IdDegreeOfParallelism { get; } = 1;
+
+ /// <summary>
+ /// Gets the minimum accepted memory size for Argon2id (in KiB).
+ /// </summary>
+ public static int MinimumArgon2IdMemorySize { get; } = 19456;
+
+ /// <summary>
+ /// Gets the minimum accepted number of iterations for Argon2id.
+ /// </summary>
+ public static int MinimumArgon2IdIterations { get; } = 2;
}
diff --git a/apps/web/src/components/settings/importexport/ImportServiceCard.tsx b/apps/web/src/components/settings/importexport/ImportServiceCard.tsx
index 6e1a74336..1be91a06f 100644
--- a/apps/web/src/components/settings/importexport/ImportServiceCard.tsx
+++ b/apps/web/src/components/settings/importexport/ImportServiceCard.tsx
@@ -4,6 +4,7 @@ import { AvexImportService, AvexDecryptionError } from '@aliasvault/client/trans
import { ImportException, ImportStage } from '@aliasvault/client/transfer/import/models/ImportException';
import { detectAndRemoveDuplicates } from '@aliasvault/client/transfer/import/writers/ImportDuplicateDetection';
import { VaultImportWriter } from '@aliasvault/client/transfer/import/writers/VaultImportWriter';
+import { yieldToPaint } from '@aliasvault/client/utilities/YieldToPaint';
import React, { useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -79,15 +80,6 @@ type ImportServiceCardProps = {
children?: React.ReactNode;
};
-/**
- * Wait until the next paint frame to let the UI update before starting heavy work to prevent blocking the progress bar.
- */
-const yieldToPaint = (): Promise<void> =>
- new Promise(resolve => {
- requestAnimationFrame(() => setTimeout(resolve, 0));
- setTimeout(resolve, 100);
- });
-
/**
* One line naming an error: its class name when that says more than "Error", then the message.
* @param error - the thrown value, which from wasm or a library is not always an Error
diff --git a/core/client/src/auth/SrpAuthService.ts b/core/client/src/auth/SrpAuthService.ts
index 716d17e09..2dcb2a866 100644
--- a/core/client/src/auth/SrpAuthService.ts
+++ b/core/client/src/auth/SrpAuthService.ts
@@ -64,15 +64,14 @@ export type NewPasswordMaterial = {
};
/**
- * Default encryption settings for Argon2Id.
- * These match the server defaults in apps/server/Utilities/AliasVault.Cryptography/Defaults.cs
+ * Default Argon2Id settings for a newly derived KEK.
*/
export const DEFAULT_ENCRYPTION = {
type: 'Argon2Id',
settings: JSON.stringify({
DegreeOfParallelism: 1,
- MemorySize: 19456,
- Iterations: 2,
+ MemorySize: 65536,
+ Iterations: 5,
}),
} as const;
diff --git a/core/client/src/crypto/EncryptionUtility.ts b/core/client/src/crypto/EncryptionUtility.ts
index 660618219..e4bdd550d 100644
--- a/core/client/src/crypto/EncryptionUtility.ts
+++ b/core/client/src/crypto/EncryptionUtility.ts
@@ -38,7 +38,7 @@ export class EncryptionUtility {
public static async deriveKeyFromPassword(
password: string,
salt: string,
- encryptionSettings: string = '{"Iterations":2,"MemorySize":19456,"DegreeOfParallelism":1}'
+ encryptionSettings: string
): Promise<Uint8Array> {
try {
return await argon2DeriveKey(password, salt, encryptionSettings);
diff --git a/core/client/src/rust/WasmRustCore.ts b/core/client/src/rust/WasmRustCore.ts
index 1ab1f6848..e4f9648fb 100644
--- a/core/client/src/rust/WasmRustCore.ts
+++ b/core/client/src/rust/WasmRustCore.ts
@@ -3,6 +3,7 @@
*/
/* eslint-disable jsdoc/require-jsdoc */
import initWasm, * as core from '../../wasm/aliasvault_core.js';
+import { yieldToPaint } from '../utilities/YieldToPaint';
import type { IRustCore, IVaultSyncSession } from './RustCoreBinding';
import type { CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, ParsedEmail, SrpEphemeral, SrpSession } from './RustCoreTypes';
@@ -64,7 +65,14 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {
decodeEmailSource: (source): Promise<Uint8Array> => ready(() => core.decodeEmailSource(source)),
extractEmailAttachment: (source, index, detachedBody): Promise<Uint8Array> => ready(() => core.extractEmailAttachment(source, index, detachedBody)),
- argon2DeriveKey: (password, salt, encryptionSettings): Promise<Uint8Array> => ready(() => core.argon2DeriveKey(password, salt, encryptionSettings)),
+ /*
+ * Argon2 blocks the thread it runs on for up to a few seconds on slow devices, so let the caller's loading
+ * indicator paint first before proceeding with the expensive operation.
+ */
+ argon2DeriveKey: async (password, salt, encryptionSettings): Promise<Uint8Array> => {
+ await yieldToPaint();
+ return ready(() => core.argon2DeriveKey(password, salt, encryptionSettings));
+ },
srpGenerateSalt: (): Promise<string> => ready(() => core.srpGenerateSalt()),
srpDerivePrivateKey: (salt, identity, passwordHash): Promise<string> => ready(() => core.srpDerivePrivateKey(salt, identity, passwordHash)),
diff --git a/core/client/src/transfer/export/AvexExportService.ts b/core/client/src/transfer/export/AvexExportService.ts
index 9cd3a2ba4..6365fafd9 100644
--- a/core/client/src/transfer/export/AvexExportService.ts
+++ b/core/client/src/transfer/export/AvexExportService.ts
@@ -8,8 +8,10 @@ import { AvexConstants } from './AvexConstants';
import type { AvexHeader } from './AvexHeader';
-/** The Argon2id parameters a new export is encrypted with: the vault key derivation defaults. */
-const ARGON2_KDF_PARAMS: Record<string, number> = JSON.parse(DEFAULT_ENCRYPTION.settings);
+/**
+ * The Argon2id parameters a new export is encrypted with.
+ */
+const ARGON2_KDF_PARAMS = { DegreeOfParallelism: 1, MemorySize: 262144, Iterations: 3 };
/**
* Writes the .avex encrypted vault export format: a JSON header, a PEM-style delimiter and the encrypted .avux payload
@@ -24,10 +26,10 @@ export class AvexExportService {
* @returns The .avex file bytes
*/
public static async encryptToAvex(avuxBytes: Uint8Array, exportPassword: string, username: string): Promise<Uint8Array> {
- // 1. A random salt and a key derived from it with Argon2id, as for the vault encryption.
+ // 1. A random salt and a key derived from it with Argon2id.
const salt = crypto.getRandomValues(new Uint8Array(32));
const saltBase64 = bytesToBase64(salt);
- const key = await argon2DeriveKey(exportPassword, saltBase64, DEFAULT_ENCRYPTION.settings);
+ const key = await argon2DeriveKey(exportPassword, saltBase64, JSON.stringify(ARGON2_KDF_PARAMS));
// 2. AES-256-GCM over the .avux bytes.
const encryptedPayload = base64ToBytes(await EncryptionUtility.symmetricEncryptBytes(avuxBytes, bytesToBase64(key)));
diff --git a/core/client/src/transfer/export/__tests__/AvexExportService.test.ts b/core/client/src/transfer/export/__tests__/AvexExportService.test.ts
index 4ab9b629f..8a3541a3a 100644
--- a/core/client/src/transfer/export/__tests__/AvexExportService.test.ts
+++ b/core/client/src/transfer/export/__tests__/AvexExportService.test.ts
@@ -16,6 +16,7 @@ describe('AvexExportService', () => {
expect(header.format).toBe('avex');
expect(header.version).toBe('1.0.0');
expect(header.kdf.type.toLowerCase()).toBe('argon2id');
+ expect(header.kdf.params).toEqual({ DegreeOfParallelism: 1, MemorySize: 262144, Iterations: 3 });
expect(header.metadata.exportedBy).toBe('tester');
const decrypted = await AvexImportService.decryptAvex(avexBytes, 'export-password');
diff --git a/core/client/src/utilities/YieldToPaint.ts b/core/client/src/utilities/YieldToPaint.ts
new file mode 100644
index 000000000..0f1e5091e
--- /dev/null
+++ b/core/client/src/utilities/YieldToPaint.ts
@@ -0,0 +1,14 @@
+/**
+ * Wait until the browser has painted, so a loading indicator is on screen before synchronous heavy work blocks the thread.
+ * Resolves at once where nothing is painted (service worker, Node). The timeout covers hidden tabs, where
+ * requestAnimationFrame does not fire.
+ */
+export function yieldToPaint(): Promise<void> {
+ if (typeof requestAnimationFrame !== 'function') {
+ return Promise.resolve();
+ }
+ return new Promise(resolve => {
+ requestAnimationFrame(() => setTimeout(resolve, 0));
+ setTimeout(resolve, 100);
+ });
+}
diff --git a/core/rust/src/crypto/argon2.rs b/core/rust/src/crypto/argon2.rs
index 00e068284..c44d8b259 100644
--- a/core/rust/src/crypto/argon2.rs
+++ b/core/rust/src/crypto/argon2.rs
@@ -6,15 +6,6 @@ use thiserror::Error;
/// Length of every derived key in bytes; the vault format assumes a 256-bit key throughout.
const ARGON2_OUTPUT_LENGTH: usize = 32;
-/// Default memory cost in KiB, used when the settings do not state one.
-const ARGON2_DEFAULT_MEMORY_KIB: u32 = 19456;
-
-/// Default number of passes, used when the settings do not state one.
-const ARGON2_DEFAULT_ITERATIONS: u32 = 2;
-
-/// Default number of lanes, used when the settings do not state one.
-const ARGON2_DEFAULT_PARALLELISM: u32 = 1;
-
/// Argon2-related errors.
#[derive(Error, Debug, Clone)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Error))]
@@ -42,32 +33,13 @@ pub struct Argon2Params {
pub parallelism: u32,
}
-impl Default for Argon2Params {
- fn default() -> Self {
- Self {
- memory_kib: ARGON2_DEFAULT_MEMORY_KIB,
- iterations: ARGON2_DEFAULT_ITERATIONS,
- parallelism: ARGON2_DEFAULT_PARALLELISM,
- }
- }
-}
-
impl Argon2Params {
/// The cost parameters from the server's `EncryptionSettings` JSON
- /// (`{"DegreeOfParallelism":1,"MemorySize":19456,"Iterations":2}`); a missing field, or an empty string, means the default.
+ /// (`{"DegreeOfParallelism":1,"MemorySize":65536,"Iterations":5}`); every field is required.
pub fn from_settings_json(settings_json: &str) -> Result<Self, Argon2Error> {
- let defaults = Self::default();
- if settings_json.trim().is_empty() {
- return Ok(defaults);
- }
-
let parsed: EncryptionSettingsJson = serde_json::from_str(settings_json).map_err(|e| Argon2Error::InvalidSettings(e.to_string()))?;
- Ok(Self {
- memory_kib: parsed.memory_size.unwrap_or(defaults.memory_kib),
- iterations: parsed.iterations.unwrap_or(defaults.iterations),
- parallelism: parsed.degree_of_parallelism.unwrap_or(defaults.parallelism),
- })
+ Ok(Self { memory_kib: parsed.memory_size, iterations: parsed.iterations, parallelism: parsed.degree_of_parallelism })
}
}
@@ -75,13 +47,13 @@ impl Argon2Params {
#[derive(Deserialize)]
struct EncryptionSettingsJson {
#[serde(rename = "MemorySize")]
- memory_size: Option<u32>,
+ memory_size: u32,
#[serde(rename = "Iterations")]
- iterations: Option<u32>,
+ iterations: u32,
#[serde(rename = "DegreeOfParallelism")]
- degree_of_parallelism: Option<u32>,
+ degree_of_parallelism: u32,
}
/// Derive a 32-byte key from a password with Argon2id under explicit cost parameters; the salt is at least 8 bytes.
@@ -102,7 +74,7 @@ pub fn argon2_derive_key(password: &[u8], salt: &[u8], params: Argon2Params) ->
}
/// Derive a 32-byte key from a password and salt (hashed as their UTF-8 bytes) under the cost parameters in
-/// `settings_json`, or the defaults for an empty string.
+/// `settings_json`.
pub fn argon2_derive_key_from_settings(password: &str, salt: &str, settings_json: &str) -> Result<Vec<u8>, Argon2Error> {
argon2_derive_key_bytes_from_settings(password.as_bytes(), salt.as_bytes(), settings_json)
}
@@ -113,3 +85,36 @@ pub fn argon2_derive_key_bytes_from_settings(password: &[u8], salt: &[u8], setti
let params = Argon2Params::from_settings_json(settings_json)?;
argon2_derive_key(password, salt, params)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::common::encoding::base64_encode;
+
+ #[test]
+ fn parses_complete_settings() {
+ let params = Argon2Params::from_settings_json(r#"{"DegreeOfParallelism":1,"MemorySize":65536,"Iterations":5}"#).unwrap();
+ assert_eq!(params, Argon2Params { memory_kib: 65536, iterations: 5, parallelism: 1 });
+ }
+
+ #[test]
+ fn rejects_incomplete_or_empty_settings() {
+ for settings in ["", "{}", r#"{"MemorySize":65536,"Iterations":5}"#] {
+ assert!(matches!(Argon2Params::from_settings_json(settings), Err(Argon2Error::InvalidSettings(_))), "accepted {settings:?}");
+ }
+ }
+
+ #[test]
+ fn matches_the_reference_implementation() {
+ // Expected keys come from libargon2 (argon2-cffi), for the pre-0.31.0 and the current default settings. A
+ // different output means existing accounts can no longer derive their key.
+ let cases = [
+ (r#"{"DegreeOfParallelism":1,"MemorySize":19456,"Iterations":2}"#, "l12OncuAll3SmDPkfv2sHtxaoEVsCXfuFulTShtBfxA="),
+ (r#"{"DegreeOfParallelism":1,"MemorySize":65536,"Iterations":5}"#, "j7bnKpt3W46ak6Qid2JENR7NxznhfgRNDWAImnpAc40="),
+ ];
+ for (settings, expected) in cases {
+ let key = argon2_derive_key_from_settings("password", "[email protected]", settings).unwrap();
+ assert_eq!(base64_encode(&key), expected, "settings {settings}");
+ }
+ }
+}
diff --git a/docs/docs/architecture.mdx b/docs/docs/architecture.mdx
index 617f8476b..e8a8f99a2 100644
--- a/docs/docs/architecture.mdx
+++ b/docs/docs/architecture.mdx
@@ -32,6 +32,8 @@ You can also view the diagram in a browser-friendly HTML format: [AliasVault Sec
### 1. Key Derivation
- When a user enters their master password, it remains strictly on the client device
- The master password is processed through Argon2id (a memory-hard key derivation function) locally
+ - Argon2id parameters used for main vault KEK: 64 MiB memory, 5 iterations, parallelism 1
+ - Argon2id parameters used for encrypted vault exports (`.avex`): 256 MiB memory, 3 iterations, parallelism 1
- The derived key serves two purposes:
- Authentication with the server through the SRP protocol
- Local encryption/decryption of vault contents using AES-256-GCM