diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fd6e6e..4d65ece 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versioning: se - An identity added with `vault add-recipient --gpub` (or `vault rotate --add-recipient`) can now open its vault: `verify`, `list`, `cat`, `open` and `rotate` unwrap the epoch key from the identity's X25519 recipient entry. Before, only symmetric recipients were matched and the added key failed with an authentication error. - `vault rotate` reseals from the epoch key it actually unwrapped, so a rotation run by an X25519 identity no longer resets the current manifest. - `vault rotate` fails closed: it refuses a kept symmetric recipient it cannot re-wrap (that recipient would be locked out), an unusable X25519 public, or a kept set no one can open; it verifies the new wraps, the new manifest and every resealed object before the header commits, and restores the old epoch on any failure. +- `geode tui` unlocks a vault with an X25519 identity added with `vault add-recipient` (and after the original key was dropped by a rotate): it unwraps the epoch key from the identity's recipient entry, the same path the CLI uses, instead of re-deriving it from the ISK. A key with no recipient entry is refused (exit 2). - `vault rotate` without `--reseal` on a vault that holds entries is now refused (exit 1, vault unchanged) with a hint to re-run with `--reseal`. It used to publish an empty new-epoch manifest, so every entry vanished from `list`/`cat`/`open`. Rotating an empty vault without `--reseal` still works. - A failed `vault rotate` now also removes the old-epoch recipients snapshot it wrote, and a failure while restoring is reported together with the original error (nonzero exit) instead of being ignored. diff --git a/crates/geode-cli/src/cmd/key.rs b/crates/geode-cli/src/cmd/key.rs index f3c8507..87623ef 100644 --- a/crates/geode-cli/src/cmd/key.rs +++ b/crates/geode-cli/src/cmd/key.rs @@ -19,11 +19,6 @@ use zeroize::Zeroizing; use crate::{cmd, OutMode}; -/// BLAKE3 domain for the identity's X25519 static secret (02-cryptography -/// 6.3: "derived from BLAKE3-expand(ISK) streams"). CLI-local until the -/// spec pins the exact string; changing it changes every `.gpub`. -const X25519_IDENTITY_DOMAIN: &str = "geode/v1/x25519-identity"; - #[derive(Args, Debug)] pub struct KeygenArgs { /// Destination key file (default ./secret.gkey, with a warning). @@ -270,18 +265,6 @@ fn keychain_store(path: &Path, label: &str, key_id: &KeyId, pass: &str) -> Resul } } -/// Derive the identity's X25519 static secret from the ISK (BLAKE3-expand -/// stream, 02-cryptography 6.3). Secret material: never log or print. -pub(crate) fn x25519_secret(isk: &[u8; 32]) -> zeroize::Zeroizing<[u8; 32]> { - zeroize::Zeroizing::new(blake3::derive_key(X25519_IDENTITY_DOMAIN, isk)) -} - -/// The identity's X25519 public key (the `.gpub` `x25519_public`). -pub(crate) fn x25519_public(isk: &[u8; 32]) -> [u8; 32] { - let sk = x25519_dalek::StaticSecret::from(*x25519_secret(isk)); - x25519_dalek::PublicKey::from(&sk).to_bytes() -} - /// Write `.gpub` (02-cryptography 6.3): a public JSON /// document — version, `key_id`, X25519 public (base64). Contains no secret /// material; written 0644. Refuses to overwrite (same as the `.gkey`). @@ -290,7 +273,9 @@ fn write_gpub(gkey_path: &std::path::Path, isk: &[u8; 32], key_id: &KeyId) -> Re let doc = serde_json::json!({ "version": 1, "key_id": cmd::hex(&key_id.0), - "x25519_public": Base64::encode_string(&x25519_public(isk)), + "x25519_public": Base64::encode_string(&geode_grotto::recipients::x25519_identity_public( + &geode_grotto::kdf::IdentitySecret::from_bytes(*isk), + )), }); let text = serde_json::to_string_pretty(&doc) .map_err(|e| Error::Format(format!("gpub serialize: {e}")))?; diff --git a/crates/geode-cli/src/cmd/mod.rs b/crates/geode-cli/src/cmd/mod.rs index ccafb4b..0834673 100644 --- a/crates/geode-cli/src/cmd/mod.rs +++ b/crates/geode-cli/src/cmd/mod.rs @@ -30,7 +30,7 @@ use std::path::{Path, PathBuf}; use geode_grotto::kdf::{self, Epoch, EpochKey, IdentitySecret, KeyId, VaultId}; use geode_grotto::manifest::{self, Manifest}; -use geode_grotto::recipients::{self, Recipient, Recipients}; +use geode_grotto::recipients::{self, Recipients}; use geode_grotto::{Error, Result}; use zeroize::Zeroize; @@ -296,32 +296,19 @@ fn load_recipients_for( let rec_text = std::fs::read_to_string(root.join("recipients.json")).map_err(Error::Io)?; let recs: Recipients = serde_json::from_str(&rec_text) .map_err(|e| Error::Format(format!("recipients.json: {e}")))?; - let own_public = key::x25519_public(isk.as_bytes()); - for r in &recs.recipients { - match r { - Recipient::Symmetric { key_id: kid, .. } if kid.0 == key_id => { - return recipients::unwrap_symmetric(r, isk, vault_id, epoch); - } - // A recipient added with `vault add-recipient --gpub` (or - // `rotate --add-recipient`) holds an X25519 wrap of the EK; its - // identity unwraps it with the ISK-derived X25519 secret. - Recipient::X25519 { public, .. } if x25519_public_matches(public, &own_public) => { - let sk = key::x25519_secret(isk.as_bytes()); - return recipients::unwrap_x25519(r, &sk, vault_id, epoch); - } - _ => {} - } + // Symmetric recipient by key_id, or the X25519 recipient (added with + // `vault add-recipient --gpub` / `rotate --add-recipient`) whose public + // is this identity's. Shared with the TUI unlock (geode-grotto). + // The caller's key_id must be this identity's (checked in every build). + if !geode_grotto::zero::ct_eq(&kdf::derive_key_id(isk)?.0, &key_id) { + return Err(Error::AuthFail); } - Err(Error::AuthFail) + recipients::unwrap_for_identity(&recs, isk, vault_id, epoch) } /// True when a recipient's base64 X25519 public equals `own` (constant time). pub(crate) fn x25519_public_matches(public_b64: &str, own: &[u8; 32]) -> bool { - use base64ct::{Base64, Encoding}; - match Base64::decode_vec(public_b64) { - Ok(bytes) if bytes.len() == 32 => geode_grotto::zero::ct_eq(&bytes, own), - _ => false, - } + recipients::x25519_public_matches(public_b64, own) } pub(crate) fn load_manifest( diff --git a/crates/geode-cli/src/cmd/vault.rs b/crates/geode-cli/src/cmd/vault.rs index b9abcef..5843cf4 100644 --- a/crates/geode-cli/src/cmd/vault.rs +++ b/crates/geode-cli/src/cmd/vault.rs @@ -338,7 +338,7 @@ fn rotate(args: &RotateArgs, global: &GlobalArgs, out: OutMode) -> Result<()> { let recs: Recipients = serde_json::from_str(&rec_text) .map_err(|e| Error::Format(format!("recipients.json: {e}")))?; let keep = select_keep(recs.recipients, &args.drop_recipient, &args.add_recipient)?; - let own_public = cmd::key::x25519_public(isk.as_bytes()); + let own_public = recipients::x25519_identity_public(&isk); // Refuse before anything touches disk: a kept recipient this operator // cannot re-wrap correctly, or a kept set nobody could open. check_keep_reachable(&keep, ctx.key_id)?; @@ -538,7 +538,7 @@ fn verify_new_wraps( let ek = match r { Recipient::Symmetric { .. } => recipients::unwrap_symmetric(r, isk, vault_id, epoch)?, Recipient::X25519 { .. } => { - let sk = cmd::key::x25519_secret(isk.as_bytes()); + let sk = recipients::x25519_identity_secret(isk); recipients::unwrap_x25519(r, &sk, vault_id, epoch)? } Recipient::Hybrid { .. } => return Err(Error::NotImplemented), diff --git a/crates/geode-core/src/recipients.rs b/crates/geode-core/src/recipients.rs index 65df0d6..fabba9a 100644 --- a/crates/geode-core/src/recipients.rs +++ b/crates/geode-core/src/recipients.rs @@ -4,9 +4,69 @@ use crate::kdf::{Epoch, EpochKey, IdentitySecret, KeyId, VaultId}; use crate::{Error, Result}; + use aegis::aegis256x2::{Aegis256X2, Nonce}; use base64ct::{Base64, Encoding}; +/// BLAKE3 derive-key context for an identity's X25519 static secret +/// (02-cryptography 6.3). The `.gpub` public is derived the same way. +pub const X25519_IDENTITY_DOMAIN: &str = "geode/v1/x25519-identity"; + +/// The identity's X25519 static secret, derived from its ISK. +/// Secret material: never log or print. +#[must_use] +pub fn x25519_identity_secret(isk: &IdentitySecret) -> zeroize::Zeroizing<[u8; 32]> { + zeroize::Zeroizing::new(blake3::derive_key(X25519_IDENTITY_DOMAIN, isk.as_bytes())) +} + +/// The identity's X25519 public key (the `.gpub` `x25519_public`). +#[must_use] +pub fn x25519_identity_public(isk: &IdentitySecret) -> [u8; 32] { + let mut raw: [u8; 32] = *x25519_identity_secret(isk); + // StaticSecret zeroizes itself on drop; clear the by-value copy too. + let sk = x25519_dalek::StaticSecret::from(raw); + zeroize::Zeroize::zeroize(&mut raw); + x25519_dalek::PublicKey::from(&sk).to_bytes() +} + +/// True when a recipient's base64 X25519 public equals `own` (constant time). +#[must_use] +pub fn x25519_public_matches(public_b64: &str, own: &[u8; 32]) -> bool { + match Base64::decode_vec(public_b64) { + Ok(bytes) if bytes.len() == 32 => crate::zero::ct_eq(&bytes, own), + _ => false, + } +} + +/// Unwrap the epoch key for the identity holding `isk` from `recs`. +/// +/// Matches the identity's symmetric recipient (by `key_id`) or its X25519 +/// recipient (by public key, e.g. added with `vault add-recipient --gpub`) +/// and unwraps that entry. No matching entry, or a wrap that does not +/// authenticate, is [`Error::AuthFail`]. Errors never contain key bytes. +pub fn unwrap_for_identity( + recs: &Recipients, + isk: &IdentitySecret, + vault_id: VaultId, + epoch: Epoch, +) -> Result { + let key_id = crate::kdf::derive_key_id(isk)?; + let own_public = x25519_identity_public(isk); + for r in &recs.recipients { + match r { + Recipient::Symmetric { key_id: kid, .. } if *kid == key_id => { + return unwrap_symmetric(r, isk, vault_id, epoch); + } + Recipient::X25519 { public, .. } if x25519_public_matches(public, &own_public) => { + let sk = x25519_identity_secret(isk); + return unwrap_x25519(r, &sk, vault_id, epoch); + } + _ => {} + } + } + Err(Error::AuthFail) +} + /// Recipient kind (03-format 6). #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", rename_all = "lowercase")] @@ -654,3 +714,75 @@ mod x25519_tests { assert!(matches!(u, Err(Error::NotImplemented)), "got {u:?}"); } } + +#[cfg(test)] +mod identity_unwrap_tests { + use super::*; + use crate::kdf::{derive_epoch_key, derive_key_id}; + + fn isk(b: u8) -> IdentitySecret { + IdentitySecret::from_bytes([b; 32]) + } + + const VID: VaultId = VaultId([0x07; 16]); + + fn recs_for(ek: &EpochKey, owner: &IdentitySecret, added: &IdentitySecret) -> Recipients { + let sym = wrap_symmetric(ek, owner, VID, Epoch(1), derive_key_id(owner).unwrap()).unwrap(); + let x = wrap_x25519( + ek, + &x25519_identity_public(added), + VID, + Epoch(1), + derive_key_id(added).unwrap(), + ) + .unwrap(); + Recipients { + vault_id: crate::vault::hex_encode(&VID.0), + epoch: 1, + recipients: vec![sym, x], + } + } + + #[test] + fn symmetric_and_x25519_identities_unwrap_same_ek() { + let (owner, added) = (isk(1), isk(2)); + let ek = derive_epoch_key(&owner, VID, Epoch(1), "").unwrap(); + let recs = recs_for(&ek, &owner, &added); + let a = unwrap_for_identity(&recs, &owner, VID, Epoch(1)).unwrap(); + let b = unwrap_for_identity(&recs, &added, VID, Epoch(1)).unwrap(); + assert_eq!(a.as_bytes(), ek.as_bytes()); + assert_eq!(b.as_bytes(), ek.as_bytes()); + } + + #[test] + fn stranger_and_wrong_epoch_are_auth_fail() { + let (owner, added) = (isk(1), isk(2)); + let ek = derive_epoch_key(&owner, VID, Epoch(1), "").unwrap(); + let recs = recs_for(&ek, &owner, &added); + assert!(matches!( + unwrap_for_identity(&recs, &isk(3), VID, Epoch(1)), + Err(Error::AuthFail) + )); + assert!(matches!( + unwrap_for_identity(&recs, &added, VID, Epoch(2)), + Err(Error::AuthFail) + )); + } + + #[test] + fn identity_public_matches_gpub_derivation() { + let k = isk(9); + let sk = x25519_dalek::StaticSecret::from(*x25519_identity_secret(&k)); + assert_eq!( + x25519_dalek::PublicKey::from(&sk).to_bytes(), + x25519_identity_public(&k) + ); + let b64 = Base64::encode_string(&x25519_identity_public(&k)); + assert!(x25519_public_matches(&b64, &x25519_identity_public(&k))); + assert!(!x25519_public_matches( + &b64, + &x25519_identity_public(&isk(8)) + )); + assert!(!x25519_public_matches("not base64!", &[0u8; 32])); + } +} diff --git a/crates/geode-core/src/session.rs b/crates/geode-core/src/session.rs index ec540b6..c009537 100644 --- a/crates/geode-core/src/session.rs +++ b/crates/geode-core/src/session.rs @@ -93,6 +93,33 @@ impl Session { }) } + /// Unlock from the vault's recipients: unwrap the EK from the entry + /// this identity holds (symmetric or X25519), then zeroize ISK. + /// + /// Use this for an on-disk vault: it works for every recipient type the + /// CLI reads, including an identity added with `vault add-recipient`, + /// and for any epoch whose EK was not derived from this ISK. + pub fn unlock_recipients( + isk: IdentitySecret, + recs: &crate::recipients::Recipients, + vault_id: VaultId, + epoch: Epoch, + idle_timeout: Duration, + ) -> Result { + let key_id = derive_key_id(&isk)?; + let ek = crate::recipients::unwrap_for_identity(recs, &isk, vault_id, epoch)?; + drop(isk); + Ok(Self { + ek: Some(ek), + vault_id, + epoch, + key_id, + context_label: String::new(), + idle_timeout, + last_activity: Instant::now(), + }) + } + /// Convenience: unwrap a passphrase-wrapped `GKEY` then unlock. /// /// Loads ISK by unwrapping `wrapped` with `passphrase` (Argon2id + @@ -427,3 +454,40 @@ mod tests { assert!(s.is_locked()); } } + +#[cfg(test)] +mod unlock_recipients_tests { + use super::*; + use crate::kdf::derive_epoch_key; + use crate::recipients::{wrap_x25519, x25519_identity_public, Recipients}; + + #[test] + fn x25519_identity_unlocks_session() { + let owner = IdentitySecret::from_bytes([1; 32]); + let added = IdentitySecret::from_bytes([2; 32]); + let vid = VaultId([0x05; 16]); + let ek = derive_epoch_key(&owner, vid, Epoch(1), "").unwrap(); + let r = wrap_x25519( + &ek, + &x25519_identity_public(&added), + vid, + Epoch(1), + derive_key_id(&added).unwrap(), + ) + .unwrap(); + let recs = Recipients { + vault_id: crate::vault::hex_encode(&vid.0), + epoch: 1, + recipients: vec![r], + }; + let added_kid = derive_key_id(&added).unwrap(); + let s = Session::unlock_recipients(added, &recs, vid, Epoch(1), Duration::ZERO).unwrap(); + assert_eq!(s.ek().unwrap().as_bytes(), ek.as_bytes()); + assert_eq!(s.key_id, added_kid); + // The owner holds no entry here: fail closed. + assert!(matches!( + Session::unlock_recipients(owner, &recs, vid, Epoch(1), Duration::ZERO), + Err(Error::AuthFail) + )); + } +} diff --git a/crates/geode-tui/src/vault.rs b/crates/geode-tui/src/vault.rs index 5cceaa9..73c6035 100644 --- a/crates/geode-tui/src/vault.rs +++ b/crates/geode-tui/src/vault.rs @@ -26,6 +26,7 @@ use geode_grotto::kdf::{ }; use geode_grotto::manifest::{self, Manifest}; use geode_grotto::object::{self, ObjectHeader}; +use geode_grotto::recipients::Recipients; use geode_grotto::session::{Session, DEFAULT_IDLE_LOCK}; use geode_grotto::vault as corevault; use geode_grotto::{wrap, Error, Result}; @@ -333,11 +334,14 @@ pub fn open(vault: &Path, key: Option<&Path>) -> Result { .map_err(|_| Error::Format("epoch overflow".into()))?, ); - // Session::unlock derives EK from ISK + vault_id + epoch + context and - // zeroizes ISK before returning. Context label "" matches vault init - // (04-vault 1); the wrapped EK in recipients.json is this same EK. + // Unwrap EK from the recipient entry this identity holds (symmetric by + // key_id, or X25519 by public, e.g. added with `vault add-recipient`), + // the same path the CLI uses; ISK is zeroized before returning. No + // matching recipient is AuthFail (exit 2). + let recs: Recipients = serde_json::from_value(read_json(&vault.join("recipients.json"))?) + .map_err(|e| Error::Format(format!("recipients.json: {e}")))?; let key_id = kdf::derive_key_id(&isk)?; - let session = Session::unlock(isk, vault_id, epoch, "", DEFAULT_IDLE_LOCK)?; + let session = Session::unlock_recipients(isk, &recs, vault_id, epoch, DEFAULT_IDLE_LOCK)?; let ek = session.ek()?; let mk = derive_manifest_key(ek, vault_id, epoch); diff --git a/crates/geode-tui/tests/x25519_unlock.rs b/crates/geode-tui/tests/x25519_unlock.rs new file mode 100644 index 0000000..9aa7a97 --- /dev/null +++ b/crates/geode-tui/tests/x25519_unlock.rs @@ -0,0 +1,155 @@ +//! TUI unlock for an X25519 identity added with `vault add-recipient`. +//! +//! The fixture is built with the `geode` CLI (subprocess, dummy keys, +//! HOME/XDG isolated); the assertions drive `geode_tui::vault::open` +//! in-process, as the TUI does. + +#![cfg(feature = "tui")] + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +fn geode_bin() -> PathBuf { + for key in ["CARGO_BIN_EXE_GEO_DE", "CARGO_BIN_EXE_geode"] { + if let Ok(p) = std::env::var(key) { + let pb = PathBuf::from(p); + if pb.is_file() { + return pb; + } + } + } + if let Ok(td) = std::env::var("CARGO_TARGET_DIR") { + let pb = PathBuf::from(td).join("debug/geode"); + if pb.is_file() { + return pb; + } + } + let target_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target"); + let pb = target_root.join("debug/geode"); + if pb.is_file() { + return pb; + } + if let Ok(entries) = std::fs::read_dir(&target_root) { + for entry in entries.flatten() { + let pb = entry.path().join("debug/geode"); + if pb.is_file() { + return pb; + } + } + } + panic!("geode binary not found (build geode-cli first)"); +} + +fn geode(dir: &Path, args: &[&str]) -> Output { + let home = dir.join("home"); + let xdg = dir.join("xdg"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(&xdg).unwrap(); + let out = Command::new(geode_bin()) + .args(args) + .current_dir(dir) + .env("HOME", &home) + .env("XDG_CONFIG_HOME", &xdg) + .env("XDG_DATA_HOME", &xdg) + .env("XDG_CACHE_HOME", &xdg) + .env("XDG_STATE_HOME", &xdg) + .env_remove("GEODE_TOKEN") + .env_remove("GEODE_PASSPHRASE") + .output() + .expect("spawn geode"); + assert!( + out.status.success(), + "geode {args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); + out +} + +fn key_id(dir: &Path, gpub: &str) -> String { + let v: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(dir.join(gpub)).unwrap()).unwrap(); + v["key_id"].as_str().unwrap().to_string() +} + +/// Vault owned by `owner.gkey` holding `src/hello.txt`, plus `added.gkey` +/// as an X25519 recipient. +fn fixture(dir: &Path) { + geode(dir, &["keygen", "--insecure-plaintext", "owner.gkey"]); + geode(dir, &["keygen", "--insecure-plaintext", "added.gkey"]); + geode(dir, &["--key", "owner.gkey", "vault", "init", "v.geode"]); + std::fs::create_dir_all(dir.join("src")).unwrap(); + std::fs::write(dir.join("src/hello.txt"), b"hello world\n").unwrap(); + geode(dir, &["--key", "owner.gkey", "seal", "src", "v.geode"]); + geode( + dir, + &[ + "--key", + "owner.gkey", + "vault", + "add-recipient", + "--gpub", + "added.gpub", + "v.geode", + ], + ); +} + +fn preview_hello(dir: &Path, key: &str) -> geode_grotto::Result> { + let ctx = geode_tui::vault::open(&dir.join("v.geode"), Some(&dir.join(key)))?; + geode_tui::vault::verify(&ctx, true)?; + let p = geode_tui::vault::preview(&ctx, "hello.txt", 64)?; + Ok(p.bytes.to_vec()) +} + +#[test] +fn tui_unlock_x25519_recipient() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + fixture(dir); + assert_eq!(preview_hello(dir, "added.gkey").unwrap(), b"hello world\n"); + assert_eq!(preview_hello(dir, "owner.gkey").unwrap(), b"hello world\n"); + let ctx = geode_tui::vault::open(&dir.join("v.geode"), Some(&dir.join("added.gkey"))).unwrap(); + assert_eq!( + geode_tui::vault::hex(&ctx.key_id().0), + key_id(dir, "added.gpub") + ); +} + +#[test] +fn tui_unlock_after_owner_dropped() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + fixture(dir); + let owner = key_id(dir, "owner.gpub"); + geode( + dir, + &[ + "--key", + "owner.gkey", + "vault", + "rotate", + "v.geode", + "--yes", + "--reseal", + "--drop-recipient", + &owner, + ], + ); + assert_eq!(preview_hello(dir, "added.gkey").unwrap(), b"hello world\n"); + assert!(matches!( + preview_hello(dir, "owner.gkey"), + Err(geode_grotto::Error::AuthFail) + )); +} + +#[test] +fn tui_unlock_stranger_is_auth_fail() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + fixture(dir); + geode(dir, &["keygen", "--insecure-plaintext", "stranger.gkey"]); + assert!(matches!( + preview_hello(dir, "stranger.gkey"), + Err(geode_grotto::Error::AuthFail) + )); +}