Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor Typescript account key hierarchy methods to call Rust core (#2469)
Leendert de Borst53306b38b943
diff --git a/apps/browser-extension/tests/helpers/manifest-v2-api.ts b/apps/browser-extension/tests/helpers/manifest-v2-api.tsindex 7f5abfaa6..19a0b4165 100644--- a/apps/browser-extension/tests/helpers/manifest-v2-api.ts+++ b/apps/browser-extension/tests/helpers/manifest-v2-api.ts@@ -10,7 +10,7 @@import { createHash } from 'crypto';import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';-import { deriveKek, getSyncableTableNames, vaultCodecCanonicalizeFromSqlite, vaultCodecGenerateManifestSalt, vaultCodecPackPayload, vaultCodecUnpackPayload } from '@aliasvault/client/rust/RustCore';+import { getSyncableTableNames, openAccountKeyChain, vaultCodecCanonicalizeFromSqlite, vaultCodecGenerateManifestSalt, vaultCodecPackPayload, vaultCodecUnpackPayload } from '@aliasvault/client/rust/RustCore';import { symmetricDecryptBytes, symmetricEncryptBytes } from './vault-crypto';@@ -131,9 +131,11 @@ export async function resolveVaultEncryptionKey(apiBaseUrl: string, token: strinthrow new Error('Vault key chain is missing the encrypted VEK');}- const kek = Buffer.from(await deriveKek(Buffer.from(derivedKey).toString('base64')), 'base64');- const accountKey = await symmetricDecryptBytes(vaultKey.encryptedAccountKey, kek);- return symmetricDecryptBytes(vaultKey.encryptedVek, accountKey);+ const opened = await openAccountKeyChain(Buffer.from(derivedKey).toString('base64'), vaultKey.encryptedAccountKey, vaultKey.encryptedVek, null);+ if (opened.status !== 'opened') {+ throw new Error(`Vault key chain did not open: ${opened.status}`);+ }+ return new Uint8Array(Buffer.from(opened.vaultEncryptionKey, 'base64'));}/**diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.ktindex 806d99637..a0077fe2a 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt@@ -5,8 +5,8 @@ import org.json.JSONArrayimport org.json.JSONObjectimport uniffi.aliasvault_core.KeyChainExceptionimport uniffi.aliasvault_core.argon2DeriveKey+import uniffi.aliasvault_core.createAccountKeyHierarchyJsonimport uniffi.aliasvault_core.decodeEmailSource-import uniffi.aliasvault_core.deriveKekimport uniffi.aliasvault_core.deriveSrpPasswordHashimport uniffi.aliasvault_core.extractDomainimport uniffi.aliasvault_core.extractEmailAttachment@@ -26,6 +26,7 @@ import uniffi.aliasvault_core.isRpIdAllowedForHostimport uniffi.aliasvault_core.openAccountKeyChainimport uniffi.aliasvault_core.parseEmailSourceimport uniffi.aliasvault_core.pruneVaultJson+import uniffi.aliasvault_core.reencryptAccountKeyJsonimport uniffi.aliasvault_core.selectFaviconTargetimport uniffi.aliasvault_core.srpDerivePrivateKeyimport uniffi.aliasvault_core.srpDeriveSession@@ -81,9 +82,10 @@ object RustCoreDispatcher {"extractEmailAttachment" -> json(extractEmailAttachment(args.bytes(0), args.uint(1), args.optionalBytes(2)))"argon2DeriveKey" -> json(argon2DeriveKey(args.string(0), args.string(1), args.string(2)))- "deriveKek" -> json(deriveKek(args.bytes(0)))"deriveSrpPasswordHash" -> json(deriveSrpPasswordHash(args.bytes(0), args.string(1)))"openAccountKeyChain" -> openKeyChain(args.bytes(0), args.string(1), args.string(2), args.optionalString(3))+ "createAccountKeyHierarchyJson" -> createAccountKeyHierarchyJson(args.bytes(0), args.string(1), args.string(2))+ "reencryptAccountKeyJson" -> reencryptAccountKeyJson(args.string(0), args.bytes(1), args.bytes(2))"srpGenerateSalt" -> json(srpGenerateSalt())"srpDerivePrivateKey" -> json(srpDerivePrivateKey(args.string(0), args.string(1), args.string(2)))diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swiftindex 9feda8b0a..c3e40e912 100644--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift@@ -1582,11 +1582,14 @@ private enum RustCoreDispatcher {case "argon2DeriveKey":return try json(bytes: try RustCoreFramework.argon2DeriveKey(password: try args.string(0), salt: try args.string(1), encryptionSettings: try args.string(2)))- case "deriveKek": return try json(bytes: RustCoreFramework.deriveKek(unlockKey: try args.data(0)))case "deriveSrpPasswordHash": return try json(try RustCoreFramework.deriveSrpPasswordHash(unlockKey: try args.data(0), encryptionType: try args.string(1)))case "openAccountKeyChain":let key = try args.data(0)return try openKeyChain(key: key, encryptedAccountKey: try args.string(1), encryptedVek: try args.string(2), encryptedAccountPrivateKey: args.optionalString(3))+ case "createAccountKeyHierarchyJson":+ return try RustCoreFramework.createAccountKeyHierarchyJson(unlockKey: try args.data(0), publicKeyJwk: try args.string(1), privateKeyJwk: try args.string(2))+ case "reencryptAccountKeyJson":+ return try RustCoreFramework.reencryptAccountKeyJson(encryptedAccountKey: try args.string(0), oldUnlockKey: try args.data(1), newUnlockKey: try args.data(2))case "srpGenerateSalt": return try json(RustCoreFramework.srpGenerateSalt())case "srpDerivePrivateKey":diff --git a/apps/mobile-app/platform/NativeRustCore.ts b/apps/mobile-app/platform/NativeRustCore.tsindex 2c0a732ef..5a4b6ea2c 100644--- a/apps/mobile-app/platform/NativeRustCore.ts+++ b/apps/mobile-app/platform/NativeRustCore.ts@@ -57,9 +57,10 @@ export const nativeRustCore: IRustCore = {extractEmailAttachment: (source, index, detachedBody) => callForBytes('extractEmailAttachment', base64(source), index, detachedBody ? base64(detachedBody) : null),argon2DeriveKey: (password, salt, encryptionSettings) => callForBytes('argon2DeriveKey', password, salt, encryptionSettings),- deriveKek: (unlockKeyBase64) => call('deriveKek', unlockKeyBase64),deriveSrpPasswordHash: (unlockKeyBase64, encryptionType) => call('deriveSrpPasswordHash', unlockKeyBase64, encryptionType),openAccountKeyChain: (storedKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey) => call('openAccountKeyChain', storedKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey),+ createAccountKeyHierarchy: (unlockKeyBase64, publicKeyJwk, privateKeyJwk) => call('createAccountKeyHierarchyJson', unlockKeyBase64, publicKeyJwk, privateKeyJwk),+ reencryptAccountKey: (encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64) => call('reencryptAccountKeyJson', encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64),srpGenerateSalt: () => call('srpGenerateSalt'),srpDerivePrivateKey: (salt, identity, passwordHash) => call('srpDerivePrivateKey', salt, identity, passwordHash),diff --git a/core/client/src/auth/MasterPasswordService.ts b/core/client/src/auth/MasterPasswordService.tsindex 024ac0b3b..23f876d73 100644--- a/core/client/src/auth/MasterPasswordService.ts+++ b/core/client/src/auth/MasterPasswordService.ts@@ -1,6 +1,6 @@import { StorageKeys } from '../constants/StorageKeys';-import { unwrapAccountKey, wrapAccountKey } from '../crypto/AccountKeys';import { getPlatform } from '../platform/ClientPlatform';+import { reencryptAccountKey } from '../rust/RustCore';import { VaultSyncHoldReason, withVaultSyncHold } from '../sync/VaultSyncHold';import { SrpAuthService, type SrpClientProof } from './SrpAuthService';@@ -103,8 +103,11 @@ export class MasterPasswordService {* @throws {IncorrectPasswordError} when the old unlock key does not open the blob (wrong current password).*/public static async reencryptAccountKey(encryptedAccountKey: string, oldUnlockKeyBase64: string, newUnlockKeyBase64: string): Promise<{ accountKey: string; newEncryptedAccountKey: string }> {- const accountKey = await MasterPasswordService.decryptAccountKey(encryptedAccountKey, oldUnlockKeyBase64);- return { accountKey, newEncryptedAccountKey: await wrapAccountKey(accountKey, newUnlockKeyBase64) };+ const reencrypted = await reencryptAccountKey(encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64);+ if (!reencrypted) {+ throw new IncorrectPasswordError();+ }+ return reencrypted;}/**@@ -156,19 +159,6 @@ export class MasterPasswordService {// Persist the new Account Key and its derivation parameters.await VaultKeyService.persistNewAccountKey(newEncryptedAccountKey, { salt: next.salt, encryptionType: next.encryptionType, encryptionSettings: next.encryptionSettings }, accountKey);}-- /**- * Decrypt the KEK-wrapped Account Key.- * @param encryptedAccountKey - the Account Key encrypted with the KEK of the entered password- * @param unlockKeyBase64 - the unlock key derived from the entered password- */- private static async decryptAccountKey(encryptedAccountKey: string, unlockKeyBase64: string): Promise<string> {- try {- return await unwrapAccountKey(encryptedAccountKey, unlockKeyBase64);- } catch {- throw new IncorrectPasswordError();- }- }}export default MasterPasswordService;diff --git a/core/client/src/crypto/AccountKeys.ts b/core/client/src/crypto/AccountKeys.tsindex 8dbe1b999..9c1cd8144 100644--- a/core/client/src/crypto/AccountKeys.ts+++ b/core/client/src/crypto/AccountKeys.ts@@ -1,62 +1,16 @@-import { deriveKek } from '../rust/RustCore';+import { createAccountKeyHierarchy as createHierarchy } from '../rust/RustCore';import { EncryptionUtility } from './EncryptionUtility';-/**- * The wrapped halves of an account key hierarchy: what the server stores, sent as-is in a register or- * migration payload.- */-export type AccountKeyBlobs = {- encryptedAccountKey: string;- encryptedVek: string;- accountPublicKey: string;- encryptedAccountPrivateKey: string;-};+import type { AccountKeyHierarchy } from '../rust/RustCoreTypes';-/**- * A newly created account key hierarchy: the wrapped blobs plus the plaintext halves the client keeps.- */-export type AccountKeyHierarchy = {- vaultEncryptionKey: string;- accountPrivateKey: string;- accountKeys: AccountKeyBlobs;-};+export type { AccountKeyBlobs, AccountKeyHierarchy } from '../rust/RustCoreTypes';/**- * Wrap the Account Key with the KEK derived from an unlock key.- * @param accountKey - the Account Key (base64)- * @param unlockKey - the unlock key (base64), the Argon2id output of the master password- */-export async function wrapAccountKey(accountKey: string, unlockKey: string): Promise<string> {- return EncryptionUtility.encryptVaultEncryptionKey(accountKey, await deriveKek(unlockKey));-}--/**- * Unwrap the Account Key with the KEK derived from an unlock key; throws when the unlock key does not open it.- * @param encryptedAccountKey - the wrapped Account Key- * @param unlockKey - the unlock key (base64), the Argon2id output of the master password- */-export async function unwrapAccountKey(encryptedAccountKey: string, unlockKey: string): Promise<string> {- return EncryptionUtility.decryptVaultEncryptionKey(encryptedAccountKey, await deriveKek(unlockKey));-}--/**- * Create a new account key hierarchy.- * @param unlockKey - the unlock key (base64) whose derived KEK wraps this account's key material+ * Create a new account key hierarchy. The keypair comes from WebCrypto, which is far faster than RSA in wasm.+ * @param unlockKey - the unlock key (base64) whose derived KEK encrypts this account's key material*/export async function createAccountKeyHierarchy(unlockKey: string): Promise<AccountKeyHierarchy> {- const vaultEncryptionKey = EncryptionUtility.generateVaultEncryptionKey();- const accountKey = EncryptionUtility.generateVaultEncryptionKey();const accountKeyPair = await EncryptionUtility.generateRsaKeyPair();-- return {- vaultEncryptionKey,- accountPrivateKey: accountKeyPair.privateKey,- accountKeys: {- encryptedAccountKey: await wrapAccountKey(accountKey, unlockKey),- encryptedVek: await EncryptionUtility.encryptVaultEncryptionKey(vaultEncryptionKey, accountKey),- accountPublicKey: accountKeyPair.publicKey,- encryptedAccountPrivateKey: await EncryptionUtility.symmetricEncrypt(accountKeyPair.privateKey, accountKey),- },- };+ return createHierarchy(unlockKey, accountKeyPair.publicKey, accountKeyPair.privateKey);}diff --git a/core/client/src/rust/RustCore.ts b/core/client/src/rust/RustCore.tsindex 0f19781c7..c50d5860e 100644--- a/core/client/src/rust/RustCore.ts+++ b/core/client/src/rust/RustCore.ts@@ -12,7 +12,7 @@ import { deviceLanguage } from '../platform/DeviceLanguage';import { AutofillMatchingMode } from './RustCoreTypes';import type { IRustCore } from './RustCoreBinding';-import type { CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, IdentityNameInput, IdentityRequest, KeyChainOpenResult, ParsedEmail } from './RustCoreTypes';+import type { AccountKeyHierarchy, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, IdentityNameInput, IdentityRequest, KeyChainOpenResult, ParsedEmail, ReencryptedAccountKey } from './RustCoreTypes';import type { Identity } from '@aliasvault/models/identity';import type { Item, PasswordSettings } from '@aliasvault/models/vault';@@ -182,17 +182,24 @@ export async function argon2DeriveKey(password: string, salt: string, encryption}/**- * The KEK (base64) that wraps the Account Key, derived from the unlock key (base64).+ * Open a key chain with a stored key: the Account Key, or an unlock key that is then replaced by the Account Key.*/-export async function deriveKek(unlockKeyBase64: string): Promise<string> {- return rustCore().deriveKek(unlockKeyBase64);+export async function openAccountKeyChain(storedKey: string, encryptedAccountKey: string, encryptedVek: string, encryptedAccountPrivateKey: string | null): Promise<KeyChainOpenResult> {+ return rustCore().openAccountKeyChain(storedKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey);}/**- * Open a key chain with a stored key: the Account Key, or an unlock key that is then replaced by the Account Key.+ * Create a new account key hierarchy for the unlock key (base64) around an account keypair (JWK) the caller generated.*/-export async function openAccountKeyChain(storedKey: string, encryptedAccountKey: string, encryptedVek: string, encryptedAccountPrivateKey: string | null): Promise<KeyChainOpenResult> {- return rustCore().openAccountKeyChain(storedKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey);+export async function createAccountKeyHierarchy(unlockKeyBase64: string, publicKeyJwk: string, privateKeyJwk: string): Promise<AccountKeyHierarchy> {+ return rustCore().createAccountKeyHierarchy(unlockKeyBase64, publicKeyJwk, privateKeyJwk);+}++/**+ * Re-encrypt the Account Key from the old to the new unlock key (base64); null when the old unlock key does not open it.+ */+export async function reencryptAccountKey(encryptedAccountKey: string, oldUnlockKeyBase64: string, newUnlockKeyBase64: string): Promise<ReencryptedAccountKey | null> {+ return rustCore().reencryptAccountKey(encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64);}/**diff --git a/core/client/src/rust/RustCoreBinding.ts b/core/client/src/rust/RustCoreBinding.tsindex 0b2f7a57e..d9d925fd9 100644--- a/core/client/src/rust/RustCoreBinding.ts+++ b/core/client/src/rust/RustCoreBinding.ts@@ -1,4 +1,4 @@-import type { CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, KeyChainOpenResult, ParsedEmail, SrpEphemeral, SrpSession } from './RustCoreTypes';+import type { AccountKeyHierarchy, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, KeyChainOpenResult, ParsedEmail, ReencryptedAccountKey, SrpEphemeral, SrpSession } from './RustCoreTypes';/*** One running operation of the Rust vault sync engine.@@ -41,9 +41,10 @@ export interface IRustCore {extractEmailAttachment(source: Uint8Array, index: number, detachedBody?: Uint8Array): Promise<Uint8Array>;argon2DeriveKey(password: string, salt: string, encryptionSettings: string): Promise<Uint8Array>;- deriveKek(unlockKeyBase64: string): Promise<string>;deriveSrpPasswordHash(unlockKeyBase64: string, encryptionType: string): Promise<string>;openAccountKeyChain(storedKey: string, encryptedAccountKey: string, encryptedVek: string, encryptedAccountPrivateKey: string | null): Promise<KeyChainOpenResult>;+ createAccountKeyHierarchy(unlockKeyBase64: string, publicKeyJwk: string, privateKeyJwk: string): Promise<AccountKeyHierarchy>;+ reencryptAccountKey(encryptedAccountKey: string, oldUnlockKeyBase64: string, newUnlockKeyBase64: string): Promise<ReencryptedAccountKey | null>;srpGenerateSalt(): Promise<string>;srpDerivePrivateKey(salt: string, identity: string, passwordHash: string): Promise<string>;diff --git a/core/client/src/rust/RustCoreTypes.ts b/core/client/src/rust/RustCoreTypes.tsindex 2b8e394ab..3008699ee 100644--- a/core/client/src/rust/RustCoreTypes.ts+++ b/core/client/src/rust/RustCoreTypes.ts@@ -89,6 +89,31 @@ export type KeyChainOpenResult =| { status: 'unlockKeyRejected' }| { status: 'keyChainUnreadable'; message: string };+/**+ * The encrypted halves of an account key hierarchy: what the server stores, sent as-is in a register or migration payload.+ */+export type AccountKeyBlobs = {+ encryptedAccountKey: string;+ encryptedVek: string;+ accountPublicKey: string;+ encryptedAccountPrivateKey: string;+};++/**+ * A newly created account key hierarchy (the Rust `create_account_key_hierarchy`): the encrypted blobs plus the plaintext halves the client keeps.+ */+export type AccountKeyHierarchy = {+ vaultEncryptionKey: string;+ accountPrivateKey: string;+ accountKeys: AccountKeyBlobs;+};++/** The Account Key (base64) re-encrypted for a new password. */+export type ReencryptedAccountKey = {+ accountKey: string;+ newEncryptedAccountKey: string;+};+/** Vault codec (manifest-v1 storage format).*/diff --git a/core/client/src/rust/WasmRustCore.ts b/core/client/src/rust/WasmRustCore.tsindex e9b479e70..9e5b4c551 100644--- a/core/client/src/rust/WasmRustCore.ts+++ b/core/client/src/rust/WasmRustCore.ts@@ -6,7 +6,7 @@ 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, KeyChainOpenResult, ParsedEmail, SrpEphemeral, SrpSession } from './RustCoreTypes';+import type { AccountKeyHierarchy, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, KeyChainOpenResult, ParsedEmail, ReencryptedAccountKey, SrpEphemeral, SrpSession } from './RustCoreTypes';/*** Where the host gets the `.wasm` binary from: bytes, or a fetch response for streaming instantiation.@@ -75,10 +75,13 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {await yieldToPaint();return ready(() => core.argon2DeriveKey(password, salt, encryptionSettings));},- deriveKek: (unlockKeyBase64): Promise<string> => ready(() => core.deriveKek(unlockKeyBase64)),deriveSrpPasswordHash: (unlockKeyBase64, encryptionType): Promise<string> => ready(() => core.deriveSrpPasswordHash(unlockKeyBase64, encryptionType)),openAccountKeyChain: (storedKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey): Promise<KeyChainOpenResult> =>ready(() => core.openAccountKeyChain(storedKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey ?? undefined) as KeyChainOpenResult),+ createAccountKeyHierarchy: (unlockKeyBase64, publicKeyJwk, privateKeyJwk): Promise<AccountKeyHierarchy> =>+ ready(() => core.createAccountKeyHierarchy(unlockKeyBase64, publicKeyJwk, privateKeyJwk) as AccountKeyHierarchy),+ reencryptAccountKey: (encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64): Promise<ReencryptedAccountKey | null> =>+ ready(() => core.reencryptAccountKey(encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64) as ReencryptedAccountKey | null),srpGenerateSalt: (): Promise<string> => ready(() => core.srpGenerateSalt()),srpDerivePrivateKey: (salt, identity, passwordHash): Promise<string> => ready(() => core.srpDerivePrivateKey(salt, identity, passwordHash)),diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rsindex 6083c3974..a465b6ed3 100644--- a/core/rust/src/bindings/uniffi_api.rs+++ b/core/rust/src/bindings/uniffi_api.rs@@ -218,10 +218,26 @@ pub fn argon2_derive_key_bytes(password: Vec<u8>, salt: Vec<u8>, encryption_settcrate::crypto::argon2::argon2_derive_key_bytes_from_settings(&password, &salt, &encryption_settings)}-/// The KEK that wraps the Account Key, HKDF-derived from the unlock key.+/// Create a new account key hierarchy for the unlock key around an account keypair (JWK) the caller generated, as JSON.#[uniffi::export]-pub fn derive_kek(unlock_key: Vec<u8>) -> Vec<u8> {- crate::crypto::derive_kek(&unlock_key).to_vec()+pub fn create_account_key_hierarchy_json(unlock_key: Vec<u8>, public_key_jwk: String, private_key_jwk: String) -> Result<String, VaultError> {+ let unlock_key = zeroize::Zeroizing::new(crate::common::encoding::base64_encode(&unlock_key));+ let key_pair = crate::crypto::RsaKeyPair { public_key: public_key_jwk, private_key: private_key_jwk };+ let hierarchy = crate::crypto::create_account_key_hierarchy_with_key_pair(&unlock_key, &key_pair)?;+ Ok(serde_json::to_string(&hierarchy)?)+}++/// Re-encrypt the Account Key from the old to the new unlock key, as JSON; `null` when the old unlock key does not open it.+#[uniffi::export]+pub fn reencrypt_account_key_json(encrypted_account_key: String, old_unlock_key: Vec<u8>, new_unlock_key: Vec<u8>) -> Result<String, VaultError> {+ use crate::common::encoding::base64_encode;+ let old_unlock_key = zeroize::Zeroizing::new(base64_encode(&old_unlock_key));+ let new_unlock_key = zeroize::Zeroizing::new(base64_encode(&new_unlock_key));+ match crate::crypto::reencrypt_account_key(&encrypted_account_key, &old_unlock_key, &new_unlock_key) {+ Ok(reencrypted) => Ok(serde_json::to_string(&reencrypted)?),+ Err(KeyChainError::UnlockKeyRejected) => Ok("null".to_string()),+ Err(e) => Err(VaultError::General(e.to_string())),+ }}/// The SRP `password_hash` (uppercase hex) for an account's `encryptionType`, from the unlock key.diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rsindex 4696ba6db..5b64120a0 100644--- a/core/rust/src/bindings/wasm.rs+++ b/core/rust/src/bindings/wasm.rs@@ -225,10 +225,21 @@ pub fn argon2_derive_key_js(password: &str, salt: &str, encryption_settings: &stcrate::crypto::argon2::argon2_derive_key_from_settings(password, salt, encryption_settings).map_err(js_err)}-/// The KEK (base64) that wraps the Account Key, HKDF-derived from the base64 unlock key.-#[wasm_bindgen(js_name = deriveKek)]-pub fn derive_kek_js(unlock_key_base64: &str) -> Result<String, JsValue> {- crate::crypto::derive_kek_base64(unlock_key_base64).map(|kek| kek.to_string()).map_err(js_err)+/// Create a new account key hierarchy for the base64 unlock key around an account keypair (JWK) the caller generated.+#[wasm_bindgen(js_name = createAccountKeyHierarchy)]+pub fn create_account_key_hierarchy_js(unlock_key_base64: &str, public_key_jwk: String, private_key_jwk: String) -> Result<JsValue, JsValue> {+ let key_pair = crate::crypto::RsaKeyPair { public_key: public_key_jwk, private_key: private_key_jwk };+ to_js(&crate::crypto::create_account_key_hierarchy_with_key_pair(unlock_key_base64, &key_pair).map_err(js_err)?)+}++/// Re-encrypt the Account Key from the old to the new base64 unlock key; `null` when the old unlock key does not open it.+#[wasm_bindgen(js_name = reencryptAccountKey)]+pub fn reencrypt_account_key_js(encrypted_account_key: &str, old_unlock_key_base64: &str, new_unlock_key_base64: &str) -> Result<JsValue, JsValue> {+ match crate::crypto::reencrypt_account_key(encrypted_account_key, old_unlock_key_base64, new_unlock_key_base64) {+ Ok(reencrypted) => to_js(&reencrypted),+ Err(crate::crypto::KeyChainError::UnlockKeyRejected) => Ok(JsValue::NULL),+ Err(e) => Err(js_err(e)),+ }}/// The SRP `password_hash` (uppercase hex) for an account's `encryptionType`, from the base64 unlock key.diff --git a/core/rust/src/crypto/key_chain.rs b/core/rust/src/crypto/key_chain.rsindex 1336f91c7..ca77580fa 100644--- a/core/rust/src/crypto/key_chain.rs+++ b/core/rust/src/crypto/key_chain.rs@@ -9,7 +9,7 @@ use thiserror::Error;use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};use super::aes_gcm::{generate_key_base64, symmetric_decrypt, symmetric_decrypt_bytes, symmetric_encrypt, symmetric_encrypt_bytes};-use super::rsa_oaep::generate_rsa_key_pair;+use super::rsa_oaep::{generate_rsa_key_pair, validate_rsa_key_pair, RsaKeyPair};use crate::common::encoding::{base64_decode, base64_encode, hex_encode_upper};use crate::common::error::VaultResult;@@ -156,9 +156,14 @@ pub fn open_account_key_chain(stored_key: &str, encrypted_account_key: &str, enc/// Create a new account key hierarchy wrapped under the KEK derived from an unlock key.pub fn create_account_key_hierarchy(unlock_key_base64: &str) -> VaultResult<AccountKeyHierarchy> {+ create_account_key_hierarchy_with_key_pair(unlock_key_base64, &generate_rsa_key_pair()?)+}++/// [`create_account_key_hierarchy`] around an account keypair the host generated, as WebCrypto is far faster than wasm.+pub fn create_account_key_hierarchy_with_key_pair(unlock_key_base64: &str, key_pair: &RsaKeyPair) -> VaultResult<AccountKeyHierarchy> {+ validate_rsa_key_pair(key_pair)?;let vault_encryption_key = generate_key_base64();let account_key = Zeroizing::new(generate_key_base64());- let key_pair = generate_rsa_key_pair()?;let account_keys = AccountKeyBlobs {encrypted_account_key: wrap_account_key(&account_key, unlock_key_base64)?,@@ -170,6 +175,23 @@ pub fn create_account_key_hierarchy(unlock_key_base64: &str) -> VaultResult<AccoOk(AccountKeyHierarchy { vault_encryption_key, account_private_key: key_pair.private_key.clone(), account_keys })}+/// The Account Key re-encrypted for a new password.+#[derive(Serialize, Zeroize, ZeroizeOnDrop)]+#[serde(rename_all = "camelCase")]+pub struct ReencryptedAccountKey {+ pub account_key: String,++ #[zeroize(skip)]+ pub new_encrypted_account_key: String,+}++/// Re-encrypt the Account Key under the KEK of a new unlock key (password change).+pub fn reencrypt_account_key(encrypted_account_key: &str, old_unlock_key_base64: &str, new_unlock_key_base64: &str) -> Result<ReencryptedAccountKey, KeyChainError> {+ let account_key = unwrap_account_key(encrypted_account_key, old_unlock_key_base64).map_err(|_| KeyChainError::UnlockKeyRejected)?;+ let new_encrypted_account_key = wrap_account_key(&account_key, new_unlock_key_base64).map_err(|e| KeyChainError::KeyChainUnreadable(e.to_string()))?;+ Ok(ReencryptedAccountKey { account_key: account_key.to_string(), new_encrypted_account_key })+}+#[cfg(test)]mod tests {use super::*;@@ -251,6 +273,39 @@ mod tests {assert!(matches!(result, Err(KeyChainError::KeyChainUnreadable(_))));}+ #[test]+ fn hierarchy_takes_a_host_key_pair_and_rejects_a_mismatched_one() {+ let unlock_key = generate_key_base64();+ let key_pair = generate_rsa_key_pair().unwrap();+ let hierarchy = create_account_key_hierarchy_with_key_pair(&unlock_key, &key_pair).unwrap();+ assert_eq!(hierarchy.account_keys.account_public_key, key_pair.public_key);+ assert_eq!(hierarchy.account_private_key, key_pair.private_key);++ let mismatched = RsaKeyPair { public_key: generate_rsa_key_pair().unwrap().public_key.clone(), private_key: key_pair.private_key.clone() };+ assert!(create_account_key_hierarchy_with_key_pair(&unlock_key, &mismatched).is_err());+ }++ #[test]+ fn reencrypted_account_key_opens_with_the_new_unlock_key_only() {+ let old_unlock_key = generate_key_base64();+ let new_unlock_key = generate_key_base64();+ let hierarchy = create_account_key_hierarchy(&old_unlock_key).unwrap();+ let blobs = &hierarchy.account_keys;++ let reencrypted = reencrypt_account_key(&blobs.encrypted_account_key, &old_unlock_key, &new_unlock_key).unwrap();+ let opened = open_account_key_chain(&new_unlock_key, &reencrypted.new_encrypted_account_key, &blobs.encrypted_vek, None).unwrap();+ assert_eq!(*opened.vault_encryption_key, hierarchy.vault_encryption_key);+ assert_eq!(*opened.account_key, reencrypted.account_key);+ assert!(open_account_key_chain(&old_unlock_key, &reencrypted.new_encrypted_account_key, &blobs.encrypted_vek, None).is_err());+ }++ #[test]+ fn reencrypt_rejects_a_wrong_old_unlock_key() {+ let hierarchy = create_account_key_hierarchy(&generate_key_base64()).unwrap();+ let result = reencrypt_account_key(&hierarchy.account_keys.encrypted_account_key, &generate_key_base64(), &generate_key_base64());+ assert_eq!(result.err(), Some(KeyChainError::UnlockKeyRejected));+ }+#[test]fn wrap_and_unwrap_round_trip() {let wrapping = generate_key_base64();diff --git a/core/rust/src/crypto/mod.rs b/core/rust/src/crypto/mod.rsindex 5d942a6a1..642b71ce4 100644--- a/core/rust/src/crypto/mod.rs+++ b/core/rust/src/crypto/mod.rs@@ -8,10 +8,10 @@ pub mod srp;pub use aes_gcm::{generate_key_base64, symmetric_decrypt, symmetric_decrypt_bytes, symmetric_encrypt, symmetric_encrypt_bytes};pub use key_chain::{- create_account_key_hierarchy, derive_kek, derive_kek_base64, derive_srp_password_hash, open_account_key_chain, unwrap_account_key, unwrap_key, wrap_account_key, wrap_key, AccountKeyBlobs,- AccountKeyHierarchy, KeyChainError, OpenedKeyChain, SrpInputError, ENCRYPTION_TYPE_ARGON2ID, ENCRYPTION_TYPE_ARGON2ID_HKDF,+ create_account_key_hierarchy, create_account_key_hierarchy_with_key_pair, derive_kek, derive_kek_base64, derive_srp_password_hash, open_account_key_chain, reencrypt_account_key, unwrap_account_key, unwrap_key, wrap_account_key, wrap_key, AccountKeyBlobs,+ AccountKeyHierarchy, KeyChainError, OpenedKeyChain, ReencryptedAccountKey, SrpInputError, ENCRYPTION_TYPE_ARGON2ID, ENCRYPTION_TYPE_ARGON2ID_HKDF,};-pub use rsa_oaep::{decrypt_with_private_key, encrypt_with_public_key, generate_rsa_key_pair, RsaKeyPair};+pub use rsa_oaep::{decrypt_with_private_key, encrypt_with_public_key, generate_rsa_key_pair, validate_rsa_key_pair, RsaKeyPair};pub use self::argon2::{argon2_derive_key, argon2_derive_key_bytes_from_settings, argon2_derive_key_from_settings, Argon2Error, Argon2Params};pub use self::srp::{diff --git a/core/rust/src/crypto/rsa_oaep.rs b/core/rust/src/crypto/rsa_oaep.rsindex 723c58c3e..7b39fb881 100644--- a/core/rust/src/crypto/rsa_oaep.rs+++ b/core/rust/src/crypto/rsa_oaep.rs@@ -56,6 +56,14 @@ pub fn generate_rsa_key_pair() -> VaultResult<RsaKeyPair> {Ok(RsaKeyPair { public_key: public_to_jwk(&public)?, private_key: private_to_jwk(&private)? })}+/// Check that a key pair generated elsewhere (WebCrypto) is a valid private key whose public half matches.+pub fn validate_rsa_key_pair(key_pair: &RsaKeyPair) -> VaultResult<()> {+ if private_from_jwk(&key_pair.private_key)?.to_public_key() != public_from_jwk(&key_pair.public_key)? {+ return Err(VaultError::General("RSA public key does not belong to the private key".to_string()));+ }+ Ok(())+}+/// Encrypt bytes for the holder of a JWK public key. Returns base64 ciphertext.pub fn encrypt_with_public_key(plaintext: &[u8], public_key_jwk: &str) -> VaultResult<String> {let public = public_from_jwk(public_key_jwk)?;