Skip to content

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

Update Rust zeroize logic and wrap terminology

Leendert de Borst3db02cac078b
diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rs
index c368aa7ff..26445ba91 100644
--- a/core/rust/src/bindings/uniffi_api.rs
+++ b/core/rust/src/bindings/uniffi_api.rs
@@ -184,7 +184,8 @@ pub fn vault_codec_unpack_payload(plain_bytes: Vec<u8>) -> Result<String, VaultE
/// Derive a 32-byte key from a password and salt (UTF-8 bytes) with Argon2id under the `EncryptionSettings` JSON (required).
#[uniffi::export]
pub fn argon2_derive_key(password: String, salt: String, encryption_settings: String) -> Result<Vec<u8>, Argon2Error> {
- crate::crypto::argon2::argon2_derive_key_from_settings(&password, &salt, &encryption_settings)
+ let password = zeroize::Zeroizing::new(password);
+ crate::crypto::argon2::argon2_derive_key_from_settings(&password, &salt, &encryption_settings).map(|mut key| std::mem::take(&mut *key))
}
/// AES-256-GCM decrypt a base64 `IV | ciphertext | tag` string into UTF-8 with a base64 key; empty stays empty.
@@ -224,7 +225,7 @@ pub fn account_signing_key_fingerprint(encrypted_signing_private_key: String, ac
crate::crypto::account_signing_key_fingerprint(&encrypted_signing_private_key, &account_key)
}
-/// A fresh random salt for a new PIN wrap.
+/// A fresh random salt for a new PIN key.
#[uniffi::export]
pub fn pin_generate_salt() -> Vec<u8> {
crate::crypto::pin_generate_salt()
@@ -233,13 +234,15 @@ pub fn pin_generate_salt() -> Vec<u8> {
/// Encrypt `secret` with a key derived from the PIN and salt. Returns `IV | ciphertext | tag`.
#[uniffi::export]
pub fn pin_encrypt(pin: String, salt: Vec<u8>, secret: Vec<u8>) -> Result<Vec<u8>, VaultError> {
+ let (pin, secret) = (zeroize::Zeroizing::new(pin), zeroize::Zeroizing::new(secret));
crate::crypto::pin_encrypt(&pin, &salt, &secret)
}
-/// Decrypt a PIN wrap. Fails for a wrong PIN.
+/// Decrypt a key encrypted with the PIN. Fails for a wrong PIN.
#[uniffi::export]
pub fn pin_decrypt(pin: String, salt: Vec<u8>, encrypted: Vec<u8>) -> Result<Vec<u8>, VaultError> {
- crate::crypto::pin_decrypt(&pin, &salt, &encrypted)
+ let pin = zeroize::Zeroizing::new(pin);
+ crate::crypto::pin_decrypt(&pin, &salt, &encrypted).map(|mut secret| std::mem::take(&mut *secret))
}
/// Whether a stored failed-attempt count means the PIN is locked.
diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rs
index c89cade88..e1445674c 100644
--- a/core/rust/src/bindings/wasm.rs
+++ b/core/rust/src/bindings/wasm.rs
@@ -194,8 +194,9 @@ pub fn extract_email_attachment_js(source: &[u8], index: usize, detached_body: O
/// Derive a 32-byte key from a password and salt (UTF-8 bytes) with Argon2id under the `EncryptionSettings` JSON (required).
#[wasm_bindgen(js_name = argon2DeriveKey)]
-pub fn argon2_derive_key_js(password: &str, salt: &str, encryption_settings: &str) -> Result<Vec<u8>, JsValue> {
- crate::crypto::argon2::argon2_derive_key_from_settings(password, salt, encryption_settings).map_err(js_err)
+pub fn argon2_derive_key_js(password: String, salt: &str, encryption_settings: &str) -> Result<js_sys::Uint8Array, JsValue> {
+ let password = zeroize::Zeroizing::new(password);
+ crate::crypto::argon2::argon2_derive_key_from_settings(&password, salt, encryption_settings).map(|key| js_sys::Uint8Array::from(&key[..])).map_err(js_err)
}
/// AES-256-GCM decrypt a base64 `IV | ciphertext | tag` string into UTF-8 with a base64 key; empty stays empty.
@@ -258,7 +259,7 @@ pub fn decrypt_manifest_invitation_name_js(encrypted_name: &str, manifest_id: &s
crate::crypto::decrypt_manifest_invitation_name(encrypted_name, manifest_id, private_key_jwk).map_err(js_err)
}
-/// A fresh random salt for a new PIN wrap.
+/// A fresh random salt for a new PIN key.
#[wasm_bindgen(js_name = pinGenerateSalt)]
pub fn pin_generate_salt_js() -> Vec<u8> {
crate::crypto::pin_generate_salt()
@@ -266,14 +267,16 @@ pub fn pin_generate_salt_js() -> Vec<u8> {
/// Encrypt `secret` with a key derived from the PIN and salt. Returns `IV | ciphertext | tag`.
#[wasm_bindgen(js_name = pinEncrypt)]
-pub fn pin_encrypt_js(pin: &str, salt: &[u8], secret: &[u8]) -> Result<Vec<u8>, JsValue> {
- crate::crypto::pin_encrypt(pin, salt, secret).map_err(js_err)
+pub fn pin_encrypt_js(pin: String, salt: &[u8], secret: Vec<u8>) -> Result<Vec<u8>, JsValue> {
+ let (pin, secret) = (zeroize::Zeroizing::new(pin), zeroize::Zeroizing::new(secret));
+ crate::crypto::pin_encrypt(&pin, salt, &secret).map_err(js_err)
}
-/// Decrypt a PIN wrap. Fails for a wrong PIN.
+/// Decrypt a key encrypted with the PIN. Fails for a wrong PIN.
#[wasm_bindgen(js_name = pinDecrypt)]
-pub fn pin_decrypt_js(pin: &str, salt: &[u8], encrypted: &[u8]) -> Result<Vec<u8>, JsValue> {
- crate::crypto::pin_decrypt(pin, salt, encrypted).map_err(js_err)
+pub fn pin_decrypt_js(pin: String, salt: &[u8], encrypted: &[u8]) -> Result<js_sys::Uint8Array, JsValue> {
+ let pin = zeroize::Zeroizing::new(pin);
+ crate::crypto::pin_decrypt(&pin, salt, encrypted).map(|secret| js_sys::Uint8Array::from(&secret[..])).map_err(js_err)
}
/// Whether a stored failed-attempt count means the PIN is locked.
diff --git a/core/rust/src/common/secret.rs b/core/rust/src/common/secret.rs
index 73df0c3d4..fdbf03c02 100644
--- a/core/rust/src/common/secret.rs
+++ b/core/rust/src/common/secret.rs
@@ -1,12 +1,12 @@
-//! Helpers for `SecretString`: moving key text in without a copy, and writing it back out over the JSON boundary.
+//! Helpers for `SecretString`: moving key text in, and writing it back out over the JSON boundary.
use secrecy::{ExposeSecret, SecretString};
use serde::Serializer;
use zeroize::Zeroizing;
-/// Moves a zeroizing string into a `SecretString` without copying the text.
-pub fn from_zeroizing(mut value: Zeroizing<String>) -> SecretString {
- SecretString::from(std::mem::take(&mut *value))
+/// Moves a zeroizing string into a `SecretString`.
+pub fn from_zeroizing(value: Zeroizing<String>) -> SecretString {
+ SecretString::from(value.as_str())
}
/// Writes an optional secret as a plain JSON string, for `#[serde(serialize_with = ...)]`.
diff --git a/core/rust/src/crypto/argon2.rs b/core/rust/src/crypto/argon2.rs
index f1046a9c9..ff1870901 100644
--- a/core/rust/src/crypto/argon2.rs
+++ b/core/rust/src/crypto/argon2.rs
@@ -2,6 +2,7 @@
use serde::Deserialize;
use thiserror::Error;
+use zeroize::Zeroizing;
/// Length of every derived key in bytes; the vault format assumes a 256-bit key throughout.
const ARGON2_OUTPUT_LENGTH: usize = 32;
@@ -66,7 +67,7 @@ struct EncryptionSettingsJson {
}
/// Derive a 32-byte key from a password with Argon2id under explicit cost parameters; the salt is at least 8 bytes.
-pub fn argon2_derive_key(password: &[u8], salt: &[u8], params: Argon2Params) -> Result<Vec<u8>, Argon2Error> {
+pub fn argon2_derive_key(password: &[u8], salt: &[u8], params: Argon2Params) -> Result<Zeroizing<Vec<u8>>, Argon2Error> {
use argon2::{Algorithm, Argon2, Params, Version};
if params.memory_kib < MIN_MEMORY_KIB || params.iterations < MIN_ITERATIONS || params.parallelism < MIN_PARALLELISM {
@@ -78,9 +79,9 @@ pub fn argon2_derive_key(password: &[u8], salt: &[u8], params: Argon2Params) ->
let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, argon2_params);
- let mut output = vec![0u8; ARGON2_OUTPUT_LENGTH];
+ let mut output = Zeroizing::new(vec![0u8; ARGON2_OUTPUT_LENGTH]);
argon2
- .hash_password_into(password, salt, &mut output)
+ .hash_password_into(password, salt, &mut output[..])
.map_err(|e| Argon2Error::InvalidParameter(format!("Argon2 hash failed: {}", e)))?;
Ok(output)
@@ -88,13 +89,13 @@ pub fn argon2_derive_key(password: &[u8], salt: &[u8], params: Argon2Params) ->
/// Derive a 32-byte key from a password and salt (hashed as their UTF-8 bytes) under the cost parameters in
/// `settings_json`.
-pub fn argon2_derive_key_from_settings(password: &str, salt: &str, settings_json: &str) -> Result<Vec<u8>, Argon2Error> {
+pub fn argon2_derive_key_from_settings(password: &str, salt: &str, settings_json: &str) -> Result<Zeroizing<Vec<u8>>, Argon2Error> {
argon2_derive_key_bytes_from_settings(password.as_bytes(), salt.as_bytes(), settings_json)
}
/// [`argon2_derive_key_from_settings`] over raw bytes: the mobile PIN unlock's Keychain/Keystore salt is random
/// bytes, not UTF-8.
-pub fn argon2_derive_key_bytes_from_settings(password: &[u8], salt: &[u8], settings_json: &str) -> Result<Vec<u8>, Argon2Error> {
+pub fn argon2_derive_key_bytes_from_settings(password: &[u8], salt: &[u8], settings_json: &str) -> Result<Zeroizing<Vec<u8>>, Argon2Error> {
let params = Argon2Params::from_settings_json(settings_json)?;
argon2_derive_key(password, salt, params)
}
diff --git a/core/rust/src/crypto/key_chain.rs b/core/rust/src/crypto/key_chain.rs
index 4e7d7a231..9d27b8789 100644
--- a/core/rust/src/crypto/key_chain.rs
+++ b/core/rust/src/crypto/key_chain.rs
@@ -17,17 +17,17 @@ use super::tokens::{ALGORITHM_AES256_GCM, ENCRYPTION_TYPE_ARGON2ID, ENCRYPTION_T
use crate::common::encoding::{base64_decode, base64_encode, hex_encode_upper};
use crate::common::error::VaultResult;
-fn account_key_wrap_algorithm() -> String {
+fn account_key_encryption_algorithm() -> String {
ALGORITHM_AES256_GCM.to_string()
}
-/// The wrapped halves of an account key hierarchy: what the server stores.
+/// The encrypted halves of an account key hierarchy: what the server stores.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountKeyBlobs {
pub encrypted_account_key: String,
/// The algorithm of `encrypted_account_key`, as a VaultKeyAlgorithm token.
- #[serde(default = "account_key_wrap_algorithm")]
+ #[serde(default = "account_key_encryption_algorithm")]
pub encrypted_account_key_algorithm: String,
pub encrypted_vek: String,
pub account_public_key: String,
@@ -39,7 +39,7 @@ pub struct AccountKeyBlobs {
pub account_public_key_signature: String,
}
-/// A newly created account key hierarchy: the wrapped blobs plus the plaintext halves the client keeps.
+/// A newly created account key hierarchy: the encrypted blobs plus the plaintext halves the client keeps.
#[derive(Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
#[serde(rename_all = "camelCase")]
pub struct AccountKeyHierarchy {
@@ -81,7 +81,7 @@ fn hkdf_expand(unlock_key: &[u8], info: &[u8]) -> Zeroizing<Vec<u8>> {
output
}
-/// The KEK that wraps the Account Key, derived from an unlock key with HKDF-SHA256 (no salt, 32 bytes).
+/// The KEK that encrypts the Account Key, derived from an unlock key with HKDF-SHA256 (no salt, 32 bytes).
pub fn derive_kek(unlock_key: &[u8]) -> Zeroizing<Vec<u8>> {
hkdf_expand(unlock_key, KEK_INFO)
}
@@ -101,36 +101,36 @@ pub fn derive_kek_base64(unlock_key_base64: &str) -> VaultResult<Zeroizing<Strin
Ok(Zeroizing::new(base64_encode(&derive_kek(&unlock_key))))
}
-/// 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)?, aad::ACCOUNT_KEY)
+/// Encrypt the Account Key with the KEK derived from an unlock key.
+pub fn encrypt_account_key(account_key_base64: &str, unlock_key_base64: &str) -> VaultResult<String> {
+ encrypt_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)?, aad::ACCOUNT_KEY)
+/// Decrypt the Account Key with the KEK derived from an unlock key. Fails when the unlock key is not the one it was
+/// encrypted for (wrong password).
+pub fn decrypt_account_key(encrypted_account_key: &str, unlock_key_base64: &str) -> VaultResult<Zeroizing<String>> {
+ decrypt_key(encrypted_account_key, &derive_kek_base64(unlock_key_base64)?, aad::ACCOUNT_KEY)
}
-/// 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)
+/// Encrypt a base64 key with another base64 key, bound to `aad` (see [`aad`]). Returns base64 of `IV | ciphertext | tag`.
+pub fn encrypt_key(key_base64: &str, with_key_base64: &str, aad: &[u8]) -> VaultResult<String> {
+ symmetric_encrypt_bytes_with_aad(&Zeroizing::new(base64_decode(key_base64)?), with_key_base64, aad)
}
-/// 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)?);
+/// Decrypt a key encrypted with [`encrypt_key`] bound to `aad`. Returns the key as base64.
+pub fn decrypt_key(encrypted_key_base64: &str, with_key_base64: &str, aad: &[u8]) -> VaultResult<Zeroizing<String>> {
+ let raw = Zeroizing::new(symmetric_decrypt_bytes_with_aad(&base64_decode(encrypted_key_base64)?, with_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)
+pub fn open_account_private_key(encrypted_account_private_key: &str, account_key_base64: &str) -> VaultResult<Zeroizing<String>> {
+ symmetric_decrypt_with_aad(encrypted_account_private_key, account_key_base64, aad::ACCOUNT_PRIVATE_KEY).map(Zeroizing::new)
}
/// Decrypt the account signing private key (base64 seed) with the Account Key.
pub fn open_account_signing_private_key(encrypted_signing_private_key: &str, account_key_base64: &str) -> VaultResult<Zeroizing<String>> {
- unwrap_key(encrypted_signing_private_key, account_key_base64, aad::ACCOUNT_SIGNING_PRIVATE_KEY)
+ decrypt_key(encrypted_signing_private_key, account_key_base64, aad::ACCOUNT_SIGNING_PRIVATE_KEY)
}
/// The fingerprint of the account's own signing key, derived from the private key so that it never depends on the
@@ -169,11 +169,11 @@ pub struct OpenedKeyChain {
pub account_private_key: Option<Zeroizing<String>>,
}
-/// Open a key chain with the unlock key (the password's Argon2id output): the KEK derived from it unwraps the Account
-/// Key, which unwraps the VEK. Never accepts the Account Key itself; see [`open_key_chain_with_account_key`].
+/// Open a key chain with the unlock key (the password's Argon2id output): the KEK derived from it decrypts the Account
+/// Key, which decrypts the VEK. Never accepts the Account Key itself; see [`open_key_chain_with_account_key`].
pub fn open_key_chain_with_unlock_key(unlock_key_base64: &str, encrypted_account_key: &str, encrypted_vek: &str, encrypted_account_private_key: Option<&str>) -> Result<OpenedKeyChain, KeyChainError> {
- let account_key = unwrap_account_key(encrypted_account_key, unlock_key_base64).map_err(|_| KeyChainError::UnlockKeyRejected)?;
- let vault_encryption_key = unwrap_key(encrypted_vek, &account_key, aad::PERSONAL_VEK).map_err(|e| KeyChainError::KeyChainUnreadable(e.to_string()))?;
+ let account_key = decrypt_account_key(encrypted_account_key, unlock_key_base64).map_err(|_| KeyChainError::UnlockKeyRejected)?;
+ let vault_encryption_key = decrypt_key(encrypted_vek, &account_key, aad::PERSONAL_VEK).map_err(|e| KeyChainError::KeyChainUnreadable(e.to_string()))?;
let account_private_key = open_optional_account_private_key(encrypted_account_private_key, &account_key);
Ok(OpenedKeyChain { vault_encryption_key, account_key, account_private_key })
}
@@ -181,36 +181,36 @@ pub fn open_key_chain_with_unlock_key(unlock_key_base64: &str, encrypted_account
/// Open a key chain with the Account Key, as a device unlock method or an unlocked session holds it. Never accepts an
/// unlock key; see [`open_key_chain_with_unlock_key`].
pub fn open_key_chain_with_account_key(account_key_base64: &str, encrypted_vek: &str, encrypted_account_private_key: Option<&str>) -> Result<OpenedKeyChain, KeyChainError> {
- let vault_encryption_key = unwrap_key(encrypted_vek, account_key_base64, aad::PERSONAL_VEK).map_err(|_| KeyChainError::AccountKeyRejected)?;
+ let vault_encryption_key = decrypt_key(encrypted_vek, account_key_base64, aad::PERSONAL_VEK).map_err(|_| KeyChainError::AccountKeyRejected)?;
let account_private_key = open_optional_account_private_key(encrypted_account_private_key, account_key_base64);
Ok(OpenedKeyChain { vault_encryption_key, account_key: Zeroizing::new(account_key_base64.to_string()), account_private_key })
}
/// The account private key when the chain carries one that opens; a failure keeps grants closed, not the vault.
fn open_optional_account_private_key(encrypted_account_private_key: Option<&str>, account_key_base64: &str) -> Option<Zeroizing<String>> {
- encrypted_account_private_key.filter(|e| !e.is_empty()).and_then(|e| open_account_private_key(e, account_key_base64).ok()).map(Zeroizing::new)
+ encrypted_account_private_key.filter(|e| !e.is_empty()).and_then(|e| open_account_private_key(e, account_key_base64).ok())
}
-/// Create a new account key hierarchy wrapped under the KEK derived from an unlock key.
+/// Create a new account key hierarchy encrypted with the KEK derived from an unlock key.
pub fn create_account_key_hierarchy(unlock_key_base64: &str) -> VaultResult<AccountKeyHierarchy> {
let key_pair = generate_rsa_key_pair()?;
- let vault_encryption_key = generate_key_base64();
+ let vault_encryption_key = Zeroizing::new(generate_key_base64());
let account_key = Zeroizing::new(generate_key_base64());
let signing_key_pair = generate_signing_key_pair();
let account_public_key_message = signing::account_public_key_message(&key_pair.public_key);
let account_keys = AccountKeyBlobs {
- encrypted_account_key: wrap_account_key(&account_key, unlock_key_base64)?,
- encrypted_account_key_algorithm: account_key_wrap_algorithm(),
- encrypted_vek: wrap_key(&vault_encryption_key, &account_key, aad::PERSONAL_VEK)?,
+ encrypted_account_key: encrypt_account_key(&account_key, unlock_key_base64)?,
+ encrypted_account_key_algorithm: account_key_encryption_algorithm(),
+ encrypted_vek: encrypt_key(&vault_encryption_key, &account_key, aad::PERSONAL_VEK)?,
account_public_key: key_pair.public_key.clone(),
encrypted_account_private_key: symmetric_encrypt_with_aad(&key_pair.private_key, &account_key, aad::ACCOUNT_PRIVATE_KEY)?,
signing_public_key: signing_key_pair.public_key.clone(),
- encrypted_signing_private_key: wrap_key(&signing_key_pair.private_key, &account_key, aad::ACCOUNT_SIGNING_PRIVATE_KEY)?,
+ encrypted_signing_private_key: encrypt_key(&signing_key_pair.private_key, &account_key, aad::ACCOUNT_SIGNING_PRIVATE_KEY)?,
account_public_key_signature: signing::sign(&signing_key_pair.private_key, &account_public_key_message)?,
};
- Ok(AccountKeyHierarchy { account_key: account_key.to_string(), vault_encryption_key, account_private_key: key_pair.private_key.clone(), signing_private_key: signing_key_pair.private_key.clone(), account_keys })
+ Ok(AccountKeyHierarchy { account_key: account_key.to_string(), vault_encryption_key: vault_encryption_key.to_string(), account_private_key: key_pair.private_key.clone(), signing_private_key: signing_key_pair.private_key.clone(), account_keys })
}
/// The Account Key re-encrypted for a new password.
@@ -225,12 +225,12 @@ pub struct ReencryptedAccountKey {
/// 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()))?;
+ let account_key = decrypt_account_key(encrypted_account_key, old_unlock_key_base64).map_err(|_| KeyChainError::UnlockKeyRejected)?;
+ let new_encrypted_account_key = encrypt_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 })
}
-/// A rotated account key hierarchy: the new wrapped blobs the server stores, what ties them to the old generation,
+/// A rotated account key hierarchy: the new encrypted blobs the server stores, what ties them to the old generation,
/// and the plaintext halves the client keeps.
#[derive(Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
#[serde(rename_all = "camelCase")]
@@ -250,7 +250,7 @@ impl fmt::Debug for RotatedAccountKeys {
}
}
-/// Rotate an account's keys: a new Account Key, VEK, account keypair and signing keypair, wrapped under the KEK of
+/// Rotate an account's keys: a new Account Key, VEK, account keypair and signing keypair, encrypted with the KEK of
/// `new_unlock_key_base64`.
pub fn rotate_account_keys(new_unlock_key_base64: &str) -> VaultResult<RotatedAccountKeys> {
let hierarchy = create_account_key_hierarchy(new_unlock_key_base64)?;
diff --git a/core/rust/src/crypto/mod.rs b/core/rust/src/crypto/mod.rs
index 1281b2275..ad573c9c5 100644
--- a/core/rust/src/crypto/mod.rs
+++ b/core/rust/src/crypto/mod.rs
@@ -1,12 +1,12 @@
//! Cryptographic modules used by the clients. Every AAD string and RSA-OAEP label lives in [`aad`].
//!
//! - [`aad`]: the associated-data and OAEP-label registry that binds each ciphertext to its slot.
-//! - [`aes_gcm`]: AES-256-GCM (`aes-gcm`), random 96-bit nonce, `IV | ciphertext | tag`; every vault payload and key wrap.
+//! - [`aes_gcm`]: AES-256-GCM (`aes-gcm`), random 96-bit nonce, `IV | ciphertext | tag`; every vault payload and every key encrypted with another key.
//! - [`argon2`]: Argon2id (`argon2`) with a parameter floor; turns the master password into the unlock key.
//! - `jwk`: RSA keys to and from JWK JSON (`rsa`), for the OAEP keys and the RS256 passkey keys.
//! - [`key_chain`]: HKDF-SHA256 (`hkdf`) KEK and SRP input from the unlock key; KEK > Account Key > VEK, private keys.
//! - [`mobile_login`]: SHA-256 public key hash and verification code of the mobile login (QR unlock) handshake.
-//! - [`pin`]: PIN unlock: Argon2id + AES-256-GCM wrap of the key the host stores, with the failed-attempt policy.
+//! - [`pin`]: PIN unlock: the key the host stores, encrypted with AES-256-GCM under an Argon2id key of the PIN, with the failed-attempt policy.
//! - [`rsa_oaep`]: RSA-2048 OAEP-SHA256 (`rsa`, blinded decryption); grants, invitation names and delivery keys.
//! - [`signing`]: Ed25519 (`ed25519-dalek`) account signatures over grants, public keys and invitation names.
//! - [`srp`]: SRP-6a client (`srp`, SHA-256, 2048-bit group); login without sending the password.
@@ -37,7 +37,7 @@ pub use aes_gcm::{
};
pub use key_chain::{
account_signing_key_fingerprint, create_account_key_hierarchy, derive_srp_password_hash, open_account_private_key, open_account_signing_private_key,
- open_key_chain_with_account_key, open_key_chain_with_unlock_key, reencrypt_account_key, rotate_account_keys, unwrap_account_key, unwrap_key, wrap_key, AccountKeyBlobs, AccountKeyHierarchy, KeyChainError,
+ decrypt_account_key, decrypt_key, encrypt_key, open_key_chain_with_account_key, open_key_chain_with_unlock_key, reencrypt_account_key, rotate_account_keys, AccountKeyBlobs, AccountKeyHierarchy, KeyChainError,
RotatedAccountKeys, SrpInputError,
};
pub use mobile_login::{mobile_login_open_approval, mobile_login_public_key_hash, mobile_login_verification_code, MobileLoginApproval};
diff --git a/core/rust/src/crypto/pin.rs b/core/rust/src/crypto/pin.rs
index 5869ee13e..fce37d8db 100644
--- a/core/rust/src/crypto/pin.rs
+++ b/core/rust/src/crypto/pin.rs
@@ -1,4 +1,4 @@
-//! PIN unlock: the key wrap and the failed-attempt policy.
+//! PIN unlock: the key encrypted with the PIN and the failed-attempt policy.
use serde::Serialize;
use zeroize::Zeroizing;
@@ -8,10 +8,10 @@ use crate::common::rng::random_bytes;
use crate::crypto::aes_gcm::{symmetric_decrypt_with_raw_key, symmetric_encrypt_with_raw_key};
use crate::crypto::argon2::argon2_derive_key_bytes_from_settings;
-/// Failed attempts after which the PIN is locked and the host deletes the wrapped key.
+/// Failed attempts after which the PIN is locked and the host deletes the encrypted key.
pub const PIN_MAX_ATTEMPTS: u32 = 4;
-/// Length of the random salt a new PIN wrap is derived with.
+/// Length of the random salt a new PIN key is derived with.
pub(super) const PIN_SALT_LENGTH: usize = 16;
/// Argon2id cost parameters for the PIN key. Note: changing this makes any existing PINs not work anymore.
@@ -26,11 +26,11 @@ pub struct PinFailure {
pub failed_attempts: u32,
/// Attempts left before the PIN locks; 0 when `locked`.
pub attempts_remaining: u32,
- /// Whether the host must now delete the wrapped key and disable PIN unlock.
+ /// Whether the host must now delete the encrypted key and disable PIN unlock.
pub locked: bool,
}
-/// A fresh random salt for a new PIN wrap.
+/// A fresh random salt for a new PIN key.
pub fn pin_generate_salt() -> Vec<u8> {
random_bytes(PIN_SALT_LENGTH)
}
@@ -40,9 +40,9 @@ pub fn pin_encrypt(pin: &str, salt: &[u8], secret: &[u8]) -> VaultResult<Vec<u8>
symmetric_encrypt_with_raw_key(secret, &derive_pin_key(pin, salt)?)
}
-/// Decrypt a PIN wrap made by [`pin_encrypt`]. Fails for a wrong PIN.
-pub fn pin_decrypt(pin: &str, salt: &[u8], encrypted: &[u8]) -> VaultResult<Vec<u8>> {
- symmetric_decrypt_with_raw_key(encrypted, &derive_pin_key(pin, salt)?)
+/// Decrypt a key encrypted by [`pin_encrypt`]. Fails for a wrong PIN.
+pub fn pin_decrypt(pin: &str, salt: &[u8], encrypted: &[u8]) -> VaultResult<Zeroizing<Vec<u8>>> {
+ symmetric_decrypt_with_raw_key(encrypted, &derive_pin_key(pin, salt)?).map(Zeroizing::new)
}
/// Whether a stored failed-attempt count means the PIN is locked.
@@ -57,5 +57,5 @@ pub fn pin_register_failure(failed_attempts: u32) -> PinFailure {
}
fn derive_pin_key(pin: &str, salt: &[u8]) -> VaultResult<Zeroizing<Vec<u8>>> {
- argon2_derive_key_bytes_from_settings(pin.as_bytes(), salt, PIN_ARGON2_SETTINGS).map(Zeroizing::new).map_err(|e| VaultError::General(e.to_string()))
+ argon2_derive_key_bytes_from_settings(pin.as_bytes(), salt, PIN_ARGON2_SETTINGS).map_err(|e| VaultError::General(e.to_string()))
}
diff --git a/core/rust/src/crypto/srp.rs b/core/rust/src/crypto/srp.rs
index d31410f15..eb70a9669 100644
--- a/core/rust/src/crypto/srp.rs
+++ b/core/rust/src/crypto/srp.rs
@@ -14,6 +14,7 @@ use srp::groups::G_2048;
use srp::utils::{compute_k, compute_u};
use subtle::ConstantTimeEq;
use thiserror::Error;
+use zeroize::{Zeroize, Zeroizing};
use crate::common::encoding::{hex_decode, hex_encode_upper as bytes_to_hex};
use crate::common::rng::random_bytes;
@@ -73,12 +74,13 @@ pub(super) fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, SrpError> {
}
/// Left-pad bytes with zeros to a specific length.
-pub(super) fn pad_to_length(bytes: Vec<u8>, target_len: usize) -> Vec<u8> {
+pub(super) fn pad_to_length(mut bytes: Vec<u8>, target_len: usize) -> Vec<u8> {
if bytes.len() >= target_len {
bytes
} else {
let mut padded = vec![0u8; target_len - bytes.len()];
- padded.extend(bytes);
+ padded.extend_from_slice(&bytes);
+ bytes.zeroize();
padded
}
}
@@ -110,7 +112,7 @@ pub fn srp_derive_private_key(salt: &str, identity: &str, password_hash: &str) -
/// The SRP verifier `v = g^x mod N` as uppercase hex (256 bytes), from the hex private key.
pub fn srp_derive_verifier(private_key: &str) -> Result<String, SrpError> {
- let x = BigUint::from_bytes_be(&hex_to_bytes(private_key)?);
+ let x = BigUint::from_bytes_be(&Zeroizing::new(hex_to_bytes(private_key)?));
let client = SrpClient::<Sha256>::new(&G_2048);
let v = client.compute_v(&x);
@@ -122,7 +124,7 @@ pub fn srp_derive_verifier(private_key: &str) -> Result<String, SrpError> {
pub fn srp_generate_ephemeral() -> SrpEphemeral {
let client = SrpClient::<Sha256>::new(&G_2048);
- let a = random_bytes(64);
+ let a = Zeroizing::new(random_bytes(64));
let a_pub = client.compute_public_ephemeral(&a);
SrpEphemeral { public: bytes_to_hex(&pad_to_length(a_pub, N_BYTES)), secret: bytes_to_hex(&a) }
@@ -131,10 +133,10 @@ pub fn srp_generate_ephemeral() -> SrpEphemeral {
/// The client session (key `K` and proof `M1`) from the server's public ephemeral `B`; hex in, hex out.
pub fn srp_derive_session(client_secret: &str, server_public: &str, salt: &str, identity: &str, private_key: &str) -> Result<SrpSession, SrpError> {
let identity = identity.to_lowercase();
- let a = BigUint::from_bytes_be(&hex_to_bytes(client_secret)?);
+ let a = BigUint::from_bytes_be(&Zeroizing::new(hex_to_bytes(client_secret)?));
let b_pub = BigUint::from_bytes_be(&hex_to_bytes(server_public)?);
let salt_bytes = hex_to_bytes(salt)?;
- let x = BigUint::from_bytes_be(&hex_to_bytes(private_key)?);
+ let x = BigUint::from_bytes_be(&Zeroizing::new(hex_to_bytes(private_key)?));
// Safeguard against malicious B (B mod N must not be 0)
if &b_pub % &G_2048.n == BigUint::default() {
@@ -166,7 +168,7 @@ pub fn srp_derive_session(client_secret: &str, server_public: &str, salt: &str,
pub fn srp_verify_session(client_public: &str, client_proof: &str, session_key: &str, server_proof: &str) -> Result<bool, SrpError> {
let a_pub_bytes = hex_to_bytes(client_public)?;
let m1_bytes = hex_to_bytes(client_proof)?;
- let key_bytes = hex_to_bytes(session_key)?;
+ let key_bytes = Zeroizing::new(hex_to_bytes(session_key)?);
let server_m2_bytes = hex_to_bytes(server_proof)?;
let expected_m2 = compute_m2(&a_pub_bytes, &m1_bytes, &key_bytes);
@@ -180,8 +182,9 @@ pub fn srp_verify_session(client_public: &str, client_proof: &str, session_key:
*/
/// Derive the session key K = H(PAD(S)) from the premaster secret.
-pub(super) fn derive_session_key(s: &BigUint) -> Vec<u8> {
- Sha256::digest(to_padded_bytes(s)).to_vec()
+pub(super) fn derive_session_key(s: &BigUint) -> Zeroizing<Vec<u8>> {
+ let padded = Zeroizing::new(to_padded_bytes(s));
+ Zeroizing::new(Sha256::digest(&*padded).to_vec())
}
/// Compute M1 = H(H(N) XOR H(g) | H(I) | s | A | B | K)
diff --git a/core/rust/src/crypto/tests/key_chain.rs b/core/rust/src/crypto/tests/key_chain.rs
index 82cd39c41..aaaffaa49 100644
--- a/core/rust/src/crypto/tests/key_chain.rs
+++ b/core/rust/src/crypto/tests/key_chain.rs
@@ -43,11 +43,11 @@ fn kek_differs_from_the_unlock_key() {
}
#[test]
-fn account_key_is_not_wrapped_with_the_raw_unlock_key() {
+fn account_key_is_not_encrypted_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, 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());
+ assert!(decrypt_key(&hierarchy.account_keys.encrypted_account_key, &unlock_key, aad::ACCOUNT_KEY).is_err());
+ assert!(decrypt_key(&hierarchy.account_keys.encrypted_account_key, &derive_kek_base64(&unlock_key).unwrap(), aad::ACCOUNT_KEY).is_ok());
}
#[test]
@@ -74,7 +74,7 @@ fn each_open_refuses_the_other_kind_of_key() {
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();
+ let account_key = decrypt_account_key(&blobs.encrypted_account_key, &unlock_key).unwrap();
assert_eq!(open_key_chain_with_account_key(&unlock_key, &blobs.encrypted_vek, None).err(), Some(KeyChainError::AccountKeyRejected));
assert_eq!(open_key_chain_with_unlock_key(&account_key, &blobs.encrypted_account_key, &blobs.encrypted_vek, None).err(), Some(KeyChainError::UnlockKeyRejected));
@@ -92,8 +92,8 @@ fn chain_rejects_a_wrong_key() {
fn chain_with_a_foreign_vek_is_unreadable_under_the_unlock_key() {
let unlock_key = generate_key_base64();
let hierarchy = create_account_key_hierarchy(&unlock_key).unwrap();
- let account_key = unwrap_account_key(&hierarchy.account_keys.encrypted_account_key, &unlock_key).unwrap();
- let foreign_vek = wrap_key(&generate_key_base64(), &generate_key_base64(), aad::PERSONAL_VEK).unwrap();
+ let account_key = decrypt_account_key(&hierarchy.account_keys.encrypted_account_key, &unlock_key).unwrap();
+ let foreign_vek = encrypt_key(&generate_key_base64(), &generate_key_base64(), aad::PERSONAL_VEK).unwrap();
// The Account Key opened, so the unlock key was right: a damaged chain, never a wrong password.
assert!(matches!(open_key_chain_with_unlock_key(&unlock_key, &hierarchy.account_keys.encrypted_account_key, &foreign_vek, None), Err(KeyChainError::KeyChainUnreadable(_))));
@@ -106,7 +106,7 @@ fn a_private_key_that_does_not_open_leaves_grants_closed_but_opens_the_vault() {
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();
+ let account_key = decrypt_account_key(&blobs.encrypted_account_key, &unlock_key).unwrap();
let opened = open_key_chain_with_account_key(&account_key, &blobs.encrypted_vek, Some(&blobs.encrypted_vek)).unwrap();
assert_eq!(*opened.vault_encryption_key, hierarchy.vault_encryption_key);
@@ -140,7 +140,7 @@ fn hierarchy_carries_a_signing_key_that_signed_the_account_public_key() {
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();
+ let account_key = decrypt_account_key(&blobs.encrypted_account_key, &unlock_key).unwrap();
let signing_private_key = open_account_signing_private_key(&blobs.encrypted_signing_private_key, &account_key).unwrap();
assert_eq!(*signing_private_key, hierarchy.signing_private_key);
@@ -173,11 +173,11 @@ fn reencrypt_rejects_a_wrong_old_unlock_key() {
}
#[test]
-fn wrap_and_unwrap_round_trip() {
- let wrapping = generate_key_base64();
+fn encrypt_and_decrypt_key_round_trip() {
+ let outer = generate_key_base64();
let key = generate_key_base64();
- 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());
+ assert_eq!(*decrypt_key(&encrypt_key(&key, &outer, b"a").unwrap(), &outer, b"a").unwrap(), key);
+ assert!(decrypt_key(&encrypt_key(&key, &outer, b"a").unwrap(), &outer, b"b").is_err());
}
#[test]
@@ -185,12 +185,12 @@ 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();
+ let account_key = decrypt_account_key(&blobs.encrypted_account_key, &unlock_key).unwrap();
- // The Account Key wrap served as the VEK wrap: refused, not read as the VEK.
+ // The encrypted Account Key served as the encrypted VEK: refused, not read as the VEK.
assert!(matches!(open_key_chain_with_unlock_key(&unlock_key, &blobs.encrypted_account_key, &blobs.encrypted_account_key, None), Err(KeyChainError::KeyChainUnreadable(_))));
assert_eq!(open_key_chain_with_account_key(&account_key, &blobs.encrypted_account_key, None).err(), Some(KeyChainError::AccountKeyRejected));
- assert!(unwrap_key(&blobs.encrypted_vek, &account_key, aad::ACCOUNT_KEY).is_err());
+ assert!(decrypt_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());
}
@@ -199,10 +199,10 @@ fn chain_ciphertexts_do_not_open_in_each_others_slot() {
fn an_account_key_encrypted_under_any_other_label_is_refused() {
let unlock_key = generate_key_base64();
let hierarchy = create_account_key_hierarchy(&unlock_key).unwrap();
- let account_key = unwrap_account_key(&hierarchy.account_keys.encrypted_account_key, &unlock_key).unwrap();
+ let account_key = decrypt_account_key(&hierarchy.account_keys.encrypted_account_key, &unlock_key).unwrap();
let kek = derive_kek_base64(&unlock_key).unwrap();
for label in [aad::PERSONAL_VEK, aad::ACCOUNT_PRIVATE_KEY, aad::ACCOUNT_SIGNING_PRIVATE_KEY, aad::MOBILE_LOGIN_ACCOUNT_KEY, aad::MOBILE_LOGIN_PAYLOAD_KEY, b""] {
- let foreign = wrap_key(&account_key, &kek, label).unwrap();
+ let foreign = encrypt_key(&account_key, &kek, label).unwrap();
let opened = open_key_chain_with_unlock_key(&unlock_key, &foreign, &hierarchy.account_keys.encrypted_vek, None);
assert_eq!(opened.err(), Some(KeyChainError::UnlockKeyRejected), "label {:?}", String::from_utf8_lossy(label));
}
diff --git a/core/rust/src/crypto/tests/pin.rs b/core/rust/src/crypto/tests/pin.rs
index a87dd0e18..d1ce09f4f 100644
--- a/core/rust/src/crypto/tests/pin.rs
+++ b/core/rust/src/crypto/tests/pin.rs
@@ -8,18 +8,18 @@ fn round_trips_and_rejects_a_wrong_pin() {
assert_eq!(salt.len(), PIN_SALT_LENGTH);
let encrypted = pin_encrypt("123456", &salt, b"account key").unwrap();
assert_eq!(encrypted.len(), 12 + b"account key".len() + 16, "layout is IV | ciphertext | tag");
- assert_eq!(pin_decrypt("123456", &salt, &encrypted).unwrap(), b"account key");
+ assert_eq!(*pin_decrypt("123456", &salt, &encrypted).unwrap(), b"account key");
assert!(pin_decrypt("654321", &salt, &encrypted).is_err());
assert!(pin_decrypt("123456", &pin_generate_salt(), &encrypted).is_err());
}
-/// A wrap stored before this module existed: Argon2id under the PIN settings, then AES-GCM with that key.
+/// A PIN key stored before this module existed: Argon2id under the PIN settings, then AES-GCM with that key.
#[test]
-fn opens_a_wrap_made_with_the_argon2_key_directly() {
+fn opens_a_key_encrypted_with_the_argon2_key_directly() {
let salt = b"some-salt-bytes!";
let key = argon2_derive_key_bytes_from_settings(b"8765432", salt, PIN_ARGON2_SETTINGS).unwrap();
let encrypted = symmetric_encrypt_with_raw_key(b"secret", &key).unwrap();
- assert_eq!(pin_decrypt("8765432", salt, &encrypted).unwrap(), b"secret");
+ assert_eq!(*pin_decrypt("8765432", salt, &encrypted).unwrap(), b"secret");
}
#[test]
diff --git a/core/rust/src/vault_sync/blob_keys.rs b/core/rust/src/vault_sync/blob_keys.rs
index 9049c298d..604d15ed6 100644
--- a/core/rust/src/vault_sync/blob_keys.rs
+++ b/core/rust/src/vault_sync/blob_keys.rs
@@ -22,13 +22,13 @@ pub(crate) fn encrypt_blob(bytes: &[u8], vek: &str, manifest_id: &str, hash: &st
let blob_key = zeroize::Zeroizing::new(crypto::generate_key_base64());
Ok(EncryptedBlob {
encrypted_data: crypto::symmetric_encrypt_raw_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))?,
+ encrypted_blob_key: crypto::encrypt_key(&blob_key, vek, &aad::blob_key(manifest_id, hash))?,
})
}
/// 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))?;
+ let blob_key = crypto::decrypt_key(&blob.encrypted_blob_key, vek, &aad::blob_key(manifest_id, hash))?;
crypto::symmetric_decrypt_bytes_with_aad(&blob.encrypted_data, &blob_key, &aad::blob_data(manifest_id, hash))
}
diff --git a/core/rust/src/vault_sync/http.rs b/core/rust/src/vault_sync/http.rs
index a65051215..4585f3031 100644
--- a/core/rust/src/vault_sync/http.rs
+++ b/core/rust/src/vault_sync/http.rs
@@ -109,7 +109,7 @@ pub(crate) async fn post_frame<B: FrameBody + Serialize, T: DeserializeOwned>(ho
/// The v2 vault endpoint (`GET`/`POST v2/Vault`).
pub(crate) const VAULT_ENDPOINT: &str = "Vault";
-/// The v2 vault key endpoint (`GET v2/VaultKey/Password`): the account's password-wrapped key chain.
+/// The v2 vault key endpoint (`GET v2/VaultKey/Password`): the account's key chain encrypted under the password.
// TODO: switch to "UnlockMethod/Password" after minimum API is 0.32.0+ that has the new URL.
pub(crate) const VAULT_KEY_PASSWORD_ENDPOINT: &str = "VaultKey/Password";
diff --git a/core/rust/src/vault_sync/keys.rs b/core/rust/src/vault_sync/keys.rs
index 1914dbe04..66cac2d6c 100644
--- a/core/rust/src/vault_sync/keys.rs
+++ b/core/rust/src/vault_sync/keys.rs
@@ -66,7 +66,7 @@ async fn open_chain(ctx: &mut Ctx, encrypted_account_key: &str, encrypted_vek: &
ctx.account_key = Some(account_key.clone());
if let Some(encrypted) = encrypted_private_key.filter(|e| !e.is_empty()) {
match crypto::open_account_private_key(encrypted, account_key.expose_secret()) {
- Ok(private_key) => ctx.account_private_key = Some(SecretString::from(private_key)),
+ Ok(private_key) => ctx.account_private_key = Some(SecretString::from(private_key.as_str())),
Err(error) => ctx.warn(format!("[Keys] The cached account private key did not open; shared grants stay closed. {}", error)).await,
}
}
@@ -256,7 +256,7 @@ pub(crate) fn decrypt_manifest_vek(encrypted_vek: &str, manifest_id: &str, priva
std::str::from_utf8(&plaintext).map(SecretString::from).map_err(|_| SyncError::Other("Decrypted manifest key is not valid text".to_string()))
}
-/// Unwrap one shared manifest's VEK from the grant this account holds on it.
+/// Decrypt one shared manifest's VEK from the grant this account holds on it.
pub(crate) async fn open_shared_manifest_vek(ctx: &Ctx, record: &SharedManifestDto) -> SyncResult<Option<SecretString>> {
if record.algorithm != ALGORITHM_RSA_OAEP_SHA256 {
ctx.warn(format!("[Sharing] Manifest {} grants its key under an unsupported algorithm \"{}\" (newer server?); leaving it closed.", record.manifest_id, record.algorithm)).await;
@@ -269,13 +269,13 @@ pub(crate) async fn open_shared_manifest_vek(ctx: &Ctx, record: &SharedManifestD
match decrypt_manifest_vek(&record.encrypted_vek, &record.manifest_id, private_key.expose_secret()) {
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;
+ ctx.warn(format!("[Sharing] Failed to decrypt the key of manifest {}; leaving it closed. {}", record.manifest_id, error)).await;
Ok(None)
}
}
}
-/// The VEK of every shared manifest this account holds a grant on, keyed by manifest id. Unwrapped once per run.
+/// The VEK of every shared manifest this account holds a grant on, keyed by manifest id. Decrypted once per run.
pub(crate) async fn open_shared_manifest_veks(ctx: &Ctx) -> SyncResult<HashMap<String, SecretString>> {
if let Some(cached) = ctx.cached_shared_veks() {
return Ok(cached);
diff --git a/core/rust/src/vault_sync/rotation.rs b/core/rust/src/vault_sync/rotation.rs
index bea576327..5a2caa554 100644
--- a/core/rust/src/vault_sync/rotation.rs
+++ b/core/rust/src/vault_sync/rotation.rs
@@ -1,5 +1,5 @@
//! Key rotation: a new Account Key, VEK, account keypair and signing keypair, with the personal vault re-encrypted and
-//! every grant rewrapped, which the server applies in one transaction or not at all.
+//! every grant reencrypted, which the server applies in one transaction or not at all.
use std::collections::HashMap;
@@ -184,7 +184,7 @@ async fn rotate(ctx: &mut Ctx) -> Outcome {
return Ok(Err(KeyRotationRefusal::ServerStateChanged));
}
- // Every grant this account holds has to open here, or the rewrap would leave that shared vault unreachable.
+ // Every grant this account holds has to open here, or re-encrypting would leave that shared vault unreachable.
let shared_records = keys::shared_manifest_records(ctx).await?;
let mut shared_veks: HashMap<String, SecretString> = HashMap::new();
for record in shared_records.values() {
@@ -207,8 +207,8 @@ async fn rotate(ctx: &mut Ctx) -> Outcome {
let posted = build_and_post(ctx, &params, &personal_manifest_id, &rotated, signing_key.expose_secret(), &new_vek, &vek, &shared_records, &shared_veks, &blob_keys.blob_keys, &certifications, &delivery_pair.public_key).await;
match posted {
- Ok(Ok((applied, rewrapped_blob_keys, rewrapped_grants, fingerprints))) => {
- adopt(ctx, &params, &personal_manifest_id, &rotated, &new_vek, &applied, &rewrapped_blob_keys, &rewrapped_grants, &fingerprints).await?;
+ Ok(Ok((applied, reencrypted_blob_keys, reencrypted_grants, fingerprints))) => {
+ adopt(ctx, &params, &personal_manifest_id, &rotated, &new_vek, &applied, &reencrypted_blob_keys, &reencrypted_grants, &fingerprints).await?;
ctx.log("[KeyRotation] The server applied the rotation; this device now holds the new keys.").await;
Ok(Ok((SecretString::from(rotated.account_key.as_str()), new_vek)))
}
@@ -225,7 +225,7 @@ async fn rotate(ctx: &mut Ctx) -> Outcome {
}
}
-/// The rewrapped blob keys, the rewrapped grants and the content fingerprints a successful rotation commits locally.
+/// The reencrypted blob keys, the reencrypted grants and the content fingerprints a successful rotation commits locally.
type Built = (Applied, HashMap<String, String>, HashMap<String, SharedManifestDto>, HashMap<String, String>);
/// Encrypt everything under the new keys, send it, and read the server's answer.
@@ -268,24 +268,24 @@ async fn build_and_post(ctx: &mut Ctx, params: &KeyRotationParams, personal_mani
// Every blob key the server holds, under the new VEK; a blob the manifest references without a key cannot be rotated.
let mut blob_keys = Vec::new();
- let mut rewrapped_blob_keys: HashMap<String, String> = HashMap::new();
+ let mut reencrypted_blob_keys: HashMap<String, String> = HashMap::new();
for blob_key in server_blob_keys {
let aad = crypto::aad::blob_key(personal_manifest_id, &blob_key.hash);
- let plain = crypto::unwrap_key(&blob_key.encrypted_blob_key, old_vek.expose_secret(), &aad).map_err(|e| SyncError::Other(format!("the key of blob {} does not open with the current vault key: {}", blob_key.hash, e)))?;
- let rewrapped = crypto::wrap_key(&plain, new_vek.expose_secret(), &aad)?;
- ensure_opens(crypto::unwrap_key(&rewrapped, new_vek.expose_secret(), &aad).is_ok_and(|k| *k == *plain), &format!("the key of blob {}", blob_key.hash))?;
- rewrapped_blob_keys.insert(blob_key.hash.clone(), rewrapped.clone());
- blob_keys.push(BlobKeyWrite { hash: blob_key.hash.clone(), encrypted_blob_key: rewrapped });
+ let plain = crypto::decrypt_key(&blob_key.encrypted_blob_key, old_vek.expose_secret(), &aad).map_err(|e| SyncError::Other(format!("the key of blob {} does not open with the current vault key: {}", blob_key.hash, e)))?;
+ let reencrypted = crypto::encrypt_key(&plain, new_vek.expose_secret(), &aad)?;
+ ensure_opens(crypto::decrypt_key(&reencrypted, new_vek.expose_secret(), &aad).is_ok_and(|k| *k == *plain), &format!("the key of blob {}", blob_key.hash))?;
+ reencrypted_blob_keys.insert(blob_key.hash.clone(), reencrypted.clone());
+ blob_keys.push(BlobKeyWrite { hash: blob_key.hash.clone(), encrypted_blob_key: reencrypted });
}
let references: Vec<BlobRef> = entry.manifest.referenced_blobs().into_iter().map(|(hash, category)| BlobRef { hash, category }).collect();
- if let Some(unkeyed) = references.iter().find(|r| !rewrapped_blob_keys.contains_key(&r.hash)) {
+ if let Some(unkeyed) = references.iter().find(|r| !reencrypted_blob_keys.contains_key(&r.hash)) {
return Err(SyncError::Other(format!("the server holds no key for referenced blob {}; sync and try again", unkeyed.hash)));
}
// Every grant, for the new account public key, signed by the new signing key.
let mut grants = Vec::new();
- let mut rewrapped_grants = shared_records.clone();
- for record in rewrapped_grants.values_mut() {
+ let mut reencrypted_grants = shared_records.clone();
+ for record in reencrypted_grants.values_mut() {
let shared_vek = &shared_veks[&record.manifest_id];
let encrypted_vek = keys::encrypt_manifest_vek(shared_vek.expose_secret(), &record.manifest_id, &rotated.account_keys.account_public_key)?;
let message = crypto::signing::grant_message(&record.manifest_id, record.key_version, &params.user_id, &rotated.account_keys.account_public_key, ALGORITHM_RSA_OAEP_SHA256, &encrypted_vek);
@@ -368,7 +368,7 @@ async fn build_and_post(ctx: &mut Ctx, params: &KeyRotationParams, personal_mani
Err(error) => return Err(error),
};
match response.status.as_str() {
- "ok" => Ok(Ok((Applied { manifest_revision: response.manifest_revision, bucket_revisions: response.bucket_revisions }, rewrapped_blob_keys, rewrapped_grants, fingerprints))),
+ "ok" => Ok(Ok((Applied { manifest_revision: response.manifest_revision, bucket_revisions: response.bucket_revisions }, reencrypted_blob_keys, reencrypted_grants, fingerprints))),
"outdated" => Ok(Err(KeyRotationRefusal::ServerStateChanged)),
other => Err(SyncError::Other(format!("the server answered the rotation with an unknown status \"{}\"", other))),
}
@@ -378,11 +378,11 @@ async fn build_and_post(ctx: &mut Ctx, params: &KeyRotationParams, personal_mani
/// server applies it, the old password no longer reaches any key, so a broken chain could not be recovered.
fn ensure_key_chain_opens(params: &KeyRotationParams, rotated: &crypto::RotatedAccountKeys, new_vek: &SecretString) -> SyncResult<()> {
let blobs = &rotated.account_keys;
- let account_key = crypto::unwrap_account_key(&blobs.encrypted_account_key, params.new_unlock_key.expose_secret()).ok().filter(|key| **key == rotated.account_key);
+ let account_key = crypto::decrypt_account_key(&blobs.encrypted_account_key, params.new_unlock_key.expose_secret()).ok().filter(|key| **key == rotated.account_key);
ensure_opens(account_key.is_some(), "the new Account Key")?;
- let vek_opens = crypto::unwrap_key(&blobs.encrypted_vek, &rotated.account_key, crypto::aad::PERSONAL_VEK).is_ok_and(|key| *key == new_vek.expose_secret());
+ let vek_opens = crypto::decrypt_key(&blobs.encrypted_vek, &rotated.account_key, crypto::aad::PERSONAL_VEK).is_ok_and(|key| *key == new_vek.expose_secret());
ensure_opens(vek_opens, "the new vault key")?;
- ensure_opens(crypto::open_account_private_key(&blobs.encrypted_account_private_key, &rotated.account_key).is_ok_and(|key| key == rotated.account_private_key), "the new account private key")?;
+ ensure_opens(crypto::open_account_private_key(&blobs.encrypted_account_private_key, &rotated.account_key).is_ok_and(|key| *key == rotated.account_private_key), "the new account private key")?;
ensure_opens(crypto::open_account_signing_private_key(&blobs.encrypted_signing_private_key, &rotated.account_key).is_ok_and(|key| *key == rotated.signing_private_key), "the new signing private key")
}
@@ -405,7 +405,7 @@ fn ensure_opens(opens: bool, what: &str) -> SyncResult<()> {
/// Take the new keys over: the cached chain, the derivation parameters, the revisions and fingerprints the server
/// now holds, the blob keys and grants under the new keys, and the stored vault under the new VEK.
#[allow(clippy::too_many_arguments)]
-async fn adopt(ctx: &mut Ctx, params: &KeyRotationParams, personal_manifest_id: &str, rotated: &crypto::RotatedAccountKeys, new_vek: &SecretString, applied: &Applied, rewrapped_blob_keys: &HashMap<String, String>, rewrapped_grants: &HashMap<String, SharedManifestDto>, fingerprints: &HashMap<String, String>) -> SyncResult<()> {
+async fn adopt(ctx: &mut Ctx, params: &KeyRotationParams, personal_manifest_id: &str, rotated: &crypto::RotatedAccountKeys, new_vek: &SecretString, applied: &Applied, reencrypted_blob_keys: &HashMap<String, String>, reencrypted_grants: &HashMap<String, SharedManifestDto>, fingerprints: &HashMap<String, String>) -> SyncResult<()> {
let blobs = &rotated.account_keys;
state::set(&ctx.host, state::ENCRYPTED_ACCOUNT_KEY, &blobs.encrypted_account_key).await?;
state::set(&ctx.host, state::ENCRYPTED_VEK, &blobs.encrypted_vek).await?;
@@ -429,8 +429,8 @@ async fn adopt(ctx: &mut Ctx, params: &KeyRotationParams, personal_manifest_id:
let mut cache: HashMap<String, EncryptedBlob> = state::get(&ctx.host, state::VAULT_BLOB_CIPHER_CACHE).await?.unwrap_or_default();
for (hash, encrypted) in cache.iter_mut() {
- if let Some(rewrapped) = rewrapped_blob_keys.get(hash) {
- encrypted.encrypted_blob_key = rewrapped.clone();
+ if let Some(reencrypted) = reencrypted_blob_keys.get(hash) {
+ encrypted.encrypted_blob_key = reencrypted.clone();
}
}
state::set(&ctx.host, state::VAULT_BLOB_CIPHER_CACHE, &cache).await?;
@@ -439,7 +439,7 @@ async fn adopt(ctx: &mut Ctx, params: &KeyRotationParams, personal_manifest_id:
ctx.account_public_key = Some(blobs.account_public_key.clone());
ctx.account_private_key = Some(SecretString::from(rotated.account_private_key.as_str()));
ctx.signing_private_key = Some(SecretString::from(rotated.signing_private_key.as_str()));
- keys::set_shared_manifest_records(ctx, rewrapped_grants, new_vek.expose_secret()).await?;
+ keys::set_shared_manifest_records(ctx, reencrypted_grants, new_vek.expose_secret()).await?;
ctx.set_encryption_key(new_vek.clone());
ctx.persist_local_vault(false).await
}
diff --git a/core/rust/src/vault_sync/sharing.rs b/core/rust/src/vault_sync/sharing.rs
index 56394df44..1c012e2be 100644
--- a/core/rust/src/vault_sync/sharing.rs
+++ b/core/rust/src/vault_sync/sharing.rs
@@ -444,7 +444,7 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {
return Ok(Err(Refusal::VaultUpgradeRequired));
}
- let manifest_vek = crypto::generate_key_base64();
+ let manifest_vek = zeroize::Zeroizing::new(crypto::generate_key_base64());
let requested_id = db::new_id();
let self_encrypted_vek = keys::encrypt_manifest_vek(&manifest_vek, &requested_id, &self_public_key)?;
let self_grant_signature = me.sign(&crypto::signing::grant_message(&requested_id, NEW_MANIFEST_KEY_VERSION, &me.user_id, &self_public_key, ALGORITHM_RSA_OAEP_SHA256, &self_encrypted_vek))?;
diff --git a/core/rust/src/vault_sync/state.rs b/core/rust/src/vault_sync/state.rs
index 2a237bbc7..faa7f6c4c 100644
--- a/core/rust/src/vault_sync/state.rs
+++ b/core/rust/src/vault_sync/state.rs
@@ -34,7 +34,7 @@ pub(crate) struct Ctx {
has_local_vault: bool,
/// The stored vault did not decrypt with the session key, so this run treats it as absent until a store replaces it.
local_vault_discarded: bool,
- /// The VEK of every shared manifest this account holds a grant on, unwrapped once per run.
+ /// The VEK of every shared manifest this account holds a grant on, decrypted once per run.
shared_veks: Mutex<Option<HashMap<String, SecretString>>>,
}
@@ -143,12 +143,12 @@ impl Ctx {
Ok(schema)
}
- /// The shared-manifest keys unwrapped earlier in this run, if any.
+ /// The shared-manifest keys decrypted earlier in this run, if any.
pub fn cached_shared_veks(&self) -> Option<HashMap<String, SecretString>> {
self.shared_veks.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()
}
- /// Remember the unwrapped shared-manifest keys; `None` forgets them (the records changed).
+ /// Remember the decrypted shared-manifest keys; `None` forgets them (the records changed).
pub fn cache_shared_veks(&self, veks: Option<HashMap<String, SecretString>>) {
*self.shared_veks.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = veks;
}
diff --git a/core/rust/src/vault_sync/tests/blob_keys.rs b/core/rust/src/vault_sync/tests/blob_keys.rs
index d92ffcc47..815ba1b3e 100644
--- a/core/rust/src/vault_sync/tests/blob_keys.rs
+++ b/core/rust/src/vault_sync/tests/blob_keys.rs
@@ -33,8 +33,8 @@ fn changing_the_vek_only_encrypts_the_blob_key_again() {
let blob = encrypt_blob(&[9; 64], &old_vek, MANIFEST, HASH).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: blob.encrypted_data.clone(), encrypted_blob_key: crypto::wrap_key(&blob_key, &new_vek, &key_aad).unwrap() };
+ let blob_key = crypto::decrypt_key(&blob.encrypted_blob_key, &old_vek, &key_aad).unwrap();
+ let rekeyed = EncryptedBlob { encrypted_data: blob.encrypted_data.clone(), encrypted_blob_key: crypto::encrypt_key(&blob_key, &new_vek, &key_aad).unwrap() };
assert_eq!(decrypt_blob(&rekeyed, &new_vek, MANIFEST, HASH).unwrap(), vec![9; 64]);
assert!(decrypt_blob(&rekeyed, &old_vek, MANIFEST, HASH).is_err());
diff --git a/core/rust/src/vault_sync/tests/keys.rs b/core/rust/src/vault_sync/tests/keys.rs
index d94ec1d2e..b80464d2e 100644
--- a/core/rust/src/vault_sync/tests/keys.rs
+++ b/core/rust/src/vault_sync/tests/keys.rs
@@ -33,7 +33,7 @@ fn resolve_vault_key_opens_the_chain_from_the_server() {
assert!(host.store_calls.is_empty(), "resolving a key never touches the stored vault");
// The operation takes the unlock key only: the Account Key itself is refused, never tried as a fallback.
- let account_key = crypto::unwrap_account_key(&hierarchy.account_keys.encrypted_account_key, &unlock_key).unwrap();
+ let account_key = crypto::decrypt_account_key(&hierarchy.account_keys.encrypted_account_key, &unlock_key).unwrap();
let mut host = TestHost::new(&account_key);
host.serve(&server);
let result = host.run("resolveVaultKey");
@@ -74,7 +74,7 @@ fn resolve_vault_key_opens_the_cached_chain_when_the_server_is_unreachable() {
}
/// A key that does not open the chain is a rejected unlock key (E-206); a chain whose VEK does not open under its
-/// own account key is damage, not a wrong password (E-207); an unknown wrap algorithm asks for an app update.
+/// own account key is damage, not a wrong password (E-207); an unknown encryption algorithm asks for an app update.
#[test]
fn resolve_vault_key_tells_the_failure_modes_apart() {
let unlock_key = crypto::generate_key_base64();
@@ -89,7 +89,7 @@ fn resolve_vault_key_tells_the_failure_modes_apart() {
assert!(result.get("encryptionKey").is_none());
let mut damaged = hierarchy.clone();
- damaged.account_keys.encrypted_vek = crypto::wrap_key(&crypto::generate_key_base64(), &crypto::generate_key_base64(), crypto::aad::PERSONAL_VEK).unwrap();
+ damaged.account_keys.encrypted_vek = crypto::encrypt_key(&crypto::generate_key_base64(), &crypto::generate_key_base64(), crypto::aad::PERSONAL_VEK).unwrap();
server.borrow_mut().set_vault_key(&damaged);
let mut host = TestHost::new(&unlock_key);
host.serve(&server);
diff --git a/core/rust/src/vault_sync/tests/migration.rs b/core/rust/src/vault_sync/tests/migration.rs
index bfdc027f1..088c3e3a7 100644
--- a/core/rust/src/vault_sync/tests/migration.rs
+++ b/core/rust/src/vault_sync/tests/migration.rs
@@ -39,7 +39,7 @@ fn manifest_migration_generates_the_key_hierarchy_and_pushes() {
let write = host.last_vault_write();
let account_keys = &write["migration"]["accountKeys"];
assert!(account_keys["encryptedAccountKey"].is_string(), "the migration push carries the key hierarchy");
- assert!(crypto::unwrap_key(account_keys["encryptedAccountKey"].as_str().unwrap(), &unlock_key, crypto::aad::ACCOUNT_KEY).is_err(), "the legacy vault key does not wrap the Account Key directly");
+ assert!(crypto::decrypt_key(account_keys["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_key_chain_with_unlock_key(&unlock_key, account_keys["encryptedAccountKey"].as_str().unwrap(), account_keys["encryptedVek"].as_str().unwrap(), None).unwrap();
assert_eq!(*opened.vault_encryption_key, new_key);
let signed = crypto::signing::account_public_key_message(account_keys["accountPublicKey"].as_str().unwrap());
diff --git a/core/rust/src/vault_sync/types.rs b/core/rust/src/vault_sync/types.rs
index cd34baec6..f765d57f2 100644
--- a/core/rust/src/vault_sync/types.rs
+++ b/core/rust/src/vault_sync/types.rs
@@ -267,7 +267,7 @@ pub enum KeyRotationRefusal {
VaultOutOfDate,
/// The server state moved on between initiate and the rotation; sync and try again.
ServerStateChanged,
- /// A shared vault's key could not be opened on this device, so its grant could not be rewrapped.
+ /// A shared vault's key could not be opened on this device, so its grant could not be reencrypted.
SharedVaultKeyUnavailable,
/// The vault or the account's key hierarchy has to finish upgrading first.
VaultUpgradeRequired,
diff --git a/core/rust/src/vault_sync/write_set.rs b/core/rust/src/vault_sync/write_set.rs
index 4e2ec2c3c..fac0a1395 100644
--- a/core/rust/src/vault_sync/write_set.rs
+++ b/core/rust/src/vault_sync/write_set.rs
@@ -25,7 +25,7 @@ pub(crate) struct ManifestRecord {
pub(crate) enum SkipReason {
/// The vault holds no rows for it, so writing it would empty it server-side.
NoRowsInVault,
- /// Its grant did not unwrap in this session.
+ /// Its grant did not decrypt in this session.
KeyDidNotOpen,
}