Skip to content

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

Add AAD to AES-GCM256 calls in Rust core (#2469)

Leendert de Borst1d4726761f4f
diff --git a/apps/web/tests/helpers/vault-tamper.ts b/apps/web/tests/helpers/vault-tamper.ts
index 01a3d2744..8080d4284 100644
--- a/apps/web/tests/helpers/vault-tamper.ts
+++ b/apps/web/tests/helpers/vault-tamper.ts
@@ -3,10 +3,9 @@
* how the app reports a vault it cannot open.
*/
-import { createHash, randomBytes } from 'node:crypto';
+import { createHash, randomBytes, webcrypto } from 'node:crypto';
import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
-import { EncryptionUtility } from '@aliasvault/client/crypto/EncryptionUtility';
import { getSyncableTableNames, vaultCodecCanonicalizeFromSqlite, vaultCodecGenerateManifestSalt, vaultCodecPackPayload } from '@aliasvault/client/rust/RustCore';
import './client-platform';
@@ -42,7 +41,19 @@ export async function writeManifestWithBrokenRow(apiUrl: string, user: TestUser,
manifest.tables[table] = [...(manifest.tables[table] ?? []), row];
const packed = await vaultCodecPackPayload(JSON.stringify(manifest));
- await writePersonalManifest(apiUrl, user, await EncryptionUtility.symmetricEncryptBytes(packed, user.vaultEncryptionKey));
+ await writePersonalManifest(apiUrl, user, await encryptManifest(packed, user.vaultEncryptionKey, manifestId));
+}
+
+/**
+ * Encrypt a packed manifest as the Rust core does: base64 of `IV | ciphertext | tag`, bound to the manifest's
+ * associated data from `core/rust/src/crypto/aad.rs`.
+ */
+async function encryptManifest(packed: Uint8Array, base64Key: string, manifestId: string): Promise<string> {
+ const key = await webcrypto.subtle.importKey('raw', Buffer.from(base64Key, 'base64'), 'AES-GCM', false, ['encrypt']);
+ const iv = randomBytes(12);
+ const additionalData = new TextEncoder().encode(`aliasvault/v1/manifest/${manifestId.trim().toLowerCase()}`);
+ const ciphertext = await webcrypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData }, key, packed);
+ return Buffer.concat([iv, Buffer.from(ciphertext)]).toString('base64');
}
/**
diff --git a/core/client/src/crypto/EncryptionUtility.ts b/core/client/src/crypto/EncryptionUtility.ts
index e4bdd550d..051206485 100644
--- a/core/client/src/crypto/EncryptionUtility.ts
+++ b/core/client/src/crypto/EncryptionUtility.ts
@@ -179,32 +179,6 @@ export class EncryptionUtility {
return new Uint8Array(decrypted);
}
- /**
- * Generates a random 256-bit Vault Encryption Key (VEK) as base64. The VEK encrypts the vault content and never
- * changes; it is stored server-side only in encryped form (encrypted with a KEK derived from an unlock method).
- */
- public static generateVaultEncryptionKey(): string {
- const vek = crypto.getRandomValues(new Uint8Array(32));
- return bytesToBase64(vek);
- }
-
- /**
- * Encrypts a VEK with a KEK using AES-256-GCM. Returns base64(IV | ciphertext | authTag).
- */
- public static async encryptVaultEncryptionKey(vekBase64: string, kekBase64: string): Promise<string> {
- const vekBytes = base64ToBytes(vekBase64);
- return this.symmetricEncryptBytes(vekBytes, kekBase64);
- }
-
- /**
- * Decrypts an encrypted VEK with a KEK. Returns the VEK as base64.
- */
- public static async decryptVaultEncryptionKey(encryptedVekBase64: string, kekBase64: string): Promise<string> {
- const encryptedBytes = base64ToBytes(encryptedVekBase64);
- const vekBytes = await this.symmetricDecryptBytes(encryptedBytes, kekBase64);
- return bytesToBase64(vekBytes);
- }
-
/**
* Generates a new RSA key pair for asymmetric encryption
*/
diff --git a/core/client/src/crypto/EncryptionUtility.vek.test.ts b/core/client/src/crypto/EncryptionUtility.vek.test.ts
deleted file mode 100644
index 3cde70f6b..000000000
--- a/core/client/src/crypto/EncryptionUtility.vek.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { describe, it, expect } from 'vitest';
-
-import EncryptionUtility from './EncryptionUtility';
-
-describe('EncryptionUtility VEK encrypt/decrypt (KEK/VEK model)', () => {
- it('generates a 256-bit VEK as base64', () => {
- const vek = EncryptionUtility.generateVaultEncryptionKey();
- expect(Buffer.from(vek, 'base64').length).toBe(32);
- });
-
- it('generates a unique VEK per call', () => {
- expect(EncryptionUtility.generateVaultEncryptionKey()).not.toBe(EncryptionUtility.generateVaultEncryptionKey());
- });
-
- it('round-trips a VEK through encrypt and decrypt with the same KEK', async () => {
- const vek = EncryptionUtility.generateVaultEncryptionKey();
- const kek = EncryptionUtility.generateVaultEncryptionKey();
-
- const encrypted = await EncryptionUtility.encryptVaultEncryptionKey(vek, kek);
- expect(encrypted).not.toBe(vek);
- // IV(12) + ciphertext(32) + tag(16) = 60 bytes.
- expect(Buffer.from(encrypted, 'base64').length).toBe(60);
-
- const decrypted = await EncryptionUtility.decryptVaultEncryptionKey(encrypted, kek);
- expect(decrypted).toBe(vek);
- });
-
- it('produces a different encrypted VEK per encrypt call (random IV)', async () => {
- const vek = EncryptionUtility.generateVaultEncryptionKey();
- const kek = EncryptionUtility.generateVaultEncryptionKey();
- expect(await EncryptionUtility.encryptVaultEncryptionKey(vek, kek)).not.toBe(await EncryptionUtility.encryptVaultEncryptionKey(vek, kek));
- });
-
- it('rejects decrypting with a wrong KEK (AES-GCM auth failure doubles as password check)', async () => {
- const vek = EncryptionUtility.generateVaultEncryptionKey();
- const kek = EncryptionUtility.generateVaultEncryptionKey();
- const wrongKek = EncryptionUtility.generateVaultEncryptionKey();
-
- const encrypted = await EncryptionUtility.encryptVaultEncryptionKey(vek, kek);
- await expect(EncryptionUtility.decryptVaultEncryptionKey(encrypted, wrongKek)).rejects.toThrow();
- });
-
- it('opens the full KEK to AK to VEK chain after a simulated password change (AK rewrap)', async () => {
- const vek = EncryptionUtility.generateVaultEncryptionKey();
- const accountKey = EncryptionUtility.generateVaultEncryptionKey();
- const oldKek = EncryptionUtility.generateVaultEncryptionKey();
- const newKek = EncryptionUtility.generateVaultEncryptionKey();
-
- const encryptedAccountKeyOld = await EncryptionUtility.encryptVaultEncryptionKey(accountKey, oldKek);
- const encryptedVek = await EncryptionUtility.encryptVaultEncryptionKey(vek, accountKey);
-
- const decryptedAccountKey = await EncryptionUtility.decryptVaultEncryptionKey(encryptedAccountKeyOld, oldKek);
- const encryptedAccountKeyNew = await EncryptionUtility.encryptVaultEncryptionKey(decryptedAccountKey, newKek);
-
- const accountKeyViaNewKek = await EncryptionUtility.decryptVaultEncryptionKey(encryptedAccountKeyNew, newKek);
- expect(accountKeyViaNewKek).toBe(accountKey);
- expect(await EncryptionUtility.decryptVaultEncryptionKey(encryptedVek, accountKeyViaNewKek)).toBe(vek);
- });
-
- it('encrypts and decrypts vault content with a VEK end-to-end', async () => {
- const vek = EncryptionUtility.generateVaultEncryptionKey();
- const ciphertext = await EncryptionUtility.symmetricEncrypt('vault-content', vek);
- expect(await EncryptionUtility.symmetricDecrypt(ciphertext, vek)).toBe('vault-content');
- });
-});
diff --git a/core/rust/Cargo.lock b/core/rust/Cargo.lock
index d7ccbb2f4..96ddeff23 100644
--- a/core/rust/Cargo.lock
+++ b/core/rust/Cargo.lock
@@ -57,6 +57,7 @@ dependencies = [
"getrandom 0.2.17",
"getrandom 0.3.4",
"hkdf",
+ "hmac",
"js-sys",
"mail-parser",
"num-bigint",
diff --git a/core/rust/Cargo.toml b/core/rust/Cargo.toml
index 119a38b87..5ade77007 100644
--- a/core/rust/Cargo.toml
+++ b/core/rust/Cargo.toml
@@ -53,6 +53,9 @@ argon2 = "0.5"
# HKDF-SHA256 (SRP/KEK derivation from unlock key)
hkdf = "0.12"
+# HMAC-SHA256 (per-manifest blob addresses)
+hmac = "0.12"
+
# AES-256-GCM (vault blobs, key wrapping) and RSA-OAEP-SHA256 (manifest key grants)
aes-gcm = "0.10"
rsa = "0.9"
diff --git a/core/rust/src/crypto/aad.rs b/core/rust/src/crypto/aad.rs
new file mode 100644
index 000000000..5dec5f01d
--- /dev/null
+++ b/core/rust/src/crypto/aad.rs
@@ -0,0 +1,63 @@
+//! Associated data for ciphertext to bind it to the slot it belongs in.
+
+/// Versions the AAD label scheme, not the API or the vault format: this should not be bumped to match either.
+const PREFIX: &str = "aliasvault/v1";
+
+/// The Account Key under the KEK.
+pub const ACCOUNT_KEY: &[u8] = b"aliasvault/v1/account-key";
+
+/// The personal manifest's VEK under the Account Key.
+pub const PERSONAL_VEK: &[u8] = b"aliasvault/v1/vek";
+
+/// The account RSA private key under the Account Key.
+pub const ACCOUNT_PRIVATE_KEY: &[u8] = b"aliasvault/v1/account-private-key";
+
+/// A manifest payload under its manifest's VEK.
+pub fn manifest(manifest_id: &str) -> Vec<u8> {
+ format!("{}/manifest/{}", PREFIX, normalize(manifest_id)).into_bytes()
+}
+
+/// A data bucket payload under its manifest's VEK.
+pub fn bucket(manifest_id: &str, category: &str) -> Vec<u8> {
+ format!("{}/bucket/{}/{}", PREFIX, normalize(manifest_id), category).into_bytes()
+}
+
+/// A shared manifest's name under its manifest's VEK.
+pub fn manifest_name(manifest_id: &str) -> Vec<u8> {
+ format!("{}/manifest-name/{}", PREFIX, normalize(manifest_id)).into_bytes()
+}
+
+/// A blob's bytes under its own blob key.
+pub fn blob_data(manifest_id: &str, hash: &str) -> Vec<u8> {
+ format!("{}/blob/{}/{}", PREFIX, normalize(manifest_id), normalize(hash)).into_bytes()
+}
+
+/// A blob key under its manifest's VEK.
+pub fn blob_key(manifest_id: &str, hash: &str) -> Vec<u8> {
+ format!("{}/blob-key/{}/{}", PREFIX, normalize(manifest_id), normalize(hash)).into_bytes()
+}
+
+/// The RSA-OAEP label of a grant: a manifest's VEK encrypted for one recipient key. The recipient is not in the label,
+/// since only the matching private key can decrypt the grant anyway.
+pub fn grant(manifest_id: &str) -> Vec<u8> {
+ format!("{}/grant/{}", PREFIX, normalize(manifest_id)).into_bytes()
+}
+
+fn normalize(id: &str) -> String {
+ id.to_ascii_lowercase()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn labels_are_stable_and_case_insensitive_on_ids() {
+ assert_eq!(manifest("0A1B2C3D-0000-0000-0000-000000000001"), b"aliasvault/v1/manifest/0a1b2c3d-0000-0000-0000-000000000001".to_vec());
+ assert_eq!(bucket("0a1b2c3d-0000-0000-0000-000000000001", "Logos"), b"aliasvault/v1/bucket/0a1b2c3d-0000-0000-0000-000000000001/Logos".to_vec());
+ assert_eq!(blob_data("ID", "ABCD"), b"aliasvault/v1/blob/id/abcd".to_vec());
+ assert_eq!(blob_key("ID", "ABCD"), b"aliasvault/v1/blob-key/id/abcd".to_vec());
+ assert_eq!(manifest_name("ID"), b"aliasvault/v1/manifest-name/id".to_vec());
+ assert_eq!(grant("ID"), b"aliasvault/v1/grant/id".to_vec());
+ }
+}
diff --git a/core/rust/src/crypto/aes_gcm.rs b/core/rust/src/crypto/aes_gcm.rs
index ac1a67019..a8f50812a 100644
--- a/core/rust/src/crypto/aes_gcm.rs
+++ b/core/rust/src/crypto/aes_gcm.rs
@@ -18,14 +18,20 @@ pub fn generate_key_base64() -> String {
base64_encode(&key[..])
}
-/// Encrypt bytes with a base64 key. Returns base64 of `IV | ciphertext | tag`.
+/// Encrypt bytes with a base64 key and no associated data, for local storage and the legacy format. Returns base64
+/// of `IV | ciphertext | tag`.
pub fn symmetric_encrypt_bytes(plaintext: &[u8], key_base64: &str) -> VaultResult<String> {
+ symmetric_encrypt_bytes_with_aad(plaintext, key_base64, &[])
+}
+
+/// Encrypt bytes bound to `aad`, which decryption must present as-is. Returns base64 of `IV | ciphertext | tag`.
+pub fn symmetric_encrypt_bytes_with_aad(plaintext: &[u8], key_base64: &str, aad: &[u8]) -> VaultResult<String> {
let cipher = cipher_for(key_base64)?;
let mut iv = [0u8; IV_LENGTH];
fill_random(&mut iv);
let ciphertext = cipher
- .encrypt(Nonce::from_slice(&iv), Payload { msg: plaintext, aad: &[] })
+ .encrypt(Nonce::from_slice(&iv), Payload { msg: plaintext, aad })
.map_err(|_| VaultError::General("AES-GCM encryption failed".to_string()))?;
let mut combined = Vec::with_capacity(IV_LENGTH + ciphertext.len());
@@ -34,15 +40,20 @@ pub fn symmetric_encrypt_bytes(plaintext: &[u8], key_base64: &str) -> VaultResul
Ok(base64_encode(&combined))
}
-/// Decrypt `IV | ciphertext | tag` bytes with a base64 key.
+/// Decrypt `IV | ciphertext | tag` bytes with a base64 key and no associated data.
pub fn symmetric_decrypt_bytes(iv_and_ciphertext: &[u8], key_base64: &str) -> VaultResult<Vec<u8>> {
+ symmetric_decrypt_bytes_with_aad(iv_and_ciphertext, key_base64, &[])
+}
+
+/// Decrypt `IV | ciphertext | tag` bytes that were encrypted bound to `aad`.
+pub fn symmetric_decrypt_bytes_with_aad(iv_and_ciphertext: &[u8], key_base64: &str, aad: &[u8]) -> VaultResult<Vec<u8>> {
if iv_and_ciphertext.len() < IV_LENGTH {
return Err(VaultError::General("AES-GCM ciphertext is too short".to_string()));
}
let cipher = cipher_for(key_base64)?;
let (iv, ciphertext) = iv_and_ciphertext.split_at(IV_LENGTH);
cipher
- .decrypt(Nonce::from_slice(iv), Payload { msg: ciphertext, aad: &[] })
+ .decrypt(Nonce::from_slice(iv), Payload { msg: ciphertext, aad })
.map_err(|_| VaultError::General("AES-GCM decryption failed (wrong key or corrupt data)".to_string()))
}
@@ -59,8 +70,18 @@ pub fn symmetric_decrypt(base64_ciphertext: &str, key_base64: &str) -> VaultResu
if base64_ciphertext.is_empty() {
return Ok(String::new());
}
+ symmetric_decrypt_with_aad(base64_ciphertext, key_base64, &[])
+}
+
+/// Encrypt a UTF-8 string bound to `aad`. An empty string is encrypted like any other value.
+pub fn symmetric_encrypt_with_aad(plaintext: &str, key_base64: &str, aad: &[u8]) -> VaultResult<String> {
+ symmetric_encrypt_bytes_with_aad(plaintext.as_bytes(), key_base64, aad)
+}
+
+/// Decrypt a base64 `IV | ciphertext | tag` string bound to `aad` into UTF-8. An empty ciphertext is an error.
+pub fn symmetric_decrypt_with_aad(base64_ciphertext: &str, key_base64: &str, aad: &[u8]) -> VaultResult<String> {
let bytes = base64_decode(base64_ciphertext)?;
- let plaintext = symmetric_decrypt_bytes(&bytes, key_base64)?;
+ let plaintext = symmetric_decrypt_bytes_with_aad(&bytes, key_base64, aad)?;
match String::from_utf8(plaintext) {
Ok(text) => Ok(text),
Err(error) => {
@@ -104,6 +125,20 @@ mod tests {
assert!(symmetric_encrypt("x", "dG9vc2hvcnQ=").is_err());
}
+ #[test]
+ fn associated_data_must_match() {
+ let key = generate_key_base64();
+ let encrypted = symmetric_encrypt_with_aad("secret", &key, b"slot-a").unwrap();
+ assert_eq!(symmetric_decrypt_with_aad(&encrypted, &key, b"slot-a").unwrap(), "secret");
+ assert!(symmetric_decrypt_with_aad(&encrypted, &key, b"slot-b").is_err());
+ assert!(symmetric_decrypt(&encrypted, &key).is_err(), "a bound ciphertext does not open without its associated data");
+
+ let empty = symmetric_encrypt_with_aad("", &key, b"slot-a").unwrap();
+ assert!(!empty.is_empty(), "an empty string is encrypted, not passed through");
+ assert_eq!(symmetric_decrypt_with_aad(&empty, &key, b"slot-a").unwrap(), "");
+ assert!(symmetric_decrypt_with_aad("", &key, b"slot-a").is_err());
+ }
+
#[test]
fn layout_is_iv_then_ciphertext_then_tag() {
let key = generate_key_base64();
diff --git a/core/rust/src/crypto/key_chain.rs b/core/rust/src/crypto/key_chain.rs
index ca77580fa..e56b525a7 100644
--- a/core/rust/src/crypto/key_chain.rs
+++ b/core/rust/src/crypto/key_chain.rs
@@ -8,7 +8,8 @@ use std::fmt;
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::aad;
+use super::aes_gcm::{generate_key_base64, symmetric_decrypt_bytes_with_aad, symmetric_decrypt_with_aad, symmetric_encrypt_bytes_with_aad, symmetric_encrypt_with_aad};
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;
@@ -95,26 +96,31 @@ pub fn derive_kek_base64(unlock_key_base64: &str) -> VaultResult<Zeroizing<Strin
/// Wrap the Account Key with the KEK derived from an unlock key.
pub fn wrap_account_key(account_key_base64: &str, unlock_key_base64: &str) -> VaultResult<String> {
- wrap_key(account_key_base64, &derive_kek_base64(unlock_key_base64)?)
+ wrap_key(account_key_base64, &derive_kek_base64(unlock_key_base64)?, aad::ACCOUNT_KEY)
}
/// Unwrap the Account Key with the KEK derived from an unlock key. Fails when the unlock key is not the one it was
/// wrapped for (wrong password).
pub fn unwrap_account_key(encrypted_account_key: &str, unlock_key_base64: &str) -> VaultResult<Zeroizing<String>> {
- unwrap_key(encrypted_account_key, &derive_kek_base64(unlock_key_base64)?)
+ unwrap_key(encrypted_account_key, &derive_kek_base64(unlock_key_base64)?, aad::ACCOUNT_KEY)
}
-/// Wrap a base64 key with another base64 key. Returns base64 of `IV | ciphertext | tag`.
-pub fn wrap_key(key_base64: &str, wrapping_key_base64: &str) -> VaultResult<String> {
- symmetric_encrypt_bytes(&Zeroizing::new(base64_decode(key_base64)?), wrapping_key_base64)
+/// Wrap a base64 key with another base64 key, bound to `aad` (see [`aad`]). Returns base64 of `IV | ciphertext | tag`.
+pub fn wrap_key(key_base64: &str, wrapping_key_base64: &str, aad: &[u8]) -> VaultResult<String> {
+ symmetric_encrypt_bytes_with_aad(&Zeroizing::new(base64_decode(key_base64)?), wrapping_key_base64, aad)
}
-/// Unwrap a wrapped key. Returns the key as base64.
-pub fn unwrap_key(wrapped_key_base64: &str, wrapping_key_base64: &str) -> VaultResult<Zeroizing<String>> {
- let raw = Zeroizing::new(symmetric_decrypt_bytes(&base64_decode(wrapped_key_base64)?, wrapping_key_base64)?);
+/// Unwrap a key wrapped bound to `aad`. Returns the key as base64.
+pub fn unwrap_key(wrapped_key_base64: &str, wrapping_key_base64: &str, aad: &[u8]) -> VaultResult<Zeroizing<String>> {
+ let raw = Zeroizing::new(symmetric_decrypt_bytes_with_aad(&base64_decode(wrapped_key_base64)?, wrapping_key_base64, aad)?);
Ok(Zeroizing::new(base64_encode(&raw[..])))
}
+/// Decrypt the account private key (a JWK) with the Account Key.
+pub fn open_account_private_key(encrypted_account_private_key: &str, account_key_base64: &str) -> VaultResult<String> {
+ symmetric_decrypt_with_aad(encrypted_account_private_key, account_key_base64, aad::ACCOUNT_PRIVATE_KEY)
+}
+
/// Why a key chain did not open.
#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Error))]
@@ -142,15 +148,15 @@ pub struct OpenedKeyChain {
/// Open a key chain with a stored key: the Account Key, or an unlock key stored before the switch to the Account Key.
pub fn open_account_key_chain(stored_key: &str, encrypted_account_key: &str, encrypted_vek: &str, encrypted_account_private_key: Option<&str>) -> Result<OpenedKeyChain, KeyChainError> {
- let (account_key, vault_encryption_key) = match unwrap_key(encrypted_vek, stored_key) {
+ let (account_key, vault_encryption_key) = match unwrap_key(encrypted_vek, stored_key, aad::PERSONAL_VEK) {
Ok(vek) => (Zeroizing::new(stored_key.to_string()), vek),
Err(_) => {
let account_key = unwrap_account_key(encrypted_account_key, stored_key).map_err(|_| KeyChainError::UnlockKeyRejected)?;
- let vek = unwrap_key(encrypted_vek, &account_key).map_err(|e| KeyChainError::KeyChainUnreadable(e.to_string()))?;
+ let vek = unwrap_key(encrypted_vek, &account_key, aad::PERSONAL_VEK).map_err(|e| KeyChainError::KeyChainUnreadable(e.to_string()))?;
(account_key, vek)
}
};
- let account_private_key = encrypted_account_private_key.filter(|e| !e.is_empty()).and_then(|e| symmetric_decrypt(e, &account_key).ok()).map(Zeroizing::new);
+ let account_private_key = encrypted_account_private_key.filter(|e| !e.is_empty()).and_then(|e| open_account_private_key(e, &account_key).ok()).map(Zeroizing::new);
Ok(OpenedKeyChain { vault_encryption_key, account_key, account_private_key })
}
@@ -167,9 +173,9 @@ pub fn create_account_key_hierarchy_with_key_pair(unlock_key_base64: &str, key_p
let account_keys = AccountKeyBlobs {
encrypted_account_key: wrap_account_key(&account_key, unlock_key_base64)?,
- encrypted_vek: wrap_key(&vault_encryption_key, &account_key)?,
+ encrypted_vek: wrap_key(&vault_encryption_key, &account_key, aad::PERSONAL_VEK)?,
account_public_key: key_pair.public_key.clone(),
- encrypted_account_private_key: symmetric_encrypt(&key_pair.private_key, &account_key)?,
+ encrypted_account_private_key: symmetric_encrypt_with_aad(&key_pair.private_key, &account_key, aad::ACCOUNT_PRIVATE_KEY)?,
};
Ok(AccountKeyHierarchy { vault_encryption_key, account_private_key: key_pair.private_key.clone(), account_keys })
@@ -237,8 +243,8 @@ mod tests {
fn account_key_is_not_wrapped_with_the_raw_unlock_key() {
let unlock_key = generate_key_base64();
let hierarchy = create_account_key_hierarchy(&unlock_key).unwrap();
- assert!(unwrap_key(&hierarchy.account_keys.encrypted_account_key, &unlock_key).is_err());
- assert!(unwrap_key(&hierarchy.account_keys.encrypted_account_key, &derive_kek_base64(&unlock_key).unwrap()).is_ok());
+ assert!(unwrap_key(&hierarchy.account_keys.encrypted_account_key, &unlock_key, aad::ACCOUNT_KEY).is_err());
+ assert!(unwrap_key(&hierarchy.account_keys.encrypted_account_key, &derive_kek_base64(&unlock_key).unwrap(), aad::ACCOUNT_KEY).is_ok());
}
#[test]
@@ -268,7 +274,7 @@ mod tests {
fn chain_with_a_foreign_vek_is_unreadable() {
let unlock_key = generate_key_base64();
let hierarchy = create_account_key_hierarchy(&unlock_key).unwrap();
- let foreign_vek = wrap_key(&generate_key_base64(), &generate_key_base64()).unwrap();
+ let foreign_vek = wrap_key(&generate_key_base64(), &generate_key_base64(), aad::PERSONAL_VEK).unwrap();
let result = open_account_key_chain(&unlock_key, &hierarchy.account_keys.encrypted_account_key, &foreign_vek, None);
assert!(matches!(result, Err(KeyChainError::KeyChainUnreadable(_))));
}
@@ -310,6 +316,22 @@ mod tests {
fn wrap_and_unwrap_round_trip() {
let wrapping = generate_key_base64();
let key = generate_key_base64();
- assert_eq!(*unwrap_key(&wrap_key(&key, &wrapping).unwrap(), &wrapping).unwrap(), key);
+ assert_eq!(*unwrap_key(&wrap_key(&key, &wrapping, b"a").unwrap(), &wrapping, b"a").unwrap(), key);
+ assert!(unwrap_key(&wrap_key(&key, &wrapping, b"a").unwrap(), &wrapping, b"b").is_err());
+ }
+
+ #[test]
+ fn chain_ciphertexts_do_not_open_in_each_others_slot() {
+ let unlock_key = generate_key_base64();
+ let hierarchy = create_account_key_hierarchy(&unlock_key).unwrap();
+ let blobs = &hierarchy.account_keys;
+ let account_key = unwrap_account_key(&blobs.encrypted_account_key, &unlock_key).unwrap();
+
+ // The Account Key wrap served as the VEK wrap, under the KEK: refused, not read as the VEK.
+ let swapped = open_account_key_chain(&unlock_key, &blobs.encrypted_account_key, &blobs.encrypted_account_key, None);
+ assert!(matches!(swapped, Err(KeyChainError::KeyChainUnreadable(_))));
+ assert!(unwrap_key(&blobs.encrypted_vek, &account_key, aad::ACCOUNT_KEY).is_err());
+ assert!(open_account_private_key(&blobs.encrypted_account_private_key, &account_key).is_ok());
+ assert!(symmetric_decrypt_with_aad(&blobs.encrypted_account_private_key, &account_key, aad::PERSONAL_VEK).is_err());
}
}
diff --git a/core/rust/src/crypto/mod.rs b/core/rust/src/crypto/mod.rs
index 642b71ce4..5e2f62853 100644
--- a/core/rust/src/crypto/mod.rs
+++ b/core/rust/src/crypto/mod.rs
@@ -1,17 +1,23 @@
//! Cryptographic modules used by the clients.
+pub mod aad;
pub mod aes_gcm;
pub mod argon2;
pub mod key_chain;
pub mod rsa_oaep;
pub mod srp;
-pub use aes_gcm::{generate_key_base64, symmetric_decrypt, symmetric_decrypt_bytes, symmetric_encrypt, symmetric_encrypt_bytes};
+pub use aes_gcm::{
+ generate_key_base64, symmetric_decrypt, symmetric_decrypt_bytes, symmetric_decrypt_bytes_with_aad, symmetric_decrypt_with_aad, symmetric_encrypt, symmetric_encrypt_bytes, symmetric_encrypt_bytes_with_aad,
+ symmetric_encrypt_with_aad,
+};
pub use key_chain::{
- 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,
+ create_account_key_hierarchy, create_account_key_hierarchy_with_key_pair, derive_kek, derive_kek_base64, derive_srp_password_hash, open_account_key_chain, open_account_private_key, 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, validate_rsa_key_pair, RsaKeyPair};
+pub use rsa_oaep::{
+ decrypt_with_private_key, decrypt_with_private_key_and_label, encrypt_with_public_key, encrypt_with_public_key_and_label, 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.rs
index 7b39fb881..79c1aea86 100644
--- a/core/rust/src/crypto/rsa_oaep.rs
+++ b/core/rust/src/crypto/rsa_oaep.rs
@@ -66,24 +66,45 @@ pub fn validate_rsa_key_pair(key_pair: &RsaKeyPair) -> VaultResult<()> {
/// 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)?;
- let ciphertext = public
- .encrypt(&mut rand_core06::OsRng, Oaep::new::<Sha256>(), plaintext)
- .map_err(|e| VaultError::General(format!("RSA-OAEP encryption failed: {}", e)))?;
- Ok(base64_encode(&ciphertext))
+ encrypt(plaintext, public_key_jwk, Oaep::new::<Sha256>())
+}
+
+/// Encrypt bytes for the holder of a JWK public key under an OAEP label, which decryption must present as-is.
+pub fn encrypt_with_public_key_and_label(plaintext: &[u8], public_key_jwk: &str, label: &[u8]) -> VaultResult<String> {
+ encrypt(plaintext, public_key_jwk, Oaep::new_with_label::<Sha256, _>(label_text(label)?))
}
/// Decrypt base64 ciphertext with a JWK private key.
pub fn decrypt_with_private_key(base64_ciphertext: &str, private_key_jwk: &str) -> VaultResult<Vec<u8>> {
+ decrypt(base64_ciphertext, private_key_jwk, Oaep::new::<Sha256>())
+}
+
+/// Decrypt base64 ciphertext that was encrypted under an OAEP label.
+pub fn decrypt_with_private_key_and_label(base64_ciphertext: &str, private_key_jwk: &str, label: &[u8]) -> VaultResult<Vec<u8>> {
+ decrypt(base64_ciphertext, private_key_jwk, Oaep::new_with_label::<Sha256, _>(label_text(label)?))
+}
+
+fn encrypt(plaintext: &[u8], public_key_jwk: &str, padding: Oaep) -> VaultResult<String> {
+ let public = public_from_jwk(public_key_jwk)?;
+ let ciphertext = public.encrypt(&mut rand_core06::OsRng, padding, plaintext).map_err(|e| VaultError::General(format!("RSA-OAEP encryption failed: {}", e)))?;
+ Ok(base64_encode(&ciphertext))
+}
+
+fn decrypt(base64_ciphertext: &str, private_key_jwk: &str, padding: Oaep) -> VaultResult<Vec<u8>> {
let private = private_from_jwk(private_key_jwk)?;
let ciphertext = base64_decode(base64_ciphertext)?;
// Blinded: plain `decrypt` runs the exponentiation on the ciphertext as given, which leaks timing an
// attacker who can submit chosen ciphertexts turns into key recovery (RUSTSEC-2023-0071, Marvin attack).
private
- .decrypt_blinded(&mut rand_core06::OsRng, Oaep::new::<Sha256>(), &ciphertext)
+ .decrypt_blinded(&mut rand_core06::OsRng, padding, &ciphertext)
.map_err(|_| VaultError::General("RSA-OAEP decryption failed (wrong key or corrupt data)".to_string()))
}
+/// The `rsa` crate takes the OAEP label as text; every label this crate uses is ASCII.
+fn label_text(label: &[u8]) -> VaultResult<String> {
+ String::from_utf8(label.to_vec()).map_err(|_| VaultError::General("RSA-OAEP label must be UTF-8".to_string()))
+}
+
fn public_from_jwk(jwk: &str) -> VaultResult<RsaPublicKey> {
let parsed = parse_jwk(jwk)?;
RsaPublicKey::new(field(&parsed.n)?, field(&parsed.e)?).map_err(|e| VaultError::General(format!("Invalid RSA public key: {}", e)))
@@ -155,3 +176,17 @@ fn private_to_jwk(private: &RsaPrivateKey) -> VaultResult<String> {
};
serde_json::to_string(&jwk).map_err(VaultError::from)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn label_must_match() {
+ let pair = generate_rsa_key_pair().unwrap();
+ let ciphertext = encrypt_with_public_key_and_label(b"vek", &pair.public_key, b"grant/a").unwrap();
+ assert_eq!(decrypt_with_private_key_and_label(&ciphertext, &pair.private_key, b"grant/a").unwrap(), b"vek");
+ assert!(decrypt_with_private_key_and_label(&ciphertext, &pair.private_key, b"grant/b").is_err());
+ assert!(decrypt_with_private_key(&ciphertext, &pair.private_key).is_err(), "a labelled ciphertext does not open without its label");
+ }
+}
diff --git a/core/rust/src/vault_codec/canonicalize.rs b/core/rust/src/vault_codec/canonicalize.rs
index ebefdd831..256d4bc41 100644
--- a/core/rust/src/vault_codec/canonicalize.rs
+++ b/core/rust/src/vault_codec/canonicalize.rs
@@ -6,7 +6,7 @@
//! - each bucketed table is split out into a data bucket per manifest: rows route by their own `ManifestId`.
//! - skip-tables are dropped;
//! - the two blob columns (`Logos.FileData`, `Attachments.Blob`) have their bytes extracted into a
-//! content-addressed blob map (hash = `sha256(salt ‖ bytes)`) and the cell replaced with
+//! content-addressed blob map (hash = `HMAC-SHA256(salt, bytes)`) and the cell replaced with
//! `{ "__blobRef": hash, "__blobKind": kind }`;
//! - every other column (including non-blob `{ "__b64" }` inline bytes) is copied as-is.
diff --git a/core/rust/src/vault_codec/hash.rs b/core/rust/src/vault_codec/hash.rs
index 39c6c9e19..36ec8ae4a 100644
--- a/core/rust/src/vault_codec/hash.rs
+++ b/core/rust/src/vault_codec/hash.rs
@@ -12,6 +12,7 @@
//! order; primitives as serde_json renders them, which matches `JSON.stringify` for the escaping and
//! integer cases that occur in vault data, so a hash computed here agrees with one a client computed.
+use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};
use crate::common::encoding::{hex_decode, hex_encode_lower, uuid_from_bytes};
@@ -71,14 +72,13 @@ pub fn content_hash(value: &serde_json::Value) -> String {
sha256_hex(canonical_json(value).as_bytes())
}
-/// Per-manifest salted blob hash `sha256(salt_bytes ‖ plaintext_bytes)`, lowercase hex.
+/// Per-manifest blob address `HMAC-SHA256(key = salt_bytes, plaintext_bytes)`, lowercase hex.
/// A missing or malformed salt is an error, since hashing without it would break the per-manifest separation.
pub fn salted_blob_hash(bytes: &[u8], manifest_salt: &str) -> VaultResult<String> {
let salt_bytes = hex_decode(manifest_salt).filter(|salt| !salt.is_empty()).ok_or_else(|| VaultError::General("manifest salt is missing or not valid hex".to_string()))?;
- let mut hasher = Sha256::new();
- hasher.update(&salt_bytes);
- hasher.update(bytes);
- Ok(hex_encode_lower(&hasher.finalize()))
+ let mut mac = Hmac::<Sha256>::new_from_slice(&salt_bytes).expect("HMAC takes a key of any length");
+ mac.update(bytes);
+ Ok(hex_encode_lower(&mac.finalize().into_bytes()))
}
#[cfg(test)]
@@ -114,12 +114,10 @@ mod tests {
assert!(matches!(&id[19..20], "8" | "9" | "a" | "b"));
}
+ /// Known-answer vector: a changed output re-addresses every stored blob. Never regenerate it.
#[test]
fn salted_hash_is_stable() {
- // Pinned vector: salt "00ff", bytes [1,2,3].
- let h = salted_blob_hash(&[1, 2, 3], "00ff").unwrap();
- // sha256(00 ff 01 02 03)
- assert_eq!(h, sha256_hex(&[0x00, 0xff, 0x01, 0x02, 0x03]));
- assert_eq!(h.len(), 64);
+ // HMAC-SHA256(key = 00 ff, message = 01 02 03).
+ assert_eq!(salted_blob_hash(&[1, 2, 3], "00ff").unwrap(), "4307c7b0faa3e0b307fc467d8f3c3db3cd548860c7555955b2f3f00fe70cbea1");
}
}
diff --git a/core/rust/src/vault_sync/blob_keys.rs b/core/rust/src/vault_sync/blob_keys.rs
index 0226a5b09..02e2ea774 100644
--- a/core/rust/src/vault_sync/blob_keys.rs
+++ b/core/rust/src/vault_sync/blob_keys.rs
@@ -2,7 +2,7 @@
use serde::{Deserialize, Serialize};
-use crate::crypto;
+use crate::crypto::{self, aad};
use crate::common::encoding::base64_decode;
use crate::common::error::VaultResult;
@@ -16,47 +16,67 @@ pub(crate) struct EncryptedBlob {
pub encrypted_blob_key: String,
}
-/// Encrypt blob bytes with a fresh blob key, and that key with the manifest's VEK.
-pub(crate) fn encrypt_blob(bytes: &[u8], vek: &str) -> VaultResult<EncryptedBlob> {
+/// Encrypt blob bytes with a fresh blob key, and that key with the manifest's VEK, both bound to the blob's address.
+pub(crate) fn encrypt_blob(bytes: &[u8], vek: &str, manifest_id: &str, hash: &str) -> VaultResult<EncryptedBlob> {
let blob_key = zeroize::Zeroizing::new(crypto::generate_key_base64());
- Ok(EncryptedBlob { encrypted_data_base64: crypto::symmetric_encrypt_bytes(bytes, &blob_key)?, encrypted_blob_key: crypto::wrap_key(&blob_key, vek)? })
+ Ok(EncryptedBlob {
+ encrypted_data_base64: crypto::symmetric_encrypt_bytes_with_aad(bytes, &blob_key, &aad::blob_data(manifest_id, hash))?,
+ encrypted_blob_key: crypto::wrap_key(&blob_key, vek, &aad::blob_key(manifest_id, hash))?,
+ })
}
-/// Decrypt a stored blob with the manifest's VEK.
-pub(crate) fn decrypt_blob(blob: &EncryptedBlob, vek: &str) -> VaultResult<Vec<u8>> {
- let blob_key = crypto::unwrap_key(&blob.encrypted_blob_key, vek)?;
- crypto::symmetric_decrypt_bytes(&base64_decode(&blob.encrypted_data_base64)?, &blob_key)
+/// Decrypt the blob stored at `(manifest_id, hash)` with the manifest's VEK.
+pub(crate) fn decrypt_blob(blob: &EncryptedBlob, vek: &str, manifest_id: &str, hash: &str) -> VaultResult<Vec<u8>> {
+ let blob_key = crypto::unwrap_key(&blob.encrypted_blob_key, vek, &aad::blob_key(manifest_id, hash))?;
+ crypto::symmetric_decrypt_bytes_with_aad(&base64_decode(&blob.encrypted_data_base64)?, &blob_key, &aad::blob_data(manifest_id, hash))
}
#[cfg(test)]
mod tests {
use super::*;
+ const MANIFEST: &str = "0a1b2c3d-0000-0000-0000-000000000001";
+ const HASH: &str = "aa11";
+
#[test]
fn a_blob_opens_with_the_vek_through_its_own_key() {
let vek = crypto::generate_key_base64();
- let blob = encrypt_blob(&[1, 2, 3, 4], &vek).unwrap();
+ let blob = encrypt_blob(&[1, 2, 3, 4], &vek, MANIFEST, HASH).unwrap();
- assert_eq!(decrypt_blob(&blob, &vek).unwrap(), vec![1, 2, 3, 4]);
+ assert_eq!(decrypt_blob(&blob, &vek, MANIFEST, HASH).unwrap(), vec![1, 2, 3, 4]);
assert!(crypto::symmetric_decrypt_bytes(&base64_decode(&blob.encrypted_data_base64).unwrap(), &vek).is_err(), "the bytes are not encrypted with the VEK itself");
- assert!(decrypt_blob(&blob, &crypto::generate_key_base64()).is_err());
+ assert!(decrypt_blob(&blob, &crypto::generate_key_base64(), MANIFEST, HASH).is_err());
+ }
+
+ #[test]
+ fn a_blob_does_not_open_at_another_address() {
+ let vek = crypto::generate_key_base64();
+ let blob = encrypt_blob(&[1, 2, 3, 4], &vek, MANIFEST, HASH).unwrap();
+ assert!(decrypt_blob(&blob, &vek, MANIFEST, "bb22").is_err(), "served under another hash");
+ assert!(decrypt_blob(&blob, &vek, "0a1b2c3d-0000-0000-0000-000000000002", HASH).is_err(), "served under another manifest");
+
+ // The blob key of one blob next to the bytes of another: neither half opens the other.
+ let other = encrypt_blob(&[5, 6], &vek, MANIFEST, "bb22").unwrap();
+ let mixed = EncryptedBlob { encrypted_data_base64: other.encrypted_data_base64, encrypted_blob_key: blob.encrypted_blob_key };
+ assert!(decrypt_blob(&mixed, &vek, MANIFEST, HASH).is_err());
}
#[test]
fn changing_the_vek_only_encrypts_the_blob_key_again() {
let (old_vek, new_vek) = (crypto::generate_key_base64(), crypto::generate_key_base64());
- let blob = encrypt_blob(&[9; 64], &old_vek).unwrap();
+ let blob = encrypt_blob(&[9; 64], &old_vek, MANIFEST, HASH).unwrap();
- let blob_key = crypto::unwrap_key(&blob.encrypted_blob_key, &old_vek).unwrap();
- let rekeyed = EncryptedBlob { encrypted_data_base64: blob.encrypted_data_base64.clone(), encrypted_blob_key: crypto::wrap_key(&blob_key, &new_vek).unwrap() };
+ let key_aad = aad::blob_key(MANIFEST, HASH);
+ let blob_key = crypto::unwrap_key(&blob.encrypted_blob_key, &old_vek, &key_aad).unwrap();
+ let rekeyed = EncryptedBlob { encrypted_data_base64: blob.encrypted_data_base64.clone(), encrypted_blob_key: crypto::wrap_key(&blob_key, &new_vek, &key_aad).unwrap() };
- assert_eq!(decrypt_blob(&rekeyed, &new_vek).unwrap(), vec![9; 64]);
- assert!(decrypt_blob(&rekeyed, &old_vek).is_err());
+ assert_eq!(decrypt_blob(&rekeyed, &new_vek, MANIFEST, HASH).unwrap(), vec![9; 64]);
+ assert!(decrypt_blob(&rekeyed, &old_vek, MANIFEST, HASH).is_err());
}
#[test]
fn a_cached_blob_reads_back_as_it_was_written() {
- let blob = encrypt_blob(&[5], &crypto::generate_key_base64()).unwrap();
+ let blob = encrypt_blob(&[5], &crypto::generate_key_base64(), MANIFEST, HASH).unwrap();
let read: EncryptedBlob = serde_json::from_value(serde_json::to_value(&blob).unwrap()).unwrap();
assert_eq!(read, blob);
}
diff --git a/core/rust/src/vault_sync/engine.rs b/core/rust/src/vault_sync/engine.rs
index 00ff7a16b..6fc96904a 100644
--- a/core/rust/src/vault_sync/engine.rs
+++ b/core/rust/src/vault_sync/engine.rs
@@ -355,7 +355,7 @@ async fn refresh_manifest_names(ctx: &mut Ctx, status: &StatusResponse, needs_pu
for record in records.values_mut() {
let Some(served) = ctx.served_manifest_names.get(&id_key(&record.manifest_id)).filter(|served| record.encrypted_name.as_ref() != Some(*served)).cloned() else { continue };
let Some(vek) = keys::open_shared_manifest_vek(ctx, record).await? else { continue };
- match pull::open_manifest_name(&served, &vek) {
+ match pull::open_manifest_name(&served, &record.manifest_id, &vek) {
Some(name) => drop(opened.insert(id_key(&record.manifest_id), name)),
None => ctx.warn(format!("[Sharing] The name of shared manifest {} did not open with its key.", record.manifest_id)).await,
}
diff --git a/core/rust/src/vault_sync/keys.rs b/core/rust/src/vault_sync/keys.rs
index 69fb6f4be..2d40ba36b 100644
--- a/core/rust/src/vault_sync/keys.rs
+++ b/core/rust/src/vault_sync/keys.rs
@@ -77,9 +77,14 @@ pub(crate) fn resolve_grant_private_key(ctx: &Ctx, public_key: &str) -> Option<S
ctx.account_private_key.clone()
}
-/// Decrypt an RSA-OAEP encrypted manifest VEK.
-pub(crate) fn decrypt_manifest_vek(encrypted_vek: &str, private_key_jwk: &str) -> SyncResult<String> {
- let plaintext = crypto::decrypt_with_private_key(encrypted_vek, private_key_jwk)?;
+/// Encrypt a manifest's VEK for one recipient key, bound to the manifest (see [`crypto::aad::grant`]).
+pub(crate) fn encrypt_manifest_vek(manifest_vek: &str, manifest_id: &str, recipient_public_key_jwk: &str) -> SyncResult<String> {
+ Ok(crypto::encrypt_with_public_key_and_label(manifest_vek.as_bytes(), recipient_public_key_jwk, &crypto::aad::grant(manifest_id))?)
+}
+
+/// Decrypt a manifest's VEK from a grant made out to this private key for that manifest.
+pub(crate) fn decrypt_manifest_vek(encrypted_vek: &str, manifest_id: &str, private_key_jwk: &str) -> SyncResult<String> {
+ let plaintext = crypto::decrypt_with_private_key_and_label(encrypted_vek, private_key_jwk, &crypto::aad::grant(manifest_id))?;
String::from_utf8(plaintext).map_err(|_| SyncError::Other("Decrypted manifest key is not valid text".to_string()))
}
@@ -93,7 +98,7 @@ pub(crate) async fn open_shared_manifest_vek(ctx: &Ctx, record: &SharedManifestD
ctx.warn(format!("[Sharing] This session holds no account private key that opens the grant on manifest {}; leaving it closed.", record.manifest_id)).await;
return Ok(None);
};
- match decrypt_manifest_vek(&record.encrypted_vek, &private_key) {
+ match decrypt_manifest_vek(&record.encrypted_vek, &record.manifest_id, &private_key) {
Ok(vek) => Ok(Some(vek)),
Err(error) => {
ctx.warn(format!("[Sharing] Failed to unwrap the key of manifest {}; leaving it closed. {}", record.manifest_id, error)).await;
@@ -236,7 +241,7 @@ async fn switch_to_vek(ctx: &mut Ctx, old_key: &str, vek: &str) -> SyncResult<()
/// Open the account private key with the Account Key and stage it for the grant flows of this run.
async fn stage_account_private_key(ctx: &mut Ctx, account_key: &str, encrypted_private_key: Option<&str>) {
let Some(encrypted) = encrypted_private_key.filter(|e| !e.is_empty()) else { return };
- match crypto::symmetric_decrypt(encrypted, account_key) {
+ match crypto::open_account_private_key(encrypted, account_key) {
Ok(private_key) => ctx.account_private_key = Some(private_key),
Err(error) => ctx.warn(format!("[VaultSync] The cached account private key did not open; shared grants stay closed. {}", error)).await,
}
diff --git a/core/rust/src/vault_sync/pull.rs b/core/rust/src/vault_sync/pull.rs
index 916d78445..4e920f3cc 100644
--- a/core/rust/src/vault_sync/pull.rs
+++ b/core/rust/src/vault_sync/pull.rs
@@ -88,8 +88,8 @@ fn base64_chars(size_bytes: i64) -> usize {
((size_bytes.max(0) as usize).div_ceil(3)) * 4
}
-/// Verify a ciphertext against the server's hash, decrypt it and open it via the codec.
-fn verify_decrypt_unpack(base64_ciphertext: &str, vek: &str, expected_ciphertext_hash: Option<&str>, label: &str) -> SyncResult<String> {
+/// Verify a ciphertext against the server's hash, decrypt it bound to `aad` and open it via the codec.
+fn verify_decrypt_unpack(base64_ciphertext: &str, vek: &str, aad: &[u8], expected_ciphertext_hash: Option<&str>, label: &str) -> SyncResult<String> {
if let Some(expected) = expected_ciphertext_hash.filter(|hash| !hash.is_empty()) {
if vault_codec::compute_ciphertext_hash(base64_ciphertext) != expected {
return Err(SyncError::ServerVaultUnreadable(format!("{} ciphertext hash mismatch, refusing to load (possible storage corruption)", label)));
@@ -97,7 +97,7 @@ fn verify_decrypt_unpack(base64_ciphertext: &str, vek: &str, expected_ciphertext
}
let unreadable = |e: crate::common::error::VaultError| SyncError::ServerVaultUnreadable(format!("{}: {}", label, e));
let encrypted = crate::common::encoding::base64_decode(base64_ciphertext).map_err(unreadable)?;
- let plain = crypto::symmetric_decrypt_bytes(&encrypted, vek).map_err(unreadable)?;
+ let plain = crypto::symmetric_decrypt_bytes_with_aad(&encrypted, vek, aad).map_err(unreadable)?;
match vault_codec::unpack_versioned_payload(&plain).map_err(unreadable)? {
UnpackedPayload::Readable(payload_json) => Ok(payload_json),
UnpackedPayload::NewerFormat(version) => Err(newer_format(label, version)),
@@ -199,7 +199,7 @@ pub(crate) async fn open_manifests_and_record_sync_state(ctx: &mut Ctx, snapshot
let (encrypted_vek, encryption_public_key, algorithm) = grant_of(dto).ok_or_else(|| SyncError::Snapshot(format!("shared manifest {} carries no grant this account can re-open, refusing to assemble", entry.manifest_id)))?;
let encrypted_name = served_encrypted_name(ctx, &previous_records, &entry.manifest_id);
if let Some(ciphertext) = &encrypted_name {
- match open_manifest_name(ciphertext, &manifest_key) {
+ match open_manifest_name(ciphertext, &entry.manifest_id, &manifest_key) {
Some(name) => drop(manifest_names.insert(id_key(&entry.manifest_id), name)),
None => ctx.warn(format!("[V2Pull] The name of shared manifest {} did not open with its key; leaving it unnamed.", entry.manifest_id)).await,
}
@@ -247,9 +247,14 @@ fn served_encrypted_name(ctx: &Ctx, previous: &HashMap<String, SharedManifestDto
.or_else(|| previous.values().find(|record| ids_equal(&record.manifest_id, manifest_id)).and_then(|record| record.encrypted_name.clone()))
}
-/// Decrypt a manifest's name with the manifest's own key.
-pub(crate) fn open_manifest_name(ciphertext: &str, manifest_key: &str) -> Option<String> {
- crypto::symmetric_decrypt(ciphertext, manifest_key).ok().filter(|name| !name.is_empty())
+/// Decrypt a shared manifest's name with the manifest's own key.
+pub(crate) fn open_manifest_name(ciphertext: &str, manifest_id: &str, manifest_key: &str) -> Option<String> {
+ crypto::symmetric_decrypt_with_aad(ciphertext, manifest_key, &crypto::aad::manifest_name(manifest_id)).ok().filter(|name| !name.is_empty())
+}
+
+/// Encrypt a shared manifest's name with the manifest's own key.
+pub(crate) fn encrypt_manifest_name(name: &str, manifest_id: &str, manifest_key: &str) -> SyncResult<String> {
+ Ok(crypto::symmetric_encrypt_with_aad(name, manifest_key, &crypto::aad::manifest_name(manifest_id))?)
}
/// Commit a snapshot's revision maps as the local believed-current revisions, manifests and buckets together.
@@ -270,7 +275,7 @@ async fn open_data_buckets(ctx: &Ctx, snapshot: &GetResponse, resolved: &[Resolv
let Some(blob) = dto.blob.as_deref().filter(|b| !b.is_empty()) else { continue };
let key = key_by_manifest.get(dto.manifest_id.as_str()).ok_or_else(|| SyncError::Snapshot(format!("data bucket \"{}\" belongs to manifest {}, which this vault did not open, refusing to assemble", dto.category, dto.manifest_id)))?;
let label = format!("\"{}\" bucket of manifest {}", dto.category, dto.manifest_id);
- let bucket_json = verify_decrypt_unpack(blob, key, dto.ciphertext_hash.as_deref(), &label)?;
+ let bucket_json = verify_decrypt_unpack(blob, key, &crypto::aad::bucket(&dto.manifest_id, &dto.category), dto.ciphertext_hash.as_deref(), &label)?;
let bucket: DataBucket = serde_json::from_str(&bucket_json)?;
ensure_readable(bucket.schema_version, &label)?;
if !ids_equal(&bucket.manifest_id, &dto.manifest_id) || bucket.category != dto.category {
@@ -327,8 +332,8 @@ async fn download_referenced_blobs(ctx: &Ctx, resolved: &[ResolvedManifest], fal
ctx.warn(format!("[V2Sync] Referenced {} blob {} was not served; its row stays not loaded and keeps the reference.", reference.category, reference.hash)).await;
continue;
};
- let key = owners.get(&reference.hash).map(|o| o.vek.as_str()).unwrap_or(fallback_vek);
- match blob_keys::decrypt_blob(encrypted, key) {
+ let (key, manifest_id) = owners.get(&reference.hash).map(|o| (o.vek.as_str(), o.manifest_id.as_str())).unwrap_or((fallback_vek, ""));
+ match blob_keys::decrypt_blob(encrypted, key, manifest_id, &reference.hash) {
Ok(bytes) => {
blob_map.insert(reference.hash.clone(), bytes);
pruned_cache.insert(reference.hash.clone(), encrypted.clone());
@@ -367,7 +372,7 @@ pub(crate) async fn materialize_to_sqlite(ctx: &mut Ctx, manifests: &[Manifest],
fn open_manifest(dto: &ManifestDto, vek: &str, is_personal: bool) -> SyncResult<ResolvedManifest> {
let label = if is_personal { "manifest".to_string() } else { format!("shared manifest {}", dto.manifest_id) };
- let manifest_json = verify_decrypt_unpack(dto.blob.as_deref().unwrap_or(""), vek, dto.ciphertext_hash.as_deref(), &label)?;
+ let manifest_json = verify_decrypt_unpack(dto.blob.as_deref().unwrap_or(""), vek, &crypto::aad::manifest(&dto.manifest_id), dto.ciphertext_hash.as_deref(), &label)?;
let manifest: Manifest = serde_json::from_str(&manifest_json)?;
ensure_readable(manifest.schema_version, &label)?;
if !ids_equal(&manifest.manifest_id, &dto.manifest_id) {
@@ -416,5 +421,5 @@ async fn resolve_granted_vek(ctx: &Ctx, dto: &ManifestDto) -> SyncResult<String>
return Err(SyncError::Snapshot(format!("shared manifest {} grants its VEK under an unsupported algorithm \"{}\" (newer server?), refusing to assemble", dto.manifest_id, algorithm)));
}
let private_key = keys::resolve_grant_private_key(ctx, &public_key).ok_or_else(|| SyncError::Snapshot(format!("this session holds no account private key that opens the grant on shared manifest {}, refusing to assemble", dto.manifest_id)))?;
- keys::decrypt_manifest_vek(&encrypted_vek, &private_key).map_err(|e| SyncError::ServerVaultUnreadable(format!("failed to decrypt the VEK of shared manifest {}, refusing to assemble: {}", dto.manifest_id, e)))
+ keys::decrypt_manifest_vek(&encrypted_vek, &dto.manifest_id, &private_key).map_err(|e| SyncError::ServerVaultUnreadable(format!("failed to decrypt the VEK of shared manifest {}, refusing to assemble: {}", dto.manifest_id, e)))
}
diff --git a/core/rust/src/vault_sync/push.rs b/core/rust/src/vault_sync/push.rs
index 047eaad90..c437d19a3 100644
--- a/core/rust/src/vault_sync/push.rs
+++ b/core/rust/src/vault_sync/push.rs
@@ -424,10 +424,10 @@ struct EncryptedPayload {
hash: String,
}
-/// Pack and encrypt a JSON payload under `key`, logging its size at every stage.
-async fn encrypt_payload(ctx: &Ctx, label: &str, plaintext: &str, key: &str) -> SyncResult<EncryptedPayload> {
+/// Pack and encrypt a JSON payload under `key` bound to `aad`, logging its size at every stage.
+async fn encrypt_payload(ctx: &Ctx, label: &str, plaintext: &str, key: &str, aad: &[u8]) -> SyncResult<EncryptedPayload> {
let packed = vault_codec::pack_payload(plaintext)?;
- let ciphertext = crypto::symmetric_encrypt_bytes(&packed, key)?;
+ let ciphertext = crypto::symmetric_encrypt_bytes_with_aad(&packed, key, aad)?;
ctx.log(format!("[V2Push] {}: raw {} > compressed {} > encrypted {}.", label, format_kb(plaintext.len()), format_kb(packed.len()), format_kb(ciphertext.len()))).await;
let hash = vault_codec::compute_ciphertext_hash(&ciphertext);
Ok(EncryptedPayload { ciphertext, hash })
@@ -579,7 +579,7 @@ async fn encrypt_changed_buckets(ctx: &Ctx, buckets: &[DataBucket], candidates:
if !validation.ok {
return Err(SyncError::UploadRejected(vec![format!("{} validation failed: {}. {}", label, validation.failed_rules.join(", "), validation.message).trim().to_string()]));
}
- let encrypted = encrypt_payload(ctx, &label, &plaintext, bucket_key).await?;
+ let encrypted = encrypt_payload(ctx, &label, &plaintext, bucket_key, &crypto::aad::bucket(&bucket.manifest_id, &bucket.category)).await?;
writes.push(BucketWrite { manifest_id: bucket.manifest_id.clone(), category: bucket.category.clone(), blob: encrypted.ciphertext, ciphertext_hash: encrypted.hash, current_revision: baselines.bucket_revision(bucket) });
written.insert(fingerprint_key, fingerprint);
}
@@ -606,7 +606,7 @@ async fn encrypt_changed_manifests(ctx: &Ctx, candidates: &[Candidate<'_>], base
ctx.warn(format!("[V2Push] {} failed validation ({}), dropping it from this write.", label, validation.failed_rules.join(", "))).await;
continue;
}
- let encrypted = encrypt_payload(ctx, &label, &plaintext, &candidate.vek).await?;
+ let encrypted = encrypt_payload(ctx, &label, &plaintext, &candidate.vek, &crypto::aad::manifest(&candidate.record.manifest_id)).await?;
// Publish the public half of this manifest's mail delivery keypair; only admins may publish a shared one.
let may_publish = candidate.record.is_personal || candidate.record.can_administer;
@@ -733,7 +733,7 @@ async fn upload_blobs(ctx: &Ctx, blobs: &UploadBlobs, hashes: &[String], overwri
let mut dtos = Vec::new();
for hash in hashes {
let entry = &blobs.entries[&hash];
- let encrypted = blob_keys::encrypt_blob(&entry.bytes, &entry.vek)?;
+ let encrypted = blob_keys::encrypt_blob(&entry.bytes, &entry.vek, &manifest_id, &hash)?;
encrypted_blobs.insert(hash.clone(), encrypted.clone());
dtos.push(BlobDto { hash, category: entry.kind.clone(), encrypted_data_base64: encrypted.encrypted_data_base64, encrypted_blob_key: encrypted.encrypted_blob_key });
}
@@ -766,7 +766,7 @@ async fn push_data_bucket_only_internal(ctx: &Ctx, bucket: &DataBucket, vek: &st
ctx.log(format!("[V2Push] {} unchanged versus server baseline, skipping upload.", label)).await;
return Ok((PushStatus::Ok, baselines.bucket_revision(bucket)));
}
- let encrypted = encrypt_payload(ctx, &label, &plaintext, vek).await?;
+ let encrypted = encrypt_payload(ctx, &label, &plaintext, vek, &crypto::aad::bucket(&bucket.manifest_id, &bucket.category)).await?;
let current_revision = baselines.bucket_revision(bucket);
let payload = VaultWriteRequest {
diff --git a/core/rust/src/vault_sync/sharing.rs b/core/rust/src/vault_sync/sharing.rs
index f480ada9c..e8dc364b2 100644
--- a/core/rust/src/vault_sync/sharing.rs
+++ b/core/rust/src/vault_sync/sharing.rs
@@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
use super::errors::{SyncError, SyncResult};
use super::state::{self, Ctx};
use super::types::{Db, FailureFields, SharedManifestDto, SharingOperationResult, SharingParams, ALGORITHM_RSA_OAEP_SHA256};
-use super::{db, engine, http, keys};
+use super::{db, engine, http, keys, pull};
use crate::crypto;
use crate::vault_codec;
use crate::vault_model::{id_key, ids_equal};
@@ -191,10 +191,9 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {
}
let manifest_vek = crypto::generate_key_base64();
- let self_encrypted_vek = crypto::encrypt_with_public_key(manifest_vek.as_bytes(), &self_public_key)?;
- // The server keeps the name for every member to fetch, encrypted with the manifest's own key.
- let encrypted_name = crypto::symmetric_encrypt(&name, &manifest_vek)?;
let requested_id = db::new_id();
+ let self_encrypted_vek = keys::encrypt_manifest_vek(&manifest_vek, &requested_id, &self_public_key)?;
+ let encrypted_name = pull::encrypt_manifest_name(&name, &requested_id, &manifest_vek)?;
let response: CreateSharedManifestResponse = http::post(
&ctx.host,
&format!("Groups/{}/manifests", group.group_id),
@@ -203,6 +202,9 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {
)
.await?;
let manifest_id = response.manifest_id;
+ if !ids_equal(&manifest_id, &requested_id) {
+ return Err(SyncError::Other(format!("The server created shared manifest {} instead of the requested {}, whose key and name are bound to the requested id", manifest_id, requested_id)));
+ }
let mut records = keys::shared_manifest_records(ctx).await?;
records.insert(
@@ -252,7 +254,7 @@ async fn update_shared_manifest(ctx: &mut Ctx) -> Outcome {
let manifest_vek = keys::open_shared_manifest_vek(ctx, &record).await?.ok_or_else(|| SyncError::Other("The key of the shared manifest did not open".to_string()))?;
// The server decides who may change a shared manifest; it only ever sees the name encrypted.
- let encrypted_name = crypto::symmetric_encrypt(&name, &manifest_vek)?;
+ let encrypted_name = pull::encrypt_manifest_name(&name, &record.manifest_id, &manifest_vek)?;
http::post_no_content(&ctx.host, &format!("Groups/{}/manifests/{}", target.group_id, record.manifest_id), &UpdateSharedManifestRequest { encrypted_name: Some(&encrypted_name) }).await?;
if let Some(held) = records.values_mut().find(|held| ids_equal(&held.manifest_id, &manifest_id)) {
@@ -301,7 +303,7 @@ async fn invite_to_shared_manifest(ctx: &mut Ctx) -> Outcome {
let grant = ManifestGrant {
recipient_user_id: member.user_id.clone(),
recipient_public_key_id,
- encrypted_vek: crypto::encrypt_with_public_key(manifest_vek.as_bytes(), &recipient_public_key)?,
+ encrypted_vek: keys::encrypt_manifest_vek(&manifest_vek, &manifest.manifest_id, &recipient_public_key)?,
encrypted_name: name.map(|name| crypto::encrypt_with_public_key(name.as_bytes(), &recipient_public_key)).transpose()?,
};
diff --git a/core/rust/src/vault_sync/tests/mod.rs b/core/rust/src/vault_sync/tests/mod.rs
index 958daef2c..6be6be85d 100644
--- a/core/rust/src/vault_sync/tests/mod.rs
+++ b/core/rust/src/vault_sync/tests/mod.rs
@@ -76,12 +76,12 @@ fn snapshot_of(conn: &rusqlite::Connection, vek: &str, revision: i64, salt: &str
})
.unwrap();
let manifest_json = serde_json::to_string(&canonicalized.manifests[0].manifest).unwrap();
- let blob = crypto::symmetric_encrypt_bytes(&vault_codec::pack_payload(&manifest_json).unwrap(), vek).unwrap();
+ let blob = crypto::symmetric_encrypt_bytes_with_aad(&vault_codec::pack_payload(&manifest_json).unwrap(), vek, &crypto::aad::manifest(PERSONAL_MANIFEST_ID)).unwrap();
let ciphertext_hash = vault_codec::compute_ciphertext_hash(&blob);
let mut buckets = Vec::new();
for bucket in &canonicalized.data_buckets {
let bucket_json = serde_json::to_string(bucket).unwrap();
- let bucket_blob = crypto::symmetric_encrypt_bytes(&vault_codec::pack_payload(&bucket_json).unwrap(), vek).unwrap();
+ let bucket_blob = crypto::symmetric_encrypt_bytes_with_aad(&vault_codec::pack_payload(&bucket_json).unwrap(), vek, &crypto::aad::bucket(&bucket.manifest_id, &bucket.category)).unwrap();
buckets.push(json!({ "manifestId": bucket.manifest_id, "category": bucket.category, "blob": bucket_blob, "ciphertextHash": vault_codec::compute_ciphertext_hash(&bucket_blob), "revision": revision }));
}
let status = json!({
@@ -187,7 +187,7 @@ fn new_account_starts_from_an_empty_vault_and_writes_its_first_revision() {
// The written manifest opens with the VEK and names the personal manifest.
let blob = body["manifests"][0]["manifestBlob"].as_str().unwrap();
- let plain = crypto::symmetric_decrypt_bytes(&crate::common::encoding::base64_decode(blob).unwrap(), &vek).unwrap();
+ let plain = crypto::symmetric_decrypt_bytes_with_aad(&crate::common::encoding::base64_decode(blob).unwrap(), &vek, &crypto::aad::manifest(PERSONAL_MANIFEST_ID)).unwrap();
let manifest: Value = serde_json::from_str(&vault_codec::unpack_payload(&plain).unwrap()).unwrap();
assert_eq!(manifest["manifestId"], PERSONAL_MANIFEST_ID);
assert_eq!(manifest["manifestSalt"], host.state[state::VAULT_MANIFEST_SALT]);
@@ -315,7 +315,7 @@ fn dirty_client_pushes_only_what_changed() {
// The written manifest decrypts with the VEK and carries both items.
let blob = body["manifests"][0]["manifestBlob"].as_str().unwrap();
- let plain = crypto::symmetric_decrypt_bytes(&crate::common::encoding::base64_decode(blob).unwrap(), &vek).unwrap();
+ let plain = crypto::symmetric_decrypt_bytes_with_aad(&crate::common::encoding::base64_decode(blob).unwrap(), &vek, &crypto::aad::manifest(PERSONAL_MANIFEST_ID)).unwrap();
let manifest: Value = serde_json::from_str(&vault_codec::unpack_payload(&plain).unwrap()).unwrap();
assert_eq!(manifest["tables"]["Items"].as_array().unwrap().len(), 2);
}
@@ -363,8 +363,9 @@ fn pushed_blobs_name_the_manifest_that_owns_them() {
// The bytes are encrypted with the blob's own key, which travels encrypted with the VEK.
let ciphertext = crate::common::encoding::base64_decode(upload["blobs"][0]["encryptedDataBase64"].as_str().unwrap()).unwrap();
assert!(crypto::symmetric_decrypt_bytes(&ciphertext, &vek).is_err());
- let blob_key = crypto::unwrap_key(upload["blobs"][0]["encryptedBlobKey"].as_str().unwrap(), &vek).unwrap();
- assert_eq!(crypto::symmetric_decrypt_bytes(&ciphertext, &blob_key).unwrap(), vec![1u8, 2, 3, 4]);
+ let hash = upload["blobs"][0]["hash"].as_str().unwrap();
+ let blob_key = crypto::unwrap_key(upload["blobs"][0]["encryptedBlobKey"].as_str().unwrap(), &vek, &crypto::aad::blob_key(PERSONAL_MANIFEST_ID, hash)).unwrap();
+ assert_eq!(crypto::symmetric_decrypt_bytes_with_aad(&ciphertext, &blob_key, &crypto::aad::blob_data(PERSONAL_MANIFEST_ID, hash)).unwrap(), vec![1u8, 2, 3, 4]);
}
#[test]
@@ -433,7 +434,7 @@ fn push_creates_and_publishes_a_missing_personal_delivery_key() {
// The keypair travels inside the manifest, so the other devices get the private half.
let blob = write["manifests"][0]["manifestBlob"].as_str().unwrap();
- let plain = crypto::symmetric_decrypt_bytes(&crate::common::encoding::base64_decode(blob).unwrap(), &vek).unwrap();
+ let plain = crypto::symmetric_decrypt_bytes_with_aad(&crate::common::encoding::base64_decode(blob).unwrap(), &vek, &crypto::aad::manifest(PERSONAL_MANIFEST_ID)).unwrap();
let manifest: Value = serde_json::from_str(&vault_codec::unpack_payload(&plain).unwrap()).unwrap();
assert_eq!(manifest["tables"]["EncryptionKeys"].as_array().unwrap().len(), 1);
@@ -509,7 +510,7 @@ fn outdated_push_merges_the_server_change_and_retries() {
assert_eq!(posts.last().unwrap().body.as_ref().unwrap()["manifests"][0]["currentRevision"], 8);
let merged: Value = {
let blob = posts.last().unwrap().body.as_ref().unwrap()["manifests"][0]["manifestBlob"].as_str().unwrap();
- let plain = crypto::symmetric_decrypt_bytes(&crate::common::encoding::base64_decode(blob).unwrap(), &vek).unwrap();
+ let plain = crypto::symmetric_decrypt_bytes_with_aad(&crate::common::encoding::base64_decode(blob).unwrap(), &vek, &crypto::aad::manifest(PERSONAL_MANIFEST_ID)).unwrap();
serde_json::from_str(&vault_codec::unpack_payload(&plain).unwrap()).unwrap()
};
assert_eq!(merged["tables"]["Items"].as_array().unwrap().len(), 3);
@@ -577,7 +578,8 @@ fn outdated_bucket_only_push_merges_the_server_bucket_instead_of_overwriting_it(
let accepted = posts.last().unwrap().body.as_ref().unwrap();
assert_eq!(accepted["buckets"][0]["currentRevision"], 8);
let bucket: Value = {
- let plain = crypto::symmetric_decrypt_bytes(&crate::common::encoding::base64_decode(accepted["buckets"][0]["blob"].as_str().unwrap()).unwrap(), &vek).unwrap();
+ let aad = crypto::aad::bucket(accepted["buckets"][0]["manifestId"].as_str().unwrap(), accepted["buckets"][0]["category"].as_str().unwrap());
+ let plain = crypto::symmetric_decrypt_bytes_with_aad(&crate::common::encoding::base64_decode(accepted["buckets"][0]["blob"].as_str().unwrap()).unwrap(), &vek, &aad).unwrap();
serde_json::from_str(&vault_codec::unpack_payload(&plain).unwrap()).unwrap()
};
assert_eq!(bucket["tables"]["ItemStats"].as_array().unwrap().len(), 2, "the other device's stats must survive: {}", bucket);
@@ -667,7 +669,7 @@ fn manifest_migration_generates_the_key_hierarchy_and_pushes() {
let posts: Vec<_> = host.requests_to("Vault").into_iter().filter(|r| r.method == "POST").collect();
let body = posts[0].body.as_ref().unwrap();
assert!(body["migration"]["accountKeys"]["encryptedAccountKey"].is_string(), "the migration push carries the key hierarchy");
- assert!(crypto::unwrap_key(body["migration"]["accountKeys"]["encryptedAccountKey"].as_str().unwrap(), &unlock_key).is_err(), "the legacy vault key does not wrap the Account Key directly");
+ assert!(crypto::unwrap_key(body["migration"]["accountKeys"]["encryptedAccountKey"].as_str().unwrap(), &unlock_key, crypto::aad::ACCOUNT_KEY).is_err(), "the legacy vault key does not wrap the Account Key directly");
let opened = crypto::open_account_key_chain(&unlock_key, body["migration"]["accountKeys"]["encryptedAccountKey"].as_str().unwrap(), body["migration"]["accountKeys"]["encryptedVek"].as_str().unwrap(), None).unwrap();
assert_eq!(*opened.vault_encryption_key, new_key);
assert!(host.state.contains_key(state::ENCRYPTED_ACCOUNT_KEY));
@@ -802,7 +804,7 @@ fn manifest_migration_of_a_dirty_pre_format_session_keeps_the_local_vault() {
let posts: Vec<_> = host.requests_to("Vault").into_iter().filter(|r| r.method == "POST").collect();
let body = posts[0].body.as_ref().unwrap();
assert_eq!(body["manifests"][0]["currentRevision"], 3, "the baseline still comes from the server");
- let manifest_json = crypto::symmetric_decrypt_bytes(&crate::common::encoding::base64_decode(body["manifests"][0]["manifestBlob"].as_str().unwrap()).unwrap(), &host.vault_key).unwrap();
+ let manifest_json = crypto::symmetric_decrypt_bytes_with_aad(&crate::common::encoding::base64_decode(body["manifests"][0]["manifestBlob"].as_str().unwrap()).unwrap(), &host.vault_key, &crypto::aad::manifest(PERSONAL_MANIFEST_ID)).unwrap();
assert!(vault_codec::unpack_payload(&manifest_json).unwrap().contains("Local item"), "the push carries the local changes");
}
@@ -964,7 +966,7 @@ fn resolve_vault_key_refuses_a_key_that_does_not_open_the_chain() {
fn resolve_vault_key_tells_an_unreadable_chain_apart_from_a_wrong_password() {
let unlock_key = crypto::generate_key_base64();
let mut hierarchy = crypto::create_account_key_hierarchy(&unlock_key).unwrap();
- hierarchy.account_keys.encrypted_vek = crypto::wrap_key(&crypto::generate_key_base64(), &crypto::generate_key_base64()).unwrap();
+ hierarchy.account_keys.encrypted_vek = crypto::wrap_key(&crypto::generate_key_base64(), &crypto::generate_key_base64(), crypto::aad::PERSONAL_VEK).unwrap();
let mut host = TestHost::new(&unlock_key);
host.respond("GET", "VaultKey/Password", vault_key_body(&hierarchy));
diff --git a/core/rust/src/vault_sync/tests/unloaded_blobs.rs b/core/rust/src/vault_sync/tests/unloaded_blobs.rs
index 802330220..3b0d56180 100644
--- a/core/rust/src/vault_sync/tests/unloaded_blobs.rs
+++ b/core/rust/src/vault_sync/tests/unloaded_blobs.rs
@@ -50,12 +50,12 @@ fn snapshot(conn: &rusqlite::Connection, vek: &str, blob_key: &str, salt: &str,
})
.unwrap();
let entry = &canonicalized.manifests[0];
- let blob = crypto::symmetric_encrypt_bytes(&vault_codec::pack_payload(&serde_json::to_string(&entry.manifest).unwrap()).unwrap(), vek).unwrap();
+ let blob = crypto::symmetric_encrypt_bytes_with_aad(&vault_codec::pack_payload(&serde_json::to_string(&entry.manifest).unwrap()).unwrap(), vek, &crypto::aad::manifest(PERSONAL_MANIFEST_ID)).unwrap();
let blobs: Vec<ServerBlob> = entry
.blobs
.iter()
.map(|(hash, b)| {
- let encrypted = blob_keys::encrypt_blob(&crate::common::encoding::base64_decode(&b.bytes_base64).unwrap(), blob_key).unwrap();
+ let encrypted = blob_keys::encrypt_blob(&crate::common::encoding::base64_decode(&b.bytes_base64).unwrap(), blob_key, PERSONAL_MANIFEST_ID, hash).unwrap();
ServerBlob { hash: hash.clone(), kind: b.kind.clone(), ciphertext: encrypted.encrypted_data_base64, encrypted_blob_key: encrypted.encrypted_blob_key }
})
.collect();