[vault] Identity: the Domi root key in the vault, mnemonic typestate, signs only certs
This commit is contained in:
@@ -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() })
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user