Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor common encoding calls to encoding.rs (#2159)
Leendert de Borstebc6b6664bbb
diff --git a/core/rust/src/crypto/aes_gcm.rs b/core/rust/src/crypto/aes_gcm.rsindex b8c4c071e..eb8132bc6 100644--- a/core/rust/src/crypto/aes_gcm.rs+++ b/core/rust/src/crypto/aes_gcm.rs@@ -2,11 +2,11 @@use aes_gcm::aead::{Aead, KeyInit, Payload};use aes_gcm::{Aes256Gcm, Nonce};-use base64::engine::general_purpose::STANDARD as BASE64;-use base64::Engine;use zeroize::{Zeroize, Zeroizing};+use crate::encoding::{base64_decode, base64_encode};use crate::error::{VaultError, VaultResult};+use crate::rng::fill_random;const IV_LENGTH: usize = 12;const KEY_LENGTH: usize = 32;@@ -14,15 +14,15 @@ const KEY_LENGTH: usize = 32;/// A fresh random 256-bit key as base64.pub fn generate_key_base64() -> String {let mut key = Zeroizing::new([0u8; KEY_LENGTH]);- super::fill_random(&mut key[..]);- BASE64.encode(&key[..])+ fill_random(&mut key[..]);+ base64_encode(&key[..])}/// Encrypt bytes with a base64 key. Returns base64 of `IV | ciphertext | tag`.pub fn symmetric_encrypt_bytes(plaintext: &[u8], key_base64: &str) -> VaultResult<String> {let cipher = cipher_for(key_base64)?;let mut iv = [0u8; IV_LENGTH];- super::fill_random(&mut iv);+ fill_random(&mut iv);let ciphertext = cipher.encrypt(Nonce::from_slice(&iv), Payload { msg: plaintext, aad: &[] })@@ -31,7 +31,7 @@ pub fn symmetric_encrypt_bytes(plaintext: &[u8], key_base64: &str) -> VaultResullet mut combined = Vec::with_capacity(IV_LENGTH + ciphertext.len());combined.extend_from_slice(&iv);combined.extend_from_slice(&ciphertext);- Ok(BASE64.encode(combined))+ Ok(base64_encode(&combined))}/// Decrypt `IV | ciphertext | tag` bytes with a base64 key.@@ -59,7 +59,7 @@ pub fn symmetric_decrypt(base64_ciphertext: &str, key_base64: &str) -> VaultResuif base64_ciphertext.is_empty() {return Ok(String::new());}- let bytes = decode_base64(base64_ciphertext)?;+ let bytes = base64_decode(base64_ciphertext)?;let plaintext = symmetric_decrypt_bytes(&bytes, key_base64)?;match String::from_utf8(plaintext) {Ok(text) => Ok(text),@@ -70,13 +70,8 @@ pub fn symmetric_decrypt(base64_ciphertext: &str, key_base64: &str) -> VaultResu}}-/// Decode a base64 string, with the error the callers report.-pub(crate) fn decode_base64(value: &str) -> VaultResult<Vec<u8>> {- BASE64.decode(value).map_err(|_| VaultError::General("Invalid base64".to_string()))-}-fn cipher_for(key_base64: &str) -> VaultResult<Aes256Gcm> {- let key = Zeroizing::new(decode_base64(key_base64)?);+ let key = Zeroizing::new(base64_decode(key_base64)?);if key.len() != KEY_LENGTH {return Err(VaultError::General(format!("AES-GCM key must be {} bytes, got {}", KEY_LENGTH, key.len())));}@@ -92,7 +87,7 @@ mod tests {let key = generate_key_base64();let bytes: Vec<u8> = (0..=255u8).collect();let encrypted = symmetric_encrypt_bytes(&bytes, &key).unwrap();- assert_eq!(symmetric_decrypt_bytes(&decode_base64(&encrypted).unwrap(), &key).unwrap(), bytes);+ assert_eq!(symmetric_decrypt_bytes(&base64_decode(&encrypted).unwrap(), &key).unwrap(), bytes);let encrypted = symmetric_encrypt("héllo ✓", &key).unwrap();assert_eq!(symmetric_decrypt(&encrypted, &key).unwrap(), "héllo ✓");@@ -112,7 +107,7 @@ mod tests {#[test]fn layout_is_iv_then_ciphertext_then_tag() {let key = generate_key_base64();- let encrypted = decode_base64(&symmetric_encrypt_bytes(b"abc", &key).unwrap()).unwrap();+ let encrypted = base64_decode(&symmetric_encrypt_bytes(b"abc", &key).unwrap()).unwrap();assert_eq!(encrypted.len(), IV_LENGTH + 3 + 16);}}diff --git a/core/rust/src/crypto/argon2.rs b/core/rust/src/crypto/argon2.rsindex a42eb0ebb..f171a7b8d 100644--- a/core/rust/src/crypto/argon2.rs+++ b/core/rust/src/crypto/argon2.rs@@ -127,6 +127,22 @@ pub fn argon2_derive_key(password: &[u8], salt: &[u8], params: Argon2Params) ->/// # Returns/// The derived key, [`ARGON2_OUTPUT_LENGTH`] bytes long.pub fn argon2_derive_key_from_settings(password: &str, salt: &str, settings_json: &str) -> Result<Vec<u8>, Argon2Error> {+ argon2_derive_key_bytes_from_settings(password.as_bytes(), salt.as_bytes(), settings_json)+}++/// Derives a 32-byte key from raw password and salt bytes using the cost parameters stated as settings JSON.+///+/// The mobile PIN unlock draws its salt from the Keychain/Keystore as random bytes, which are not+/// valid UTF-8, so it needs this byte entry point rather than the string one.+///+/// # Arguments+/// * `password` - The password bytes.+/// * `salt` - The salt bytes, at least 8 bytes long.+/// * `settings_json` - The `EncryptionSettings` JSON, or an empty string for the defaults.+///+/// # Returns+/// The derived key, [`ARGON2_OUTPUT_LENGTH`] bytes long.+pub fn argon2_derive_key_bytes_from_settings(password: &[u8], salt: &[u8], settings_json: &str) -> Result<Vec<u8>, Argon2Error> {let params = Argon2Params::from_settings_json(settings_json)?;- argon2_derive_key(password.as_bytes(), salt.as_bytes(), params)+ argon2_derive_key(password, salt, params)}diff --git a/core/rust/src/crypto/key_chain.rs b/core/rust/src/crypto/key_chain.rsindex d2da64cca..33a7c6edc 100644--- a/core/rust/src/crypto/key_chain.rs+++ b/core/rust/src/crypto/key_chain.rs@@ -5,11 +5,10 @@ use serde::{Deserialize, Serialize};use std::fmt;use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};-use super::aes_gcm::{decode_base64, generate_key_base64, symmetric_decrypt_bytes, symmetric_encrypt, symmetric_encrypt_bytes};+use super::aes_gcm::{generate_key_base64, symmetric_decrypt_bytes, symmetric_encrypt, symmetric_encrypt_bytes};use super::rsa_oaep::generate_rsa_key_pair;+use crate::encoding::{base64_decode, base64_encode};use crate::error::VaultResult;-use base64::engine::general_purpose::STANDARD as BASE64;-use base64::Engine;/// The wrapped halves of an account key hierarchy: what the server stores.#[derive(Debug, Clone, Serialize, Deserialize)]@@ -44,13 +43,13 @@ impl fmt::Debug for AccountKeyHierarchy {/// Wrap a base64 key with another base64 key. Returns base64 of `IV | ciphertext | tag`.pub fn wrap_key(key_base64: &str, wrapping_key_base64: &str) -> VaultResult<String> {- symmetric_encrypt_bytes(&Zeroizing::new(decode_base64(key_base64)?), wrapping_key_base64)+ symmetric_encrypt_bytes(&Zeroizing::new(base64_decode(key_base64)?), wrapping_key_base64)}/// Unwrap a wrapped key. Returns the key as base64.pub fn unwrap_key(wrapped_key_base64: &str, wrapping_key_base64: &str) -> VaultResult<Zeroizing<String>> {- let raw = Zeroizing::new(symmetric_decrypt_bytes(&decode_base64(wrapped_key_base64)?, wrapping_key_base64)?);- Ok(Zeroizing::new(BASE64.encode(&raw[..])))+ let raw = Zeroizing::new(symmetric_decrypt_bytes(&base64_decode(wrapped_key_base64)?, wrapping_key_base64)?);+ Ok(Zeroizing::new(base64_encode(&raw[..])))}/// Turn a password-derived key into the vault encryption key: KEK > Account Key > VEK. Returns the VEK and thediff --git a/core/rust/src/crypto/mod.rs b/core/rust/src/crypto/mod.rsindex d44a09863..c529a5a3f 100644--- a/core/rust/src/crypto/mod.rs+++ b/core/rust/src/crypto/mod.rs@@ -10,14 +10,9 @@ pub use aes_gcm::{generate_key_base64, symmetric_decrypt, symmetric_decrypt_bytepub use key_chain::{create_account_key_hierarchy, resolve_vault_encryption_key, unwrap_key, wrap_key, AccountKeyBlobs, AccountKeyHierarchy};pub use rsa_oaep::{decrypt_with_private_key, encrypt_with_public_key, generate_rsa_key_pair, RsaKeyPair};-pub use self::argon2::{argon2_derive_key, argon2_derive_key_from_settings, Argon2Error, Argon2Params};+pub use self::argon2::{argon2_derive_key, argon2_derive_key_bytes_from_settings, argon2_derive_key_from_settings, Argon2Error, Argon2Params};pub use self::srp::{srp_derive_private_key, srp_derive_session, srp_derive_session_server, srp_derive_verifier,- srp_generate_ephemeral, srp_generate_ephemeral_server, srp_generate_salt,+ srp_generate_ephemeral, srp_generate_ephemeral_server, srp_generate_salt, srp_verify_session,SrpEphemeral, SrpError, SrpSession,};--/// Fill a buffer from the operating system's CSPRNG.-pub(crate) fn fill_random(dest: &mut [u8]) {- getrandom::fill(dest).expect("the OS CSPRNG is unavailable");-}diff --git a/core/rust/src/crypto/rsa_oaep.rs b/core/rust/src/crypto/rsa_oaep.rsindex 720a9042c..297cb143a 100644--- a/core/rust/src/crypto/rsa_oaep.rs+++ b/core/rust/src/crypto/rsa_oaep.rs@@ -1,6 +1,6 @@//! RSA-OAEP (SHA-256) with keys carried as JWK JSON strings compatible with the WebCrypto API.-use base64::engine::general_purpose::{STANDARD as BASE64, URL_SAFE_NO_PAD as BASE64_URL};+use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64_URL;use base64::Engine;use rsa::traits::{PrivateKeyParts, PublicKeyParts};use rsa::{BigUint, Oaep, RsaPrivateKey, RsaPublicKey};@@ -9,6 +9,7 @@ use sha2::Sha256;use std::fmt;use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};+use crate::encoding::{base64_decode, base64_encode};use crate::error::{VaultError, VaultResult};const MODULUS_BITS: usize = 2048;@@ -50,37 +51,9 @@ struct RsaJwk {qi: Option<String>,}-/// Adapts the crate's CSPRNG to the `rand_core` version the `rsa` crate draws from.-struct CoreRng;--impl rand_core06::RngCore for CoreRng {- fn next_u32(&mut self) -> u32 {- let mut bytes = [0u8; 4];- super::fill_random(&mut bytes);- u32::from_le_bytes(bytes)- }-- fn next_u64(&mut self) -> u64 {- let mut bytes = [0u8; 8];- super::fill_random(&mut bytes);- u64::from_le_bytes(bytes)- }-- fn fill_bytes(&mut self, dest: &mut [u8]) {- super::fill_random(dest);- }-- fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core06::Error> {- super::fill_random(dest);- Ok(())- }-}--impl rand_core06::CryptoRng for CoreRng {}-/// Generate a 2048-bit RSA key pair for RSA-OAEP-256 grants.pub fn generate_rsa_key_pair() -> VaultResult<RsaKeyPair> {- let private = RsaPrivateKey::new(&mut CoreRng, MODULUS_BITS).map_err(|e| VaultError::General(format!("RSA key generation failed: {}", e)))?;+ let private = RsaPrivateKey::new(&mut rand_core06::OsRng, MODULUS_BITS).map_err(|e| VaultError::General(format!("RSA key generation failed: {}", e)))?;let public = private.to_public_key();Ok(RsaKeyPair { public_key: public_to_jwk(&public)?, private_key: private_to_jwk(&private)? })}@@ -89,19 +62,19 @@ pub fn generate_rsa_key_pair() -> VaultResult<RsaKeyPair> {pub fn encrypt_with_public_key(plaintext: &[u8], public_key_jwk: &str) -> VaultResult<String> {let public = public_from_jwk(public_key_jwk)?;let ciphertext = public- .encrypt(&mut CoreRng, Oaep::new::<Sha256>(), plaintext)+ .encrypt(&mut rand_core06::OsRng, Oaep::new::<Sha256>(), plaintext).map_err(|e| VaultError::General(format!("RSA-OAEP encryption failed: {}", e)))?;- Ok(BASE64.encode(ciphertext))+ Ok(base64_encode(&ciphertext))}/// Decrypt base64 ciphertext with a JWK private key.pub fn decrypt_with_private_key(base64_ciphertext: &str, private_key_jwk: &str) -> VaultResult<Vec<u8>> {let private = private_from_jwk(private_key_jwk)?;- let ciphertext = super::aes_gcm::decode_base64(base64_ciphertext)?;+ let ciphertext = base64_decode(base64_ciphertext)?;// Blinded: plain `decrypt` runs the exponentiation on the ciphertext as given, which leaks timing an// attacker who can submit chosen ciphertexts turns into key recovery (RUSTSEC-2023-0071, Marvin attack).private- .decrypt_blinded(&mut CoreRng, Oaep::new::<Sha256>(), &ciphertext)+ .decrypt_blinded(&mut rand_core06::OsRng, Oaep::new::<Sha256>(), &ciphertext).map_err(|_| VaultError::General("RSA-OAEP decryption failed (wrong key or corrupt data)".to_string()))}diff --git a/core/rust/src/crypto/srp.rs b/core/rust/src/crypto/srp.rsindex 54a49a27a..f05403df8 100644--- a/core/rust/src/crypto/srp.rs+++ b/core/rust/src/crypto/srp.rs@@ -15,7 +15,8 @@ use srp::utils::{compute_k, compute_u};use subtle::ConstantTimeEq;use thiserror::Error;-use crate::hex::bytes_to_hex;+use crate::encoding::{hex_decode, hex_encode_upper as bytes_to_hex};+use crate::rng::fill_random;/// Byte length of the 2048-bit group modulus N; all padded values use this size.const N_BYTES: usize = 256;@@ -53,49 +54,20 @@ pub enum SrpError {// Hex / Byte Helpers// ═══════════════════════════════════════════════════════════════════════════════-/// Convert hex string (upper- or lowercase, optional 0x prefix) to bytes.+/// Decode a hex parameter (either case, optional 0x prefix).fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, SrpError> {let hex = hex.trim();+ let hex = hex.strip_prefix("0x").or_else(|| hex.strip_prefix("0X")).unwrap_or(hex);if hex.is_empty() {return Err(SrpError::InvalidHex("empty hex string".to_string()));}-- let hex = hex- .strip_prefix("0x")- .or_else(|| hex.strip_prefix("0X"))- .unwrap_or(hex);-- let bytes = hex.as_bytes();- if bytes.len() % 2 != 0 {- return Err(SrpError::InvalidHex(format!(- "odd length hex string: {}",- bytes.len()- )));- }-- fn nibble(b: u8, pos: usize) -> Result<u8, SrpError> {- match b {- b'0'..=b'9' => Ok(b - b'0'),- b'a'..=b'f' => Ok(b - b'a' + 10),- b'A'..=b'F' => Ok(b - b'A' + 10),- _ => Err(SrpError::InvalidHex(format!(- "invalid hex at position {}",- pos- ))),- }- }-- bytes- .chunks_exact(2)- .enumerate()- .map(|(i, pair)| Ok(nibble(pair[0], i * 2)? << 4 | nibble(pair[1], i * 2 + 1)?))- .collect()+ hex_decode(hex).ok_or_else(|| SrpError::InvalidHex(format!("malformed hex string of length {}", hex.len())))}/// Generate cryptographically secure random bytes.fn generate_random_bytes(len: usize) -> Vec<u8> {let mut bytes = vec![0u8; len];- super::fill_random(&mut bytes);+ fill_random(&mut bytes);bytes}diff --git a/core/rust/src/encoding.rs b/core/rust/src/encoding.rsnew file mode 100644index 000000000..2bdeff5fc--- /dev/null+++ b/core/rust/src/encoding.rs@@ -0,0 +1,83 @@+//! Crate-wide byte encodings: hex, base64 and the UUID text form.++use base64::engine::general_purpose::STANDARD as BASE64;+use base64::Engine;++use crate::error::{VaultError, VaultResult};++/// Lowercase hex of a byte slice.+pub(crate) fn hex_encode_lower(bytes: &[u8]) -> String {+ hex_encode(bytes, b"0123456789abcdef")+}++/// Uppercase hex of a byte slice.+pub(crate) fn hex_encode_upper(bytes: &[u8]) -> String {+ hex_encode(bytes, b"0123456789ABCDEF")+}++fn hex_encode(bytes: &[u8], alphabet: &[u8; 16]) -> String {+ let mut out = String::with_capacity(bytes.len() * 2);+ for &b in bytes {+ out.push(alphabet[(b >> 4) as usize] as char);+ out.push(alphabet[(b & 0x0F) as usize] as char);+ }+ out+}++/// Decode a hex string of either case. `None` on odd length or a non-hex character.+pub(crate) fn hex_decode(hex: &str) -> Option<Vec<u8>> {+ let bytes = hex.as_bytes();+ if bytes.len() % 2 != 0 {+ return None;+ }+ bytes.chunks_exact(2).map(|pair| Some((nibble(pair[0])? << 4) | nibble(pair[1])?)).collect()+}++fn nibble(b: u8) -> Option<u8> {+ match b {+ b'0'..=b'9' => Some(b - b'0'),+ b'a'..=b'f' => Some(b - b'a' + 10),+ b'A'..=b'F' => Some(b - b'A' + 10),+ _ => None,+ }+}++/// Standard base64 (padded) of a byte slice.+pub(crate) fn base64_encode(bytes: &[u8]) -> String {+ BASE64.encode(bytes)+}++/// Decode a standard base64 string, with the error the callers report.+pub(crate) fn base64_decode(value: &str) -> VaultResult<Vec<u8>> {+ BASE64.decode(value).map_err(|_| VaultError::General("Invalid base64".to_string()))+}++/// The lowercase `8-4-4-4-12` text form of 16 bytes.+pub(crate) fn format_uuid(bytes: &[u8; 16]) -> String {+ let hex = hex_encode_lower(bytes);+ format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32])+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn hex_round_trips_in_both_cases() {+ let bytes = vec![0x00u8, 0x1f, 0xab, 0xff];+ assert_eq!(hex_encode_lower(&bytes), "001fabff");+ assert_eq!(hex_encode_upper(&bytes), "001FABFF");+ assert_eq!(hex_decode("001fabff").unwrap(), bytes);+ assert_eq!(hex_decode("001FABFF").unwrap(), bytes);+ assert_eq!(hex_decode(""), Some(Vec::new()));+ assert_eq!(hex_decode("abc"), None);+ assert_eq!(hex_decode("gg"), None);+ assert_eq!(hex_decode("0é9"), None);+ }++ #[test]+ fn uuid_text_form_is_lowercase_and_grouped() {+ let bytes = [0xABu8; 16];+ assert_eq!(format_uuid(&bytes), "abababab-abab-abab-abab-abababababab");+ }+}diff --git a/core/rust/src/error.rs b/core/rust/src/error.rsindex 4719c5ee9..040cd0ec4 100644--- a/core/rust/src/error.rs+++ b/core/rust/src/error.rs@@ -1,5 +1,7 @@//! Error types for the AliasVault core library.+use serde::de::DeserializeOwned;+use serde::Serialize;use thiserror::Error;/// Errors that can occur during vault operations.@@ -27,3 +29,8 @@ impl From<serde_json::Error> for VaultError {/// Result type alias for vault operations.pub type VaultResult<T> = Result<T, VaultError>;++/// Run a typed entry point on JSON: parse the input, serialize the output. The bindings' JSON siblings.+pub fn json_call<I: DeserializeOwned, O: Serialize>(input_json: &str, f: impl FnOnce(I) -> VaultResult<O>) -> VaultResult<String> {+ Ok(serde_json::to_string(&f(serde_json::from_str(input_json)?)?)?)+}