Skip to content

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

Store key derivation params locally for offline password unlock (#771)

Leendert de Borst255ac518a2b6
diff --git a/apps/mobile-app/app/_layout.tsx b/apps/mobile-app/app/_layout.tsx
index c012f1c9b..ecc60122b 100644
--- a/apps/mobile-app/app/_layout.tsx
+++ b/apps/mobile-app/app/_layout.tsx
@@ -147,6 +147,14 @@ function RootLayoutNav() : React.ReactNode {
}
]
);
+ },
+ /**
+ * Handle error during vault sync.
+ */
+ onError: () => {
+ // Navigate to the manual unlock screen.
+ setRedirectTarget('/unlock');
+ setBootComplete(true);
}
});
};
diff --git a/apps/mobile-app/app/login.tsx b/apps/mobile-app/app/login.tsx
index b77c1e215..063c14148 100644
--- a/apps/mobile-app/app/login.tsx
+++ b/apps/mobile-app/app/login.tsx
@@ -35,6 +35,7 @@ import { AppInfo } from '@/utils/AppInfo';
import LoadingIndicator from '@/components/LoadingIndicator';
import { LoginResponse } from '@/utils/types/webapi/Login';
import { VaultResponse } from '@/utils/types/webapi/VaultResponse';
+import { EncryptionKeyDerivationParams } from '@/utils/types/messaging/EncryptionKeyDerivationParams';
/**
* Login screen.
@@ -87,7 +88,7 @@ export default function LoginScreen() : React.ReactNode {
const [error, setError] = useState<string | null>(null);
const [twoFactorRequired, setTwoFactorRequired] = useState(false);
const [twoFactorCode, setTwoFactorCode] = useState('');
- const [loginResponse, setLoginResponse] = useState<LoginResponse | null>(null);
+ const [initiateLoginResponse, setInitiateLoginResponse] = useState<LoginResponse | null>(null);
const [passwordHashString, setPasswordHashString] = useState<string | null>(null);
const [passwordHashBase64, setPasswordHashBase64] = useState<string | null>(null);
const [loginStatus, setLoginStatus] = useState<string | null>(null);
@@ -109,17 +110,28 @@ export default function LoginScreen() : React.ReactNode {
token: string,
refreshToken: string,
vaultResponseJson: VaultResponse,
- passwordHashBase64: string
+ passwordHashBase64: string,
+ initiateLoginResponse: LoginResponse
) : Promise<void> => {
+
+ // Create KeyDerivationParams from initiateLoginResponse
+ const encryptionKeyDerivationParams : EncryptionKeyDerivationParams = {
+ encryptionType: initiateLoginResponse.encryptionType,
+ encryptionSettings: initiateLoginResponse.encryptionSettings,
+ salt: initiateLoginResponse.salt,
+ };
+
await authContext.setAuthTokens(credentials.username, token, refreshToken);
- await dbContext.initializeDatabase(vaultResponseJson, passwordHashBase64);
+ await dbContext.storeEncryptionKey(passwordHashBase64);
+ await dbContext.storeEncryptionKeyDerivationParams(encryptionKeyDerivationParams);
+ await dbContext.initializeDatabase(vaultResponseJson);
await authContext.login();
setTwoFactorRequired(false);
setTwoFactorCode('');
setPasswordHashString(null);
setPasswordHashBase64(null);
- setLoginResponse(null);
+ setInitiateLoginResponse(null);
setLoginStatus(null);
router.replace('/(tabs)/credentials');
setIsLoading(false);
@@ -145,13 +157,13 @@ export default function LoginScreen() : React.ReactNode {
try {
authContext.clearGlobalMessage();
- const loginResponse = await srpUtil.initiateLogin(credentials.username);
+ const initiateLoginResponse = await srpUtil.initiateLogin(credentials.username);
const passwordHash = await EncryptionUtility.deriveKeyFromPassword(
credentials.password,
- loginResponse.salt,
- loginResponse.encryptionType,
- loginResponse.encryptionSettings
+ initiateLoginResponse.salt,
+ initiateLoginResponse.encryptionType,
+ initiateLoginResponse.encryptionSettings
);
const passwordHashString = Buffer.from(passwordHash).toString('hex').toUpperCase();
@@ -163,11 +175,11 @@ export default function LoginScreen() : React.ReactNode {
credentials.username,
passwordHashString,
rememberMe,
- loginResponse
+ initiateLoginResponse
);
if (validationResponse.requiresTwoFactor) {
- setLoginResponse(loginResponse);
+ setInitiateLoginResponse(initiateLoginResponse);
setPasswordHashString(passwordHashString);
setPasswordHashBase64(passwordHashBase64);
setTwoFactorRequired(true);
@@ -199,7 +211,8 @@ export default function LoginScreen() : React.ReactNode {
validationResponse.token.token,
validationResponse.token.refreshToken,
vaultResponseJson,
- passwordHashBase64
+ passwordHashBase64,
+ initiateLoginResponse
);
} catch (err) {
if (err instanceof ApiAuthError) {
@@ -224,7 +237,7 @@ export default function LoginScreen() : React.ReactNode {
await new Promise(resolve => requestAnimationFrame(resolve));
try {
- if (!passwordHashString || !passwordHashBase64 || !loginResponse) {
+ if (!passwordHashString || !passwordHashBase64 || !initiateLoginResponse) {
throw new Error('Required login data not found');
}
@@ -237,7 +250,7 @@ export default function LoginScreen() : React.ReactNode {
credentials.username,
passwordHashString,
rememberMe,
- loginResponse,
+ initiateLoginResponse,
parseInt(twoFactorCode)
);
@@ -262,7 +275,8 @@ export default function LoginScreen() : React.ReactNode {
validationResponse.token.token,
validationResponse.token.refreshToken,
vaultResponseJson,
- passwordHashBase64
+ passwordHashBase64,
+ initiateLoginResponse
);
} catch (err) {
console.error('2FA error:', err);
diff --git a/apps/mobile-app/app/reinitialize.tsx b/apps/mobile-app/app/reinitialize.tsx
index 4ef12041a..eb963b463 100644
--- a/apps/mobile-app/app/reinitialize.tsx
+++ b/apps/mobile-app/app/reinitialize.tsx
@@ -175,10 +175,13 @@ export default function ReinitializeScreen() : React.ReactNode {
flex: 1,
justifyContent: 'center',
},
- message: {
+ message1: {
marginTop: 5,
textAlign: 'center',
},
+ message2: {
+ textAlign: 'center',
+ },
messageContainer: {
backgroundColor: colors.accentBackground,
borderRadius: 10,
@@ -189,7 +192,8 @@ export default function ReinitializeScreen() : React.ReactNode {
return (
<ThemedView style={styles.container}>
<View style={styles.messageContainer}>
- <ThemedText style={styles.message}>Vault auto-locked after timeout. Attempting to unlock...</ThemedText>
+ <ThemedText style={styles.message1}>Vault auto-locked after timeout.</ThemedText>
+ <ThemedText style={styles.message2}>Attempting to unlock.</ThemedText>
{status ? <LoadingIndicator status={status} /> : null}
</View>
</ThemedView>
diff --git a/apps/mobile-app/app/unlock.tsx b/apps/mobile-app/app/unlock.tsx
index 662da434b..1ab9dc692 100644
--- a/apps/mobile-app/app/unlock.tsx
+++ b/apps/mobile-app/app/unlock.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useCallback } from 'react';
import { StyleSheet, View, TextInput, TouchableOpacity, Alert, Image, KeyboardAvoidingView, Platform } from 'react-native';
import { router } from 'expo-router';
import { MaterialIcons } from '@expo/vector-icons';
@@ -9,11 +9,11 @@ import { ThemedView } from '@/components/themed/ThemedView';
import { ThemedText } from '@/components/themed/ThemedText';
import LoadingIndicator from '@/components/LoadingIndicator';
import { useColors } from '@/hooks/useColorScheme';
-import Logo from '@/assets/images/logo.svg';
import EncryptionUtility from '@/utils/EncryptionUtility';
-import { SrpUtility } from '@/utils/SrpUtility';
import { useWebApi } from '@/context/WebApiContext';
import avatarImage from '@/assets/images/avatar.webp';
+import { TitleContainer } from '@/components/ui/TitleContainer';
+import NativeVaultManager from '@/specs/NativeVaultManager';
/**
* Unlock screen.
@@ -26,9 +26,24 @@ export default function UnlockScreen() : React.ReactNode {
const [isFaceIDAvailable, setIsFaceIDAvailable] = useState(false);
const colors = useColors();
const webApi = useWebApi();
- const srpUtil = new SrpUtility(webApi);
+
+ /**
+ * Check if the key derivation parameters are stored in native storage.
+ * If not, we can't unlock the vault so logout instead to redirect user to login screen.
+ */
+ const getKeyDerivationParams = useCallback(async () : Promise<string | null> => {
+ const encryptionKeyDerivationParams = await NativeVaultManager.getEncryptionKeyDerivationParams();
+ if (!encryptionKeyDerivationParams) {
+ await webApi.logout();
+ router.replace('/login');
+ return null;
+ }
+ return encryptionKeyDerivationParams;
+ }, [webApi]);
useEffect(() => {
+ getKeyDerivationParams();
+
/**
* Check the face ID status.
*/
@@ -37,7 +52,7 @@ export default function UnlockScreen() : React.ReactNode {
setIsFaceIDAvailable(enabled);
};
checkFaceIDStatus();
- }, [isFaceIDEnabled]);
+ }, [isFaceIDEnabled, getKeyDerivationParams]);
/**
* Handle the unlock.
@@ -56,14 +71,21 @@ export default function UnlockScreen() : React.ReactNode {
return;
}
- // Initialize the database with the provided password
- const loginResponse = await srpUtil.initiateLogin(username);
+ // Get the key derivation parameters from native storage
+ const encryptionKeyDerivationParams = await getKeyDerivationParams();
+ if (!encryptionKeyDerivationParams) {
+ return;
+ }
+
+ // Parse the key derivation parameters
+ const params = JSON.parse(encryptionKeyDerivationParams);
+ // Derive the encryption key from the password using the stored parameters
const passwordHash = await EncryptionUtility.deriveKeyFromPassword(
password,
- loginResponse.salt,
- loginResponse.encryptionType,
- loginResponse.encryptionSettings
+ params.salt,
+ params.encryptionType,
+ params.encryptionSettings
);
const passwordHashBase64 = Buffer.from(passwordHash).toString('base64');
@@ -132,13 +154,15 @@ export default function UnlockScreen() : React.ReactNode {
flex: 1,
},
content: {
+ backgroundColor: colors.accentBackground,
+ borderRadius: 10,
+ padding: 20,
width: '100%',
},
faceIdButton: {
alignItems: 'center',
height: 50,
justifyContent: 'center',
- marginBottom: 16,
width: '100%',
},
faceIdButtonText: {
@@ -146,7 +170,12 @@ export default function UnlockScreen() : React.ReactNode {
fontSize: 16,
fontWeight: '600',
},
+ headerContainer: {
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
input: {
+ backgroundColor: colors.background,
color: colors.text,
flex: 1,
fontSize: 16,
@@ -155,7 +184,7 @@ export default function UnlockScreen() : React.ReactNode {
},
inputContainer: {
alignItems: 'center',
- backgroundColor: colors.accentBackground,
+ backgroundColor: colors.background,
borderColor: colors.accentBorder,
borderRadius: 8,
borderWidth: 1,
@@ -177,14 +206,6 @@ export default function UnlockScreen() : React.ReactNode {
flex: 1,
justifyContent: 'center',
},
- logo: {
- height: 80,
- width: 200,
- },
- logoContainer: {
- alignItems: 'center',
- marginBottom: 16,
- },
logoutButton: {
alignItems: 'center',
height: 50,
@@ -192,7 +213,7 @@ export default function UnlockScreen() : React.ReactNode {
width: '100%',
},
logoutButtonText: {
- color: colors.primary,
+ color: colors.red,
fontSize: 16,
},
subtitle: {
@@ -202,14 +223,6 @@ export default function UnlockScreen() : React.ReactNode {
opacity: 0.7,
textAlign: 'center',
},
- title: {
- color: colors.text,
- fontSize: 28,
- fontWeight: 'bold',
- marginBottom: 16,
- paddingTop: 4,
- textAlign: 'center',
- },
username: {
color: colors.text,
fontSize: 18,
@@ -222,18 +235,18 @@ export default function UnlockScreen() : React.ReactNode {
<ThemedView style={styles.container}>
{isLoading ? (
<View style={styles.loadingContainer}>
- <LoadingIndicator status="Unlocking vault..." />
+ <LoadingIndicator status="Unlocking vault" />
</View>
) : (
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
style={styles.keyboardAvoidingView}
>
+ <View style={styles.headerContainer}>
+ <TitleContainer title="Unlock Vault" />
+ </View>
+
<View style={styles.content}>
- <View style={styles.logoContainer}>
- <Logo style={styles.logo} />
- </View>
- <ThemedText style={styles.title}>Unlock Vault</ThemedText>
<View style={styles.avatarContainer}>
<Image
source={avatarImage}
@@ -280,14 +293,14 @@ export default function UnlockScreen() : React.ReactNode {
<ThemedText style={styles.faceIdButtonText}>Try Face ID Again</ThemedText>
</TouchableOpacity>
)}
-
- <TouchableOpacity
- style={styles.logoutButton}
- onPress={handleLogout}
- >
- <ThemedText style={styles.logoutButtonText}>Logout</ThemedText>
- </TouchableOpacity>
</View>
+
+ <TouchableOpacity
+ style={styles.logoutButton}
+ onPress={handleLogout}
+ >
+ <ThemedText style={styles.logoutButtonText}>Logout</ThemedText>
+ </TouchableOpacity>
</KeyboardAvoidingView>
)}
</ThemedView>
diff --git a/apps/mobile-app/constants/Colors.ts b/apps/mobile-app/constants/Colors.ts
index c5c04478d..90ca535dd 100644
--- a/apps/mobile-app/constants/Colors.ts
+++ b/apps/mobile-app/constants/Colors.ts
@@ -27,6 +27,7 @@ export const Colors = {
loginHeader: '#f6dfc4',
greenBackground: '#22c55e',
skeleton: '#rgba(255,255,255,0.4)',
+ red: '#ff0000',
},
dark: {
white: '#ffffff',
@@ -52,6 +53,7 @@ export const Colors = {
loginHeader: '#5c4331',
greenBackground: '#22c55e',
skeleton: '#rgba(255,255,255,0.2)',
+ red: '#ff0000',
},
} as const;
diff --git a/apps/mobile-app/context/DbContext.tsx b/apps/mobile-app/context/DbContext.tsx
index 83ae63e3f..a34f34cb9 100644
--- a/apps/mobile-app/context/DbContext.tsx
+++ b/apps/mobile-app/context/DbContext.tsx
@@ -4,12 +4,15 @@ import NativeVaultManager from '@/specs/NativeVaultManager';
import SqliteClient from '@/utils/SqliteClient';
import { VaultResponse } from '@/utils/types/webapi/VaultResponse';
import { VaultMetadata } from '@/utils/types/messaging/VaultMetadata';
+import { EncryptionKeyDerivationParams } from '@/utils/types/messaging/EncryptionKeyDerivationParams';
type DbContextType = {
sqliteClient: SqliteClient | null;
dbInitialized: boolean;
dbAvailable: boolean;
- initializeDatabase: (vaultResponse: VaultResponse, derivedKey: string | null) => Promise<void>;
+ storeEncryptionKey: (derivedKey: string) => Promise<void>;
+ storeEncryptionKeyDerivationParams: (keyDerivationParams: EncryptionKeyDerivationParams) => Promise<void>;
+ initializeDatabase: (vaultResponse: VaultResponse) => Promise<void>;
clearDatabase: () => void;
getVaultMetadata: () => Promise<VaultMetadata | null>;
testDatabaseConnection: (derivedKey: string) => Promise<boolean>;
@@ -51,15 +54,32 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
}
}, []);
- const initializeDatabase = useCallback(async (vaultResponse: VaultResponse, derivedKey: string | null = null) => {
- /*
- * If the derived key is provided, store it in the keychain.
- * Otherwise we assume the encryption key is already stored in the keychain.
- */
- if (derivedKey) {
- await sqliteClient.storeEncryptionKey(derivedKey);
- }
+ /**
+ * Store the encryption key in the Native module (in memory and optionally keychain).
+ *
+ * @param derivedKey The derived encryption key
+ * @param keyDerivationParams The key derivation parameters (used for deriving the encryption key from the plain text password in the unlock screen)
+ */
+ const storeEncryptionKey = useCallback(async (derivedKey: string) => {
+ await sqliteClient.storeEncryptionKey(derivedKey
+ );
+ }, [sqliteClient]);
+ /**
+ * Store the key derivation parameters in the Native module (in memory and optionally keychain).
+ *
+ * @param keyDerivationParams The key derivation parameters
+ */
+ const storeEncryptionKeyDerivationParams = useCallback(async (keyDerivationParams: EncryptionKeyDerivationParams) => {
+ await sqliteClient.storeEncryptionKeyDerivationParams(keyDerivationParams);
+ }, [sqliteClient]);
+
+ /**
+ * Initialize the database in the native module.
+ *
+ * @param vaultResponse The vault response from the API
+ */
+ const initializeDatabase = useCallback(async (vaultResponse: VaultResponse) => {
const metadata: VaultMetadata = {
publicEmailDomains: vaultResponse.vault.publicEmailDomainList,
privateEmailDomains: vaultResponse.vault.privateEmailDomainList,
@@ -164,7 +184,9 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
getVaultMetadata,
testDatabaseConnection,
unlockVault,
- }), [sqliteClient, dbInitialized, dbAvailable, initializeDatabase, clearDatabase, getVaultMetadata, testDatabaseConnection, unlockVault]);
+ storeEncryptionKey,
+ storeEncryptionKeyDerivationParams,
+ }), [sqliteClient, dbInitialized, dbAvailable, initializeDatabase, clearDatabase, getVaultMetadata, testDatabaseConnection, unlockVault, storeEncryptionKey, storeEncryptionKeyDerivationParams]);
return (
<DbContext.Provider value={contextValue}>
diff --git a/apps/mobile-app/hooks/useVaultSync.ts b/apps/mobile-app/hooks/useVaultSync.ts
index a130a8c0e..3f96dbca5 100644
--- a/apps/mobile-app/hooks/useVaultSync.ts
+++ b/apps/mobile-app/hooks/useVaultSync.ts
@@ -113,7 +113,7 @@ export const useVaultSync = () : {
}
try {
- await dbContext.initializeDatabase(vaultResponseJson as VaultResponse, null);
+ await dbContext.initializeDatabase(vaultResponseJson as VaultResponse);
onSuccess?.(true);
return true;
} catch {
diff --git a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
index c461e8afd..ce8a34d1f 100644
--- a/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
+++ b/apps/mobile-app/ios/Autofill/CredentialProviderViewController.swift
@@ -19,11 +19,6 @@ public class CredentialProviderViewController: ASCredentialProviderViewControlle
private var isChoosingTextToInsert = false
private var initialServiceUrl: String?
- override public func viewDidLoad() {
- super.viewDidLoad()
- // Keep view empty until we confirm everything is valid in viewWillAppear
- }
-
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index 18c2b003a..3f83e7add 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -97,6 +97,14 @@
[vaultManager storeEncryptionKey:base64EncryptionKey resolver:resolve rejecter:reject];
}
+- (void)storeEncryptionKeyDerivationParams:(NSString *)keyDerivationParams resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager storeEncryptionKeyDerivationParams:keyDerivationParams resolver:resolve rejecter:reject];
+}
+
+- (void)getEncryptionKeyDerivationParams:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager getEncryptionKeyDerivationParams:resolve rejecter:reject];
+}
+
- (void)unlockVault:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
[vaultManager unlockVault:resolve rejecter:reject];
}
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index 4dc58619c..4f7c2ec3c 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -79,6 +79,28 @@ public class VaultManager: NSObject {
}
}
+ @objc
+ func storeEncryptionKeyDerivationParams(_ keyDerivationParams: String,
+ resolver resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ do {
+ try vaultStore.storeEncryptionKeyDerivationParams(keyDerivationParams)
+ resolve(nil)
+ } catch {
+ reject("KEYCHAIN_ERROR", "Failed to store encryption key derivation params: \(error.localizedDescription)", error)
+ }
+ }
+
+ @objc
+ func getEncryptionKeyDerivationParams(_ resolve: @escaping RCTPromiseResolveBlock,
+ rejecter reject: @escaping RCTPromiseRejectBlock) {
+ if let params = vaultStore.getEncryptionKeyDerivationParams() {
+ resolve(params)
+ } else {
+ resolve(nil)
+ }
+ }
+
@objc
func executeQuery(_ query: String,
params: [Any],
diff --git a/apps/mobile-app/ios/VaultModels/EncryptionKeyDerivationParams.swift b/apps/mobile-app/ios/VaultModels/EncryptionKeyDerivationParams.swift
new file mode 100644
index 000000000..43a07cd73
--- /dev/null
+++ b/apps/mobile-app/ios/VaultModels/EncryptionKeyDerivationParams.swift
@@ -0,0 +1,13 @@
+import Foundation
+
+public struct EncryptionKeyDerivationParams: Codable {
+ public var encryptionType: String?
+ public var encryptionSettings: String?
+ public var salt: String?
+
+ public init(encryptionType: String? = nil, encryptionSettings: String? = nil, salt: String? = nil) {
+ self.encryptionType = encryptionType
+ self.encryptionSettings = encryptionSettings
+ self.salt = salt
+ }
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultConstants.swift b/apps/mobile-app/ios/VaultStoreKit/VaultConstants.swift
index d48cb6357..921d9ad29 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultConstants.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultConstants.swift
@@ -12,6 +12,7 @@ public struct VaultConstants {
static let encryptedDbFileName = "encrypted_db.sqlite"
static let authMethodsKey = "aliasvault_auth_methods"
static let autoLockTimeoutKey = "aliasvault_auto_lock_timeout"
+ static let encryptionKeyDerivationParamsKey = "aliasvault_encryption_key_derivation_params"
static let defaultAutoLockTimeout: Int = 3600 // 1 hour in seconds
static let defaultAuthMethods: AuthMethods = [.password, .faceID]
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
index dda344b80..eb2e02383 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Cache.swift
@@ -29,13 +29,20 @@ extension VaultStore {
throw error
}
+ // Clear the UserDefaults to remove all locally persisted data
self.userDefaults.removeObject(forKey: VaultConstants.vaultMetadataKey)
self.userDefaults.removeObject(forKey: VaultConstants.authMethodsKey)
self.userDefaults.removeObject(forKey: VaultConstants.autoLockTimeoutKey)
+ self.userDefaults.removeObject(forKey: VaultConstants.encryptionKeyDerivationParamsKey)
self.userDefaults.synchronize()
print("Cleared UserDefaults")
- clearCache()
+ // Clear the cache to remove all in-memory data
+ self.encryptionKey = nil
+ self.dbConnection = nil
+ self.enabledAuthMethods = VaultConstants.defaultAuthMethods
+ self.autoLockTimeout = VaultConstants.defaultAutoLockTimeout
+ self.keyDerivationParams = nil
}
/// Set the auto-lock timeout - the number of seconds after which the vault will be locked automatically
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
index 0f7b66c5a..5e8534c67 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
@@ -16,19 +16,28 @@ extension VaultStore {
}
self.encryptionKey = keyData
- print("Stored key in memory")
+ print("Stored key in memory, will be persisted in keychain upon succesful decrypt operation")
+ }
- if self.enabledAuthMethods.contains(.faceID) {
- print("Face ID is enabled, storing key in keychain")
- do {
- try storeKeyInKeychain(keyData)
- print("Encryption key saved successfully to keychain")
- } catch {
- print("Failed to save encryption key to keychain: \(error)")
- }
- } else {
- print("Face ID is disabled, not storing encryption key in keychain")
- }
+ /// Check if a encryption key is stored in memory
+ public func hasEncryptionKeyInMemory() -> Bool {
+ return self.encryptionKey != nil
+ }
+
+ /// Store the key derivation parameters used for deriving the encryption key from the plain text password
+ public func storeEncryptionKeyDerivationParams(_ keyDerivationParams: String) throws {
+ // Store the key derivation params in memory
+ self.keyDerivationParams = keyDerivationParams
+
+ // Store the key derivation params in UserDefaults
+ self.userDefaults.set(keyDerivationParams, forKey: VaultConstants.encryptionKeyDerivationParamsKey)
+
+ print("Stored key derivation params in UserDefaults")
+ }
+
+ /// Get the key derivation parameters used for deriving the encryption key from the plain text password
+ public func getEncryptionKeyDerivationParams() -> String? {
+ return self.keyDerivationParams
}
/// Encrypt the data using the encryption key
@@ -46,7 +55,27 @@ extension VaultStore {
let key = SymmetricKey(data: encryptionKey)
let sealedBox = try AES.GCM.SealedBox(combined: data)
- return try AES.GCM.open(sealedBox, using: key)
+ do {
+ let decryptedData = try AES.GCM.open(sealedBox, using: key)
+
+ // If the decryption succeeds, we persist the used encryption key in the keychain
+ // This makes sure that on future password unlock attempts, only succesful decryptions
+ // will be remembered and used so failed re-authentication attempts won't overwrite
+ // a previous successful decryption key stored in the keychain.
+ try storeKeyInKeychain(encryptionKey)
+
+ return decryptedData
+ } catch {
+ print("Decryption failed: \(error)")
+
+ // If the decryption fails, we remove the encryption key from memory
+ // so that the next password unlock attempt will require a fresh
+ // re-authentication attempt (either via Face ID or passcode) or
+ // manual password unlock.
+ self.encryptionKey = nil
+
+ throw NSError(domain: "VaultStore", code: 12, userInfo: [NSLocalizedDescriptionKey: "Decryption failed"])
+ }
}
/// Get the encryption key - the key used to encrypt and decrypt the vault.
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
index 23680389d..a6fbc3860 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Database.swift
@@ -30,28 +30,11 @@ extension VaultStore {
let encryptedDbData = Data(base64Encoded: encryptedDbBase64)!
- // Try to decrypt the database twice to handle cases where the first attempt fails
- // and this first attempt was using the cached encryption key.
- if encryptionKey != nil {
- // There is a cached encryption key, so we try to decrypt the database with it.
- // If this fails, we remove the cached key and try a second time triggering
- // re-authentication.
- do {
- let decryptedDbBase64 = try decrypt(data: encryptedDbData)
- try setupDatabaseWithDecryptedData(decryptedDbBase64)
- return
- } catch {
- print("First decryption attempt with cached key failed: \(error)")
- encryptionKey = nil
- }
- }
-
- // No cached key or first attempt failed — trigger authentication and try again
do {
let decryptedDbBase64 = try decrypt(data: encryptedDbData)
try setupDatabaseWithDecryptedData(decryptedDbBase64)
} catch {
- print("Second decryption attempt after reauth failed: \(error)")
+ print("Decryption failed: \(error)")
throw NSError(domain: "VaultStore", code: 5, userInfo: [NSLocalizedDescriptionKey: "Could not unlock vault"])
}
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
index 9bfa0b686..39cf4088a 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
@@ -32,6 +32,9 @@ public class VaultStore {
/// The encryption key for the vault.
internal var encryptionKey: Data?
+ /// The key derivation parameters used to derive the encryption key from the password.
+ internal var keyDerivationParams: String?
+
/// The timer for the auto-lock timeout.
private var clearCacheTimer: Timer?
@@ -61,6 +64,10 @@ public class VaultStore {
if userDefaults.object(forKey: VaultConstants.autoLockTimeoutKey) != nil {
self.autoLockTimeout = userDefaults.integer(forKey: VaultConstants.autoLockTimeoutKey)
}
+
+ if let savedParams = userDefaults.string(forKey: VaultConstants.encryptionKeyDerivationParamsKey) {
+ self.keyDerivationParams = savedParams
+ }
}
private func setupNotificationObservers() {
diff --git a/apps/mobile-app/ios/VaultStoreKitTests/VaultStoreKitTests.swift b/apps/mobile-app/ios/VaultStoreKitTests/VaultStoreKitTests.swift
index c5ea33031..f97659330 100644
--- a/apps/mobile-app/ios/VaultStoreKitTests/VaultStoreKitTests.swift
+++ b/apps/mobile-app/ios/VaultStoreKitTests/VaultStoreKitTests.swift
@@ -32,7 +32,11 @@ final public class VaultStoreKitTests: XCTestCase {
override public func tearDown() {
// Clean up after each test
- vaultStore.clearVault()
+ do {
+ try vaultStore.clearVault()
+ } catch {
+ // Ignore.
+ }
super.tearDown()
}
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index 7a30e7a86..94483a39b 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -16,6 +16,8 @@ export interface Spec extends TurboModule {
storeMetadata(metadata: string): Promise<void>;
setAuthMethods(authMethods: string[]): Promise<void>;
storeEncryptionKey(base64EncryptionKey: string): Promise<void>;
+ storeEncryptionKeyDerivationParams(keyDerivationParams: string): Promise<void>;
+ getEncryptionKeyDerivationParams(): Promise<string | null>;
hasEncryptedDatabase(): Promise<boolean>;
getEncryptedDatabase(): Promise<string | null>;
getCurrentVaultRevisionNumber(): Promise<number>;
diff --git a/apps/mobile-app/utils/SqliteClient.tsx b/apps/mobile-app/utils/SqliteClient.tsx
index 655b03c98..7132a713e 100644
--- a/apps/mobile-app/utils/SqliteClient.tsx
+++ b/apps/mobile-app/utils/SqliteClient.tsx
@@ -1,9 +1,10 @@
-import NativeVaultManager from '@/specs/NativeVaultManager';
-import { Credential } from '@/utils/types/Credential';
-import { EncryptionKey } from '@/utils/types/EncryptionKey';
import { TotpCode } from '@/utils/types/TotpCode';
import { PasswordSettings } from '@/utils/types/PasswordSettings';
import { VaultMetadata } from '@/utils/types/messaging/VaultMetadata';
+import { Credential } from '@/utils/types/Credential';
+import { EncryptionKey } from '@/utils/types/EncryptionKey';
+import { EncryptionKeyDerivationParams } from '@/utils/types/messaging/EncryptionKeyDerivationParams';
+import NativeVaultManager from '@/specs/NativeVaultManager';
type SQLiteBindValue = string | number | null | Uint8Array;
@@ -123,9 +124,12 @@ class SqliteClient {
/**
* Store the encryption key in the native keychain
+ *
+ * @param base64EncryptionKey The base64 encoded encryption key
*/
public async storeEncryptionKey(base64EncryptionKey: string): Promise<void> {
try {
+ // Store the encryption key in the native module
await NativeVaultManager.storeEncryptionKey(base64EncryptionKey);
} catch (error) {
console.error('Error storing encryption key:', error);
@@ -133,6 +137,21 @@ class SqliteClient {
}
}
+ /**
+ * Store the key derivation params in the native keychain
+ *
+ * @param keyDerivationParams The key derivation parameters
+ */
+ public async storeEncryptionKeyDerivationParams(keyDerivationParams: EncryptionKeyDerivationParams): Promise<void> {
+ try {
+ const keyDerivationParamsJson = JSON.stringify(keyDerivationParams);
+ await NativeVaultManager.storeEncryptionKeyDerivationParams(keyDerivationParamsJson);
+ } catch (error) {
+ console.error('Error storing encryption key derivation params:', error);
+ throw error;
+ }
+ }
+
/**
* Execute a SELECT query
*/
diff --git a/apps/mobile-app/utils/types/messaging/EncryptionKeyDerivationParams.ts b/apps/mobile-app/utils/types/messaging/EncryptionKeyDerivationParams.ts
new file mode 100644
index 000000000..725d0875a
--- /dev/null
+++ b/apps/mobile-app/utils/types/messaging/EncryptionKeyDerivationParams.ts
@@ -0,0 +1,10 @@
+/**
+ * These parameters for deriving encryption key from plain text password. These are stored
+ * as metadata in the vault upon initial login, and are used to derive the encryption key
+ * from the plain text password in the unlock screen.
+ */
+export type EncryptionKeyDerivationParams = {
+ encryptionType: string,
+ encryptionSettings: string,
+ salt: string,
+};