fix: harden the vault before release
Require a private passphrase and loopback-or-token admin auth. New vaults use Argon2id; existing PBKDF2 vaults still open, and new snapshot metadata is encrypted. Wormhole tokens survive restart, offset uploads seal into the vault, and client-certificate uploads are real. Reject the command provider and keep Postgres passwords off the process arguments. Keep the interruptible canvas motion.
This commit is contained in:
@@ -1,10 +1,11 @@
|
||||
use aes_gcm::aead::generic_array::GenericArray;
|
||||
use aes_gcm::aead::{Aead, NewAead};
|
||||
use aes_gcm::Aes256Gcm;
|
||||
use aes_gcm::aead::Aead;
|
||||
use aes_gcm::{Aes256Gcm, KeyInit};
|
||||
use anyhow::{anyhow, Result};
|
||||
use hmac::Hmac;
|
||||
use pbkdf2::pbkdf2;
|
||||
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;
|
||||
@@ -17,25 +18,37 @@ pub struct VaultKey {
|
||||
}
|
||||
|
||||
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<Self> {
|
||||
let salt = if salt_path.exists() {
|
||||
fs::read(salt_path)?
|
||||
} else {
|
||||
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)?;
|
||||
salt.to_vec()
|
||||
};
|
||||
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 key = [0u8; 32];
|
||||
pbkdf2::<Hmac<Sha256>>(passphrase.as_bytes(), &salt, 100_000, &mut key);
|
||||
|
||||
let cipher =
|
||||
Aes256Gcm::new_from_slice(&key).map_err(|e| anyhow!("cipher key: {e}"))?;
|
||||
Ok(Self { cipher })
|
||||
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<Vec<u8>> {
|
||||
@@ -63,6 +76,100 @@ impl VaultKey {
|
||||
}
|
||||
}
|
||||
|
||||
#[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<Sha256>;
|
||||
let mut block = {
|
||||
let mut mac =
|
||||
<HmacSha256 as 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 =
|
||||
<HmacSha256 as 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<VaultKey> {
|
||||
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<VaultKey> {
|
||||
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))
|
||||
@@ -76,6 +183,9 @@ pub fn pack_path(data_dir: &Path, id: &str) -> std::path::PathBuf {
|
||||
#[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]
|
||||
@@ -87,4 +197,63 @@ mod tests {
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user