Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Fix Swift base64 sqlite decryption flow (#771)
Leendert de Borstf8b5f4a3ddbe
diff --git a/mobile-app/context/DbContext.tsx b/mobile-app/context/DbContext.tsxindex e4f0d042c..ab6cf7eea 100644--- a/mobile-app/context/DbContext.tsx+++ b/mobile-app/context/DbContext.tsx@@ -3,6 +3,7 @@ import SqliteClient from '@/utils/SqliteClient';import { VaultResponse } from '@/utils/types/webapi/VaultResponse';import EncryptionUtility from '@/utils/EncryptionUtility';import { VaultResponse as messageVaultResponse } from '@/utils/types/messaging/VaultResponse';+import { NativeModules } from 'react-native';type DbContextType = {sqliteClient: SqliteClient | null;@@ -21,6 +22,8 @@ const DbContext = createContext<DbContextType | undefined>(undefined);* DbProvider to provide the SQLite client to the app that components can use to make database queries.*/export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ const credentialManager = NativeModules.CredentialManager;+/*** SQLite client.*/@@ -53,17 +56,16 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }const initializeDatabase = useCallback(async (vaultResponse: VaultResponse, derivedKey: string) => {// Attempt to decrypt the blob.- console.log('attempt to decrypt vault');+ /*console.log('attempt to decrypt vault');const decryptedBlob = await EncryptionUtility.symmetricDecrypt(vaultResponse.vault.blob,derivedKey- );-- console.log('decrypted blob', decryptedBlob);+ );*/// Initialize the SQLite client.const client = new SqliteClient();- await client.initializeFromBase64(decryptedBlob);+ await client.storeEncryptionKey(derivedKey);+ await client.storeEncryptedDatabase(vaultResponse.vault.blob);setSqliteClient(client);setDbInitialized(true);diff --git a/mobile-app/ios/CredentialManager/CredentialManager.swift b/mobile-app/ios/CredentialManager/CredentialManager.swiftindex 61a5b1740..15fb8d7ef 100644--- a/mobile-app/ios/CredentialManager/CredentialManager.swift+++ b/mobile-app/ios/CredentialManager/CredentialManager.swift@@ -32,16 +32,16 @@ class CredentialManager: NSObject {resolver resolve: @escaping RCTPromiseResolveBlock,rejecter reject: @escaping RCTPromiseRejectBlock) {do {- // Store the encryption key in the keychain with biometric protection+ // Store the encryption key in the keychain with biometric or PIN protectionlet context = LAContext()var error: NSError?- guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {- reject("BIOMETRICS_UNAVAILABLE", "Biometrics not available: \(error?.localizedDescription ?? "Unknown error")", error)+ guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else {+ reject("AUTH_UNAVAILABLE", "Authentication not available: \(error?.localizedDescription ?? "Unknown error")", error)return}- // Store the key in the keychain with biometric protection+ // Store the key in the keychain with authentication protectiontry credentialStore.storeEncryptionKey(base64EncryptionKey)resolve(nil)} catch {diff --git a/mobile-app/ios/CredentialManager/SharedCredentialStore.swift b/mobile-app/ios/CredentialManager/SharedCredentialStore.swiftindex 8cedc4ee2..07c78c9cc 100644--- a/mobile-app/ios/CredentialManager/SharedCredentialStore.swift+++ b/mobile-app/ios/CredentialManager/SharedCredentialStore.swift@@ -12,22 +12,51 @@ class SharedCredentialStore {private let encryptionKeyKey = "aliasvault_encryption_key"private let encryptedDbFileName = "encrypted_db.sqlite"private var db: Connection?+ private var encryptionKey: Data?private init() {}// MARK: - Encryption Key Management+ private func getEncryptionKey() throws -> Data {+ if let key = encryptionKey {+ // print as base64 for debugging+ print("Key found in memory: \(key.base64EncodedString())")+ return key+ }++ guard let keyData = try? keychain+ .authenticationPrompt("Authenticate to unlock your vault")+ .getData(encryptionKeyKey) else {+ throw NSError(domain: "SharedCredentialStore", code: 2, userInfo: [NSLocalizedDescriptionKey: "No encryption key found"])+ }++ encryptionKey = keyData+ // print as base64 for debugging+ print("Key found in keychain: \(keyData.base64EncodedString())")+ return keyData+ }+func storeEncryptionKey(_ base64Key: String) throws {print("Storing encryption key")++ // Convert base64 string to bytesguard let keyData = Data(base64Encoded: base64Key) else {throw NSError(domain: "SharedCredentialStore", code: 6, userInfo: [NSLocalizedDescriptionKey: "Invalid base64 key"])}+ // Validate key length (AES-256 requires 32 bytes)+ guard keyData.count == 32 else {+ throw NSError(domain: "SharedCredentialStore", code: 7, userInfo: [NSLocalizedDescriptionKey: "Invalid key length. Expected 32 bytes"])+ }+do {try keychain.authenticationPrompt("Authenticate to unlock your vault").set(keyData, key: encryptionKeyKey)- print("Key saved in keychain")+ encryptionKey = keyData+ // print as base64 for debugging+ print("Key saved in keychain: \(keyData.base64EncodedString())")} catch {print("Failed to save key to keychain: \(error)")throw error@@ -42,18 +71,15 @@ class SharedCredentialStore {}func storeEncryptedDatabase(_ base64EncryptedDb: String) throws {- guard let encryptedData = Data(base64Encoded: base64EncryptedDb) else {- throw NSError(domain: "SharedCredentialStore", code: 3, userInfo: [NSLocalizedDescriptionKey: "Invalid base64 data"])- }-- // Store the encrypted database in the app's documents directory- try encryptedData.write(to: getEncryptedDbPath())+ // Store the encrypted database (base64 encoded) in the app's documents directory+ try base64EncryptedDb.write(to: getEncryptedDbPath(), atomically: true, encoding: .utf8)}+ // Get the encrypted database as a base64 encoded stringfunc getEncryptedDatabase() -> String? {do {- let encryptedData = try Data(contentsOf: getEncryptedDbPath())- return encryptedData.base64EncodedString()+ // Return the base64 encoded string+ return try String(contentsOf: getEncryptedDbPath(), encoding: .utf8)} catch {return nil}@@ -61,30 +87,60 @@ class SharedCredentialStore {func initializeDatabase() throws {// Get the encrypted database- guard let base64EncryptedDb = getEncryptedDatabase() else {+ guard let encryptedDbBase64 = getEncryptedDatabase() else {throw NSError(domain: "SharedCredentialStore", code: 1, userInfo: [NSLocalizedDescriptionKey: "No encrypted database found"])}+ let encryptedDbData = Data(base64Encoded: encryptedDbBase64)!+// Get the encryption key- guard let keyData = try? keychain- .authenticationPrompt("Authenticate to unlock your vault")- .getData(encryptionKeyKey) else {- throw NSError(domain: "SharedCredentialStore", code: 2, userInfo: [NSLocalizedDescriptionKey: "No encryption key found"])+ let encryptionKey = try getEncryptionKey()+ let decryptedDbBase64 = try decrypt(data: encryptedDbData, key: encryptionKey)++ // The decrypted data is still base64 encoded, so decode it+ guard let decryptedDbData = Data(base64Encoded: decryptedDbBase64) else {+ throw NSError(domain: "SharedCredentialStore", code: 10, userInfo: [NSLocalizedDescriptionKey: "Failed to decode base64 data after decryption"])}++ // Check SQLite header+ let header = decryptedDbData.prefix(24)+ let headerString = String(bytes: header, encoding: .ascii) ?? "Non-ascii"+ print("SQLite header: \(headerString)")+ print("Header bytes: \(header.map { String(format: "%02x", $0) }.joined(separator: " "))")- // Convert base64 strings to data- guard let encryptedData = Data(base64Encoded: base64EncryptedDb) else {- throw NSError(domain: "SharedCredentialStore", code: 3, userInfo: [NSLocalizedDescriptionKey: "Invalid base64 data"])+ // Verify it matches expected SQLite header+ let expectedHeader = "SQLite format 3\0"+ if headerString != expectedHeader {+ print("WARNING: SQLite header does not match expected format!")}++ print("decrypted data raw print?")+ print(decryptedDbData)++ let tag = decryptedDbData.suffix(16)+ print("tag: \(tag.base64EncodedString())")++ // Create a temporary file for the decrypted database in the same directory as the encrypted one+ let tempDbPath = FileManager.default.temporaryDirectory.appendingPathComponent("temp_db.sqlite")+ try decryptedDbData.write(to: tempDbPath)- // Decrypt the database- let decryptedData = try decrypt(data: encryptedData, key: keyData)+ do {+ let tempDb = try Connection(tempDbPath.path)+ let tables = try tempDb.prepare("SELECT name FROM sqlite_master WHERE type='table'")+ for table in tables {+ print("Table:", table[0] as? String ?? "Unknown")+ }+ } catch {+ print("Direct DB open error:", error)+ }// Create an in-memory databasedb = try Connection(":memory:")// Import the decrypted database into memory- try db?.execute("ATTACH DATABASE '\(decryptedData)' AS source")+ //try db?.attach(.uri(tempDbPath.path, parameters: [.mode(.readOnly)]), as: "source")+ // make query and print it before actually attaching+ try db?.attach(.uri(tempDbPath.path, parameters: [.mode(.readOnly)]), as: "source")try db?.execute("BEGIN TRANSACTION")// Copy all tables from source to memory@@ -97,6 +153,9 @@ class SharedCredentialStore {try db?.execute("COMMIT")try db?.execute("DETACH DATABASE source")+ // Clean up the temporary file+ try? FileManager.default.removeItem(at: tempDbPath)+// Setup database pragmastry db?.execute("PRAGMA journal_mode = WAL")try db?.execute("PRAGMA synchronous = NORMAL")@@ -106,6 +165,7 @@ class SharedCredentialStore {// MARK: - Encryption/Decryptionprivate func encrypt(data: Data, key: Data) throws -> Data {+ // TODO: make sure we encrypt the data the same as decryption works with combined iv/content/tag.let key = SymmetricKey(data: key)let sealedBox = try AES.GCM.seal(data, using: key)return sealedBox.combined!diff --git a/mobile-app/utils/EncryptionUtility.tsx b/mobile-app/utils/EncryptionUtility.tsxindex 33a7080cf..c4de1ee63 100644--- a/mobile-app/utils/EncryptionUtility.tsx+++ b/mobile-app/utils/EncryptionUtility.tsx@@ -94,6 +94,9 @@ class EncryptionUtility {const ivHex = Buffer.from(iv).toString('hex');const tagHex = Buffer.from(tag).toString('hex');+ console.log('ivHex: ', ivHex);+ console.log('tagHex: ', tagHex);+const decryptedData = await AesGcmCrypto.decrypt(contentBase64,base64Key,diff --git a/mobile-app/utils/SqliteClient.tsx b/mobile-app/utils/SqliteClient.tsxindex f7206e9ed..5bef43ea9 100644--- a/mobile-app/utils/SqliteClient.tsx+++ b/mobile-app/utils/SqliteClient.tsx@@ -18,9 +18,9 @@ class SqliteClient {private credentialManager = NativeModules.CredentialManager;/**- * Initialize the SQLite database from a base64 string+ * Store the encrypted database via the native code implementation.*/- public async initializeFromBase64(base64String: string): Promise<void> {+ public async storeEncryptedDatabase(base64String: string): Promise<void> {try {await this.credentialManager.storeDatabase(base64String);} catch (error) {