Compare commits

..

5 Commits

19 changed files with 1128 additions and 19 deletions
+1
View File
@@ -20,6 +20,7 @@ docs/KEYS.md secret keys, API keys and key pairs
docs/SEAL.md sealed boxes and the match code
docs/SHARE.md the share blob and link format (versioned like FORMAT.md)
docs/THREAT_MODEL.md what is and is not protected
docs/IDENTITY.md the Domi identity: the root key in the vault, the mnemonic order, signing certs
```
## Commands
Generated
+48 -8
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"
@@ -243,7 +270,7 @@ dependencies = [
[[package]]
name = "custos-gen"
version = "0.4.0"
version = "0.7.0"
dependencies = [
"custos-vault",
"data-encoding",
@@ -255,7 +282,7 @@ dependencies = [
[[package]]
name = "custos-keys"
version = "0.4.0"
version = "0.7.0"
dependencies = [
"custos-vault",
"ed25519-dalek",
@@ -268,11 +295,11 @@ dependencies = [
[[package]]
name = "custos-qr"
version = "0.4.0"
version = "0.7.0"
[[package]]
name = "custos-seal"
version = "0.4.0"
version = "0.7.0"
dependencies = [
"chacha20poly1305",
"hkdf",
@@ -285,7 +312,7 @@ dependencies = [
[[package]]
name = "custos-share"
version = "0.4.0"
version = "0.7.0"
dependencies = [
"argon2",
"chacha20poly1305",
@@ -302,7 +329,7 @@ dependencies = [
[[package]]
name = "custos-totp"
version = "0.4.0"
version = "0.7.0"
dependencies = [
"custos-vault",
"data-encoding",
@@ -315,10 +342,13 @@ dependencies = [
[[package]]
name = "custos-vault"
version = "0.4.0"
version = "0.7.0"
dependencies = [
"argon2",
"bip39",
"chacha20poly1305",
"data-encoding",
"ed25519-dalek",
"hkdf",
"rand 0.10.3",
"serde",
@@ -331,9 +361,10 @@ dependencies = [
[[package]]
name = "custos-wasm"
version = "0.4.0"
version = "0.7.0"
dependencies = [
"custos-qr",
"custos-seal",
"custos-share",
"custos-totp",
"custos-vault",
@@ -522,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"
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*"]
[workspace.package]
version = "0.5.0"
version = "0.7.0"
edition = "2024"
license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
+9
View File
@@ -142,6 +142,15 @@ pub fn match_code(public: &[u8]) -> String {
format!("{n:06}")
}
/// The match code of the one-time key a box was sealed with. When the receiver must know who sealed a
/// box (pairing a phone), the sealing screen shows this code and the receiving screen checks it.
pub fn sender_code(sealed: &[u8]) -> Result<String, SealError> {
if sealed.len() < 4 + 32 + NONCE + TAG || &sealed[..4] != MAGIC {
return Err(SealError::Malformed);
}
Ok(match_code(&sealed[4..36]))
}
/// Seals data the factor service keeps on disk, with its own key (from a systemd credential).
pub fn seal_at_rest(key: &[u8; 32], context: &[u8], plaintext: &[u8]) -> Vec<u8> {
let k = derive(key, b"", &[b"custos rest v1", context]);
+11 -1
View File
@@ -1,6 +1,6 @@
//! Mandatory tests for sealed boxes (docs/SEAL.md).
use custos_seal::{Recipient, SealError, match_code, open_at_rest, seal, seal_at_rest};
use custos_seal::{Recipient, SealError, match_code, open_at_rest, seal, seal_at_rest, sender_code};
#[test]
fn only_the_recipient_opens_and_only_for_its_purpose() {
@@ -53,6 +53,16 @@ fn the_match_code_is_six_digits_and_follows_the_key() {
/// SHA-256("custos match v1" ‖ 0x07 × 32), first four bytes big-endian, mod 1 000 000.
const KNOWN_MATCH_CODE: &str = "684361";
#[test]
fn the_sender_code_differs_per_box_and_needs_a_box() {
let r = Recipient::generate();
let a = seal(&r.public(), b"pair:1", b"x").unwrap();
let b = seal(&r.public(), b"pair:1", b"x").unwrap();
assert_eq!(sender_code(&a).unwrap(), match_code(&a[4..36]));
assert_ne!(a[4..36], b[4..36], "a fresh one-time key per box");
assert_eq!(sender_code(&a[..40]), Err(SealError::Malformed));
}
#[test]
fn at_rest_seals_open_with_the_same_key_and_context_only() {
let key = [9u8; 32];
+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() })
}
}
+97 -8
View File
@@ -19,6 +19,7 @@
mod crypto;
mod device;
mod format;
pub mod identity;
mod item;
mod save;
mod secret;
@@ -57,8 +58,18 @@ pub enum Error {
NeedTwoFactors,
#[error("this factor does not open the vault")]
FactorRejected,
#[error("these two factors are kept on the same device; use one of them with another factor")]
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),
}
@@ -248,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.
@@ -257,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.
@@ -269,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 {
@@ -277,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()
}
}
@@ -309,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)
@@ -358,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).
@@ -373,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)?;
@@ -387,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());
@@ -398,6 +432,7 @@ impl Vault {
items: Vec::new(),
factors: vec![rec],
kdf_new: KdfParams::DEFAULT,
identity: None,
})
}
@@ -448,7 +483,8 @@ impl Vault {
return Err(Error::NeedTwoFactors);
}
let (x, y) = if fa.id < fb.id { (fa.id, fb.id) } else { (fb.id, fa.id) };
let slot = header.pair_slots().into_iter().find(|p| p.a == x && p.b == y).ok_or(Error::Corrupted)?;
// Both factors opened, so a missing pair is one added apart from the other (one device).
let slot = header.pair_slots().into_iter().find(|p| p.a == x && p.b == y).ok_or(Error::SameDevice)?;
let k = crypto::open(&pair_kek(&fa, &fb), &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::Corrupted)?;
Vault::open_body(bytes, header, body_at, key32(k)?)
}
@@ -501,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();
@@ -513,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
@@ -546,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);
@@ -594,6 +636,18 @@ impl Vault {
/// Adds a factor to a version-2 vault: only the new factor's material is needed (docs/FACTORS.md).
/// Returns its id. A second master password is refused; use [`Vault::change_password`].
pub fn add_factor(&mut self, u: Unlock, label: &str) -> Result<String, Error> {
self.add_factor_apart(u, label, &[])
}
/// Adds a factor that never pairs with the factors `apart` (ids of factors kept on the same device, such
/// 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<_, _>>()?;
if apart.iter().any(|a| !self.factors.iter().any(|f| f.id == *a)) {
return Err(Error::FactorRejected);
}
if self.version != VERSION_2 {
return Err(Error::NeedTwoFactors);
}
@@ -611,7 +665,7 @@ impl Vault {
let rec = FactorRec { id, kind: u.kind(), label: label.into(), created: now_ms(), key: crypto::random_key() };
let slot = factor_slot(id, &rec.key, &u, self.kdf_new)?;
self.slots.push(slot.raw());
for other in &self.factors {
for other in self.factors.iter().filter(|f| !apart.contains(&f.id)) {
self.slots.push(pair_slot(&self.key, &rec, other).raw());
}
self.factors.push(rec);
@@ -638,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));
}
@@ -711,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(())
}
}
+28
View File
@@ -211,3 +211,31 @@ fn the_key_pair_item_type_round_trips() {
let item = back.items().iter().find(|i| i.kind == ItemType::KeyPair).unwrap();
assert!(item.fields.iter().any(|f| f.name == "private-key" && f.secret));
}
#[test]
fn factors_on_one_device_never_open_together() {
let mut v = two_factor_vault();
let passkey = v.add_factor(Unlock::Material(FactorKind::Passkey, &PHONE), "Phone passkey").unwrap();
let approval = [12u8; 32];
v.add_factor_apart(Unlock::Material(FactorKind::Approval, &approval), "Phone", &[&passkey]).unwrap();
let bytes = v.to_bytes().unwrap();
let phone = Unlock::Material(FactorKind::Passkey, &PHONE);
let phone_approval = Unlock::Material(FactorKind::Approval, &approval);
assert!(matches!(open(&bytes, phone, phone_approval), Err(Error::SameDevice)));
assert!(matches!(open(&bytes, phone_approval, phone), Err(Error::SameDevice)));
// Each still pairs with everything else.
let p = pw("Orbit7-Fable3");
assert!(open(&bytes, Unlock::Password(&p), phone).is_ok());
assert!(open(&bytes, Unlock::Password(&p), phone_approval).is_ok());
assert!(open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), phone_approval).is_ok());
// A factor added later pairs with both.
let mut v = open(&bytes, Unlock::Password(&p), phone).unwrap();
v.add_factor(Unlock::Material(FactorKind::Totp, &TOTP), "TOTP backup").unwrap();
let bytes = v.to_bytes().unwrap();
assert!(open(&bytes, Unlock::Material(FactorKind::Totp, &TOTP), phone_approval).is_ok());
// Only existing factors can be named.
assert!(matches!(
v.add_factor_apart(Unlock::Material(FactorKind::Device, &[13; 32]), "x", &["00112233445566778899aabbccddeeff"]),
Err(Error::FactorRejected)
));
}
+219
View File
@@ -0,0 +1,219 @@
//! Mandatory tests for the Domi identity (docs/IDENTITY.md): the mnemonic order, the vector shared with
//! Fundamentum, signing only certs, persistence, and no way to get the root key out.
use custos_vault::identity::{Enrollment, Issued};
use custos_vault::{Error, FactorKind, KdfParams, SecretString, Unlock, Vault};
use ed25519_dalek::{Signature, VerifyingKey};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
/// The root public key of `abandon` × 23 + `art` (Fundamentum `crates/tessera/tests/mandatory.rs`).
const ROOT_PUB_ZERO: &str = "vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs";
const CERT_DOMAIN: &[u8] = b"tessera cert v1\0";
fn vault() -> Vault {
Vault::create(&SecretString::from("pw"), FAST).unwrap()
}
fn b64url(s: &str) -> Vec<u8> {
data_encoding::BASE64URL_NOPAD.decode(s.as_bytes()).unwrap()
}
/// Runs the whole enrolment with known entropy, typing the right words. Returns the words shown.
fn enrol(v: &mut Vault, entropy: [u8; 32]) -> Vec<String> {
let mut words = Vec::new();
let shown = Enrollment::with_entropy(entropy).show(|w| words = w.iter().map(|s| s.to_string()).collect());
let pick = shown.challenge().map(|i| words[i - 1].clone());
let confirmed = shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap();
confirmed.import(v).unwrap();
words
}
#[test]
fn the_zero_vector_matches_fundamentum() {
let mut v = vault();
let words = enrol(&mut v, [0; 32]);
assert_eq!(words.len(), 24);
assert!(words[..23].iter().all(|w| w == "abandon") && words[23] == "art");
assert_eq!(v.domi_root_public().unwrap().to_vec(), b64url(ROOT_PUB_ZERO));
}
#[test]
fn the_same_mnemonic_gives_the_same_root() {
let (mut a, mut b) = (vault(), vault());
enrol(&mut a, [42; 32]);
enrol(&mut b, [42; 32]);
assert_eq!(a.domi_root_public(), b.domi_root_public());
let mut c = vault();
enrol(&mut c, [43; 32]);
assert_ne!(a.domi_root_public(), c.domi_root_public());
}
#[test]
fn the_mnemonic_is_shown_before_anything_is_imported() {
// The order trap at run time; at compile time see the compile_fail doctests in src/identity.rs.
let v = vault();
let mut log = Vec::new();
let shown = Enrollment::begin().show(|w| {
assert_eq!(w.len(), 24);
log.push("shown");
});
assert_eq!(log, ["shown"]);
assert!(v.domi_root_public().is_none(), "nothing in the vault before confirm + import");
// Wrong words: refused, and the same Shown comes back to try again.
let (shown, e) = shown.confirm(&["zoo", "zoo", "zoo"]).expect_err("wrong words are refused");
assert!(matches!(e, Error::WrongWords));
let c = shown.challenge();
assert!(c.iter().all(|&i| (1..=24).contains(&i)) && c[0] != c[1] && c[1] != c[2] && c[0] != c[2]);
assert!(v.domi_root_public().is_none());
}
#[test]
fn the_challenge_accepts_any_spacing_and_case() {
let mut v = vault();
let mut words = Vec::new();
let shown = Enrollment::with_entropy([5; 32]).show(|w| words = w.iter().map(|s| s.to_string()).collect());
let pick = shown.challenge().map(|i| format!(" {} ", words[i - 1].to_uppercase()));
shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap().import(&mut v).unwrap();
assert!(v.domi_root_public().is_some());
}
#[test]
fn an_identity_is_created_once() {
let mut v = vault();
enrol(&mut v, [1; 32]);
let first = v.domi_root_public();
let mut words = Vec::new();
let shown = Enrollment::with_entropy([2; 32]).show(|w| words = w.iter().map(|s| s.to_string()).collect());
let pick = shown.challenge().map(|i| words[i - 1].clone());
let c = shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap();
assert!(matches!(c.import(&mut v), Err(Error::IdentityExists)));
assert_eq!(v.domi_root_public(), first);
}
/// A cert's to-be-signed bytes as tessera makes them: TSC1 ‖ root ‖ subkey ‖ ids ‖ validity.
fn tbs(root: &[u8; 32]) -> Vec<u8> {
let mut t = b"TSC1".to_vec();
t.extend_from_slice(root);
t.extend_from_slice(&[9; 32]);
t.extend_from_slice(b"\x06fiscus\x04sync");
t.extend_from_slice(&1u64.to_be_bytes());
t.extend_from_slice(&2u64.to_be_bytes());
t
}
#[test]
fn the_root_signs_certs_and_nothing_else() {
let mut v = vault();
assert!(matches!(v.domi_sign_cert(&tbs(&[0; 32])), Err(Error::NoIdentity)));
enrol(&mut v, [0; 32]);
let root = v.domi_root_public().unwrap();
let t = tbs(&root);
let sig = v.domi_sign_cert(&t).unwrap();
let vk = VerifyingKey::from_bytes(&root).unwrap();
vk.verify_strict(&[CERT_DOMAIN, &t].concat(), &Signature::from_bytes(&sig)).unwrap();
// Not a cert, a cert for another root, the bare prefix: refused.
assert!(matches!(v.domi_sign_cert(b"pay 100 CZK to mallory"), Err(Error::NotACert)));
assert!(matches!(v.domi_sign_cert(&tbs(&[1; 32])), Err(Error::NotACert)));
assert!(matches!(v.domi_sign_cert(&t[..36]), Err(Error::NotACert)));
}
#[test]
fn the_identity_survives_saving_in_both_versions() {
let issued = Issued {
kind: "app".into(),
app_id: "fiscus".into(),
purpose: "sync".into(),
subkey: "CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk".into(),
label: "fiscus.exe".into(),
not_before: 1,
not_after: 2,
issued: 3,
};
// Version 1.
let mut v = vault();
enrol(&mut v, [0; 32]);
v.domi_record(issued.clone()).unwrap();
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(back.domi_root_public(), v.domi_root_public());
assert_eq!(back.domi_issued(), std::slice::from_ref(&issued));
assert!(back.domi_created().is_some());
let t = tbs(&back.domi_root_public().unwrap());
assert_eq!(back.domi_sign_cert(&t).unwrap(), v.domi_sign_cert(&t).unwrap(), "the same key came back");
// Version 2.
let pw = SecretString::from("pw");
let mut v2 =
Vault::create_with(Unlock::Password(&pw), "pw", Unlock::Material(FactorKind::Device, &[7; 32]), "pc", FAST)
.unwrap();
enrol(&mut v2, [3; 32]);
let bytes = v2.to_bytes().unwrap();
let back = Vault::open_with(&bytes, Unlock::Password(&pw), Unlock::Material(FactorKind::Device, &[7; 32])).unwrap();
assert_eq!(back.domi_root_public(), v2.domi_root_public());
// A vault without an identity still opens and has none.
let plain = Vault::open(&vault().to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert!(plain.domi_root_public().is_none() && plain.domi_issued().is_empty());
}
#[test]
fn a_record_needs_an_identity() {
let mut v = vault();
let i = Issued {
kind: "app".into(),
app_id: "x".into(),
purpose: "y".into(),
subkey: String::new(),
label: String::new(),
not_before: 0,
not_after: 1,
issued: 0,
};
assert!(matches!(v.domi_record(i), Err(Error::NoIdentity)));
}
#[test]
fn nothing_prints_the_root() {
let mut v = vault();
let mut words = Vec::new();
let e = Enrollment::with_entropy([0; 32]);
assert_eq!(format!("{e:?}"), "Enrollment([redacted])");
let shown = e.show(|w| words = w.iter().map(|s| s.to_string()).collect());
assert_eq!(format!("{shown:?}"), "Shown([redacted])");
let pick = shown.challenge().map(|i| words[i - 1].clone());
let c = shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap();
assert_eq!(format!("{c:?}"), "Confirmed([redacted])");
c.import(&mut v).unwrap();
let dbg = format!("{v:?}");
assert!(!dbg.contains("abandon") && !dbg.to_lowercase().contains("root"), "{dbg}");
}
/// No key export: the public surface of the identity module is locked. A new public function fails this
/// test until it has been checked to return no secret.
#[test]
fn the_identity_surface_is_locked() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut got = Vec::new();
for file in ["identity.rs", "lib.rs"] {
let text = std::fs::read_to_string(dir.join(file)).unwrap();
for line in text.lines() {
let l = line.trim();
if l.starts_with("pub fn ") && (file == "identity.rs" || l.starts_with("pub fn domi_")) {
got.push(format!("{file}: {}", l.trim_end_matches(" {")));
}
}
}
got.sort();
let mut want = vec![
"identity.rs: pub fn begin() -> Enrollment",
"identity.rs: pub fn challenge(&self) -> [usize; 3]",
"identity.rs: pub fn confirm(self, words: &[&str; 3]) -> Result<Confirmed, (Shown, Error)>",
"identity.rs: pub fn import(self, vault: &mut Vault) -> Result<[u8; 32], Error>",
"identity.rs: pub fn show(self, display: impl FnOnce(&[&str])) -> Shown",
"identity.rs: pub fn with_entropy(entropy: [u8; 32]) -> Enrollment",
"lib.rs: pub fn domi_created(&self) -> Option<i64>",
"lib.rs: pub fn domi_issued(&self) -> &[identity::Issued]",
"lib.rs: pub fn domi_record(&mut self, issued: identity::Issued) -> Result<(), Error>",
"lib.rs: pub fn domi_root_public(&self) -> Option<[u8; 32]>",
"lib.rs: pub fn domi_sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error>",
];
want.sort();
assert_eq!(got, want, "review the identity surface: it must never return the root secret");
}
+1
View File
@@ -14,6 +14,7 @@ custos-vault = { path = "../custos-vault" }
custos-share = { path = "../custos-share" }
custos-totp = { path = "../custos-totp" }
custos-qr = { path = "../custos-qr" }
custos-seal = { path = "../custos-seal" }
serde.workspace = true
serde_json.workspace = true
data-encoding.workspace = true
+198 -1
View File
@@ -16,9 +16,15 @@
//! Requests are `{"op": …, …}`; responses `{"ok": true, …}` or `{"ok": false, "error": "<message>"}`.
//! See [`handle`] for the operations. One vault at a time is held here while unlocked; `lock` drops it
//! (and with it the key, wiped).
//!
//! Two factors (docs/FACTORS.md, docs/SEAL.md): the page asks for a one-time key (`recipient`), sends its
//! public half to the factor service, and passes the sealed answer back in `open_with`. The key's secret
//! half never leaves this module. A paired phone keeps its approval material wrapped with its passkey's
//! PRF output (`phone_enrol`, `phone_approve`); unwrapped, it exists only inside one call.
use custos_seal::Recipient;
use custos_share::{Payload, ShareError};
use custos_vault::{Item, ItemType, SecretString, Vault};
use custos_vault::{FactorKind, Item, ItemType, SecretString, Unlock, Vault};
use data_encoding::BASE64;
use qrcode::render::svg;
use qrcode::{EcLevel, QrCode};
@@ -29,6 +35,24 @@ use zeroize::Zeroizing;
thread_local! {
static VAULT: RefCell<Option<Vault>> = const { RefCell::new(None) };
/// One-time keys waiting for a sealed answer, by their public key (base64). Each is used once.
static RECIPIENTS: RefCell<Vec<(String, Recipient)>> = const { RefCell::new(Vec::new()) };
}
/// At most this many one-time keys wait at once; the oldest goes first.
const MAX_RECIPIENTS: usize = 8;
/// The at-rest context of a phone's approval material, wrapped with its passkey's PRF output.
const PHONE_APPROVAL: &[u8] = b"custos phone approval v1";
/// One factor given to `open_with`.
#[derive(Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", rename_all_fields = "camelCase")]
enum FactorIn {
Password { password: SecretString },
/// A factor service's or a device's answer, sealed to a key from `recipient` (`pub`) for `context`.
Sealed { factor: FactorKind, r#pub: String, sealed: String, context: String },
/// Material the page holds itself: a passkey's PRF output (base64).
Material { factor: FactorKind, material: SecretString },
}
#[derive(Deserialize)]
@@ -67,6 +91,47 @@ enum Request {
fragment: String,
password: Option<SecretString>,
},
/// The format version and the factors (id, type) of a vault, from its header alone.
Factors {
vault: String,
},
/// A new one-time key: `{pub, match}`.
Recipient,
/// The match code of a public key (base64), for example a requesting device's.
MatchCode {
r#pub: String,
},
/// Opens a version-2 vault with two different factors.
OpenWith {
vault: String,
factors: Vec<FactorIn>,
},
/// Pairs this phone with a PC that waits with the one-time key `pub`: makes the phone's approval
/// material and seals it with the passkey's PRF output (`prf`, base64) to the PC for `context`.
/// Returns the box, its sender code, and the material wrapped with the PRF output (`wrapped`).
PhoneEnrol {
r#pub: String,
context: String,
label: String,
prf: SecretString,
},
/// Approves a request: unwraps this phone's approval material with the PRF output and seals it to
/// the requester's key for `context` (`approval:<factor>:<request id>`).
PhoneApprove {
wrapped: String,
prf: SecretString,
r#pub: String,
context: String,
},
/// Pairs this phone as a Domi device (Custos docs/07_domi_identity.md): seals its device label and its
/// Ed25519 device public key (`device`, base64url, made non-extractable by the page) to the PC that
/// waits with `pub`, for `domi-pair:<id>`. Returns the box and its sender code. Nothing secret goes in.
DomiPair {
r#pub: String,
id: String,
label: String,
device: String,
},
}
fn err(msg: impl ToString) -> Value {
@@ -178,6 +243,48 @@ fn payload_json(p: &Payload) -> Value {
})
}
fn b64(s: &str) -> Option<Zeroizing<Vec<u8>>> {
BASE64.decode(s.as_bytes()).ok().map(Zeroizing::new)
}
fn key32(s: &SecretString) -> Option<Zeroizing<[u8; 32]>> {
let v = b64(s.expose())?;
let a: [u8; 32] = v.as_slice().try_into().ok()?;
Some(Zeroizing::new(a))
}
fn take_recipient(public: &str) -> Option<Recipient> {
RECIPIENTS.with_borrow_mut(|r| r.iter().position(|(p, _)| p == public).map(|i| r.remove(i).1))
}
/// The material for one factor; a password stays a password.
enum Given {
Password(SecretString),
Material(FactorKind, Zeroizing<Vec<u8>>),
}
fn given(f: FactorIn) -> Result<Given, String> {
match f {
FactorIn::Password { password } => Ok(Given::Password(password)),
FactorIn::Material { factor, material } => {
Ok(Given::Material(factor, b64(material.expose()).ok_or("A malformed factor.")?))
}
FactorIn::Sealed { factor, r#pub, sealed, context } => {
let me = take_recipient(&r#pub).ok_or("That request expired. Ask again.")?;
let sealed = b64(&sealed).ok_or("A malformed answer.")?;
let m = me.open(&sealed, context.as_bytes()).map_err(|e| e.to_string())?;
Ok(Given::Material(factor, m))
}
}
}
fn unlock(g: &Given) -> Unlock<'_> {
match g {
Given::Password(p) => Unlock::Password(p),
Given::Material(k, m) => Unlock::Material(*k, m),
}
}
fn share_error(e: ShareError) -> Value {
json!({ "ok": false, "error": e.to_string(), "code": format!("{e:?}") })
}
@@ -254,6 +361,96 @@ pub fn handle(request: &[u8]) -> Value {
Err(e) => share_error(e),
}
}
Request::Factors { vault } => {
let Some(bytes) = b64(&vault) else { return err("The vault file is damaged.") };
match (Vault::version_of(&bytes), Vault::factor_ids(&bytes)) {
(Ok(version), Ok(ids)) => json!({
"ok": true,
"version": version,
"factors": ids.iter().map(|(id, kind)| json!({ "id": id, "kind": kind })).collect::<Vec<_>>(),
}),
(Err(e), _) | (_, Err(e)) => err(e),
}
}
Request::Recipient => {
let me = Recipient::generate();
let public = BASE64.encode(&me.public());
let code = me.match_code();
RECIPIENTS.with_borrow_mut(|r| {
if r.len() >= MAX_RECIPIENTS {
r.remove(0);
}
r.push((public.clone(), me));
});
json!({ "ok": true, "pub": public, "match": code })
}
Request::MatchCode { r#pub } => match b64(&r#pub) {
Some(p) if p.len() == 32 => json!({ "ok": true, "match": custos_seal::match_code(&p) }),
_ => err("Not a valid public key."),
},
Request::OpenWith { vault, factors } => {
let Some(bytes) = b64(&vault) else { return err("The vault file is damaged.") };
let mut factors = factors.into_iter();
let (Some(a), Some(b), None) = (factors.next(), factors.next(), factors.next()) else {
return err("Choose two different factors.");
};
let (a, b) = match (given(a), given(b)) {
(Ok(a), Ok(b)) => (a, b),
(Err(e), _) | (_, Err(e)) => return err(e),
};
match Vault::open_with(&bytes, unlock(&a), unlock(&b)) {
Ok(v) => {
let out = items(&v);
VAULT.set(Some(v));
out
}
Err(e) => err(e),
}
}
Request::PhoneEnrol { r#pub, context, label, prf } => {
let (Some(public), Some(prf_key)) = (b64(&r#pub), key32(&prf)) else { return err("A malformed request.") };
let material = custos_seal::random_bytes();
let plain = Zeroizing::new(
json!({ "label": label, "passkey": prf.expose(), "approval": BASE64.encode(material.as_ref()) })
.to_string(),
);
match custos_seal::seal(&public, context.as_bytes(), plain.as_bytes()) {
Ok(sealed) => json!({
"ok": true,
"code": custos_seal::sender_code(&sealed).unwrap_or_default(),
"sealed": BASE64.encode(&sealed),
"wrapped": BASE64.encode(&custos_seal::seal_at_rest(&prf_key, PHONE_APPROVAL, material.as_ref())),
}),
Err(e) => err(e),
}
}
Request::DomiPair { r#pub, id, label, device } => {
let device_ok = data_encoding::BASE64URL_NOPAD.decode(device.as_bytes()).is_ok_and(|d| d.len() == 32);
let id_ok = !id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
let (Some(public), true, true) = (b64(&r#pub), device_ok, id_ok) else { return err("A malformed request.") };
let label: String = label.trim().chars().filter(|c| !c.is_control()).take(40).collect();
let plain = json!({ "label": label, "device": device }).to_string();
match custos_seal::seal(&public, format!("domi-pair:{id}").as_bytes(), plain.as_bytes()) {
Ok(sealed) => json!({
"ok": true,
"code": custos_seal::sender_code(&sealed).unwrap_or_default(),
"sealed": BASE64.encode(&sealed),
}),
Err(e) => err(e),
}
}
Request::PhoneApprove { wrapped, prf, r#pub, context } => {
let (Some(wrapped), Some(prf_key), Some(public)) = (b64(&wrapped), key32(&prf), b64(&r#pub)) else {
return err("A malformed request.");
};
let Ok(material) = custos_seal::open_at_rest(&prf_key, PHONE_APPROVAL, &wrapped) else {
return err("This passkey does not belong to this phone's pairing.");
};
match custos_seal::seal(&public, context.as_bytes(), &material) {
Ok(sealed) => json!({ "ok": true, "sealed": BASE64.encode(&sealed) }),
Err(e) => err(e),
}
}
}
}
+158
View File
@@ -0,0 +1,158 @@
//! Two factors in the browser: opening a version-2 vault with a sealed answer or a passkey's PRF output,
//! and a phone's pairing and approvals (docs/FACTORS.md, docs/SEAL.md).
use custos_seal::Recipient;
use custos_vault::{FactorKind, Item, ItemType, KdfParams, SecretString, Unlock, Vault};
use data_encoding::BASE64;
use serde_json::{Value, json};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const PASSWORD: &str = "Test4-Vault7-Only2";
const SECRET: &str = "s3cret-Ž!";
fn call(v: Value) -> Value {
custos_wasm::handle(v.to_string().as_bytes())
}
/// A version-2 vault: the master password and a TOTP factor with `totp` as its material.
fn vault(totp: &[u8]) -> Vault {
let pw = SecretString::from(PASSWORD);
let mut v = Vault::create_with(Unlock::Password(&pw), "Master password", Unlock::Material(FactorKind::Totp, totp), "TOTP", FAST)
.unwrap();
let mut login = Item::new(ItemType::WebLogin, "GitHub", 0);
login.set("password", SECRET, 0);
v.add(login);
v
}
fn b64(v: &Vault) -> String {
BASE64.encode(&v.to_bytes().unwrap())
}
#[test]
fn factors_from_the_header() {
let v = vault(&[3; 32]);
let r = call(json!({ "op": "factors", "vault": b64(&v) }));
assert_eq!(r["version"], 2, "{r}");
let kinds: Vec<&str> = r["factors"].as_array().unwrap().iter().map(|f| f["kind"].as_str().unwrap()).collect();
assert_eq!(kinds, ["password", "totp"]);
let totp = v.factors().into_iter().find(|f| f.kind == FactorKind::Totp).unwrap();
assert_eq!(r["factors"][1]["id"], totp.id.as_str());
}
#[test]
fn open_with_password_and_a_sealed_totp_release() {
let material = [3u8; 32];
let v = vault(&material);
let file = b64(&v);
let totp = v.factors().into_iter().find(|f| f.kind == FactorKind::Totp).unwrap().id;
let context = format!("totp:{totp}");
let me = call(json!({ "op": "recipient" }));
let public = BASE64.decode(me["pub"].as_str().unwrap().as_bytes()).unwrap();
assert_eq!(me["match"], custos_seal::match_code(&public));
// What the factor service sends back after a valid code.
let sealed = BASE64.encode(&custos_seal::seal(&public, context.as_bytes(), &material).unwrap());
let sealed_in = |ctx: &str| json!({ "kind": "sealed", "factor": "totp", "pub": me["pub"], "sealed": sealed, "context": ctx });
let password = json!({ "kind": "password", "password": PASSWORD });
// Only the right context opens it.
let wrong = call(json!({ "op": "open_with", "vault": file, "factors": [password, sealed_in("totp:other")] }));
assert_eq!(wrong["ok"], false);
// The key is used once, even when the answer was refused.
let again = call(json!({ "op": "open_with", "vault": file, "factors": [password, sealed_in(&context)] }));
assert_eq!(again["error"], "That request expired. Ask again.");
let me = call(json!({ "op": "recipient" }));
let public = BASE64.decode(me["pub"].as_str().unwrap().as_bytes()).unwrap();
let sealed = BASE64.encode(&custos_seal::seal(&public, context.as_bytes(), &material).unwrap());
let ok = call(json!({ "op": "open_with", "vault": file, "factors": [
{ "kind": "sealed", "factor": "totp", "pub": me["pub"], "sealed": sealed, "context": context },
password,
]}));
assert_eq!(ok["ok"], true, "{ok}");
assert_eq!(ok["items"].as_array().unwrap().len(), 1);
assert!(!ok.to_string().contains(SECRET));
call(json!({ "op": "lock" }));
// One factor, or the same one twice, never opens it.
for factors in [json!([password]), json!([password, password])] {
let r = call(json!({ "op": "open_with", "vault": file, "factors": factors }));
assert_eq!(r["ok"], false, "{r}");
}
}
#[test]
fn a_phone_pairs_then_opens_and_approves() {
let mut v = vault(&[3; 32]);
let prf = [9u8; 32];
let prf64 = BASE64.encode(&prf);
// The PC waits with a one-time key; the phone seals its pairing to it.
let pc = Recipient::generate();
let context = "pair:abc";
let r = call(json!({ "op": "phone_enrol", "pub": BASE64.encode(&pc.public()), "context": context, "label": "Phone", "prf": prf64 }));
assert_eq!(r["ok"], true, "{r}");
let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap();
assert_eq!(r["code"], custos_seal::sender_code(&sealed).unwrap(), "the PC checks the code the phone shows");
assert!(pc.open(&sealed, b"pair:other").is_err());
let plain: Value = serde_json::from_slice(&pc.open(&sealed, context.as_bytes()).unwrap()).unwrap();
assert_eq!((plain["label"].as_str(), plain["passkey"].as_str()), (Some("Phone"), Some(prf64.as_str())));
let approval = BASE64.decode(plain["approval"].as_str().unwrap().as_bytes()).unwrap();
assert_eq!(approval.len(), 32);
let wrapped = r["wrapped"].as_str().unwrap();
assert!(!r.to_string().contains(plain["approval"].as_str().unwrap()), "the material leaves only sealed or wrapped");
// The PC adds both factors.
let passkey_id = v.add_factor(Unlock::Material(FactorKind::Passkey, &prf), "Phone passkey").unwrap();
let approval_id = v.add_factor_apart(Unlock::Material(FactorKind::Approval, &approval), "Phone", &[&passkey_id]).unwrap();
let file = b64(&v);
// The phone opens it with its passkey and the master password.
let r = call(json!({ "op": "open_with", "vault": file, "factors": [
{ "kind": "material", "factor": "passkey", "material": prf64 },
{ "kind": "password", "password": PASSWORD },
]}));
assert_eq!(r["ok"], true, "{r}");
call(json!({ "op": "lock" }));
// Its two factors never open it together.
let me = call(json!({ "op": "recipient" }));
let public = BASE64.decode(me["pub"].as_str().unwrap().as_bytes()).unwrap();
let sealed = BASE64.encode(&custos_seal::seal(&public, b"approval:x:y", &approval).unwrap());
let r = call(json!({ "op": "open_with", "vault": file, "factors": [
{ "kind": "material", "factor": "passkey", "material": prf64 },
{ "kind": "sealed", "factor": "approval", "pub": me["pub"], "sealed": sealed, "context": "approval:x:y" },
]}));
assert_eq!(r["error"], "these two factors are kept on the same device; use one of them with another factor");
// The PC asks the phone; the phone approves with its passkey.
let requester = Recipient::generate();
let req_pub = BASE64.encode(&requester.public());
assert_eq!(call(json!({ "op": "match_code", "pub": req_pub }))["match"], requester.match_code());
let ctx = format!("approval:{approval_id}:r1");
let wrong_key = call(json!({ "op": "phone_approve", "wrapped": wrapped, "prf": BASE64.encode(&[8u8; 32]), "pub": req_pub, "context": ctx }));
assert_eq!(wrong_key["ok"], false);
let r = call(json!({ "op": "phone_approve", "wrapped": wrapped, "prf": prf64, "pub": req_pub, "context": ctx }));
let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap();
let m = requester.open(&sealed, ctx.as_bytes()).unwrap();
let pw = SecretString::from(PASSWORD);
assert!(Vault::open_with(&v.to_bytes().unwrap(), Unlock::Password(&pw), Unlock::Material(FactorKind::Approval, &m)).is_ok());
}
#[test]
fn a_phone_pairs_as_a_domi_device() {
// The PC waits with a one-time key; the phone seals its device public key and label to it.
let pc = Recipient::generate();
let device = data_encoding::BASE64URL_NOPAD.encode(&[5u8; 32]);
let r = call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc_-1", "label": " Pixel\n", "device": device }));
assert_eq!(r["ok"], true, "{r}");
let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap();
assert_eq!(r["code"], custos_seal::sender_code(&sealed).unwrap());
assert!(pc.open(&sealed, b"domi-pair:other").is_err(), "the box is for this pairing only");
let plain: Value = serde_json::from_slice(&pc.open(&sealed, b"domi-pair:abc_-1").unwrap()).unwrap();
assert_eq!(plain, json!({ "label": "Pixel", "device": device }));
// Malformed: a device key of the wrong length, an id that would change the context.
let short = data_encoding::BASE64URL_NOPAD.encode(&[5u8; 31]);
assert_eq!(call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc", "label": "x", "device": short }))["ok"], false);
assert_eq!(call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "a:b", "label": "x", "device": device }))["ok"], false);
}
+23
View File
@@ -95,6 +95,29 @@ slot, then the body.
because ids and types are not secret. The app uses them to ask the TOTP service or a paired device for a
factor. Those services pass material through a mailbox they cannot read; see `docs/SEAL.md`.
## In the browser and on a phone
`custos-wasm` opens a version-2 vault with any two factors (`open_with`). A factor that comes from the
factor service or from another device arrives as a box sealed to a one-time key the module made
(`recipient`); the key's secret half never leaves WebAssembly memory and is used once.
**Pairing a phone** gives the vault two factors at once, both added by the PC (which writes the file):
1. The PC waits with a one-time key and shows its match code; the phone shows the same code.
2. On the phone, a passkey is created and evaluated with the WebAuthn PRF extension
(salt `SHA-256("custos passkey v1")`). Its 32-byte output is the **passkey** factor's material.
3. `phone_enrol` makes 32 random bytes, the phone's **approval** material, and seals both to the PC
(context `pair:<pairing id>`). The phone keeps the approval material only wrapped with the PRF output
(at-rest sealing, context `custos phone approval v1`), so stolen browser storage is not a factor.
4. The phone shows the box's sender code (`docs/SEAL.md`); the PC adds the factors only after you confirm it
shows the same code. It adds the approval factor **apart** from the passkey (`add_factor_apart`).
**Factors on one device never pair.** `add_factor_apart` writes no pair slot between the new factor and the
ones named, so those two open nothing together (`Error::SameDevice`) while each still pairs with every other
factor. A phone's passkey and its approval key, or a PC's device key and its approval key, are added apart.
`phone_approve` unwraps the approval material with a fresh PRF output (Face ID, Touch ID) and seals it to a
requesting device, for `approval:<factor id>:<request id>`. The material exists unwrapped only inside that call.
## Body
`"format": 2`, and a `factors` list next to `items`:
+2
View File
@@ -119,6 +119,8 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed:
- `fields` is an ordered list; a name may repeat (several `url`s). Unknown names are kept as custom fields.
- `history` keeps the previous value of a secret field each time it changes (newest last, at most 20 per item).
- Readers ignore JSON members they do not know, so later versions can add them.
- `identity` (optional, core 0.7.0): the Domi identity's root key and the certs it issued (docs/IDENTITY.md).
An older Custos drops it when it saves, so every Custos that saves the vault must be 0.7.0 or later.
### Item types and their fields (v1)
+70
View File
@@ -0,0 +1,70 @@
# The Domi identity (`custos-vault`, `identity`)
Every Domi app gets its own subkey, certified by **one root Ed25519 key per person**. The root key lives in
the vault and never leaves it: no function of this crate returns it, and the vault signs nothing with it but
subkey certificates. The certificate format, the match code and verification are in Fundamentum
(`crates/tessera`, `docs/TESSERA.md`); this page is the vault side.
## Creating it: the order is mandatory
```
entropy 32 bytes from the OS CSPRNG
mnemonic BIP39 English, 24 words, shown ONCE
confirm the person types 3 words the vault picks at random
root Ed25519 secret = HKDF-SHA256(salt = "tessera root v1", ikm = BIP39 seed(mnemonic, ""), info = "ed25519")
import the secret goes into the vault; entropy, seed and mnemonic are wiped
```
A key that was created non-extractable first could never be backed up. So the code cannot do it in the other
order: `identity::Enrollment` is a typestate.
| Type | Holds | Only way forward |
|:--|:--|:--|
| `Enrollment` | the entropy | `show(display)`: hands the 24 words to `display`, once |
| `Shown` | the entropy, 3 word positions | `confirm(words)`: the 3 words, or it hands itself back to try again |
| `Confirmed` | the derived root secret; the entropy is wiped | `import(&mut vault)`: stores the root, returns its public key |
`import` exists only on `Confirmed`, `Confirmed` only comes from `confirm`, and `confirm` only from `show`.
Swapping the order does not compile (`compile_fail` doctests in `src/identity.rs`). None of the three types
is `Clone` or `Serialize`; each prints `[redacted]`.
Test vector: entropy `00` × 32 → `abandon` × 23 + `art` → root public key
`vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs` (base64url). Fundamentum pins the same value.
## In the vault file
A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it open as before:
```json
"identity": {
"root": "<64 hex: the Ed25519 secret>",
"public": "<64 hex>",
"created": 1793000000000,
"issued": [
{ "kind": "app", "app_id": "fiscus", "purpose": "sync", "subkey": "<base64url>", "label": "fiscus.exe",
"not_before": 1793000000, "not_after": 1824536000, "issued": 1793000000000 }
]
}
```
- `issued` records each cert the vault signed, for *Domi identity → apps and devices*. It is a record, not
a trust list: revocation is v1.1.
- **An older Custos drops the member when it saves the vault** (it ignores members it does not know). Every
Custos that saves this vault must run core 0.7.0 or later. The mnemonic recovers the root either way.
## Using it
| Function | What |
|:--|:--|
| `Vault::domi_root_public()` | the root public key, if there is an identity |
| `Vault::domi_sign_cert(tbs)` | Ed25519 over `"tessera cert v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TSC1` followed by this root's public key |
| `Vault::domi_issued()`, `domi_record(issued)` | the record of issued certs |
The prefix check means the vault is not a general signing oracle: whatever the app hands it, the result
can only ever verify as a certificate naming this root.
## What it does not protect
The root secret is in the vault body, so everything in docs/THREAT_MODEL.md about an unlocked vault applies:
malware running as you while the vault is open can read it from memory. It never reaches the webview, the
Domi pipe, logs or the web vault.
+6
View File
@@ -36,6 +36,12 @@ approval to the key the box is sealed for.
Test vector: R = `07` × 32 → `684361`.
### The sender code
The match code of a box's ephemeral key E (`sender_code`). When the receiver must know who sealed a box,
as when a PC adds a phone's factors, the sealing screen shows this code and the receiving screen asks the
person to confirm it. E is fresh for every box, so each box has its own code.
## At rest
The factor service keeps each TOTP share sealed with its own key, which comes from a systemd credential
+4
View File
@@ -61,6 +61,10 @@ just as plainly, what it does not.
- **The factor service holds one factor.** It releases the TOTP factor after a valid code, so whoever
controls the home server has that factor. It is one factor, never enough alone. Approval material and
cloud secrets pass through it only as sealed boxes (`docs/SEAL.md`), which it cannot open.
- **A paired phone's browser storage** holds its approval material wrapped with the passkey's PRF output,
which the authenticator gives only after Face ID or Touch ID. The passkey and the approval key are added
apart (docs/FACTORS.md), so the phone alone is one device and opens nothing: it still needs the master
password, the TOTP code or a PC.
- **An approval is only as careful as the person approving.** Compare the six-digit match code on both
screens; a request you did not start is someone else's.