Skip to content

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

Refactor (#1340)

Leendert de Borst4a0c6d949902
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt
index d26faae75..1f45e6f46 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt
@@ -51,7 +51,7 @@ sealed class PinUnlockException(message: String) : Exception(message) {
*
* Security features:
* - 4 failed attempts maximum before requiring full password
- * - Device pepper stored in Android Keystore (makes offline brute-force impossible)
+ * - Salt stored in Android Keystore (makes offline brute-force impossible)
* - Failed attempts counter stored in Keystore (prevents tampering)
* - Encryption key derived using Argon2id (memory-hard, GPU-resistant)
* - Encrypted data automatically deleted after max failed attempts
@@ -85,7 +85,6 @@ class VaultPin(
* Android Keystore aliases for secure data storage.
*/
private const val KEYSTORE_ALIAS_PIN_DATA = "aliasvault_pin_data"
- private const val KEYSTORE_ALIAS_PIN_PEPPER = "aliasvault_pin_pepper"
private const val KEYSTORE_ALIAS_FAILED_ATTEMPTS = "aliasvault_pin_failed_attempts"
private const val KEYSTORE_ALIAS_DATA_ENCRYPTION = "aliasvault_pin_data_encryption_key"
@@ -107,11 +106,6 @@ class VaultPin(
*/
private const val GCM_IV_LENGTH = 12
private const val GCM_TAG_LENGTH = 128
-
- /**
- * Device pepper size (32 bytes for strong security).
- */
- private const val PEPPER_SIZE = 32
}
// MARK: - PIN Status Methods
@@ -167,11 +161,8 @@ class VaultPin(
val salt = ByteArray(16)
SecureRandom().nextBytes(salt)
- // Generate or retrieve device pepper (device-bound secret)
- val pepper = getOrCreateDevicePepper()
-
- // Derive key from PIN + pepper using Argon2id
- val pinKey = derivePinKey(pin, salt, pepper)
+ // Derive key from PIN + salt using Argon2id
+ val pinKey = derivePinKey(pin, salt)
// Encrypt the vault encryption key using AES-GCM
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
@@ -202,7 +193,7 @@ class VaultPin(
apply()
}
- Log.d(TAG, "PIN unlock enabled successfully with device pepper")
+ Log.d(TAG, "PIN unlock enabled successfully")
}
// MARK: - PIN Unlock Methods
@@ -224,16 +215,15 @@ class VaultPin(
}
try {
- // Retrieve encrypted key, salt, and pepper from Keystore
+ // Retrieve encrypted key and salt from Keystore
val (encryptedKey, salt) = retrievePinDataFromKeystore()
- val pepper = retrieveDevicePepper()
// Decode encrypted package
val iv = encryptedKey.copyOfRange(0, GCM_IV_LENGTH)
val encryptedData = encryptedKey.copyOfRange(GCM_IV_LENGTH, encryptedKey.size)
- // Derive key from PIN + pepper
- val pinKey = derivePinKey(pin, salt, pepper)
+ // Derive key from PIN + salt
+ val pinKey = derivePinKey(pin, salt)
// Decrypt the vault encryption key
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
@@ -286,9 +276,6 @@ class VaultPin(
// Remove failed attempts counter from Keystore
removePinFailedAttemptsFromKeystore()
- // Note: We DO NOT remove the device pepper - it's reused if PIN is re-enabled
- // This maintains consistency and doesn't degrade security
-
// Clear PIN metadata from SharedPreferences
sharedPreferences.edit().apply {
remove(PIN_ENABLED_KEY)
@@ -296,7 +283,7 @@ class VaultPin(
apply()
}
- Log.d(TAG, "PIN unlock disabled and all data removed (pepper retained)")
+ Log.d(TAG, "PIN unlock disabled and all data removed")
} catch (e: Exception) {
Log.e(TAG, "Error removing PIN data", e)
throw Exception("Failed to remove PIN data", e)
@@ -306,36 +293,27 @@ class VaultPin(
// MARK: - Private PIN Methods
/**
- * Derive encryption key from PIN + pepper using Argon2id.
- *
- * Uses Argon2id with high memory cost (64 MB) and a device-bound pepper
- * to make offline brute-force attacks infeasible even if the encrypted blob is exfiltrated.
+ * Derive encryption key from PIN + salt using Argon2id.
*
- * The pepper is a 32-byte random value stored in Android Keystore,
- * which means an attacker who steals the encrypted blob cannot brute-force offline
- * because they don't have the pepper.
+ * Uses Argon2id with high memory cost (64 MB) to make brute-force attacks expensive.
+ * The salt is stored in Android Keystore with device-unlock protection, which means
+ * an attacker who steals the encrypted blob cannot brute-force offline because they
+ * cannot access the salt without unlocking the device.
*
* @param pin User's PIN (low entropy)
- * @param salt Random salt (stored with encrypted data)
- * @param pepper Device-bound secret (stored in Keystore, not with encrypted data)
+ * @param salt Random salt (stored in Keystore, requires device unlock to access)
* @return The derived key bytes (32 bytes)
* @throws Exception if key derivation fails
*/
@Throws(Exception::class)
- private fun derivePinKey(pin: String, salt: ByteArray, pepper: ByteArray): ByteArray {
+ private fun derivePinKey(pin: String, salt: ByteArray): ByteArray {
try {
- // Concatenate PIN + pepper before hashing
- // This ensures offline brute-force is impossible without the pepper
val pinBytes = pin.toByteArray(Charsets.UTF_8)
- val combinedInput = ByteArray(pinBytes.size + pepper.size)
- System.arraycopy(pinBytes, 0, combinedInput, 0, pinBytes.size)
- System.arraycopy(pepper, 0, combinedInput, pinBytes.size, pepper.size)
-
val argon2 = Argon2Kt()
val hashResult = argon2.hash(
mode = Argon2Mode.ARGON2_ID,
- password = combinedInput,
+ password = pinBytes,
salt = salt,
tCostInIterations = ARGON2_ITERATIONS,
mCostInKibibyte = ARGON2_MEMORY_KB,
@@ -351,103 +329,10 @@ class VaultPin(
}
}
- // MARK: - Device Pepper Management
-
- /**
- * Get or create device pepper (device-bound secret).
- *
- * The pepper is a 32-byte random value stored in Android Keystore.
- * It's only readable when the device is unlocked (device credential required).
- * This makes offline brute-force impossible because the pepper isn't in the encrypted blob.
- */
- @Throws(Exception::class)
- private fun getOrCreateDevicePepper(): ByteArray {
- // Try to retrieve existing pepper
- return try {
- retrieveDevicePepper()
- } catch (e: Exception) {
- // Pepper doesn't exist, generate new 32-byte pepper
- Log.d(TAG, "Device pepper not found, creating new one", e)
- val pepper = ByteArray(PEPPER_SIZE)
- SecureRandom().nextBytes(pepper)
-
- // Store pepper in Android Keystore with strong device protection
- storePepperInKeystore(pepper)
-
- Log.d(TAG, "Device pepper created and stored securely")
- pepper
- }
- }
-
- /**
- * Store pepper in Android Keystore with device-bound protection.
- */
- @Throws(Exception::class)
- private fun storePepperInKeystore(pepper: ByteArray) {
- // Create encryption key for pepper storage in Keystore
- val keyGenerator = KeyGenerator.getInstance(
- KeyProperties.KEY_ALGORITHM_AES,
- "AndroidKeyStore",
- )
-
- val keySpec = KeyGenParameterSpec.Builder(
- KEYSTORE_ALIAS_PIN_PEPPER,
- KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
- )
- .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
- .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
- .setUserAuthenticationRequired(false)
- // Require device to be unlocked (equivalent to iOS's kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
- .setUnlockedDeviceRequired(true)
- .build()
-
- keyGenerator.init(keySpec)
- val secretKey = keyGenerator.generateKey()
-
- // Encrypt pepper
- val cipher = Cipher.getInstance("AES/GCM/NoPadding")
- cipher.init(Cipher.ENCRYPT_MODE, secretKey)
- val encryptedPepper = cipher.doFinal(pepper)
- val iv = cipher.iv
-
- // Combine IV + encrypted pepper
- val combined = ByteArray(iv.size + encryptedPepper.size)
- System.arraycopy(iv, 0, combined, 0, iv.size)
- System.arraycopy(encryptedPepper, 0, combined, iv.size, encryptedPepper.size)
-
- // Store in SharedPreferences (encrypted by Keystore key)
- val pepperBase64 = Base64.encodeToString(combined, Base64.NO_WRAP)
- sharedPreferences.edit().putString(KEYSTORE_ALIAS_PIN_PEPPER, pepperBase64).apply()
- }
-
- /**
- * Retrieve pepper from Android Keystore.
- */
- @Throws(Exception::class)
- private fun retrieveDevicePepper(): ByteArray {
- // Get encrypted pepper from SharedPreferences
- val pepperBase64 = sharedPreferences.getString(KEYSTORE_ALIAS_PIN_PEPPER, null)
- ?: throw Exception("Device pepper not found")
-
- val combined = Base64.decode(pepperBase64, Base64.NO_WRAP)
- val iv = combined.copyOfRange(0, GCM_IV_LENGTH)
- val encryptedPepper = combined.copyOfRange(GCM_IV_LENGTH, combined.size)
-
- // Get decryption key from Keystore
- val secretKey = keyStore.getKey(KEYSTORE_ALIAS_PIN_PEPPER, null) as? SecretKey
- ?: throw Exception("Keystore key for pepper not found")
-
- // Decrypt pepper
- val cipher = Cipher.getInstance("AES/GCM/NoPadding")
- cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(GCM_TAG_LENGTH, iv))
- return cipher.doFinal(encryptedPepper)
- }
-
// MARK: - PIN Data Storage (Encrypted Key + Salt)
/**
* Store PIN data (encrypted key and salt) in Android Keystore.
- * Note: We DO NOT store the pepper here - it's separate for security.
*/
@Throws(Exception::class)
private fun storePinDataInKeystore(encryptedKey: ByteArray, salt: ByteArray) {
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift
index 714695588..800c72cb1 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift
@@ -10,7 +10,6 @@ extension VaultStore {
private static let pinEncryptedKeyKey = "pinEncryptedKey"
private static let pinSaltKey = "pinSalt"
- private static let pinPepperKey = "pinPepper" // Device-bound secret
private static let pinLengthKey = "pinLength"
private static let pinFailedAttemptsKey = "pinFailedAttempts"
private static let maxPinAttempts = 4
@@ -56,11 +55,8 @@ extension VaultStore {
throw NSError(domain: "VaultStore", code: 22, userInfo: [NSLocalizedDescriptionKey: "Failed to generate random salt"])
}
- // Generate or retrieve device pepper (device-bound secret)
- let pepper = try getOrCreateDevicePepper()
-
- // Derive key from PIN + pepper using Argon2id
- let pinKey = try derivePinKey(pin: pin, salt: salt, pepper: pepper)
+ // Derive key from PIN + salt using Argon2id
+ let pinKey = try derivePinKey(pin: pin, salt: salt)
// Encrypt the vault encryption key using AES-GCM
let symmetricKey = SymmetricKey(data: pinKey)
@@ -80,7 +76,7 @@ extension VaultStore {
userDefaults.set(pin.count, forKey: Self.pinLengthKey)
userDefaults.synchronize()
- print("PIN unlock enabled successfully with device pepper")
+ print("PIN unlock enabled successfully")
}
// MARK: - PIN Unlock Methods
@@ -98,12 +94,11 @@ extension VaultStore {
}
do {
- // Retrieve encrypted key, salt, and pepper from keychain
+ // Retrieve encrypted key and salt from keychain
let (encryptedKey, salt) = try retrievePinDataFromKeychain()
- let pepper = try retrieveDevicePepper()
- // Derive key from PIN + pepper
- let pinKey = try derivePinKey(pin: pin, salt: salt, pepper: pepper)
+ // Derive key from PIN + salt
+ let pinKey = try derivePinKey(pin: pin, salt: salt)
// Decrypt the vault encryption key
let symmetricKey = SymmetricKey(data: pinKey)
@@ -146,49 +141,37 @@ extension VaultStore {
// Remove failed attempts counter from keychain
try removePinFailedAttemptsFromKeychain()
- // Note: We DO NOT remove the device pepper - it's reused if PIN is re-enabled
- // This maintains consistency and doesn't degrade security
-
// Clear PIN metadata from UserDefaults
userDefaults.removeObject(forKey: VaultConstants.pinEnabledKey)
userDefaults.removeObject(forKey: Self.pinLengthKey)
userDefaults.synchronize()
- print("PIN unlock disabled and all data removed (pepper retained)")
+ print("PIN unlock disabled and all data removed")
}
// MARK: - Private PIN Methods
- /// Derive encryption key from PIN + pepper using Argon2id
- ///
- /// Uses Argon2id with high memory cost (64 MB) and a device-bound pepper
- /// to make offline brute-force attacks infeasible even if the encrypted blob is exfiltrated.
+ /// Derive encryption key from PIN + salt using Argon2id
///
- /// The pepper is a 32-byte random value stored in the Secure Enclave-protected Keychain,
- /// which means an attacker who steals the encrypted blob cannot brute-force offline
- /// because they don't have the pepper.
+ /// Uses Argon2id with high memory cost (64 MB) to make brute-force attacks expensive.
+ /// The salt is stored in Keychain with device-unlock protection, which means an attacker
+ /// who steals the encrypted blob cannot brute-force offline because they cannot access
+ /// the salt without unlocking the device.
///
/// Parameters:
/// - pin: User's PIN (low entropy)
- /// - salt: Random salt (stored with encrypted data)
- /// - pepper: Device-bound secret
- private func derivePinKey(pin: String, salt: Data, pepper: Data) throws -> Data {
+ /// - salt: Random salt (stored in Keychain, requires device unlock to access)
+ private func derivePinKey(pin: String, salt: Data) throws -> Data {
guard let pinData = pin.data(using: .utf8) else {
throw NSError(domain: "VaultStore", code: 28, userInfo: [NSLocalizedDescriptionKey: "Failed to convert PIN to data"])
}
- // Concatenate PIN + pepper before hashing
- // This ensures offline brute-force is impossible without the pepper
- var combinedInput = Data()
- combinedInput.append(pinData)
- combinedInput.append(pepper)
-
- // Use SignalArgon2 to hash (PIN + pepper) via Argon2id
+ // Use SignalArgon2 to hash PIN via Argon2id
guard let derivedKeyTuple = try? Argon2.hash(
iterations: 3,
memoryInKiB: 65536, // 64 MB
threads: 1,
- password: combinedInput,
+ password: pinData,
salt: salt,
desiredLength: 32,
variant: .id,
@@ -200,74 +183,9 @@ extension VaultStore {
return derivedKeyTuple.raw
}
- /// Get or create device pepper (device-bound secret)
- ///
- /// The pepper is a 32-byte random value stored in Keychain with Secure Enclave protection.
- /// It's only readable when the device is unlocked (passcode entered), but can be cached in memory.
- /// This prevents offline brute-force when only the encrypted blob would be captured.
- private func getOrCreateDevicePepper() throws -> Data {
- // Try to retrieve existing pepper
- if let pepper = try? retrieveDevicePepper() {
- return pepper
- }
-
- // Generate new 32-byte pepper
- var pepper = Data(count: 32)
- let result = pepper.withUnsafeMutableBytes {
- SecRandomCopyBytes(kSecRandomDefault, 32, $0.baseAddress!)
- }
- guard result == errSecSuccess else {
- throw NSError(domain: "VaultStore", code: 36, userInfo: [NSLocalizedDescriptionKey: "Failed to generate device pepper"])
- }
-
- // Store pepper in Keychain with device passcode protection
- // This uses kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly which provides:
- // 1. Device-bound (cannot be moved to another device)
- // 2. Requires passcode to be set
- // 3. Available when device is unlocked
- let query: [String: Any] = [
- kSecClass as String: kSecClassGenericPassword,
- kSecAttrService as String: VaultConstants.keychainService,
- kSecAttrAccount as String: Self.pinPepperKey,
- kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup,
- kSecValueData as String: pepper,
- kSecAttrAccessible as String: kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
- ]
-
- let status = SecItemAdd(query as CFDictionary, nil)
- guard status == errSecSuccess else {
- throw NSError(domain: "VaultStore", code: 37, userInfo: [NSLocalizedDescriptionKey: "Failed to store device pepper: \(status)"])
- }
-
- print("Device pepper created and stored securely")
- return pepper
- }
-
- /// Retrieve device pepper from Keychain
- private func retrieveDevicePepper() throws -> Data {
- let query: [String: Any] = [
- kSecClass as String: kSecClassGenericPassword,
- kSecAttrService as String: VaultConstants.keychainService,
- kSecAttrAccount as String: Self.pinPepperKey,
- kSecAttrAccessGroup as String: VaultConstants.keychainAccessGroup,
- kSecReturnData as String: true,
- kSecMatchLimit as String: kSecMatchLimitOne
- ]
-
- var result: AnyObject?
- let status = SecItemCopyMatching(query as CFDictionary, &result)
-
- guard status == errSecSuccess, let pepper = result as? Data else {
- throw NSError(domain: "VaultStore", code: 38, userInfo: [NSLocalizedDescriptionKey: "Device pepper not found"])
- }
-
- return pepper
- }
-
/// Store PIN encrypted data in keychain (without biometric protection)
private func storePinDataInKeychain(encryptedKey: Data, salt: Data) throws {
// Create a dictionary to store both encrypted key and salt
- // Note: We DO NOT store the pepper here - it's separate for security
let pinData: [String: Data] = [
"encryptedKey": encryptedKey,
"salt": salt