Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Simplify RSA-OAEP, Argon2 and gzip helpers in Rust core
Leendert de Borst4f9143bc9a4a
diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rsindex 851d965e4..f58f38f2d 100644--- a/core/rust/src/bindings/uniffi_api.rs+++ b/core/rust/src/bindings/uniffi_api.rs@@ -185,7 +185,8 @@ pub fn vault_codec_unpack_payload(plain_bytes: Vec<u8>) -> Result<String, VaultE#[uniffi::export]pub fn argon2_derive_key(password: String, salt: String, encryption_settings: String) -> Result<Vec<u8>, Argon2Error> {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))+ let params = crate::crypto::argon2::Argon2Params::from_settings_json(&encryption_settings)?;+ crate::crypto::argon2::argon2_derive_key(password.as_bytes(), salt.as_bytes(), params).map(|mut key| std::mem::take(&mut *key))}/// AES-256-GCM decrypt a base64 `IV | ciphertext | tag` string (no AAD) into UTF-8 with a base64 key. An empty ciphertext is an error.@@ -367,19 +368,19 @@ pub fn srp_verify_session(client_public: String, client_proof: String, session_k/// RSA-OAEP-256 decrypt base64 ciphertext with a JWK private key.#[uniffi::export]pub fn rsa_decrypt(base64_ciphertext: String, private_key_jwk: String) -> Result<Vec<u8>, VaultError> {- crate::crypto::decrypt_with_private_key(&base64_ciphertext, &private_key_jwk)+ crate::crypto::rsa_oaep::decrypt(&base64_ciphertext, &private_key_jwk, &[])}/// Decrypt the shared manifest name encrypted into an invitation for this JWK private key.#[uniffi::export]pub fn decrypt_manifest_invitation_name(encrypted_name: String, manifest_id: String, private_key_jwk: String) -> Result<String, VaultError> {- crate::crypto::decrypt_manifest_invitation_name(&encrypted_name, &manifest_id, &private_key_jwk)+ crate::vault_sync::keys::decrypt_manifest_invitation_name(&encrypted_name, &manifest_id, &private_key_jwk)}/// RSA-OAEP-256 encrypt the Account Key for a mobile login request's JWK public key, as base64.#[uniffi::export]pub fn mobile_login_encrypt_account_key(account_key: Vec<u8>, public_key_jwk: String) -> Result<String, VaultError> {- crate::crypto::encrypt_with_public_key_and_label(&account_key, &public_key_jwk, crate::crypto::aad::MOBILE_LOGIN_ACCOUNT_KEY)+ crate::crypto::mobile_login_encrypt_account_key(&account_key, &public_key_jwk)}/// SHA-256 of a mobile login request's public key JWK string, unpadded base64url; the QR code carries it.diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rsindex a18da483a..c622a905f 100644--- a/core/rust/src/bindings/wasm.rs+++ b/core/rust/src/bindings/wasm.rs@@ -196,7 +196,8 @@ pub fn extract_email_attachment_js(source: &[u8], index: usize, detached_body: O#[wasm_bindgen(js_name = argon2DeriveKey)]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)+ let params = crate::crypto::argon2::Argon2Params::from_settings_json(encryption_settings).map_err(js_err)?;+ crate::crypto::argon2::argon2_derive_key(password.as_bytes(), salt.as_bytes(), params).map(|key| js_sys::Uint8Array::from(&key[..])).map_err(js_err)}/// AES-256-GCM decrypt a base64 `IV | ciphertext | tag` string (no AAD) into UTF-8 with a base64 key. An empty ciphertext is an error.@@ -250,13 +251,13 @@ pub fn generate_rsa_key_pair_js() -> Result<JsValue, JsValue> {/// RSA-OAEP-256 decrypt base64 ciphertext with a JWK private key.#[wasm_bindgen(js_name = rsaDecrypt)]pub fn rsa_decrypt_js(base64_ciphertext: &str, private_key_jwk: &str) -> Result<Vec<u8>, JsValue> {- crate::crypto::decrypt_with_private_key(base64_ciphertext, private_key_jwk).map_err(js_err)+ crate::crypto::rsa_oaep::decrypt(base64_ciphertext, private_key_jwk, &[]).map_err(js_err)}/// Decrypt the shared manifest name encrypted into an invitation for this JWK private key.#[wasm_bindgen(js_name = decryptManifestInvitationName)]pub fn decrypt_manifest_invitation_name_js(encrypted_name: &str, manifest_id: &str, private_key_jwk: &str) -> Result<String, JsValue> {- crate::crypto::decrypt_manifest_invitation_name(encrypted_name, manifest_id, private_key_jwk).map_err(js_err)+ crate::vault_sync::keys::decrypt_manifest_invitation_name(encrypted_name, manifest_id, private_key_jwk).map_err(js_err)}/// Encrypt .avux bytes into an .avex file under the export password.diff --git a/core/rust/src/common/gzip.rs b/core/rust/src/common/gzip.rsindex cad4ac8ab..59a019e01 100644--- a/core/rust/src/common/gzip.rs+++ b/core/rust/src/common/gzip.rs@@ -1,14 +1,29 @@-//! Capped gunzip shared by the vault payload codec and the email parser.+//! gzip and capped gunzip shared by the vault payload codec and the email parser.-use std::io::Read;+use std::io::{Read, Write};++use flate2::write::GzEncoder;+use flate2::Compression;use crate::common::error::{VaultError, VaultResult};/// gzip magic bytes (RFC 1952) that every gzip stream starts with.-pub(crate) const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b];+const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b];++/// gzip the given bytes.+pub(crate) fn gzip(bytes: &[u8]) -> VaultResult<Vec<u8>> {+ let mut encoder = GzEncoder::new(Vec::new(), Compression::default());+ encoder.write_all(bytes).map_err(|e| VaultError::General(format!("gzip write failed: {}", e)))?;+ encoder.finish().map_err(|e| VaultError::General(format!("gzip finish failed: {}", e)))+}++/// Whether `bytes` start with the gzip magic bytes.+pub(crate) fn is_gzip(bytes: &[u8]) -> bool {+ bytes.starts_with(&GZIP_MAGIC)+}/// Gunzip `bytes`, refusing output above `limit` bytes.-pub(crate) fn gunzip_capped(bytes: &[u8], limit: u64) -> VaultResult<Vec<u8>> {+pub(crate) fn gunzip(bytes: &[u8], limit: u64) -> VaultResult<Vec<u8>> {let mut out = Vec::new();flate2::read::GzDecoder::new(bytes).take(limit + 1).read_to_end(&mut out).map_err(|e| VaultError::General(format!("gunzip failed: {}", e)))?;if out.len() as u64 > limit {diff --git a/core/rust/src/common/tests/gzip.rs b/core/rust/src/common/tests/gzip.rsnew file mode 100644index 000000000..60f05c88b--- /dev/null+++ b/core/rust/src/common/tests/gzip.rs@@ -0,0 +1,22 @@+use crate::common::gzip::*;++#[test]+fn gzip_round_trips() {+ let text = r#"{"hello":"world","n":42}"#;+ let gz = gzip(text.as_bytes()).unwrap();+ assert!(is_gzip(&gz));+ assert_eq!(gunzip(&gz, 1024).unwrap(), text.as_bytes());+}++#[test]+fn rejects_input_that_is_not_gzip() {+ assert!(!is_gzip(b"{}"));+ assert!(gunzip(b"{}", 1024).is_err());+}++#[test]+fn rejects_output_over_the_limit() {+ let gz = gzip(&[b'a'; 1025]).unwrap();+ assert!(gunzip(&gz, 1024).is_err());+ assert_eq!(gunzip(&gz, 1025).unwrap().len(), 1025);+}diff --git a/core/rust/src/common/tests/mod.rs b/core/rust/src/common/tests/mod.rsindex 10ab6fb80..28ffbe799 100644--- a/core/rust/src/common/tests/mod.rs+++ b/core/rust/src/common/tests/mod.rs@@ -1,6 +1,7 @@//! Tests of the common modules, one file per module.mod encoding;+mod gzip;mod rng;mod secret;mod timestamp;diff --git a/core/rust/src/crypto/argon2.rs b/core/rust/src/crypto/argon2.rsindex ff1870901..f8d0ba20b 100644--- a/core/rust/src/crypto/argon2.rs+++ b/core/rust/src/crypto/argon2.rs@@ -86,16 +86,3 @@ pub fn argon2_derive_key(password: &[u8], salt: &[u8], params: Argon2Params) ->Ok(output)}--/// 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<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<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/mobile_login.rs b/core/rust/src/crypto/mobile_login.rsindex 2615e6510..ac7dfd8bc 100644--- a/core/rust/src/crypto/mobile_login.rs+++ b/core/rust/src/crypto/mobile_login.rs@@ -7,7 +7,7 @@ use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};use super::aad;use super::aes_gcm::decrypt_text;-use super::rsa_oaep::decrypt_with_private_key_and_label;+use super::rsa_oaep;use crate::common::encoding::{base64_encode, base64url_encode};use crate::common::error::VaultResult;@@ -37,9 +37,14 @@ pub struct MobileLoginApproval {pub payload: String,}+/// Encrypt the Account Key for a mobile login request's JWK public key, as base64.+pub fn mobile_login_encrypt_account_key(account_key: &[u8], public_key_jwk: &str) -> VaultResult<String> {+ rsa_oaep::encrypt(account_key, public_key_jwk, aad::MOBILE_LOGIN_ACCOUNT_KEY)+}+/// Open an approved mobile login request with the request's one-off JWK private key.pub fn mobile_login_open_approval(private_key_jwk: &str, encrypted_account_key: &str, encrypted_payload_key: &str, encrypted_payload: &str) -> VaultResult<MobileLoginApproval> {- let account_key = Zeroizing::new(decrypt_with_private_key_and_label(encrypted_account_key, private_key_jwk, aad::MOBILE_LOGIN_ACCOUNT_KEY)?);- let payload_key = Zeroizing::new(base64_encode(&Zeroizing::new(decrypt_with_private_key_and_label(encrypted_payload_key, private_key_jwk, aad::MOBILE_LOGIN_PAYLOAD_KEY)?)));+ let account_key = Zeroizing::new(rsa_oaep::decrypt(encrypted_account_key, private_key_jwk, aad::MOBILE_LOGIN_ACCOUNT_KEY)?);+ let payload_key = Zeroizing::new(base64_encode(&Zeroizing::new(rsa_oaep::decrypt(encrypted_payload_key, private_key_jwk, aad::MOBILE_LOGIN_PAYLOAD_KEY)?)));Ok(MobileLoginApproval { account_key: base64_encode(&account_key), payload: decrypt_text(encrypted_payload, &payload_key, &[])? })}diff --git a/core/rust/src/crypto/mod.rs b/core/rust/src/crypto/mod.rsindex 540992874..dc162c662 100644--- a/core/rust/src/crypto/mod.rs+++ b/core/rust/src/crypto/mod.rs@@ -39,9 +39,9 @@ pub use key_chain::{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};+pub use mobile_login::{mobile_login_encrypt_account_key, mobile_login_open_approval, mobile_login_public_key_hash, mobile_login_verification_code, MobileLoginApproval};pub use pin::{pin_decrypt, pin_encrypt, pin_extension_salt, pin_generate_salt, pin_is_locked, pin_register_failure, PinFailure};-pub use rsa_oaep::{decrypt_manifest_invitation_name, decrypt_with_private_key, decrypt_with_private_key_and_label, encrypt_with_public_key_and_label, generate_rsa_key_pair, RsaKeyPair};+pub use rsa_oaep::{generate_rsa_key_pair, RsaKeyPair};pub use signing::generate_signing_key_pair;pub use vault_blob::{vault_blob_decrypt, vault_blob_encrypt};diff --git a/core/rust/src/crypto/pin.rs b/core/rust/src/crypto/pin.rsindex c15361b38..559663ce0 100644--- a/core/rust/src/crypto/pin.rs+++ b/core/rust/src/crypto/pin.rs@@ -8,7 +8,7 @@ use crate::common::error::{VaultError, VaultResult};use crate::common::rng::random_bytes;use crate::common::encoding::base64_encode;use crate::crypto::aes_gcm;-use crate::crypto::argon2::argon2_derive_key_bytes_from_settings;+use crate::crypto::argon2::{argon2_derive_key, Argon2Params};/// Failed attempts after which the PIN is locked and the host deletes the encrypted key.pub const PIN_MAX_ATTEMPTS: u32 = 4;@@ -17,7 +17,7 @@ pub const PIN_MAX_ATTEMPTS: u32 = 4;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.-pub(super) const PIN_ARGON2_SETTINGS: &str = r#"{"MemorySize":65536,"Iterations":3,"DegreeOfParallelism":1}"#;+pub(super) const PIN_ARGON2_PARAMS: Argon2Params = Argon2Params { memory_kib: 65536, iterations: 3, parallelism: 1 };/// The counter state after a failed PIN attempt.#[derive(Clone, Debug, PartialEq, Eq, Serialize)]@@ -68,6 +68,6 @@ pub fn pin_register_failure(failed_attempts: u32) -> PinFailure {}fn derive_pin_key(pin: &str, salt: &[u8]) -> VaultResult<Zeroizing<String>> {- let key = argon2_derive_key_bytes_from_settings(pin.as_bytes(), salt, PIN_ARGON2_SETTINGS).map_err(|e| VaultError::General(e.to_string()))?;+ let key = argon2_derive_key(pin.as_bytes(), salt, PIN_ARGON2_PARAMS).map_err(|e| VaultError::General(e.to_string()))?;Ok(Zeroizing::new(base64_encode(&key)))}diff --git a/core/rust/src/crypto/rsa_oaep.rs b/core/rust/src/crypto/rsa_oaep.rsindex cbb00ffbe..98f87d19d 100644--- a/core/rust/src/crypto/rsa_oaep.rs+++ b/core/rust/src/crypto/rsa_oaep.rs@@ -47,36 +47,20 @@ pub fn validate_rsa_key_pair(key_pair: &RsaKeyPair) -> VaultResult<()> {Ok(())}-/// 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)?))-}--/// Decrypt the shared manifest name encrypted into an invitation for this JWK private key, as UTF-8 text.-pub fn decrypt_manifest_invitation_name(encrypted_name: &str, manifest_id: &str, private_key_jwk: &str) -> VaultResult<String> {- let plaintext = decrypt_with_private_key_and_label(encrypted_name, private_key_jwk, &super::aad::invitation_name(manifest_id))?;- String::from_utf8(plaintext).map_err(|_| VaultError::General("Decrypted invitation name is not valid text".to_string()))-}--fn encrypt(plaintext: &[u8], public_key_jwk: &str, padding: Oaep) -> VaultResult<String> {+/// Encrypt bytes for the holder of a JWK public key under an OAEP label, which decryption must present as-is. Returns base64.+/// An empty label is plain OAEP.+pub fn encrypt(plaintext: &[u8], public_key_jwk: &str, label: &[u8]) -> VaultResult<String> {let public = oaep_public_from_jwk(public_key_jwk)?;+ let padding = Oaep::new_with_label::<Sha256, _>(label_text(label)?);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>> {+/// Decrypt base64 ciphertext with a JWK private key, under the OAEP label it was encrypted with.+pub fn decrypt(base64_ciphertext: &str, private_key_jwk: &str, label: &[u8]) -> VaultResult<Vec<u8>> {let private = rsa_private_from_jwk(private_key_jwk)?;let ciphertext = base64_decode(base64_ciphertext)?;+ let padding = Oaep::new_with_label::<Sha256, _>(label_text(label)?);// Blinded, which reduces but does not remove the timing leak of RUSTSEC-2023-0071 (Marvin attack): the rsa crate's// big-integer arithmetic is not constant time. Accepted because decryption runs on the client only.privatediff --git a/core/rust/src/crypto/tests/argon2.rs b/core/rust/src/crypto/tests/argon2.rsindex cb6be52df..c88d72278 100644--- a/core/rust/src/crypto/tests/argon2.rs+++ b/core/rust/src/crypto/tests/argon2.rs@@ -17,7 +17,7 @@ fn rejects_incomplete_or_empty_settings() {#[test]fn rejects_params_below_the_minimum() {for settings in [r#"{"DegreeOfParallelism":1,"MemorySize":19455,"Iterations":2}"#, r#"{"DegreeOfParallelism":1,"MemorySize":65536,"Iterations":1}"#, r#"{"DegreeOfParallelism":0,"MemorySize":65536,"Iterations":5}"#] {- assert!(matches!(argon2_derive_key_from_settings("password", "[email protected]", settings), Err(Argon2Error::InvalidParameter(_))), "accepted {settings}");+ assert!(matches!(derive("password", "[email protected]", settings), Err(Argon2Error::InvalidParameter(_))), "accepted {settings}");}}@@ -30,7 +30,11 @@ fn matches_the_reference_implementation() {(r#"{"DegreeOfParallelism":1,"MemorySize":65536,"Iterations":5}"#, "j7bnKpt3W46ak6Qid2JENR7NxznhfgRNDWAImnpAc40="),];for (settings, expected) in cases {- let key = argon2_derive_key_from_settings("password", "[email protected]", settings).unwrap();+ let key = derive("password", "[email protected]", settings).unwrap();assert_eq!(base64_encode(&key), expected, "settings {settings}");}}++fn derive(password: &str, salt: &str, settings: &str) -> Result<zeroize::Zeroizing<Vec<u8>>, Argon2Error> {+ argon2_derive_key(password.as_bytes(), salt.as_bytes(), Argon2Params::from_settings_json(settings)?)+}diff --git a/core/rust/src/crypto/tests/mobile_login.rs b/core/rust/src/crypto/tests/mobile_login.rsindex 89125daf8..407db1438 100644--- a/core/rust/src/crypto/tests/mobile_login.rs+++ b/core/rust/src/crypto/tests/mobile_login.rs@@ -1,7 +1,7 @@use crate::crypto::aad;use crate::crypto::aes_gcm::{encrypt_text, generate_key};use crate::crypto::mobile_login::*;-use crate::crypto::rsa_oaep::{encrypt_with_public_key_and_label, generate_rsa_key_pair};+use crate::crypto::rsa_oaep::{self, generate_rsa_key_pair};/// Known-answer vectors from the former TypeScript implementation, which released clients still run. A changed output/// means an old and a new client no longer agree on the QR code or the code they show. Never regenerate them.@@ -19,8 +19,8 @@ fn approval_opens_with_the_request_key_and_rejects_swapped_labels() {let pair = generate_rsa_key_pair().unwrap();let account_key = [7u8; 32];let payload_key = generate_key();- let encrypted_account_key = encrypt_with_public_key_and_label(&account_key, &pair.public_key, aad::MOBILE_LOGIN_ACCOUNT_KEY).unwrap();- let encrypted_payload_key = encrypt_with_public_key_and_label(&crate::common::encoding::base64_decode(&payload_key).unwrap(), &pair.public_key, aad::MOBILE_LOGIN_PAYLOAD_KEY).unwrap();+ let encrypted_account_key = mobile_login_encrypt_account_key(&account_key, &pair.public_key).unwrap();+ let encrypted_payload_key = rsa_oaep::encrypt(&crate::common::encoding::base64_decode(&payload_key).unwrap(), &pair.public_key, aad::MOBILE_LOGIN_PAYLOAD_KEY).unwrap();let encrypted_payload = encrypt_text(r#"{"username":"u"}"#, &payload_key, &[]).unwrap();let approval = mobile_login_open_approval(&pair.private_key, &encrypted_account_key, &encrypted_payload_key, &encrypted_payload).unwrap();diff --git a/core/rust/src/crypto/tests/pin.rs b/core/rust/src/crypto/tests/pin.rsindex ba84c4da4..133f50193 100644--- a/core/rust/src/crypto/tests/pin.rs+++ b/core/rust/src/crypto/tests/pin.rs@@ -1,6 +1,6 @@use crate::common::encoding::base64_encode;use crate::crypto::aes_gcm;-use crate::crypto::argon2::argon2_derive_key_bytes_from_settings;+use crate::crypto::argon2::argon2_derive_key;use crate::crypto::pin::*;#[test]@@ -18,7 +18,7 @@ fn round_trips_and_rejects_a_wrong_pin() {#[test]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 key = argon2_derive_key(b"8765432", salt, PIN_ARGON2_PARAMS).unwrap();let encrypted = aes_gcm::encrypt(b"secret", &base64_encode(&key), &[]).unwrap();assert_eq!(*pin_decrypt("8765432", salt, &encrypted).unwrap(), b"secret");}diff --git a/core/rust/src/crypto/tests/rsa_oaep.rs b/core/rust/src/crypto/tests/rsa_oaep.rsindex e664cb395..b67facf01 100644--- a/core/rust/src/crypto/tests/rsa_oaep.rs+++ b/core/rust/src/crypto/tests/rsa_oaep.rs@@ -1,30 +1,21 @@-use crate::crypto::aad;use crate::crypto::rsa_oaep::*;#[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");+ let ciphertext = encrypt(b"vek", &pair.public_key, b"grant/a").unwrap();+ assert_eq!(decrypt(&ciphertext, &pair.private_key, b"grant/a").unwrap(), b"vek");+ assert!(decrypt(&ciphertext, &pair.private_key, b"grant/b").is_err());+ assert!(decrypt(&ciphertext, &pair.private_key, b"").is_err(), "a labelled ciphertext does not open without its label");}#[test]fn unlabelled_ciphertext_opens_without_a_label_only() {let pair = generate_rsa_key_pair().unwrap();- let ciphertext = encrypt_with_public_key_and_label(b"email key", &pair.public_key, b"").unwrap();- assert_eq!(decrypt_with_private_key(&ciphertext, &pair.private_key).unwrap(), b"email key", "an empty label is the plain OAEP the server uses for email keys");- assert!(decrypt_with_private_key_and_label(&ciphertext, &pair.private_key, b"grant/a").is_err());- assert!(decrypt_with_private_key(&ciphertext, &generate_rsa_key_pair().unwrap().private_key).is_err());-}--#[test]-fn manifest_invitation_name_is_bound_to_its_manifest() {- let pair = generate_rsa_key_pair().unwrap();- let ciphertext = encrypt_with_public_key_and_label("Family".as_bytes(), &pair.public_key, &aad::invitation_name("A")).unwrap();- assert_eq!(decrypt_manifest_invitation_name(&ciphertext, "a", &pair.private_key).unwrap(), "Family");- assert!(decrypt_manifest_invitation_name(&ciphertext, "b", &pair.private_key).is_err());+ let ciphertext = encrypt(b"email key", &pair.public_key, b"").unwrap();+ assert_eq!(decrypt(&ciphertext, &pair.private_key, b"").unwrap(), b"email key", "an empty label is the plain OAEP the server uses for email keys");+ assert!(decrypt(&ciphertext, &pair.private_key, b"grant/a").is_err());+ assert!(decrypt(&ciphertext, &generate_rsa_key_pair().unwrap().private_key, b"").is_err());}#[test]diff --git a/core/rust/src/email_parser/mod.rs b/core/rust/src/email_parser/mod.rsindex 76bc3938b..609344fb5 100644--- a/core/rust/src/email_parser/mod.rs+++ b/core/rust/src/email_parser/mod.rs@@ -3,7 +3,7 @@ use mail_parser::{GetHeader, Message, MessageParser, MessagePart, MimeHeaders};use serde::Serialize;use crate::common::error::{VaultError, VaultResult};-use crate::common::gzip::{gunzip_capped, GZIP_MAGIC};+use crate::common::gzip::{gunzip, is_gzip};/// Header the server stamps on an attachment whose body it detached from the source at ingest, carrying the/// index that body is stored and requested under. Reading the index from the message itself keeps it@@ -82,10 +82,10 @@ pub fn parse_email_source(source: &[u8]) -> VaultResult<ParsedEmail> {/// Turn a stored email source into the raw RFC 822 message bytes: gunzip the source-only storage/// format, repair the double encoding of the legacy format. Clients use this for the source view.pub fn decode_email_source(source: &[u8]) -> VaultResult<Vec<u8>> {- Ok(match decompress_if_gzip(source)? {- MaybeDecompressed::Decompressed(raw) => raw,- MaybeDecompressed::AsIs(raw) => repair_legacy_double_encoding(raw),- })+ if is_gzip(source) {+ return gunzip(source, MAX_DECOMPRESSED_EMAIL_BYTES);+ }+ Ok(repair_legacy_double_encoding(source.to_vec()))}/// Extract the decoded bytes of a single attachment, identified by its index in@@ -159,24 +159,7 @@ fn header_u64(part: &MessagePart<'_>, name: &str) -> Option<u64> {/// Decompress a stored detached attachment body. Unlike the message source there is no legacy encoding to/// repair: detached parts only exist in the source-only storage format.fn decode_detached_part(body: &[u8]) -> VaultResult<Vec<u8>> {- Ok(match decompress_if_gzip(body)? {- MaybeDecompressed::Decompressed(bytes) | MaybeDecompressed::AsIs(bytes) => bytes,- })-}--/// The outcome of the gzip check, which also tells the caller which storage format the source came from.-enum MaybeDecompressed {- Decompressed(Vec<u8>),- AsIs(Vec<u8>),-}--/// Gunzip the input when it starts with the gzip magic bytes (0x1f 0x8b), pass it through otherwise.-fn decompress_if_gzip(source: &[u8]) -> VaultResult<MaybeDecompressed> {- if !source.starts_with(&GZIP_MAGIC) {- return Ok(MaybeDecompressed::AsIs(source.to_vec()));- }-- gunzip_capped(source, MAX_DECOMPRESSED_EMAIL_BYTES).map(MaybeDecompressed::Decompressed)+ gunzip(body, MAX_DECOMPRESSED_EMAIL_BYTES)}/// Undo the Latin-1 then UTF-8 double encoding of legacy (pre-0.31.0) stored sources, where `é` (`C3 A9`) became `C3 83 C2 A9`.diff --git a/core/rust/src/email_parser/tests/mod.rs b/core/rust/src/email_parser/tests/mod.rsindex 6738f54d5..579263487 100644--- a/core/rust/src/email_parser/tests/mod.rs+++ b/core/rust/src/email_parser/tests/mod.rs@@ -1,5 +1,4 @@use super::*;-use std::io::Write;const PLAIN_EMAIL: &str = "From: Alice <[email protected]>\r\n\To: [email protected]\r\n\@@ -45,9 +44,7 @@ Content-Transfer-Encoding: 8bit\r\n\Special symbols: é€ñ ∑ • ≈\r\n";fn gzip(data: &[u8]) -> Vec<u8> {- let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());- encoder.write_all(data).unwrap();- encoder.finish().unwrap()+ crate::common::gzip::gzip(data).unwrap()}/// Reproduce how the server used to store a legacy email source: the raw bytes read back as Latin-1@@ -230,10 +227,3 @@ fn json_output_uses_camel_case_fields() {assert!(json.contains("\"mimeType\""));assert!(!json.contains("\"contentBase64\""), "attachment bytes must not ride along in the parse result");}--#[test]-fn gunzip_rejects_output_over_the_limit() {- let compressed = gzip(&[b'a'; 1025]);- assert!(gunzip_capped(&compressed, 1024).is_err());- assert_eq!(gunzip_capped(&compressed, 1025).unwrap().len(), 1025);-}diff --git a/core/rust/src/vault_codec/compress.rs b/core/rust/src/vault_codec/compress.rsdeleted file mode 100644index 178daba8e..000000000--- a/core/rust/src/vault_codec/compress.rs+++ /dev/null@@ -1,45 +0,0 @@-//! gzip compress / gunzip decompress.--use std::io::Write;--use flate2::write::GzEncoder;-use flate2::Compression;--use crate::common::error::{VaultError, VaultResult};-use crate::common::gzip::{gunzip_capped, GZIP_MAGIC};--/// gzip the given bytes.-pub fn gzip(bytes: &[u8]) -> VaultResult<Vec<u8>> {- let mut encoder = GzEncoder::new(Vec::new(), Compression::default());- encoder- .write_all(bytes)- .map_err(|e| VaultError::General(format!("gzip write failed: {}", e)))?;- encoder- .finish()- .map_err(|e| VaultError::General(format!("gzip finish failed: {}", e)))-}--/// Cap on a decompressed payload, so a gzip bomb in a shared manifest cannot exhaust memory. Derived from the-/// server's default `MAX_UPLOAD_SIZE_MB` (100 MB per vault write, compressed): 5x that leaves room for highly-/// compressible JSON.-pub const MAX_DECOMPRESSED_PAYLOAD_BYTES: u64 = 512 * 1024 * 1024;--/// Decompress gzipped bytes into a UTF-8 string, refusing output above [`MAX_DECOMPRESSED_PAYLOAD_BYTES`].-pub fn gunzip_to_string(bytes: &[u8]) -> VaultResult<String> {- gunzip_to_string_capped(bytes, MAX_DECOMPRESSED_PAYLOAD_BYTES)-}--/// Decompress gzipped bytes into a UTF-8 string, refusing output above `limit` bytes.-pub(super) fn gunzip_to_string_capped(bytes: &[u8], limit: u64) -> VaultResult<String> {- String::from_utf8(gunzip_capped(bytes, limit)?).map_err(|e| VaultError::General(format!("gunzip failed: {}", e)))-}--/// Decompress a packed payload to its envelope JSON string, supporting both gzipped and plain values:-/// gzip (leading `1f 8b`) is gunzipped; anything else is treated as raw, uncompressed UTF-8 JSON.-pub fn decompress_to_string(bytes: &[u8]) -> VaultResult<String> {- if bytes.starts_with(&GZIP_MAGIC) {- return gunzip_to_string(bytes);- }- String::from_utf8(bytes.to_vec())- .map_err(|e| VaultError::General(format!("uncompressed payload is not valid UTF-8: {}", e)))-}diff --git a/core/rust/src/vault_codec/mod.rs b/core/rust/src/vault_codec/mod.rsindex 125534252..1da44ed52 100644--- a/core/rust/src/vault_codec/mod.rs+++ b/core/rust/src/vault_codec/mod.rs@@ -1,9 +1,8 @@//! The manifest-v1 storage format: `canonicalize` maps the local SQLite tables to manifests, data buckets and//! content-addressed blobs, `materialize` maps them back. The codec knows the format rules (routing by manifest,-//! `integrity`, `logos`, `normalize`), the payload envelope (`hash`, `compress`) and `validate`; encryption and+//! `integrity`, `logos`, `normalize`), the payload envelope (`hash`, gzip) and `validate`; encryption and//! storage stay with the caller.-mod compress;mod canonicalize;pub(crate) mod integrity;pub(crate) mod normalize;@@ -19,6 +18,7 @@ mod validate;use serde_json::json;use crate::common::encoding::hex_encode_lower;+use crate::common::gzip::{gunzip, gzip};use crate::common::error::{VaultError, VaultResult};pub use types::SCHEMA_VERSION;@@ -68,16 +68,21 @@ pub fn pack_payload(payload_json: &str) -> VaultResult<Vec<u8>> {"payload": payload,});let envelope_json = serde_json::to_string(&envelope)?;- compress::gzip(envelope_json.as_bytes())+ gzip(envelope_json.as_bytes())}+/// Cap on a decompressed payload, so a gzip bomb in a shared manifest cannot exhaust memory. Derived from the+/// server's default `MAX_UPLOAD_SIZE_MB` (100 MB per vault write, compressed): 5x that leaves room for highly+/// compressible JSON.+const MAX_DECOMPRESSED_PAYLOAD_BYTES: u64 = 512 * 1024 * 1024;+/// A decompressed payload envelope: its content, or the format version of one this build cannot read.pub enum UnpackedPayload {Readable(String),NewerFormat(u32),}-/// Unpack a payload: decompress (gzip or plain JSON) > parse envelope > verify the embedded content hash.+/// Unpack a payload: gunzip > parse envelope > verify the embedded content hash./// Refuses an envelope written at a format version this build cannot read.pub fn unpack_payload(plain_bytes: &[u8]) -> VaultResult<String> {match unpack_versioned_payload(plain_bytes)? {@@ -89,8 +94,9 @@ pub fn unpack_payload(plain_bytes: &[u8]) -> VaultResult<String> {/// [`unpack_payload`], reporting a newer format version as a value instead of an error. The version is read/// before the content hash, since a newer format may hash differently and must not read as corruption.pub fn unpack_versioned_payload(plain_bytes: &[u8]) -> VaultResult<UnpackedPayload> {- let envelope_json = compress::decompress_to_string(plain_bytes)?;- let envelope: serde_json::Value = serde_json::from_str(&envelope_json)?;+ let decompressed = gunzip(plain_bytes, MAX_DECOMPRESSED_PAYLOAD_BYTES)?;+ let envelope_json = std::str::from_utf8(&decompressed).map_err(|e| VaultError::General(format!("payload is not valid UTF-8: {}", e)))?;+ let envelope: serde_json::Value = serde_json::from_str(envelope_json)?;let version = envelope.get("schemaVersion").and_then(|v| v.as_u64()).ok_or_else(|| VaultError::General("envelope missing schemaVersion".to_string()))?;let version = u32::try_from(version).unwrap_or(u32::MAX);diff --git a/core/rust/src/vault_codec/tests/compress.rs b/core/rust/src/vault_codec/tests/compress.rsdeleted file mode 100644index 44d3a2423..000000000--- a/core/rust/src/vault_codec/tests/compress.rs+++ /dev/null@@ -1,16 +0,0 @@-use crate::vault_codec::compress::*;--#[test]-fn gzip_roundtrips() {- let text = r#"{"hello":"world","n":42}"#;- let gz = gzip(text.as_bytes()).unwrap();- assert_eq!(&gz[0..2], &[0x1f, 0x8b]);- assert_eq!(gunzip_to_string(&gz).unwrap(), text);-}--#[test]-fn gunzip_rejects_output_over_the_limit() {- let gz = gzip(&[b'a'; 1025]).unwrap();- assert!(gunzip_to_string_capped(&gz, 1024).is_err());- assert_eq!(gunzip_to_string_capped(&gz, 1025).unwrap().len(), 1025);-}diff --git a/core/rust/src/vault_codec/tests/mod.rs b/core/rust/src/vault_codec/tests/mod.rsindex f65849425..71990f6c3 100644--- a/core/rust/src/vault_codec/tests/mod.rs+++ b/core/rust/src/vault_codec/tests/mod.rs@@ -5,7 +5,6 @@pub(crate) mod support;mod sharing;-mod compress;mod hash;mod integrity;mod normalize;@@ -147,11 +146,11 @@ fn packing_wraps_a_payload_in_a_verified_envelope() {// Tampered: the original hash over a changed payload.let envelope = json!({ "schemaVersion": 1, "contentHash": super::hash::content_hash(&json!({ "a": 1 })), "payload": { "a": 2 } });- assert!(unpack_payload(&super::compress::gzip(envelope.to_string().as_bytes()).unwrap()).is_err());+ assert!(unpack_payload(&crate::common::gzip::gzip(envelope.to_string().as_bytes()).unwrap()).is_err());// A format version this build cannot read is reported as such, before the hash is checked.let newer = json!({ "schemaVersion": SCHEMA_VERSION + 1, "contentHash": "x", "payload": {} });- assert!(matches!(unpack_versioned_payload(&super::compress::gzip(newer.to_string().as_bytes()).unwrap()).unwrap(), UnpackedPayload::NewerFormat(v) if v == SCHEMA_VERSION + 1));+ assert!(matches!(unpack_versioned_payload(&crate::common::gzip::gzip(newer.to_string().as_bytes()).unwrap()).unwrap(), UnpackedPayload::NewerFormat(v) if v == SCHEMA_VERSION + 1));}#[test]diff --git a/core/rust/src/vault_sync/keys.rs b/core/rust/src/vault_sync/keys.rsindex fea0ff716..71df9a794 100644--- a/core/rust/src/vault_sync/keys.rs+++ b/core/rust/src/vault_sync/keys.rs@@ -9,6 +9,7 @@ use super::session::Host;use super::state::{self, Ctx};use super::types::{ManifestDto, SharedManifestDto, VaultKeyGetResponse, VaultKeyResponse, ALGORITHM_AES256_GCM, ALGORITHM_RSA_OAEP_SHA256};use super::http;+use crate::common::error::{VaultError, VaultResult};use crate::common::secret::from_zeroizing;use secrecy::{ExposeSecret, SecretString};use crate::crypto;@@ -247,15 +248,26 @@ pub(crate) async fn resolve_grant_private_key(ctx: &Ctx, public_key: &str) -> Sy/// 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))?)+ Ok(crypto::rsa_oaep::encrypt(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<SecretString> {- let plaintext = Zeroizing::new(crypto::decrypt_with_private_key_and_label(encrypted_vek, private_key_jwk, &crypto::aad::grant(manifest_id))?);+ let plaintext = Zeroizing::new(crypto::rsa_oaep::decrypt(encrypted_vek, private_key_jwk, &crypto::aad::grant(manifest_id))?);std::str::from_utf8(&plaintext).map(SecretString::from).map_err(|_| SyncError::Other("Decrypted manifest key is not valid text".to_string()))}+/// Encrypt a shared manifest's name into an invitation for one recipient key, bound to the manifest (see [`crypto::aad::invitation_name`]).+pub(crate) fn encrypt_manifest_invitation_name(name: &str, manifest_id: &str, recipient_public_key_jwk: &str) -> VaultResult<String> {+ crypto::rsa_oaep::encrypt(name.as_bytes(), recipient_public_key_jwk, &crypto::aad::invitation_name(manifest_id))+}++/// Decrypt the shared manifest name encrypted into an invitation for this JWK private key, as UTF-8 text.+pub(crate) fn decrypt_manifest_invitation_name(encrypted_name: &str, manifest_id: &str, private_key_jwk: &str) -> VaultResult<String> {+ let plaintext = crypto::rsa_oaep::decrypt(encrypted_name, private_key_jwk, &crypto::aad::invitation_name(manifest_id))?;+ String::from_utf8(plaintext).map_err(|_| VaultError::General("Decrypted invitation name is not valid text".to_string()))+}+/// 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 {diff --git a/core/rust/src/vault_sync/mod.rs b/core/rust/src/vault_sync/mod.rsindex a9711d31b..1b9be9d46 100644--- a/core/rust/src/vault_sync/mod.rs+++ b/core/rust/src/vault_sync/mod.rs@@ -7,7 +7,7 @@ mod engine;pub(crate) mod errors;mod frame;mod http;-mod keys;+pub(crate) mod keys;mod legacy;mod merge;mod migration;diff --git a/core/rust/src/vault_sync/sharing.rs b/core/rust/src/vault_sync/sharing.rsindex b29cc5b77..3af6d1315 100644--- a/core/rust/src/vault_sync/sharing.rs+++ b/core/rust/src/vault_sync/sharing.rs@@ -598,7 +598,7 @@ async fn invite_to_shared_manifest(ctx: &mut Ctx) -> Outcome {// The name travels encrypted in the invitation, so the recipient sees what they are invited to.let name = record.encrypted_name.as_deref().and_then(|ciphertext| pull::open_manifest_name(ciphertext, &manifest.manifest_id, manifest_vek.expose_secret())).filter(|name| name.len() <= MAX_SHARED_MANIFEST_NAME_BYTES);let encrypted_vek = keys::encrypt_manifest_vek(manifest_vek.expose_secret(), &manifest.manifest_id, &recipient_public_key)?;- let encrypted_name = name.map(|name| crypto::encrypt_with_public_key_and_label(name.as_bytes(), &recipient_public_key, &crypto::aad::invitation_name(&manifest.manifest_id))).transpose()?;+ let encrypted_name = name.map(|name| keys::encrypt_manifest_invitation_name(&name, &manifest.manifest_id, &recipient_public_key)).transpose()?;let grant = ManifestGrant {recipient_user_id: recipient.user_id.clone(),recipient_account_public_key_id: recipient_public_key_id,diff --git a/core/rust/src/vault_sync/tests/keys.rs b/core/rust/src/vault_sync/tests/keys.rsindex db1ee3052..17a7ab266 100644--- a/core/rust/src/vault_sync/tests/keys.rs+++ b/core/rust/src/vault_sync/tests/keys.rs@@ -7,6 +7,7 @@ use super::test_host::{open_schema_db, TestHost};use super::{insert_item, legacy_device, server_with_item, state, ITEM_A, PERSONAL_MANIFEST_ID};use crate::crypto;use crate::vault_codec;+use crate::vault_sync::keys::{decrypt_manifest_invitation_name, encrypt_manifest_invitation_name};use crate::vault_sync::types::Command;use secrecy::ExposeSecret;@@ -169,3 +170,11 @@ fn a_legacy_account_is_probed_for_a_vault_key_only_when_it_pulls_or_pushes() {assert_eq!(result["success"], true, "{}", result);assert_eq!(host.requests_to("VaultKey/Password").len(), 1, "dirty: probed once");}++#[test]+fn manifest_invitation_name_is_bound_to_its_manifest() {+ let pair = crypto::generate_rsa_key_pair().unwrap();+ let ciphertext = encrypt_manifest_invitation_name("Family", "A", &pair.public_key).unwrap();+ assert_eq!(decrypt_manifest_invitation_name(&ciphertext, "a", &pair.private_key).unwrap(), "Family");+ assert!(decrypt_manifest_invitation_name(&ciphertext, "b", &pair.private_key).is_err());+}