Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
21 changes: 3 additions & 18 deletions crates/geode-cli/src/cmd/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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 `<keyfile stem>.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`).
Expand All @@ -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}")))?;
Expand Down
31 changes: 9 additions & 22 deletions crates/geode-cli/src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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(
Expand Down
4 changes: 2 additions & 2 deletions crates/geode-cli/src/cmd/vault.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)?;
Expand Down Expand Up @@ -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),
Expand Down
132 changes: 132 additions & 0 deletions crates/geode-core/src/recipients.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<EpochKey> {
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")]
Expand Down Expand Up @@ -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]));
}
}
64 changes: 64 additions & 0 deletions crates/geode-core/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Self> {
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 +
Expand Down Expand Up @@ -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)
));
}
}
12 changes: 8 additions & 4 deletions crates/geode-tui/src/vault.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -333,11 +334,14 @@ pub fn open(vault: &Path, key: Option<&Path>) -> Result<VaultCtx> {
.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);
Expand Down
Loading
Loading