use aes_gcm::aead::generic_array::GenericArray; use aes_gcm::aead::Aead; use aes_gcm::{Aes256Gcm, KeyInit}; use anyhow::{anyhow, Result}; use argon2::{Algorithm, Argon2, Params, Version}; use hmac::{Hmac, Mac}; use rand::RngCore; use serde::{Deserialize, Serialize}; use sha2::Sha256; use std::fs; use std::path::Path; const NONCE_LEN: usize = 12; const SALT_LEN: usize = 16; pub struct VaultKey { cipher: Aes256Gcm, } impl VaultKey { /// Opens an existing key or creates one. A salt with no `kdf.json` stays /// PBKDF2 so vaults created before Argon2id still open. A missing salt is a /// new vault and uses Argon2id. pub fn derive_from_passphrase(passphrase: &str, salt_path: &Path) -> Result { if passphrase.is_empty() { anyhow::bail!("vault passphrase is required"); } let marker = salt_path.with_file_name("kdf.json"); if marker.exists() { let spec: KdfSpec = serde_json::from_slice(&fs::read(&marker)?)?; let salt = fs::read(salt_path)?; restrict_secret_file(salt_path)?; return derive_marked(passphrase, &salt, &spec); } if salt_path.exists() { restrict_secret_file(salt_path)?; let salt = fs::read(salt_path)?; return cipher_from_key(&pbkdf2_key(passphrase, &salt)); } let mut salt = [0u8; SALT_LEN]; rand::thread_rng().fill_bytes(&mut salt); if let Some(parent) = salt_path.parent() { fs::create_dir_all(parent)?; } fs::write(salt_path, salt)?; restrict_secret_file(salt_path)?; let spec = KdfSpec::argon2id(); fs::write(&marker, serde_json::to_vec_pretty(&spec)?)?; restrict_secret_file(&marker)?; derive_marked(passphrase, &salt, &spec) } pub fn encrypt(&self, plaintext: &[u8]) -> Result> { let mut nonce_bytes = [0u8; NONCE_LEN]; rand::thread_rng().fill_bytes(&mut nonce_bytes); let nonce = GenericArray::from_slice(&nonce_bytes); let ciphertext = self .cipher .encrypt(nonce, plaintext) .map_err(|e| anyhow!("encrypt: {e}"))?; let mut out = nonce_bytes.to_vec(); out.extend(ciphertext); Ok(out) } pub fn decrypt(&self, blob: &[u8]) -> Result> { if blob.len() < NONCE_LEN { anyhow::bail!("blob too short"); } let (nonce_bytes, ct) = blob.split_at(NONCE_LEN); let nonce = GenericArray::from_slice(nonce_bytes); self.cipher .decrypt(nonce, ct) .map_err(|e| anyhow!("decrypt: {e}")) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] struct KdfSpec { kdf: String, #[serde(default = "default_m_kib")] m_kib: u32, #[serde(default = "default_t")] t: u32, #[serde(default = "default_p")] p: u32, } fn default_m_kib() -> u32 { 19_456 } fn default_t() -> u32 { 2 } fn default_p() -> u32 { 1 } impl KdfSpec { fn argon2id() -> Self { Self { kdf: "argon2id".into(), m_kib: default_m_kib(), t: default_t(), p: default_p(), } } } fn pbkdf2_key(passphrase: &str, salt: &[u8]) -> [u8; 32] { pbkdf2_hmac_sha256(passphrase.as_bytes(), salt, 100_000) } fn pbkdf2_hmac_sha256(password: &[u8], salt: &[u8], iterations: u32) -> [u8; 32] { // RFC 8018 PBKDF2-HMAC-SHA256, one block (dkLen = 32). This is the historical // vault KDF, so existing salt files still open. type HmacSha256 = Hmac; let mut block = { let mut mac = ::new_from_slice(password).expect("hmac accepts any key length"); mac.update(salt); mac.update(&1u32.to_be_bytes()); mac.finalize().into_bytes() }; let mut derived = block; for _ in 1..iterations { let mut mac = ::new_from_slice(password).expect("hmac accepts any key length"); mac.update(&block); block = mac.finalize().into_bytes(); for (slot, byte) in derived.iter_mut().zip(block.iter()) { *slot ^= *byte; } } derived.into() } fn derive_marked(passphrase: &str, salt: &[u8], spec: &KdfSpec) -> Result { let key = match spec.kdf.as_str() { "argon2id" => { let params = Params::new(spec.m_kib, spec.t, spec.p, Some(32)) .map_err(|e| anyhow!("argon2 params: {e}"))?; let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params); let mut key = [0u8; 32]; argon .hash_password_into(passphrase.as_bytes(), salt, &mut key) .map_err(|e| anyhow!("argon2id: {e}"))?; key } "pbkdf2" => pbkdf2_key(passphrase, salt), other => anyhow::bail!("unknown vault kdf: {other}"), }; cipher_from_key(&key) } fn cipher_from_key(key: &[u8; 32]) -> Result { let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| anyhow!("cipher key: {e}"))?; Ok(VaultKey { cipher }) } fn restrict_secret_file(path: &Path) -> Result<()> { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; fs::set_permissions(path, fs::Permissions::from_mode(0o600))?; } #[cfg(not(unix))] let _ = path; Ok(()) } pub fn content_id(data: &[u8]) -> String { use sha2::Digest; hex::encode(Sha256::digest(data)) } pub fn pack_path(data_dir: &Path, id: &str) -> std::path::PathBuf { let prefix = &id[..2.min(id.len())]; data_dir.join(prefix).join(id) } #[cfg(test)] mod tests { use super::*; use aes_gcm::aead::generic_array::GenericArray; use aes_gcm::aead::Aead; use aes_gcm::{Aes256Gcm, KeyInit}; use tempfile::tempdir; #[test] fn roundtrip_crypto() { let dir = tempdir().unwrap(); let salt = dir.path().join("salt"); let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap(); let enc = key.encrypt(b"stardust").unwrap(); let plain = key.decrypt(&enc).unwrap(); assert_eq!(plain, b"stardust"); } #[test] fn rejects_empty_passphrase() { let dir = tempdir().unwrap(); let err = VaultKey::derive_from_passphrase("", &dir.path().join("salt")); assert!(err.is_err()); } #[cfg(unix)] #[test] fn salt_file_is_owner_only() { use std::os::unix::fs::PermissionsExt; let dir = tempdir().unwrap(); let salt = dir.path().join("salt"); VaultKey::derive_from_passphrase("test-vault", &salt).unwrap(); let mode = fs::metadata(&salt).unwrap().permissions().mode() & 0o777; assert_eq!(mode, 0o600); } #[test] fn new_vault_uses_argon2id() { let dir = tempdir().unwrap(); let salt = dir.path().join("tessera.salt"); let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap(); let marker: serde_json::Value = serde_json::from_slice(&fs::read(dir.path().join("kdf.json")).unwrap()).unwrap(); assert_eq!(marker["kdf"], "argon2id"); let enc = key.encrypt(b"stardust").unwrap(); let raw_salt = fs::read(&salt).unwrap(); let legacy = pbkdf2_key("test-vault", &raw_salt); let legacy_cipher = Aes256Gcm::new_from_slice(&legacy).unwrap(); let nonce = GenericArray::from_slice(&enc[..NONCE_LEN]); assert!(legacy_cipher.decrypt(nonce, &enc[NONCE_LEN..]).is_err()); assert_eq!(key.decrypt(&enc).unwrap(), b"stardust"); } #[test] fn pbkdf2_matches_the_rfc_vector() { let key = super::pbkdf2_hmac_sha256(b"password", b"salt", 4096); assert_eq!( hex::encode(key), "c5e478d59288c841aa530db6845c4c8d962893a001ce4e11a4963873aa98134a" ); } #[test] fn existing_pbkdf2_salt_still_opens() { let dir = tempdir().unwrap(); let salt = dir.path().join("tessera.salt"); fs::write(&salt, b"0123456789abcdef").unwrap(); let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap(); assert!(!dir.path().join("kdf.json").exists()); let enc = key.encrypt(b"legacy").unwrap(); let legacy = pbkdf2_key("test-vault", b"0123456789abcdef"); let legacy_cipher = Aes256Gcm::new_from_slice(&legacy).unwrap(); let nonce = GenericArray::from_slice(&enc[..NONCE_LEN]); let plain = legacy_cipher.decrypt(nonce, &enc[NONCE_LEN..]).unwrap(); assert_eq!(plain, b"legacy"); } }