[vault] Identity: the Domi root key in the vault, mnemonic typestate, signs only certs

This commit is contained in:
2026-11-03 18:52:01 +01:00
parent 680b66cff7
commit 1c4bf4b373
5 changed files with 373 additions and 7 deletions
Generated
+39
View File
@@ -34,6 +34,12 @@ dependencies = [
"zeroize",
]
[[package]]
name = "arrayvec"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
[[package]]
name = "autocfg"
version = "1.5.1"
@@ -52,6 +58,27 @@ version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bip39"
version = "2.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc"
dependencies = [
"bitcoin_hashes",
"serde",
"unicode-normalization",
"zeroize",
]
[[package]]
name = "bitcoin_hashes"
version = "0.14.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bca4c7abb40c8817d77403c880988cfd484f23ab2365726afb2f798363e2c4a2"
dependencies = [
"hex-conservative",
]
[[package]]
name = "bitflags"
version = "2.13.2"
@@ -318,7 +345,10 @@ name = "custos-vault"
version = "0.6.0"
dependencies = [
"argon2",
"bip39",
"chacha20poly1305",
"data-encoding",
"ed25519-dalek",
"hkdf",
"rand 0.10.3",
"serde",
@@ -523,6 +553,15 @@ dependencies = [
"subtle",
]
[[package]]
name = "hex-conservative"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db3fef046dca3ca91ee1408a8c1b80ab777e80a4d308d1bf4e7adb3fcb047e08"
dependencies = [
"arrayvec",
]
[[package]]
name = "hkdf"
version = "0.13.0"
+4
View File
@@ -16,6 +16,10 @@ serde_json.workspace = true
thiserror.workspace = true
hkdf.workspace = true
sha2.workspace = true
# The Domi identity (docs/IDENTITY.md): the mnemonic and the root key.
bip39 = { version = "2", default-features = false, features = ["std", "zeroize"] }
ed25519-dalek = { version = "2", default-features = false, features = ["std", "zeroize"] }
[dev-dependencies]
tempfile = "3"
data-encoding.workspace = true
+15
View File
@@ -66,3 +66,18 @@ pub fn hkdf(ikm: &[u8], salt: &[u8], info: &[u8]) -> Zeroizing<[u8; KEY_LEN]> {
pub fn open(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], ciphertext: &[u8], aad: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
cipher(key).decrypt(&nonce(n), Payload { msg: ciphertext, aad }).ok().map(Zeroizing::new)
}
/// The Domi root secret from a 24-word mnemonic (docs/IDENTITY.md): HKDF-SHA256 over its BIP39 seed.
pub fn domi_root_secret(mnemonic: &bip39::Mnemonic) -> Zeroizing<[u8; KEY_LEN]> {
let seed = Zeroizing::new(mnemonic.to_seed_normalized(""));
hkdf(seed.as_ref(), b"tessera root v1", b"ed25519")
}
pub fn ed25519_public(secret: &[u8; KEY_LEN]) -> [u8; 32] {
ed25519_dalek::SigningKey::from_bytes(secret).verifying_key().to_bytes()
}
pub fn ed25519_sign(secret: &[u8; KEY_LEN], msg: &[u8]) -> [u8; 64] {
use ed25519_dalek::Signer;
ed25519_dalek::SigningKey::from_bytes(secret).sign(msg).to_bytes()
}
+233
View File
@@ -0,0 +1,233 @@
//! The Domi identity's root key (docs/IDENTITY.md). It lives in the vault body and never leaves it: nothing
//! here or on [`Vault`] returns it, and the vault signs nothing with it but subkey certificates.
//!
//! Creating it is a typestate, so the mnemonic is always shown before the root exists:
//!
//! ```
//! # use custos_vault::{identity::Enrollment, KdfParams, SecretString, Vault};
//! # let mut vault = Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 })?;
//! let mut words = Vec::new();
//! let shown = Enrollment::begin().show(|w| words = w.iter().map(|s| s.to_string()).collect());
//! let typed = shown.challenge().map(|i| words[i - 1].clone()); // the person types these back
//! let confirmed = shown.confirm(&[&typed[0], &typed[1], &typed[2]]).map_err(|(_, e)| e)?;
//! let root_public = confirmed.import(&mut vault)?;
//! # Ok::<(), custos_vault::Error>(())
//! ```
//!
//! Importing before the mnemonic was shown does not compile:
//!
//! ```compile_fail
//! # use custos_vault::{identity::Enrollment, KdfParams, SecretString, Vault};
//! # let mut vault = Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
//! Enrollment::begin().import(&mut vault);
//! ```
//!
//! Nor does confirming words that were never shown:
//!
//! ```compile_fail
//! # use custos_vault::identity::Enrollment;
//! Enrollment::begin().confirm(&["abandon", "abandon", "art"]);
//! ```
//!
//! Nor importing straight after showing, without the person typing the words back:
//!
//! ```compile_fail
//! # use custos_vault::{identity::Enrollment, KdfParams, SecretString, Vault};
//! # let mut vault = Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
//! Enrollment::begin().show(|_| {}).import(&mut vault);
//! ```
use crate::crypto::{self, KEY_LEN};
use crate::{Error, SecretString, Vault, hex, now_ms, unhex};
use serde::{Deserialize, Serialize};
use std::fmt;
use zeroize::Zeroizing;
/// The root signs `CERT_DOMAIN ‖ tbs`, and only a `tbs` that starts with `CERT_MAGIC ‖ its public key`.
const CERT_DOMAIN: &[u8] = b"tessera cert v1\0";
const CERT_MAGIC: &[u8] = b"TSC1";
const WORDS: usize = 24;
/// Step 1: fresh entropy. Nothing is derived from it until the words have been shown.
pub struct Enrollment {
entropy: Zeroizing<[u8; 32]>,
}
/// Step 2: the words were shown; the person must type three of them back.
pub struct Shown {
entropy: Zeroizing<[u8; 32]>,
challenge: [usize; 3],
}
/// Step 3: the words were confirmed. Holds the root secret; the entropy is gone.
pub struct Confirmed {
secret: Zeroizing<[u8; KEY_LEN]>,
}
fn mnemonic(entropy: &[u8; 32]) -> bip39::Mnemonic {
bip39::Mnemonic::from_entropy_in(bip39::Language::English, entropy)
.expect("32 bytes is a valid BIP39 entropy length")
}
fn normalize(w: &str) -> String {
w.trim().to_lowercase()
}
/// Three different word positions, 1-based, ascending.
fn random_challenge() -> [usize; 3] {
let mut picked = Vec::with_capacity(3);
while picked.len() < 3 {
let mut b = [0u8; 1];
crypto::fill_random(&mut b);
// 240 = 10 × 24: rejection sampling keeps every position equally likely.
if b[0] < 240 {
let i = (b[0] as usize % WORDS) + 1;
if !picked.contains(&i) {
picked.push(i);
}
}
}
picked.sort();
[picked[0], picked[1], picked[2]]
}
impl Enrollment {
/// 32 bytes from the OS CSPRNG.
pub fn begin() -> Enrollment {
let mut entropy = Zeroizing::new([0u8; 32]);
crypto::fill_random(entropy.as_mut());
Enrollment { entropy }
}
/// Known entropy, for test vectors.
pub fn with_entropy(entropy: [u8; 32]) -> Enrollment {
Enrollment { entropy: Zeroizing::new(entropy) }
}
/// Hands the 24 words to `display`, once. The only way to [`Shown`].
pub fn show(self, display: impl FnOnce(&[&str])) -> Shown {
let phrase = Zeroizing::new(mnemonic(&self.entropy).to_string());
let words: Vec<&str> = phrase.split(' ').collect();
display(&words);
Shown { entropy: self.entropy, challenge: random_challenge() }
}
}
impl Shown {
/// The positions (1–24) of the three words to type back.
pub fn challenge(&self) -> [usize; 3] {
self.challenge
}
/// Checks the three typed words (any case, surrounding spaces ignored). On a mismatch this `Shown` comes
/// back with [`Error::WrongWords`], so the person can try again; the words are not shown again.
pub fn confirm(self, words: &[&str; 3]) -> Result<Confirmed, (Shown, Error)> {
let m = mnemonic(&self.entropy);
let phrase = Zeroizing::new(m.to_string());
let all: Vec<&str> = phrase.split(' ').collect();
let ok = self.challenge.iter().zip(words).all(|(&i, typed)| *Zeroizing::new(normalize(typed)) == all[i - 1]);
if !ok {
return Err((self, Error::WrongWords));
}
Ok(Confirmed { secret: crypto::domi_root_secret(&m) })
}
}
impl Confirmed {
/// Stores the root in `vault` and returns its public key. The caller saves the vault. A vault has one
/// identity: a second import is [`Error::IdentityExists`].
pub fn import(self, vault: &mut Vault) -> Result<[u8; 32], Error> {
if vault.identity.is_some() {
return Err(Error::IdentityExists);
}
let public = crypto::ed25519_public(&self.secret);
vault.identity = Some(Root { secret: self.secret, public, created: now_ms(), issued: Vec::new() });
Ok(public)
}
}
impl fmt::Debug for Enrollment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Enrollment([redacted])")
}
}
impl fmt::Debug for Shown {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Shown([redacted])")
}
}
impl fmt::Debug for Confirmed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Confirmed([redacted])")
}
}
/// A cert the vault signed, for display (docs/IDENTITY.md). A record, not a trust list.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Issued {
/// `app` or `device`.
pub kind: String,
pub app_id: String,
pub purpose: String,
/// The subkey's public key, base64url.
pub subkey: String,
/// The program or device it was issued to.
pub label: String,
/// Unix seconds.
pub not_before: u64,
pub not_after: u64,
/// Unix milliseconds.
pub issued: i64,
}
/// The identity in an unlocked vault.
pub(crate) struct Root {
secret: Zeroizing<[u8; KEY_LEN]>,
pub(crate) public: [u8; 32],
pub(crate) created: i64,
pub(crate) issued: Vec<Issued>,
}
/// The `identity` body member.
#[derive(Serialize, Deserialize)]
pub(crate) struct RootJson {
root: SecretString,
public: String,
created: i64,
#[serde(default)]
issued: Vec<Issued>,
}
impl Root {
pub(crate) fn sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
let names_me = tbs.len() > CERT_MAGIC.len() + 32
&& &tbs[..CERT_MAGIC.len()] == CERT_MAGIC
&& tbs[CERT_MAGIC.len()..CERT_MAGIC.len() + 32] == self.public;
if !names_me {
return Err(Error::NotACert);
}
let msg = Zeroizing::new([CERT_DOMAIN, tbs].concat());
Ok(crypto::ed25519_sign(&self.secret, &msg))
}
pub(crate) fn json(&self) -> RootJson {
RootJson {
root: SecretString::new(hex(self.secret.as_ref())),
public: hex(&self.public),
created: self.created,
issued: self.issued.clone(),
}
}
/// `None` when malformed, or when the public key is not the secret's.
pub(crate) fn from_json(j: &RootJson) -> Option<Root> {
let secret = Zeroizing::new(unhex::<KEY_LEN>(j.root.expose())?);
let public = unhex::<32>(&j.public)?;
if crypto::ed25519_public(&secret) != public {
return None;
}
Some(Root { secret, public, created: j.created, issued: j.issued.clone() })
}
}
+82 -7
View File
@@ -19,6 +19,7 @@
mod crypto;
mod device;
mod format;
pub mod identity;
mod item;
mod save;
mod secret;
@@ -61,6 +62,14 @@ pub enum Error {
SameDevice,
#[error("a vault has at most 8 factors and one master password")]
TooManyFactors,
#[error("this vault has no Domi identity yet")]
NoIdentity,
#[error("this vault already has a Domi identity")]
IdentityExists,
#[error("the Domi identity signs only certificates that name it")]
NotACert,
#[error("those words are not the ones in the recovery phrase")]
WrongWords,
#[error("{0}")]
Io(#[from] std::io::Error),
}
@@ -250,6 +259,8 @@ struct Body {
items: Vec<Item>,
#[serde(default)]
factors: Vec<FactorJson>,
#[serde(default)]
identity: Option<identity::RootJson>,
}
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
@@ -259,6 +270,8 @@ struct BodyRef<'a> {
items: &'a [Item],
#[serde(skip_serializing_if = "Vec::is_empty")]
factors: Vec<FactorJson>,
#[serde(skip_serializing_if = "Option::is_none")]
identity: Option<identity::RootJson>,
}
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
@@ -271,6 +284,8 @@ pub struct Vault {
factors: Vec<FactorRec>,
/// Argon2 parameters for a password factor added later.
kdf_new: KdfParams,
/// The Domi identity's root key (docs/IDENTITY.md), never handed out.
identity: Option<identity::Root>,
}
impl fmt::Debug for Vault {
@@ -279,6 +294,7 @@ impl fmt::Debug for Vault {
.field("version", &self.version)
.field("items", &self.items.len())
.field("factors", &self.factors.len())
.field("identity", &self.identity.is_some())
.finish_non_exhaustive()
}
}
@@ -311,7 +327,8 @@ fn factor_slot(id: [u8; ID_LEN], key: &[u8; KEY_LEN], u: &Unlock, kdf: KdfParams
}
let mut salt = [0u8; SALT_LEN];
crypto::fill_random(&mut salt);
let mut slot = FactorSlot { id, kind: u.kind().code(), kdf, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() };
let mut slot =
FactorSlot { id, kind: u.kind().code(), kdf, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() };
let kek = factor_kek(u, &slot.salt, slot.kdf)?;
slot.wrapped = crypto::seal(&kek, &slot.nonce, key, &slot.aad());
Ok(slot)
@@ -360,7 +377,15 @@ impl Vault {
pub fn create(password: &SecretString, kdf: KdfParams) -> Result<Vault, Error> {
let key = crypto::random_key();
let slot = password_slot(&key, password, kdf)?;
Ok(Vault { key, version: VERSION, slots: vec![slot.raw()], items: Vec::new(), factors: Vec::new(), kdf_new: kdf })
Ok(Vault {
key,
version: VERSION,
slots: vec![slot.raw()],
items: Vec::new(),
factors: Vec::new(),
kdf_new: kdf,
identity: None,
})
}
/// A new, empty version-2 vault that opens with these two factors together (docs/FACTORS.md).
@@ -375,6 +400,7 @@ impl Vault {
items: Vec::new(),
factors: Vec::new(),
kdf_new: kdf,
identity: None,
};
v.add_factor(a, label_a)?;
v.add_factor(b, label_b)?;
@@ -389,7 +415,13 @@ impl Vault {
let key = crypto::random_key();
let mut id = [0u8; ID_LEN];
crypto::fill_random(&mut id);
let rec = FactorRec { id, kind: FactorKind::Device, label: label.into(), created: now_ms(), key: crypto::random_key() };
let rec = FactorRec {
id,
kind: FactorKind::Device,
label: label.into(),
created: now_ms(),
key: crypto::random_key(),
};
let fslot = factor_slot(id, &rec.key, &u, KdfParams::DEFAULT)?;
let mut single = SingleSlot { id, nonce: crypto::random_nonce(), wrapped: Vec::new() };
single.wrapped = crypto::seal(&single_kek(&rec), &single.nonce, key.as_ref(), &single.aad());
@@ -400,6 +432,7 @@ impl Vault {
items: Vec::new(),
factors: vec![rec],
kdf_new: KdfParams::DEFAULT,
identity: None,
})
}
@@ -504,7 +537,8 @@ impl Vault {
if body.format != want {
return Err(Error::Corrupted);
}
let factors: Vec<FactorRec> = body.factors.iter().map(FactorRec::from_json).collect::<Option<_>>().ok_or(Error::Corrupted)?;
let factors: Vec<FactorRec> =
body.factors.iter().map(FactorRec::from_json).collect::<Option<_>>().ok_or(Error::Corrupted)?;
// Every factor slot in the header has its key in the body, and the other way round.
if header.version == VERSION_2 {
let mut in_header: Vec<_> = header.factor_slots().iter().map(|s| s.id).collect();
@@ -516,7 +550,11 @@ impl Vault {
}
}
let kdf_new = header.factor_slots().iter().find_map(|s| s.kdf).unwrap_or(KdfParams::DEFAULT);
Ok(Vault { key, version: header.version, slots: header.slots, items: body.items, factors, kdf_new })
let identity = match &body.identity {
Some(j) => Some(identity::Root::from_json(j).ok_or(Error::Corrupted)?),
None => None,
};
Ok(Vault { key, version: header.version, slots: header.slots, items: body.items, factors, kdf_new, identity })
}
/// Wraps the vault key for device unlock with key material only this device can produce (e.g. a
@@ -549,6 +587,7 @@ impl Vault {
format: if v2 { BODY_FORMAT_2 } else { BODY_FORMAT },
items: &self.items,
factors: self.factors.iter().map(FactorRec::json).collect(),
identity: self.identity.as_ref().map(identity::Root::json),
};
serde_json::to_writer(&mut *json, &body).map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?;
let sealed = crypto::seal(&self.key, &body_nonce, &json, &out);
@@ -604,7 +643,8 @@ impl Vault {
/// as a phone's passkey and its approval key): together they open nothing, so one device is never two
/// factors. Returns its id.
pub fn add_factor_apart(&mut self, u: Unlock, label: &str, apart: &[&str]) -> Result<String, Error> {
let apart: Vec<[u8; ID_LEN]> = apart.iter().map(|a| unhex(a).ok_or(Error::FactorRejected)).collect::<Result<_, _>>()?;
let apart: Vec<[u8; ID_LEN]> =
apart.iter().map(|a| unhex(a).ok_or(Error::FactorRejected)).collect::<Result<_, _>>()?;
if apart.iter().any(|a| !self.factors.iter().any(|f| f.id == *a)) {
return Err(Error::FactorRejected);
}
@@ -652,7 +692,13 @@ impl Vault {
/// Turns an unlocked version-1 vault into version 2 with its password and a second factor.
/// The vault key and the items stay; from the next save on, the password alone opens nothing.
pub fn upgrade_to_two_factors(&mut self, password: &SecretString, kdf: KdfParams, second: Unlock, label: &str) -> Result<(), Error> {
pub fn upgrade_to_two_factors(
&mut self,
password: &SecretString,
kdf: KdfParams,
second: Unlock,
label: &str,
) -> Result<(), Error> {
if self.version != VERSION {
return Err(Error::UnsupportedVersion(self.version));
}
@@ -725,4 +771,33 @@ impl Vault {
let i = self.items.iter().position(|it| it.id == id)?;
Some(self.items.remove(i))
}
// ---- the Domi identity (docs/IDENTITY.md); created with identity::Enrollment ----
/// The root public key, if this vault has a Domi identity.
pub fn domi_root_public(&self) -> Option<[u8; 32]> {
self.identity.as_ref().map(|r| r.public)
}
/// When the identity was created (Unix milliseconds).
pub fn domi_created(&self) -> Option<i64> {
self.identity.as_ref().map(|r| r.created)
}
/// Ed25519 with the root over `"tessera cert v1" ‖ tbs`. Refuses a `tbs` that does not start with
/// `TSC1` and this root's public key ([`Error::NotACert`]): the root signs certificates and nothing else.
pub fn domi_sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
self.identity.as_ref().ok_or(Error::NoIdentity)?.sign_cert(tbs)
}
/// The certs this vault has signed, oldest first.
pub fn domi_issued(&self) -> &[identity::Issued] {
self.identity.as_ref().map(|r| r.issued.as_slice()).unwrap_or(&[])
}
/// Records a cert this vault signed. The caller saves the vault.
pub fn domi_record(&mut self, issued: identity::Issued) -> Result<(), Error> {
self.identity.as_mut().ok_or(Error::NoIdentity)?.issued.push(issued);
Ok(())
}
}