Compare commits

...

24 Commits

Author SHA1 Message Date
mnovak 73d9de2304 [repo] Merge: feature/domi-identity (the Domi identity's root key in the vault, domi_pair, PR #9) 2026-11-03 19:04:24 +01:00
mnovak 6c696ba3a6 [wasm] Domi pairing: seal a phone's device key and label to the waiting PC; v0.7.0 2026-11-03 18:54:09 +01:00
mnovak 1c4bf4b373 [vault] Identity: the Domi root key in the vault, mnemonic typestate, signs only certs 2026-11-03 18:52:10 +01:00
mnovak 680b66cff7 [vault] Identity: docs/IDENTITY.md and the mandatory tests, before the code 2026-11-03 18:52:01 +01:00
mnovak 6e4da02351 [repo] Merge: feature/web-factors (two factors in the browser, phone pairing, factors apart, PR #8) 2026-11-03 15:28:30 +01:00
mnovak e365f21d54 [wasm] Two factors in the browser: open_with (sealed answers, passkey PRF), phone pairing and approvals; factors added apart never pair; sender code; v0.6.0 2026-11-03 12:07:59 +01:00
mnovak df7c149b25 [repo] Merge: feature/seal-import (sealed boxes, key import, factor ids, PR #7) 2026-11-03 11:56:56 +01:00
mnovak 7a7a628fa5 [seal] Sealed boxes and key import: custos-seal (X25519 + XChaCha20-Poly1305, match code, at-rest sealing), custos_keys::import, Vault::factor_ids; v0.5.0 2026-11-02 18:05:00 +01:00
mnovak 7893dd199c [repo] Merge: feature/two-factors (format v2, machine store, key pairs and API keys, PR #6) 2026-11-02 16:24:43 +01:00
mnovak 3f3cd26590 [keys] Key pairs and API keys: custos-keys (Ed25519, ECDSA P-256, RSA), secret_key, api_key; threat model; v0.4.0 2026-11-02 15:49:07 +01:00
mnovak 12783c9b92 [docs] Keys: secret keys, API keys, key pairs; tests first 2026-11-02 15:46:44 +01:00
mnovak 02c6795f53 [vault] Format v2: factor, pair and single slots; open_with any two factors; upgrade from v1; key-pair item type 2026-11-02 15:45:55 +01:00
mnovak df6565941e [vault] Tests: any two factors, never one; factors added and removed alone; v1 upgrade; tamper; machine store 2026-11-02 15:45:54 +01:00
mnovak 4daffdff73 [docs] Factors: format version 2, any two of password, device, TOTP, approval, passkey; machine store 2026-11-02 15:39:47 +01:00
mnovak e3128b35aa [repo] Merge: feature/share-wasm (share links, browser build, PR #5) 2026-10-31 18:31:49 +01:00
mnovak 5ee1c0da6b [share] Share links and the browser build: custos-share (blob v1, key in the fragment, optional password), custos-wasm (JSON ABI, no wasm-bindgen), docs/SHARE.md, threat model (v0.3.0) 2026-10-31 18:20:51 +01:00
mnovak 4aac99fb47 [repo] Merge: feature/real-words (real English words only, ASCII-only symbols, PR #4) 2026-10-31 13:55:00 +01:00
mnovak faa5d8dfc9 [gen] Real words: memorable passwords from EFF words a US English dictionary knows; strict-site symbols ASCII only (v0.2.1) 2026-10-31 13:54:44 +01:00
mnovak a68b3b46bf [repo] Merge: feature/totp-qr (TOTP, QR payloads, device key wrap, PR #3) 2026-10-31 10:44:58 +01:00
mnovak 0b9cce40e2 [core] TOTP, QR payloads, device key wrap: custos-totp, custos-qr, Vault::wrap_for_device (v0.2.0) 2026-10-31 10:44:24 +01:00
mnovak fe90e7691b [core] Tests: RFC 6238/4226 vectors, otpauth parsing, Wi-Fi escaping, device key wrap 2026-10-31 10:44:24 +01:00
mnovak 686c662835 [repo] Merge: feature/nickname-parts (nickname follows the title, PR #2) 2026-10-31 10:24:00 +01:00
mnovak fba6e5492a [gen] Nickname: draw word and number once, render them for any title (NicknameParts) 2026-10-31 10:23:53 +01:00
mnovak fac0184e46 [repo] Merge: feature/core (vault file v1, generators, PR #1) 2026-10-31 10:13:46 +01:00
52 changed files with 13089 additions and 139 deletions
+4
View File
@@ -0,0 +1,4 @@
# The browser build takes its randomness from crypto.getRandomValues through getrandom's custom
# backend (crates/custos-wasm/src/lib.rs, `random_fill`): no wasm-bindgen.
[target.wasm32-unknown-unknown]
rustflags = ['--cfg', 'getrandom_backend="custom"']
+21 -4
View File
@@ -7,24 +7,41 @@ The Windows app lives in the private `Custos` repo and depends on this one by gi
## Layout ## Layout
``` ```
crates/custos-vault file format, Argon2id + XChaCha20-Poly1305, atomic save, item model, SecretString crates/custos-vault file format, Argon2id + XChaCha20-Poly1305, atomic save, item model, SecretString
crates/custos-gen memorable password, nickname, random, PIN, strict-site generators + wordlists crates/custos-gen memorable password, nickname, random, PIN, strict-site, secret-key and API-key generators
docs/FORMAT.md the vault file format (versioned; change it before the code) crates/custos-keys key pairs (Ed25519, ECDSA P-256, RSA) as OpenSSH and PKCS#8 PEM
crates/custos-totp TOTP / HOTP (RFC 6238 / 4226 vectors are tests), otpauth:// parsing
crates/custos-qr QR payload strings (Wi-Fi escaping); rendering is the app's job
crates/custos-seal sealed boxes (X25519 + XChaCha20-Poly1305) for factor material through a mailbox; at-rest sealing
crates/custos-share private share links: XChaCha20-Poly1305 blob, key in the URL fragment, optional password
crates/custos-wasm the browser build (web vault + share page): JSON `call` ABI, no wasm-bindgen; js/custos.mjs
docs/FORMAT.md the vault file format, version 1 (versioned; change it before the code)
docs/FACTORS.md version 2: any two factors open the vault; the machine store
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/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 ## Commands
``` ```
cargo test --workspace # all mandatory tests cargo test --workspace # all mandatory tests
cargo test --workspace --release # same, faster Argon2 cargo test --workspace --release # same, faster Argon2
# the browser build, with the server's toolchain (WSL + Nix here; nixpkgs rev as in the Custos flake):
nix shell nixpkgs#cargo nixpkgs#rustc nixpkgs#stdenv.cc nixpkgs#lld -c \n cargo build --release --target wasm32-unknown-unknown -p custos-wasm
node crates/custos-wasm/js/test.mjs <custos_wasm.wasm> [<vault> <password>] # the JS loader against it
``` ```
- `.cargo/config.toml` selects getrandom's custom backend for wasm32: `random_fill` → `crypto.getRandomValues`.
- WSL: run commands with `wsl -d Debian --exec bash -lc '…'`; plain `wsl -- …` expands `$VARS` too early.
On the dev machine set `CARGO_HOME=F:\C-Drive-Migration\future-caches\cargo` (C: is off limits). On the dev machine set `CARGO_HOME=F:\C-Drive-Migration\future-caches\cargo` (C: is off limits).
## Rules ## Rules
- Commits: `[<crate>] <Feature>: <description>`, e.g. `[vault] Format: authenticate slot parameters`. - Commits: `[<crate>] <Feature>: <description>`, e.g. `[vault] Format: authenticate slot parameters`.
- **No AI attribution in commits or PRs, ever**: no `Co-Authored-By`, no session links, no "Generated with". - **No AI attribution in commits or PRs, ever**: no `Co-Authored-By`, no session links, no "Generated with".
- No binaries in git. - No binaries in git.
- **No custom crypto.** Only RustCrypto / rust-random crates (`argon2`, `chacha20poly1305`, `zeroize`, - **No custom crypto.** Only RustCrypto / rust-random crates (`argon2`, `chacha20poly1305`, `hkdf`, `zeroize`,
`rand` with `SysRng`). Randomness from the OS CSPRNG only. `rand` with `SysRng`; for key pairs `ssh-key`, `p256`, `rsa` and `ed25519-dalek`, RustCrypto's Ed25519
backend; `x25519-dalek` for sealed boxes). Randomness from the OS CSPRNG only.
- **Secrets never in logs, panics, error messages, `Debug`/`Display` output or test snapshots.** - **Secrets never in logs, panics, error messages, `Debug`/`Display` output or test snapshots.**
Secret-holding types print `[redacted]`; there is a test for each one. Secret-holding types print `[redacted]`; there is a test for each one.
- Tests here are mandatory (it is public and holds the crypto). A format change updates `docs/FORMAT.md` - Tests here are mandatory (it is public and holds the crypto). A format change updates `docs/FORMAT.md`
Generated
+825 -26
View File
File diff suppressed because it is too large Load Diff
+7 -1
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*"] members = ["crates/*"]
[workspace.package] [workspace.package]
version = "0.1.0" version = "0.7.0"
edition = "2024" edition = "2024"
license = "MPL-2.0" license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic" repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
@@ -17,3 +17,9 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
thiserror = "2" thiserror = "2"
unicode-normalization = "0.1" unicode-normalization = "0.1"
hmac = "0.13"
sha1 = "0.11"
sha2 = "0.11"
hkdf = "0.13"
data-encoding = "2"
percent-encoding = "2"
+5 -1
View File
@@ -7,6 +7,10 @@ password and secret manager: everything that touches plaintext or keys.
|:--|:--| |:--|:--|
| `custos-vault` | The `.custos` file: Argon2id → key slot → XChaCha20-Poly1305, atomic save, typed items | | `custos-vault` | The `.custos` file: Argon2id → key slot → XChaCha20-Poly1305, atomic save, typed items |
| `custos-gen` | Memorable passwords (`Word7-Other3-Third9-Fourth2`), nicknames (`GitHub.Lantern.47`), random, PIN, strict-site | | `custos-gen` | Memorable passwords (`Word7-Other3-Third9-Fourth2`), nicknames (`GitHub.Lantern.47`), random, PIN, strict-site |
| `custos-totp` | TOTP (RFC 6238) and HOTP (RFC 4226), `otpauth://` URIs |
| `custos-qr` | QR payloads: Wi-Fi join codes (escaped), plain secrets |
| `custos-share` | Private share links: encrypted in the sender's app, key in the link's `#fragment`, optional password ([`docs/SHARE.md`](docs/SHARE.md)) |
| `custos-wasm` | The same code compiled to WebAssembly for the web vault and the share page (no wasm-bindgen; `js/custos.mjs` is the whole JS side) |
Read [`docs/FORMAT.md`](docs/FORMAT.md) for the file format and [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md) Read [`docs/FORMAT.md`](docs/FORMAT.md) for the file format and [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md)
for what it does and does not protect. Report vulnerabilities as described in [`SECURITY.md`](SECURITY.md). for what it does and does not protect. Report vulnerabilities as described in [`SECURITY.md`](SECURITY.md).
@@ -15,4 +19,4 @@ for what it does and does not protect. Report vulnerabilities as described in [`
cargo test --workspace cargo test --workspace
``` ```
Licence: MPL-2.0. The EFF wordlist is CC BY 3.0 US (see `crates/custos-gen/wordlists/SOURCES.md`). Licence: MPL-2.0. The memorable-password words come from the EFF wordlist (CC BY 3.0 US), filtered with the ESDB/SCOWL English dictionary (see `crates/custos-gen/wordlists/SOURCES.md`).
+1
View File
@@ -11,6 +11,7 @@ custos-vault = { path = "../custos-vault" }
rand.workspace = true rand.workspace = true
zeroize.workspace = true zeroize.workspace = true
unicode-normalization.workspace = true unicode-normalization.workspace = true
data-encoding.workspace = true
[dev-dependencies] [dev-dependencies]
regex = "1" regex = "1"
+169 -56
View File
@@ -48,23 +48,16 @@ const DIGITS: [char; 10] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
// ---------- word lists ---------- // ---------- word lists ----------
/// The EFF large wordlist (7,776 words), with its four hyphenated words made plain: the hyphen is
/// removed, and `yo-yo` (the list also has `yoyo`) becomes `yoyos`, so all 7,776 stay distinct.
pub static EFF_WORDS: LazyLock<Vec<String>> = LazyLock::new(|| {
include_str!("../wordlists/eff_large_wordlist.txt")
.lines()
.filter_map(|l| l.split('\t').nth(1))
.map(|w| match w.trim() {
"yo-yo" => "yoyos".to_owned(),
w => w.replace('-', ""),
})
.collect()
});
fn plain_list(text: &'static str) -> Vec<&'static str> { fn plain_list(text: &'static str) -> Vec<&'static str> {
text.lines().filter(|l| !l.starts_with('#')).flat_map(str::split_whitespace).collect() text.lines().filter(|l| !l.starts_with('#')).flat_map(str::split_whitespace).collect()
} }
/// The words of memorable passwords (7,322): the EFF large wordlist without the words a standard US
/// English spellchecker dictionary does not know (brand names, names, coinages, hyphenated words).
/// See `wordlists/SOURCES.md`.
pub static MEMORABLE_WORDS: LazyLock<Vec<&str>> =
LazyLock::new(|| plain_list(include_str!("../wordlists/memorable.txt")));
static NOUNS: LazyLock<Vec<&str>> = LazyLock::new(|| plain_list(include_str!("../wordlists/nouns.txt"))); static NOUNS: LazyLock<Vec<&str>> = LazyLock::new(|| plain_list(include_str!("../wordlists/nouns.txt")));
static ADJECTIVES: LazyLock<Vec<&str>> = LazyLock::new(|| plain_list(include_str!("../wordlists/adjectives.txt"))); static ADJECTIVES: LazyLock<Vec<&str>> = LazyLock::new(|| plain_list(include_str!("../wordlists/adjectives.txt")));
static VERBS: LazyLock<Vec<&str>> = LazyLock::new(|| plain_list(include_str!("../wordlists/verbs.txt"))); static VERBS: LazyLock<Vec<&str>> = LazyLock::new(|| plain_list(include_str!("../wordlists/verbs.txt")));
@@ -144,7 +137,7 @@ pub const MAX_WORDS: u8 = 10;
/// Bits of entropy of a memorable password with these options. /// Bits of entropy of a memorable password with these options.
pub fn memorable_entropy(o: &MemorableOptions) -> f64 { pub fn memorable_entropy(o: &MemorableOptions) -> f64 {
let n = o.words.clamp(MIN_WORDS, MAX_WORDS) as f64; let n = o.words.clamp(MIN_WORDS, MAX_WORDS) as f64;
let per_word = (EFF_WORDS.len() as f64).log2() + if o.digit_after_word { 10f64.log2() } else { 0.0 }; let per_word = (MEMORABLE_WORDS.len() as f64).log2() + if o.digit_after_word { 10f64.log2() } else { 0.0 };
n * per_word + (n - 1.0) * (o.separator.choices().len() as f64).log2() n * per_word + (n - 1.0) * (o.separator.choices().len() as f64).log2()
} }
@@ -157,7 +150,7 @@ pub fn memorable(o: &MemorableOptions) -> Generated {
if i > 0 { if i > 0 {
out.push(pick(&seps)); out.push(pick(&seps));
} }
let w = &EFF_WORDS[rng().random_range(0..EFF_WORDS.len())]; let w = pick(&MEMORABLE_WORDS);
if o.capitalize { if o.capitalize {
out.push_str(&capitalize(w)); out.push_str(&capitalize(w));
} else { } else {
@@ -284,59 +277,99 @@ fn leetify(w: &str) -> String {
.collect::<String>() .collect::<String>()
} }
/// A nickname from the template, e.g. `GitHub.Lantern.47`. With an empty (normalised) title, `{Name}` /// The random parts of a nickname, drawn once. The title can keep changing afterwards: [`render`]
/// is left out together with the literal separator next to it. /// fills it in without drawing new words or numbers (a new web login's nickname follows its title as
pub fn nickname(title: &str, o: &NicknameOptions) -> Result<Generated, GenError> { /// it is typed).
let mut tokens = parse_template(&o.template)?; ///
/// [`render`]: NicknameParts::render
#[derive(Clone, Debug)]
pub struct NicknameParts {
/// One per `{Word}` in the template, capitalised (and leetified if asked).
pub words: Vec<String>,
/// One per `{Number}` in the template.
pub numbers: Vec<String>,
pub entropy_bits: f64,
}
fn word_pool(kinds: &[WordKind]) -> Vec<&'static str> {
let mut pool: Vec<&'static str> = kinds.iter().flat_map(|k| words(*k).iter().copied()).collect();
// Overlapping lists: count each word once, so the entropy stays honest.
pool.sort_unstable();
pool.dedup();
pool
}
/// Draws the words and numbers for `o.template`.
pub fn nickname_parts(o: &NicknameOptions) -> Result<NicknameParts, GenError> {
let tokens = parse_template(&o.template)?;
if !(1..=4).contains(&o.digits) { if !(1..=4).contains(&o.digits) {
return fail("the number must have 1 to 4 digits"); return fail("the number must have 1 to 4 digits");
} }
let name = normalize_name(title); let pool = word_pool(&o.kinds);
if name.is_empty() { let mut parts = NicknameParts { words: Vec::new(), numbers: Vec::new(), entropy_bits: 0.0 };
while let Some(i) = tokens.iter().position(|t| *t == Token::Name) {
tokens.remove(i);
if i == 0 {
if matches!(tokens.first(), Some(Token::Literal(_))) {
tokens.remove(0);
}
} else if matches!(tokens.get(i - 1), Some(Token::Literal(_))) {
tokens.remove(i - 1);
}
}
}
let mut pool: Vec<&str> = Vec::new();
for k in &o.kinds {
if !pool.is_empty() && pool.iter().any(|w| words(*k).contains(w)) {
// Overlapping lists: keep the union without duplicates, so entropy stays honest.
pool.extend(words(*k).iter().filter(|w| !pool.contains(w)).collect::<Vec<_>>());
} else {
pool.extend_from_slice(words(*k));
}
}
if pool.is_empty() && tokens.contains(&Token::Word) {
return fail("choose at least one kind of word");
}
let mut out = String::new();
let mut bits = 0.0;
for t in &tokens { for t in &tokens {
match t { match t {
Token::Literal(s) => out.push_str(s),
Token::Name => out.push_str(&name),
Token::Word => { Token::Word => {
if pool.is_empty() {
return fail("choose at least one kind of word");
}
let w = capitalize(pick(&pool)); let w = capitalize(pick(&pool));
out.push_str(&if o.leet { leetify(&w) } else { w }); parts.words.push(if o.leet { leetify(&w) } else { w });
bits += (pool.len() as f64).log2(); parts.entropy_bits += (pool.len() as f64).log2();
} }
Token::Number => { Token::Number => {
(0..o.digits).for_each(|_| out.push(digit())); parts.numbers.push((0..o.digits).map(|_| digit()).collect());
bits += o.digits as f64 * 10f64.log2(); parts.entropy_bits += o.digits as f64 * 10f64.log2();
} }
Token::Literal(_) | Token::Name => {}
} }
} }
Ok(Generated { value: SecretString::new(out), entropy_bits: bits }) Ok(parts)
}
impl NicknameParts {
/// The nickname for `title`. With an empty (normalised) title, `{Name}` is left out together with
/// the literal separator next to it. `template` must be the one the parts were drawn for.
pub fn render(&self, title: &str, template: &str) -> Result<String, GenError> {
let mut tokens = parse_template(template)?;
let name = normalize_name(title);
if name.is_empty() {
while let Some(i) = tokens.iter().position(|t| *t == Token::Name) {
tokens.remove(i);
if i == 0 {
if matches!(tokens.first(), Some(Token::Literal(_))) {
tokens.remove(0);
}
} else if matches!(tokens.get(i - 1), Some(Token::Literal(_))) {
tokens.remove(i - 1);
}
}
}
let (mut words, mut numbers) = (self.words.iter(), self.numbers.iter());
let mismatch = || GenError("the template changed since its words were drawn".into());
let mut out = String::new();
for t in &tokens {
match t {
Token::Literal(s) => out.push_str(s),
Token::Name => out.push_str(&name),
Token::Word => out.push_str(words.next().ok_or_else(mismatch)?),
Token::Number => out.push_str(numbers.next().ok_or_else(mismatch)?),
}
}
Ok(out)
}
}
/// A nickname from the template, e.g. `GitHub.Lantern.47`. With an empty (normalised) title, `{Name}`
/// is left out together with the literal separator next to it.
pub fn nickname(title: &str, o: &NicknameOptions) -> Result<Generated, GenError> {
let parts = nickname_parts(o)?;
let value = parts.render(title, &o.template)?;
Ok(Generated { value: SecretString::new(value), entropy_bits: parts.entropy_bits })
} }
// ---------- random, strict site, PIN ---------- // ---------- random, strict site, PIN ----------
// Only English letters A–Z/a–z, digits 0–9 and ASCII symbols: every keyboard layout can type them.
pub const RANDOM_SYMBOLS: &str = "!@#$%^&*()-_=+[]{};:,.?/~"; pub const RANDOM_SYMBOLS: &str = "!@#$%^&*()-_=+[]{};:,.?/~";
pub const LOOKALIKES: &str = "Il1O0o|"; pub const LOOKALIKES: &str = "Il1O0o|";
@@ -413,7 +446,8 @@ pub struct StrictOptions {
pub upper: ClassRule, pub upper: ClassRule,
pub digits: ClassRule, pub digits: ClassRule,
pub symbols: ClassRule, pub symbols: ClassRule,
/// The symbols the site accepts. /// The symbols the site accepts. Only ASCII symbols count: letters, digits, spaces and anything
/// outside ASCII (`€`, `§`, `ž`) are ignored.
pub allowed_symbols: String, pub allowed_symbols: String,
} }
@@ -432,8 +466,7 @@ impl Default for StrictOptions {
pub fn strict(o: &StrictOptions) -> Result<Generated, GenError> { pub fn strict(o: &StrictOptions) -> Result<Generated, GenError> {
let len = check_length(o.length)?; let len = check_length(o.length)?;
let mut symbols: Vec<char> = let mut symbols: Vec<char> = o.allowed_symbols.chars().filter(char::is_ascii_punctuation).collect();
o.allowed_symbols.chars().filter(|c| !c.is_alphanumeric() && !c.is_whitespace()).collect();
symbols.sort_unstable(); symbols.sort_unstable();
symbols.dedup(); symbols.dedup();
let rules = [ let rules = [
@@ -481,3 +514,83 @@ pub fn pin(length: u8) -> Generated {
let value: String = (0..len).map(|_| digit()).collect(); let value: String = (0..len).map(|_| digit()).collect();
Generated { value: SecretString::new(value), entropy_bits: len as f64 * 10f64.log2() } Generated { value: SecretString::new(value), entropy_bits: len as f64 * 10f64.log2() }
} }
// ---------- keys and API keys (docs/KEYS.md) ----------
/// How a secret key is written out.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum KeyEncoding {
/// Lowercase hex.
Hex,
/// Base64url without padding.
Base64Url,
/// Standard base64 with padding.
Base64,
}
/// `bytes` random bytes (16..=128), encoded: symmetric keys, HMAC and JWT secrets.
pub fn secret_key(bytes: usize, encoding: KeyEncoding) -> Result<Generated, GenError> {
if !(16..=128).contains(&bytes) {
return Err(GenError("a secret key is 16 to 128 bytes".into()));
}
let mut raw = zeroize::Zeroizing::new(vec![0u8; bytes]);
rand::Rng::fill_bytes(&mut rng(), &mut raw);
let value = match encoding {
KeyEncoding::Hex => data_encoding::HEXLOWER.encode(&raw),
KeyEncoding::Base64Url => data_encoding::BASE64URL_NOPAD.encode(&raw),
KeyEncoding::Base64 => data_encoding::BASE64.encode(&raw),
};
Ok(Generated { value: SecretString::new(value), entropy_bits: 8.0 * bytes as f64 })
}
const BASE62: &[u8; 62] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const API_KEY_RANDOM: usize = 32;
/// CRC-32 (IEEE 802.3, reflected, as zlib computes it): the API key checksum. Not a security feature.
fn crc32(data: &[u8]) -> u32 {
let mut crc = !0u32;
for &b in data {
crc ^= b as u32;
for _ in 0..8 {
crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
}
}
!crc
}
fn checksum6(body: &str) -> String {
let mut n = crc32(body.as_bytes()) as u64;
let mut out = [b'0'; 6];
for c in out.iter_mut().rev() {
*c = BASE62[(n % 62) as usize];
n /= 62;
}
String::from_utf8(out.to_vec()).expect("base62 is ASCII")
}
/// `<prefix>_` + 32 uniform base62 characters (190.5 bits) + a 6-character CRC-32 checksum.
/// The prefix is empty, or a lowercase letter and up to 15 lowercase letters or digits.
pub fn api_key(prefix: &str) -> Result<Generated, GenError> {
let ok = prefix.is_empty()
|| (prefix.len() <= 16
&& prefix.starts_with(|c: char| c.is_ascii_lowercase())
&& prefix.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()));
if !ok {
return Err(GenError("the prefix is a lowercase letter and up to 15 lowercase letters or digits".into()));
}
let mut body = if prefix.is_empty() { String::new() } else { format!("{prefix}_") };
for _ in 0..API_KEY_RANDOM {
body.push(BASE62[rng().random_range(0..62)] as char);
}
let sum = checksum6(&body);
body.push_str(&sum);
Ok(Generated { value: SecretString::new(body), entropy_bits: API_KEY_RANDOM as f64 * 62f64.log2() })
}
/// Whether an API key's last 6 characters are the checksum of the rest (a typo, or not one of ours).
pub fn api_key_checksum_ok(key: &str) -> bool {
key.len() > 6 && key.is_char_boundary(key.len() - 6) && {
let (body, sum) = key.split_at(key.len() - 6);
checksum6(body) == sum
}
}
+50
View File
@@ -0,0 +1,50 @@
//! Mandatory tests for the key and API-key generators (docs/KEYS.md).
use custos_gen::{KeyEncoding, api_key, api_key_checksum_ok, secret_key};
#[test]
fn secret_keys_have_the_asked_length_encoding_and_entropy() {
let hex = secret_key(32, KeyEncoding::Hex).unwrap();
assert_eq!(hex.value.expose().len(), 64);
assert!(hex.value.expose().chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));
assert_eq!(hex.entropy_bits, 256.0);
let b64 = secret_key(32, KeyEncoding::Base64Url).unwrap();
assert_eq!(b64.value.expose().len(), 43);
assert!(b64.value.expose().chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'));
let std = secret_key(48, KeyEncoding::Base64).unwrap();
assert_eq!(std.value.expose().len(), 64);
// Never the same twice; refused outside 16..=128 bytes.
assert_ne!(secret_key(32, KeyEncoding::Hex).unwrap().value, hex.value);
assert!(secret_key(15, KeyEncoding::Hex).is_err());
assert!(secret_key(129, KeyEncoding::Hex).is_err());
}
#[test]
fn api_keys_carry_a_prefix_190_random_bits_and_a_checksum() {
let k = api_key("domi").unwrap();
let v = k.value.expose();
assert!(v.starts_with("domi_"), "{v}");
assert_eq!(v.len(), "domi_".len() + 32 + 6);
assert!(v["domi_".len()..].chars().all(|c| c.is_ascii_alphanumeric()));
assert!((k.entropy_bits - 190.5).abs() < 0.1, "{}", k.entropy_bits);
assert!(api_key_checksum_ok(v));
// A typo is caught by the checksum.
let mut typo: Vec<char> = v.chars().collect();
let i = "domi_".len() + 3;
typo[i] = if typo[i] == 'a' { 'b' } else { 'a' };
assert!(!api_key_checksum_ok(&typo.into_iter().collect::<String>()));
// No prefix is allowed; a bad one is refused.
let bare = api_key("").unwrap();
assert_eq!(bare.value.expose().len(), 38);
assert!(api_key_checksum_ok(bare.value.expose()));
for bad in ["Domi", "do mi", "1abc", "averyveryverylongprefix"] {
assert!(api_key(bad).is_err(), "{bad}");
}
}
#[test]
fn generated_keys_never_print() {
let k = secret_key(32, KeyEncoding::Hex).unwrap();
let printed = format!("{k:?}");
assert!(!printed.contains(k.value.expose()), "{printed}");
}
+52 -9
View File
@@ -1,8 +1,8 @@
//! The mandatory generator tests (CLAUDE.md). //! The mandatory generator tests (CLAUDE.md).
use custos_gen::{ use custos_gen::{
ClassRule, EFF_WORDS, MemorableOptions, NicknameOptions, RandomOptions, Separator, StrictOptions, WordKind, ClassRule, MAX_LENGTH, MEMORABLE_WORDS, MemorableOptions, NicknameOptions, RandomOptions, Separator, StrictOptions,
memorable, memorable_entropy, nickname, normalize_name, pin, random, strict, WordKind, memorable, memorable_entropy, nickname, nickname_parts, normalize_name, pin, random, strict,
}; };
use regex::Regex; use regex::Regex;
use std::collections::HashSet; use std::collections::HashSet;
@@ -10,11 +10,24 @@ use std::collections::HashSet;
const SAMPLES: usize = 10_000; const SAMPLES: usize = 10_000;
#[test] #[test]
fn eff_list_is_complete_and_plain() { fn memorable_words_are_real_english_words() {
assert_eq!(EFF_WORDS.len(), 7_776); assert_eq!(MEMORABLE_WORDS.len(), 7_322);
let unique: HashSet<_> = EFF_WORDS.iter().collect(); let unique: HashSet<_> = MEMORABLE_WORDS.iter().collect();
assert_eq!(unique.len(), 7_776, "a word repeats after removing hyphens"); assert_eq!(unique.len(), 7_322);
assert!(EFF_WORDS.iter().all(|w| !w.is_empty() && w.bytes().all(|b| b.is_ascii_lowercase()))); assert!(MEMORABLE_WORDS.iter().all(|w| w.len() >= 3 && w.bytes().all(|b| b.is_ascii_lowercase())));
// Every word comes from the EFF list...
let eff: HashSet<&str> = include_str!("../wordlists/eff_large_wordlist.txt")
.lines()
.filter_map(|l| l.split('\t').nth(1))
.map(str::trim)
.collect();
assert!(MEMORABLE_WORDS.iter().all(|w| eff.contains(w)));
// ...minus brand names, names, coinages and hyphenated words that no dictionary lists.
for not_a_word in ["walmart", "iphone", "skype", "myspace", "monday", "december", "pranker", "finlike", "felt-tip"]
{
assert!(eff.contains(not_a_word), "{not_a_word} is not in the EFF list any more");
assert!(!MEMORABLE_WORDS.contains(&not_a_word), "{not_a_word}");
}
} }
#[test] #[test]
@@ -57,7 +70,7 @@ fn memorable_shape_at_every_slider_value_and_option() {
#[test] #[test]
fn memorable_entropy_counts_only_random_choices() { fn memorable_entropy_counts_only_random_choices() {
let per_word = 7_776f64.log2() + 10f64.log2(); let per_word = 7_322f64.log2() + 10f64.log2();
for words in 3..=10u8 { for words in 3..=10u8 {
let o = MemorableOptions { words, ..Default::default() }; let o = MemorableOptions { words, ..Default::default() };
let e = memorable_entropy(&o); let e = memorable_entropy(&o);
@@ -70,7 +83,7 @@ fn memorable_entropy_counts_only_random_choices() {
let four = memorable_entropy(&MemorableOptions::default()); let four = memorable_entropy(&MemorableOptions::default());
assert!((64.0..66.0).contains(&four), "4 words with digits is about 65 bits: {four}"); assert!((64.0..66.0).contains(&four), "4 words with digits is about 65 bits: {four}");
let no_digits = MemorableOptions { digit_after_word: false, ..Default::default() }; let no_digits = MemorableOptions { digit_after_word: false, ..Default::default() };
assert!((memorable_entropy(&no_digits) - 4.0 * 7_776f64.log2()).abs() < 1e-9); assert!((memorable_entropy(&no_digits) - 4.0 * 7_322f64.log2()).abs() < 1e-9);
// A random-digit separator is a random choice per gap. // A random-digit separator is a random choice per gap.
let digit_sep = MemorableOptions { separator: Separator::Digit, ..Default::default() }; let digit_sep = MemorableOptions { separator: Separator::Digit, ..Default::default() };
assert!((memorable_entropy(&digit_sep) - (four + 3.0 * 10f64.log2())).abs() < 1e-9); assert!((memorable_entropy(&digit_sep) - (four + 3.0 * 10f64.log2())).abs() < 1e-9);
@@ -140,6 +153,18 @@ fn nickname_options_and_entropy() {
assert!(nickname("x", &NicknameOptions { template: "{Word".into(), ..Default::default() }).is_err()); assert!(nickname("x", &NicknameOptions { template: "{Word".into(), ..Default::default() }).is_err());
} }
#[test]
fn nickname_parts_keep_word_and_number_while_the_title_changes() {
let o = NicknameOptions::default();
let parts = nickname_parts(&o).unwrap();
let typed: Vec<String> = ["", "G", "Gi", "GitHub"].iter().map(|t| parts.render(t, &o.template).unwrap()).collect();
let tail = typed[0].clone(); // "Lantern.47": no title, so {Name} and its "." are left out
assert!(Regex::new(r"^[A-Z][a-z]+\.[0-9]{2}$").unwrap().is_match(&tail), "{tail}");
assert_eq!(typed[1], format!("G.{tail}"));
assert_eq!(typed[3], format!("GitHub.{tail}"));
assert!(parts.render("x", "{Word}{Word}").is_err(), "a template with more tokens than parts");
}
#[test] #[test]
fn name_normalisation() { fn name_normalisation() {
assert_eq!(normalize_name("Česká spořitelna"), "CeskaSporitelna"); assert_eq!(normalize_name("Česká spořitelna"), "CeskaSporitelna");
@@ -222,6 +247,24 @@ fn random_and_pin() {
assert!((p.entropy_bits - 6.0 * 10f64.log2()).abs() < 1e-9); assert!((p.entropy_bits - 6.0 * 10f64.log2()).abs() < 1e-9);
} }
#[test]
fn random_and_strict_use_only_english_letters_digits_and_ascii_symbols() {
let ok = |c: char| c.is_ascii_alphanumeric() || c.is_ascii_punctuation();
let all = RandomOptions { length: MAX_LENGTH, ..RandomOptions::default() };
for _ in 0..SAMPLES / 10 {
let s = random(&all).unwrap().value.expose().to_owned();
assert!(s.chars().all(ok), "{s}");
}
// Symbols the site lists outside ASCII, letters, digits and spaces are ignored.
let o = StrictOptions { length: 32, allowed_symbols: "€§ž é1!".into(), ..StrictOptions::default() };
for _ in 0..SAMPLES / 10 {
let s = strict(&o).unwrap().value.expose().to_owned();
assert!(s.chars().all(|c| c.is_ascii_alphanumeric() || c == '!'), "{s}");
}
let none_left = StrictOptions { allowed_symbols: "€§".into(), ..StrictOptions::default() };
assert!(strict(&none_left).is_err(), "required symbols, but none of the listed ones is ASCII");
}
/// Nicknames (≈ 30 000 combinations by design: they are names, not secrets) and short PINs are /// Nicknames (≈ 30 000 combinations by design: they are names, not secrets) and short PINs are
/// excluded: their spaces are small enough that repeats in 10 000 draws are expected. /// excluded: their spaces are small enough that repeats in 10 000 draws are expected.
#[test] #[test]
+19 -5
View File
@@ -2,14 +2,28 @@
| File | Used for | Source | Licence | | File | Used for | Source | Licence |
|:--|:--|:--|:--| |:--|:--|:--|:--|
| `eff_large_wordlist.txt` | Memorable passwords (7,776 words, 12.925 bits each) | Electronic Frontier Foundation, "Deep Dive: EFF's New Wordlists for Random Passphrases" (2016), downloaded unchanged from https://www.eff.org/files/2016/07/18/eff_large_wordlist.txt (sha256 `addd35536511597a02fa0a9ff1e5284677b8883b83e986e43f15a3db996b903e`) | CC BY 3.0 US. Attribution: © Electronic Frontier Foundation. | | `eff_large_wordlist.txt` | The source of `memorable.txt` (kept as published) | Electronic Frontier Foundation, "Deep Dive: EFF's New Wordlists for Random Passphrases" (2016), downloaded unchanged from https://www.eff.org/files/2016/07/18/eff_large_wordlist.txt (sha256 `addd35536511597a02fa0a9ff1e5284677b8883b83e986e43f15a3db996b903e`) | CC BY 3.0 US. Attribution: © Electronic Frontier Foundation. |
| `memorable.txt` | Memorable passwords (7,322 words, 12.838 bits each) | The EFF list minus every word that SCOWL/ESDB size 60, US spelling (the size of hunspell's `en_US` dictionary) does not list as a plain lowercase word. Made by `derive_memorable.py` from https://app.aspell.net/create?max_size=60&spelling=US&max_variant=0&diacritic=strip&download=wordlist&encoding=utf-8&format=inline (ESDB revision 1e5b7d3, 2026-06-24; sha256 of the download `bfbc258a6baaa50aec6fe07330b25b57cd90f3dd429345b8280df0414ccf242c`) | CC BY 3.0 US (© Electronic Frontier Foundation), and the ESDB notice below |
| `nouns.txt`, `adjectives.txt`, `verbs.txt` | Nicknames (`{Word}`) | Written for Custos Domi in 2026 by hand: common, family-friendly English words | CC0 1.0 (public domain dedication) | | `nouns.txt`, `adjectives.txt`, `verbs.txt` | Nicknames (`{Word}`) | Written for Custos Domi in 2026 by hand: common, family-friendly English words | CC0 1.0 (public domain dedication) |
## How they are used ## How they are used
- The EFF list file is kept as published. Four of its words contain a hyphen (`drop-down`, `felt-tip`, - Memorable passwords use only real English words. The EFF list has brand names (`walmart`, `iphone`,
`t-shirt`, `yo-yo`); the generator removes the hyphen so every word is plain letters (`dropdown`, …). `skype`), names (`monday`, `december`), coinages (`pranker`, `finlike`) and four hyphenated words
`yoyo` is already in the list, so `yo-yo` becomes `yoyos` instead. All 7,776 words stay distinct (tested), (`felt-tip`, …); a word stays only if the standard US spellchecker dictionary knows it. 454 words go,
so each word is still worth log2(7,776) bits. 7,322 stay (tested, with examples), so each word is worth log2(7,322) = 12.838 bits instead of 12.925.
- To rebuild `memorable.txt`, download the URL above and run `python derive_memorable.py <file>`.
- The nickname lists are not secret material: a nickname is a name, not a password. They are kept short, - The nickname lists are not secret material: a nickname is a name, not a password. They are kept short,
friendly and unique (tested), and each word has at least three letters. friendly and unique (tested), and each word has at least three letters.
## ESDB (SCOWL) notice
Copyright 2000-2026 by Kevin Atkinson
Permission to use, copy, modify, distribute, and sell any part of the English
Speller Database (ESDB, previously known as SCOWLv2), or word lists
created from it, is hereby granted without fee, provided that the above
copyright notice appears in all copies and that both the above copyright
notice and this notice appear in supporting documentation. Kevin Atkinson
makes no representations about the suitability of this database for any
purpose. It is provided "as is" without express or implied warranty.
@@ -0,0 +1,24 @@
"""Rebuilds memorable.txt: the EFF large wordlist minus every word that the standard US English
spellchecker dictionary (SCOWL/ESDB size 60, the size of hunspell's en_US) does not list as a plain
lowercase word. That removes brand names (walmart), names and capitalised words (monday) and coinages
(pranker). See SOURCES.md for the exact download.
python derive_memorable.py <scowl-size-60.txt>
"""
import sys
from pathlib import Path
here = Path(__file__).parent
scowl = Path(sys.argv[1]).read_text(encoding="utf-8")
dictionary = set(scowl.split("---", 1)[1].split())
eff = [line.split("\t")[1].strip() for line in (here / "eff_large_wordlist.txt").read_text().splitlines()]
kept = [w for w in eff if w in dictionary]
header = """\
# Memorable-password words: the EFF large wordlist (CC BY 3.0 US, (c) Electronic Frontier Foundation)
# minus the words not in SCOWL/ESDB size 60 (US). Word list (c) 2000-2026 by Kevin Atkinson, see SOURCES.md.
# Generated by derive_memorable.py; do not edit by hand.
"""
(here / "memorable.txt").write_text(header + "\n".join(kept) + "\n", encoding="utf-8", newline="\n")
print(f"kept {len(kept)} of {len(eff)}")
File diff suppressed because it is too large Load Diff
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "custos-keys"
description = "Custos key pairs: Ed25519, ECDSA P-256 and RSA, as OpenSSH and PKCS#8 PEM (docs/KEYS.md)"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-vault = { path = "../custos-vault" }
thiserror.workspace = true
# RustCrypto's SSH key formats and the key types they build on (rand_core 0.6 generation API).
ssh-key = { version = "0.6", default-features = false, features = ["std", "ed25519", "p256", "rsa", "rand_core"] }
ed25519-dalek = { version = "2", features = ["pkcs8", "pem", "rand_core"] }
p256 = { version = "0.13", features = ["ecdsa", "pkcs8", "pem"] }
rsa = { version = "0.9", features = ["pem"] }
rand_core = { version = "0.6", features = ["getrandom"] }
+223
View File
@@ -0,0 +1,223 @@
//! Key pairs for the `key-pair` item type (docs/KEYS.md): Ed25519, ECDSA P-256 and RSA, written as an
//! OpenSSH public line, SPKI PEM, PKCS#8 PEM and an OpenSSH private key. RustCrypto crates only; the
//! randomness is the OS CSPRNG (`rand_core::OsRng`).
use custos_vault::SecretString;
use ed25519_dalek::pkcs8::spki::der::pem::LineEnding;
use rand_core::OsRng;
use ssh_key::private::{EcdsaKeypair, Ed25519Keypair, KeypairData, RsaKeypair};
use ssh_key::{HashAlg, PrivateKey};
#[derive(Debug, thiserror::Error)]
pub enum KeyError {
#[error("the key could not be generated or encoded")]
Encode,
#[error("not a valid key of this algorithm")]
Invalid,
#[error("the key is protected with a passphrase; remove it or import the key in the Custos app")]
Encrypted,
#[error("not a private key Custos can import (Ed25519, ECDSA P-256 or RSA 2048-4096 bits)")]
Unsupported,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Algorithm {
Ed25519,
EcdsaP256,
Rsa3072,
Rsa4096,
}
impl Algorithm {
pub const ALL: [Algorithm; 4] = [Algorithm::Ed25519, Algorithm::EcdsaP256, Algorithm::Rsa3072, Algorithm::Rsa4096];
/// The value of the item's `algorithm` field.
pub fn name(self) -> &'static str {
match self {
Algorithm::Ed25519 => "ed25519",
Algorithm::EcdsaP256 => "ecdsa-p256",
Algorithm::Rsa3072 => "rsa-3072",
Algorithm::Rsa4096 => "rsa-4096",
}
}
pub fn from_name(s: &str) -> Option<Self> {
Algorithm::ALL.into_iter().find(|a| a.name() == s)
}
}
/// A generated key pair, ready to become a `key-pair` item. `Debug` never shows the private parts.
#[derive(Clone, Debug)]
pub struct KeyPair {
pub algorithm: String,
/// `ssh-ed25519 AAAA… comment`.
pub public_openssh: String,
/// SubjectPublicKeyInfo PEM.
pub public_pem: String,
/// PKCS#8 PEM, unencrypted (the vault is its encryption).
pub private_pem: SecretString,
/// OpenSSH private key, unencrypted.
pub private_openssh: SecretString,
/// `SHA256:…`, as `ssh-keygen -l` prints it.
pub fingerprint: String,
}
fn enc<T, E>(r: Result<T, E>) -> Result<T, KeyError> {
r.map_err(|_| KeyError::Encode)
}
/// A new key pair. RSA takes a few seconds (prime generation).
pub fn generate(alg: Algorithm, comment: &str) -> Result<KeyPair, KeyError> {
match alg {
Algorithm::Ed25519 => from_ed25519(ed25519_dalek::SigningKey::generate(&mut OsRng), comment),
Algorithm::EcdsaP256 => from_p256(p256::SecretKey::random(&mut OsRng), comment),
Algorithm::Rsa3072 | Algorithm::Rsa4096 => {
let bits = if alg == Algorithm::Rsa3072 { 3072 } else { 4096 };
from_rsa(enc(rsa::RsaPrivateKey::new(&mut OsRng, bits))?, comment)
}
}
}
/// An existing private key as a key pair (docs/KEYS.md, "Importing"): an OpenSSH private key, PKCS#8
/// (`BEGIN PRIVATE KEY`), PKCS#1 (`BEGIN RSA PRIVATE KEY`) or SEC1 (`BEGIN EC PRIVATE KEY`), unencrypted.
/// The public parts and the fingerprint are derived from the private key, never taken from the input.
/// An OpenSSH key keeps its own comment unless it has none.
pub fn import(text: &str, comment: &str) -> Result<KeyPair, KeyError> {
// Pasted or read from a Windows file: CRLF line ends.
let text = text.replace("
", "
");
let text = text.trim();
let has = |label: &str| text.contains(&format!("-----BEGIN {label}-----"));
if has("ENCRYPTED PRIVATE KEY") || text.contains("Proc-Type: 4,ENCRYPTED") {
return Err(KeyError::Encrypted);
}
if has("OPENSSH PRIVATE KEY") {
let key = PrivateKey::from_openssh(text).map_err(|_| KeyError::Invalid)?;
if key.is_encrypted() {
return Err(KeyError::Encrypted);
}
let comment = if key.comment().is_empty() { comment.to_owned() } else { key.comment().to_owned() };
return match key.key_data() {
KeypairData::Ed25519(k) => from_ed25519(ed25519_dalek::SigningKey::from_bytes(&k.private.to_bytes()), &comment),
KeypairData::Ecdsa(EcdsaKeypair::NistP256 { private, .. }) => {
from_p256(p256::SecretKey::from_slice(private.as_slice()).map_err(|_| KeyError::Invalid)?, &comment)
}
KeypairData::Rsa(k) => from_rsa(rsa_from_openssh(k)?, &comment),
KeypairData::Encrypted(_) => Err(KeyError::Encrypted),
_ => Err(KeyError::Unsupported),
};
}
if has("PRIVATE KEY") {
use ed25519_dalek::pkcs8::DecodePrivateKey;
if let Ok(sk) = ed25519_dalek::SigningKey::from_pkcs8_pem(text) {
return from_ed25519(sk, comment);
}
if let Ok(sk) = p256::SecretKey::from_pkcs8_pem(text) {
return from_p256(sk, comment);
}
if let Ok(sk) = rsa::RsaPrivateKey::from_pkcs8_pem(text) {
return from_rsa(sk, comment);
}
return Err(KeyError::Unsupported);
}
if has("RSA PRIVATE KEY") {
use rsa::pkcs1::DecodeRsaPrivateKey;
return from_rsa(rsa::RsaPrivateKey::from_pkcs1_pem(text).map_err(|_| KeyError::Invalid)?, comment);
}
if has("EC PRIVATE KEY") {
return from_p256(p256::SecretKey::from_sec1_pem(text).map_err(|_| KeyError::Unsupported)?, comment);
}
Err(KeyError::Unsupported)
}
/// ssh-key 0.6.7's own `TryFrom<&RsaKeypair>` passes `p` twice instead of `p` and `q`, so the key is
/// rebuilt from its components here.
fn rsa_from_openssh(k: &RsaKeypair) -> Result<rsa::RsaPrivateKey, KeyError> {
let n = |m: &ssh_key::Mpint| rsa::BigUint::try_from(m).map_err(|_| KeyError::Invalid);
let sk = rsa::RsaPrivateKey::from_components(n(&k.public.n)?, n(&k.public.e)?, n(&k.private.d)?, vec![n(&k.private.p)?, n(&k.private.q)?])
.map_err(|_| KeyError::Invalid)?;
sk.validate().map_err(|_| KeyError::Invalid)?;
Ok(sk)
}
fn from_ed25519(sk: ed25519_dalek::SigningKey, comment: &str) -> Result<KeyPair, KeyError> {
use ed25519_dalek::pkcs8::{EncodePrivateKey, EncodePublicKey};
let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string();
let public_pem = enc(sk.verifying_key().to_public_key_pem(LineEnding::LF))?;
assemble("ed25519", KeypairData::Ed25519(Ed25519Keypair::from(&sk)), private_pem, public_pem, comment)
}
fn from_p256(sk: p256::SecretKey, comment: &str) -> Result<KeyPair, KeyError> {
use p256::pkcs8::{EncodePrivateKey, EncodePublicKey};
let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string();
let public_pem = enc(sk.public_key().to_public_key_pem(LineEnding::LF))?;
let public = sk.public_key();
let data = KeypairData::Ecdsa(EcdsaKeypair::NistP256 { private: sk.into(), public: public.into() });
assemble("ecdsa-p256", data, private_pem, public_pem, comment)
}
fn from_rsa(sk: rsa::RsaPrivateKey, comment: &str) -> Result<KeyPair, KeyError> {
use rsa::pkcs8::{EncodePrivateKey, EncodePublicKey};
use rsa::traits::PublicKeyParts;
let bits = sk.size() * 8;
if !(2048..=4096).contains(&bits) {
return Err(KeyError::Unsupported);
}
let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string();
let public_pem = enc(sk.to_public_key().to_public_key_pem(LineEnding::LF))?;
assemble(&format!("rsa-{bits}"), KeypairData::Rsa(enc(RsaKeypair::try_from(sk))?), private_pem, public_pem, comment)
}
fn assemble(algorithm: &str, data: KeypairData, private_pem: String, public_pem: String, comment: &str) -> Result<KeyPair, KeyError> {
let private = enc(PrivateKey::new(data, comment))?;
let public = private.public_key();
Ok(KeyPair {
algorithm: algorithm.into(),
public_openssh: enc(public.to_openssh())?,
public_pem,
private_pem: SecretString::new(private_pem),
private_openssh: SecretString::new(enc(private.to_openssh(ssh_key::LineEnding::LF))?.to_string()),
fingerprint: public.fingerprint(HashAlg::Sha256).to_string(),
})
}
/// Whether a PKCS#8 private key and an SPKI public key belong together (tests, and a check before
/// importing a key pair someone pasted).
pub fn pem_matches(alg: Algorithm, private_pem: &str, public_pem: &str) -> Result<bool, KeyError> {
let derived = match alg {
Algorithm::Ed25519 => {
use ed25519_dalek::pkcs8::{DecodePrivateKey, EncodePublicKey};
let sk = ed25519_dalek::SigningKey::from_pkcs8_pem(private_pem).map_err(|_| KeyError::Invalid)?;
enc(sk.verifying_key().to_public_key_pem(LineEnding::LF))?
}
Algorithm::EcdsaP256 => {
use p256::pkcs8::{DecodePrivateKey, EncodePublicKey};
let sk = p256::SecretKey::from_pkcs8_pem(private_pem).map_err(|_| KeyError::Invalid)?;
enc(sk.public_key().to_public_key_pem(LineEnding::LF))?
}
Algorithm::Rsa3072 | Algorithm::Rsa4096 => {
use rsa::pkcs8::{DecodePrivateKey, EncodePublicKey};
let sk = rsa::RsaPrivateKey::from_pkcs8_pem(private_pem).map_err(|_| KeyError::Invalid)?;
enc(sk.to_public_key().to_public_key_pem(LineEnding::LF))?
}
};
Ok(derived.trim() == public_pem.trim())
}
/// An Ed25519 signature (64 bytes) of `message` with a PKCS#8 private key.
pub fn sign_ed25519(private_pem: &str, message: &[u8]) -> Result<Vec<u8>, KeyError> {
use ed25519_dalek::Signer;
use ed25519_dalek::pkcs8::DecodePrivateKey;
let sk = ed25519_dalek::SigningKey::from_pkcs8_pem(private_pem).map_err(|_| KeyError::Invalid)?;
Ok(sk.sign(message).to_bytes().to_vec())
}
/// Whether `signature` is a valid Ed25519 signature of `message` under an SPKI public key.
pub fn verify_ed25519(public_pem: &str, message: &[u8], signature: &[u8]) -> Result<bool, KeyError> {
use ed25519_dalek::Verifier;
use ed25519_dalek::pkcs8::DecodePublicKey;
let vk = ed25519_dalek::VerifyingKey::from_public_key_pem(public_pem).map_err(|_| KeyError::Invalid)?;
let sig = ed25519_dalek::Signature::from_slice(signature).map_err(|_| KeyError::Invalid)?;
Ok(vk.verify(message, &sig).is_ok())
}
+7
View File
@@ -0,0 +1,7 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACDt2TW39UZy8qwtg1TjmyyP6tQyICmROg6Ed8wT8LfNMAAAAJDgLH6c4Cx+
nAAAAAtzc2gtZWQyNTUxOQAAACDt2TW39UZy8qwtg1TjmyyP6tQyICmROg6Ed8wT8LfNMA
AAAEBnrsV5Mk4SOUMLEChNqaRAd2+aSJlQup0lVfIDpgs0ZO3ZNbf1RnLyrC2DVOObLI/q
1DIgKZE6DoR3zBPwt80wAAAADGZpeHR1cmVAdGVzdAE=
-----END OPENSSH PRIVATE KEY-----
@@ -0,0 +1,8 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABD6DWv11a
60wSTEmglCO465AAAAGAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAILvNKbmysLcBtsSO
rLTfznA6I1TNJa6UryfZvKCK8m8SAAAAkFMVbzEv6H/wWf5oYKy2l9wRAZzrvy2mqkyLRm
DyIuKemJsVxFao1sL84IpcMC809PUX4qHLT5qFb/wOcv3fJKsFluHJS3c26CAqe6pbgP6W
pXPKKKedbzrcRxfgVORw36fBNJdMQbFAUsYq2ytId0vHb8JYHCzjO3vSYPAaG+kfwrfRxn
7wvt5tz4/9N14Wag==
-----END OPENSSH PRIVATE KEY-----
+111
View File
@@ -0,0 +1,111 @@
//! Mandatory tests for key pairs (docs/KEYS.md): every format parses back to the same key, the
//! fingerprint is ssh-keygen's, Ed25519 signs and verifies, nothing private prints.
use custos_keys::{Algorithm, generate};
#[test]
fn every_algorithm_round_trips_through_every_format() {
for alg in [Algorithm::Ed25519, Algorithm::EcdsaP256, Algorithm::Rsa3072] {
let k = generate(alg, "deploy@home").unwrap();
assert_eq!(k.algorithm, alg.name());
// The OpenSSH private key parses back and carries the same public key and comment.
let private = ssh_key::PrivateKey::from_openssh(k.private_openssh.expose()).unwrap();
assert_eq!(private.public_key().to_openssh().unwrap(), k.public_openssh);
assert_eq!(private.comment(), "deploy@home");
assert!(k.public_openssh.ends_with(" deploy@home"));
// The fingerprint is the one ssh-keygen -l prints.
assert_eq!(private.public_key().fingerprint(ssh_key::HashAlg::Sha256).to_string(), k.fingerprint);
assert!(k.fingerprint.starts_with("SHA256:"));
// PKCS#8 and SPKI PEM have the right headers and parse back to the same public key.
assert!(k.private_pem.expose().starts_with("-----BEGIN PRIVATE KEY-----"));
assert!(k.public_pem.starts_with("-----BEGIN PUBLIC KEY-----"));
assert!(custos_keys::pem_matches(alg, k.private_pem.expose(), &k.public_pem).unwrap(), "{alg:?}");
}
}
#[test]
fn ed25519_signs_and_verifies() {
let k = generate(Algorithm::Ed25519, "").unwrap();
let sig = custos_keys::sign_ed25519(k.private_pem.expose(), b"release 1.0").unwrap();
assert!(custos_keys::verify_ed25519(&k.public_pem, b"release 1.0", &sig).unwrap());
assert!(!custos_keys::verify_ed25519(&k.public_pem, b"release 1.1", &sig).unwrap());
}
#[test]
fn keys_are_unique_and_nothing_private_prints() {
let a = generate(Algorithm::Ed25519, "a").unwrap();
let b = generate(Algorithm::Ed25519, "a").unwrap();
assert_ne!(a.public_openssh, b.public_openssh);
let printed = format!("{a:?}");
assert!(!printed.contains("PRIVATE"), "{printed}");
assert!(!printed.contains(a.private_openssh.expose().lines().nth(1).unwrap()), "{printed}");
}
#[test]
fn algorithm_names_parse() {
for alg in Algorithm::ALL {
assert_eq!(Algorithm::from_name(alg.name()), Some(alg));
}
assert_eq!(Algorithm::from_name("dsa"), None);
}
// ---- importing (docs/KEYS.md, "Importing") ----
/// A throwaway key made by `ssh-keygen -t ed25519 -C fixture@test` for these tests only.
const SSH_KEYGEN_ED25519: &str = include_str!("fixtures/ssh-keygen-ed25519");
/// The same kind of key with the passphrase `fixture-pass`.
const SSH_KEYGEN_ENCRYPTED: &str = include_str!("fixtures/ssh-keygen-ed25519-passphrase");
#[test]
fn an_ssh_keygen_key_imports_with_its_own_fingerprint_and_comment() {
let k = custos_keys::import(SSH_KEYGEN_ED25519, "fallback").unwrap();
assert_eq!(k.algorithm, "ed25519");
// What `ssh-keygen -l -f` printed for the fixture.
assert_eq!(k.fingerprint, "SHA256:IGwHpAF8aVpXvaBckNayqTMlHUvRgN9+w1uS7iyLPGE");
assert!(k.public_openssh.ends_with(" fixture@test"));
assert!(custos_keys::pem_matches(Algorithm::Ed25519, k.private_pem.expose(), &k.public_pem).unwrap());
}
#[test]
fn every_private_key_format_imports_to_the_same_key() {
use p256::pkcs8::DecodePrivateKey as _;
use rsa::pkcs1::EncodeRsaPrivateKey;
for alg in [Algorithm::Ed25519, Algorithm::EcdsaP256, Algorithm::Rsa3072] {
let k = generate(alg, "deploy").unwrap();
let mut inputs = vec![k.private_openssh.expose().to_owned(), k.private_pem.expose().to_owned()];
match alg {
Algorithm::EcdsaP256 => {
let sk = p256::SecretKey::from_pkcs8_pem(k.private_pem.expose()).unwrap();
inputs.push(sk.to_sec1_pem(p256::pkcs8::LineEnding::LF).unwrap().to_string());
}
Algorithm::Rsa3072 => {
let sk = rsa::RsaPrivateKey::from_pkcs8_pem(k.private_pem.expose()).unwrap();
inputs.push(sk.to_pkcs1_pem(rsa::pkcs8::LineEnding::LF).unwrap().to_string());
}
_ => {}
}
for text in inputs {
// Surrounding whitespace (a paste, a file with CRLF line ends) does not matter.
let pasted = format!("\r\n {}\r\n", text.replace('\n', "\r\n"));
let i = custos_keys::import(&pasted, "deploy").unwrap_or_else(|e| panic!("{alg:?} {}: {e:?}", text.lines().next().unwrap()));
assert_eq!((i.algorithm.as_str(), i.fingerprint.as_str()), (alg.name(), k.fingerprint.as_str()), "{alg:?}");
assert_eq!(i.public_pem, k.public_pem);
}
}
}
#[test]
fn protected_and_unknown_keys_are_refused() {
use custos_keys::KeyError;
assert!(matches!(custos_keys::import(SSH_KEYGEN_ENCRYPTED, "x"), Err(KeyError::Encrypted)));
let pkcs8_encrypted = "-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIB\n-----END ENCRYPTED PRIVATE KEY-----";
assert!(matches!(custos_keys::import(pkcs8_encrypted, "x"), Err(KeyError::Encrypted)));
let pkcs1_encrypted = "-----BEGIN RSA PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,00\n\nAAAA\n-----END RSA PRIVATE KEY-----";
assert!(matches!(custos_keys::import(pkcs1_encrypted, "x"), Err(KeyError::Encrypted)));
// A public key, a password, garbage: nothing to import, and the error never repeats the input.
let public = generate(Algorithm::Ed25519, "p").unwrap().public_openssh;
for text in [public.as_str(), "hunter2-not-a-key", "-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----"] {
let e = custos_keys::import(text, "x").unwrap_err();
assert!(!e.to_string().contains("hunter2") && !e.to_string().contains("AAAA"), "{e}");
}
}
+9
View File
@@ -0,0 +1,9 @@
[package]
name = "custos-qr"
description = "Custos QR payloads: Wi-Fi join codes and plain secrets (payload strings only, no rendering)"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
+58
View File
@@ -0,0 +1,58 @@
//! QR payload strings. Rendering happens in the app; this crate only decides what the code says.
/// Security of a Wi-Fi network as the `WIFI:` payload names it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WifiSecurity {
/// WPA, WPA2 or WPA3 (`T:WPA`).
Wpa,
Wep,
/// Open network (`T:nopass`).
None,
}
impl WifiSecurity {
/// From the vault's `security` field (`WPA`, `WEP`, `nopass`); anything else counts as WPA.
pub fn parse(s: &str) -> WifiSecurity {
match s.trim().to_ascii_uppercase().as_str() {
"WEP" => WifiSecurity::Wep,
"NOPASS" | "NONE" | "OPEN" => WifiSecurity::None,
_ => WifiSecurity::Wpa,
}
}
fn token(self) -> &'static str {
match self {
WifiSecurity::Wpa => "WPA",
WifiSecurity::Wep => "WEP",
WifiSecurity::None => "nopass",
}
}
}
/// Escapes `\`, `;`, `,`, `:` and `"` with a backslash, as the `WIFI:` format requires.
pub fn escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if matches!(c, '\\' | ';' | ',' | ':' | '"') {
out.push('\\');
}
out.push(c);
}
out
}
/// `WIFI:T:<WPA|WEP|nopass>;S:<ssid>;P:<password>;H:<true|false>;;` — a phone camera joins from it.
/// An open network gets no `P:` field.
pub fn wifi_payload(ssid: &str, password: &str, security: WifiSecurity, hidden: bool) -> String {
let mut p = format!("WIFI:T:{};S:{};", security.token(), escape(ssid));
if security != WifiSecurity::None {
p.push_str(&format!("P:{};", escape(password)));
}
p.push_str(&format!("H:{hidden};;"));
p
}
/// A QR code that shows a secret to a phone camera is the plain value, so it can be typed elsewhere.
pub fn secret_payload(value: &str) -> String {
value.to_owned()
}
+72
View File
@@ -0,0 +1,72 @@
//! Wi-Fi QR payloads: every special character escaped, so a phone reads back exactly what was stored.
use custos_qr::{WifiSecurity, escape, secret_payload, wifi_payload};
/// What a reader does: split on unescaped `;`, undo `\x` escapes.
fn parse(payload: &str) -> Vec<(String, String)> {
let body = payload.strip_prefix("WIFI:").expect("prefix").strip_suffix(";;").expect("suffix");
let mut fields = Vec::new();
let mut cur = String::new();
let mut chars = body.chars();
while let Some(c) = chars.next() {
match c {
'\\' => cur.push(chars.next().expect("escape at end")),
';' => fields.push(std::mem::take(&mut cur)),
c => cur.push(c),
}
}
fields.push(cur);
fields
.into_iter()
.map(|f| {
let (k, v) = f.split_once(':').expect("key:value");
(k.to_owned(), v.to_owned())
})
.collect()
}
#[test]
fn escapes_every_special_character() {
assert_eq!(escape(r#"\;,:""#), r#"\\\;\,\:\""#);
assert_eq!(escape("plain-text_123 ok"), "plain-text_123 ok");
}
#[test]
fn ssid_and_password_with_every_special_character_survive() {
let nasty = r#"My\Net;5G,"home":x"#;
let pass = r#"p\a;s,s:w"o"r;d\"#;
let p = wifi_payload(nasty, pass, WifiSecurity::Wpa, true);
assert_eq!(p, r#"WIFI:T:WPA;S:My\\Net\;5G\,\"home\"\:x;P:p\\a\;s\,s\:w\"o\"r\;d\\;H:true;;"#);
let f = parse(&p);
assert_eq!(
f,
vec![
("T".into(), "WPA".into()),
("S".into(), nasty.into()),
("P".into(), pass.into()),
("H".into(), "true".into()),
]
);
}
#[test]
fn security_kinds_and_hidden_flag() {
assert_eq!(wifi_payload("Cafe", "secret", WifiSecurity::Wep, false), "WIFI:T:WEP;S:Cafe;P:secret;H:false;;");
// An open network has no password field.
assert_eq!(wifi_payload("Open", "ignored", WifiSecurity::None, false), "WIFI:T:nopass;S:Open;H:false;;");
assert_eq!(WifiSecurity::parse("WPA"), WifiSecurity::Wpa);
assert_eq!(WifiSecurity::parse("nopass"), WifiSecurity::None);
assert_eq!(WifiSecurity::parse("WEP"), WifiSecurity::Wep);
assert_eq!(WifiSecurity::parse("anything else"), WifiSecurity::Wpa);
}
#[test]
fn unicode_ssid_is_kept() {
let p = wifi_payload("Žluťoučký kůň 📶", "heslo", WifiSecurity::Wpa, false);
assert_eq!(parse(&p)[1].1, "Žluťoučký kůň 📶");
}
#[test]
fn secret_payload_is_the_value_itself() {
assert_eq!(secret_payload("sk-test;with:specials"), "sk-test;with:specials");
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "custos-seal"
description = "Custos sealed boxes: a secret encrypted to one device's X25519 key, and at-rest sealing for the factor service (docs/SEAL.md)"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
x25519-dalek = { version = "2", features = ["static_secrets", "zeroize"] }
chacha20poly1305.workspace = true
hkdf.workspace = true
sha2.workspace = true
rand.workspace = true
zeroize.workspace = true
thiserror.workspace = true
+180
View File
@@ -0,0 +1,180 @@
//! Sealed boxes (docs/SEAL.md). A device that wants a secret makes a one-time X25519 key pair and sends
//! only its public key; whoever releases the secret seals it to that key, so the mailbox in between (the
//! factor service on the home server) carries ciphertext it cannot open. Also the factor service's
//! at-rest sealing of the TOTP shares it keeps.
//!
//! ```text
//! sealed = "CSL1" ‖ ephemeral public (32) ‖ nonce (24) ‖ XChaCha20-Poly1305(key, nonce, plaintext, aad)
//! key = HKDF-SHA256(X25519(ephemeral, recipient), salt = ephemeral pub ‖ recipient pub,
//! info = "custos seal v1" ‖ context)
//! aad = "CSL1" ‖ ephemeral public ‖ context
//!
//! at rest = "CSR1" ‖ nonce (24) ‖ XChaCha20-Poly1305(HKDF(key, "", "custos rest v1" ‖ context), nonce,
//! plaintext, "CSR1" ‖ context)
//! ```
//!
//! `context` binds a box to its purpose (e.g. `approval:<factor id>:<request id>`): a box sealed for one
//! request does not open as another.
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use rand::Rng;
use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use sha2::{Digest, Sha256};
use x25519_dalek::{PublicKey, StaticSecret};
use zeroize::Zeroizing;
const MAGIC: &[u8; 4] = b"CSL1";
const REST: &[u8; 4] = b"CSR1";
const NONCE: usize = 24;
const TAG: usize = 16;
/// The largest plaintext a box carries (a key pair's private key fits many times over).
pub const MAX_PLAINTEXT: usize = 32 * 1024;
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum SealError {
#[error("not a sealed box, or it was changed")]
Malformed,
#[error("this box was not sealed for this key and purpose")]
Rejected,
#[error("not a valid public key")]
BadKey,
#[error("the secret is too large to seal")]
TooLarge,
}
fn random<const N: usize>() -> Zeroizing<[u8; N]> {
let mut b = Zeroizing::new([0u8; N]);
UnwrapErr(SysRng).fill_bytes(b.as_mut());
b
}
fn derive(ikm: &[u8], salt: &[u8], info: &[&[u8]]) -> Zeroizing<[u8; 32]> {
let mut k = Zeroizing::new([0u8; 32]);
hkdf::Hkdf::<Sha256>::new(Some(salt), ikm).expand(&info.concat(), k.as_mut()).expect("32 bytes is a valid HKDF length");
k
}
fn cipher(key: &[u8; 32]) -> XChaCha20Poly1305 {
XChaCha20Poly1305::new_from_slice(key).expect("32-byte key")
}
fn xnonce(n: &[u8]) -> XNonce {
XNonce::try_from(n).expect("24-byte nonce")
}
/// The one-time key pair of a device waiting for a secret. Its secret half never leaves memory and is
/// wiped on drop.
pub struct Recipient {
secret: StaticSecret,
public: [u8; 32],
}
impl Recipient {
pub fn generate() -> Recipient {
let secret = StaticSecret::from(*random::<32>());
let public = PublicKey::from(&secret).to_bytes();
Recipient { secret, public }
}
/// What the device sends: 32 bytes.
pub fn public(&self) -> [u8; 32] {
self.public
}
/// The six digits both screens show, so the person approving sees it is this request.
pub fn match_code(&self) -> String {
match_code(&self.public)
}
/// Opens a box sealed to this key for `context`.
pub fn open(&self, sealed: &[u8], context: &[u8]) -> Result<Zeroizing<Vec<u8>>, SealError> {
if sealed.len() < 4 + 32 + NONCE + TAG || &sealed[..4] != MAGIC {
return Err(SealError::Malformed);
}
let eph: [u8; 32] = sealed[4..36].try_into().expect("32 bytes");
let shared = self.secret.diffie_hellman(&PublicKey::from(eph));
if !shared.was_contributory() {
return Err(SealError::Rejected);
}
let key = derive(shared.as_bytes(), &[eph.as_slice(), &self.public].concat(), &[b"custos seal v1", context]);
let aad = [MAGIC.as_slice(), &eph, context].concat();
cipher(&key)
.decrypt(&xnonce(&sealed[36..36 + NONCE]), Payload { msg: &sealed[36 + NONCE..], aad: &aad })
.map(Zeroizing::new)
.map_err(|_| SealError::Rejected)
}
}
impl std::fmt::Debug for Recipient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Recipient {{ match_code: {} }}", self.match_code())
}
}
/// Seals `plaintext` to a recipient's public key for `context`. Only that recipient opens it.
pub fn seal(recipient: &[u8], context: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, SealError> {
let recipient: [u8; 32] = recipient.try_into().map_err(|_| SealError::BadKey)?;
if plaintext.len() > MAX_PLAINTEXT {
return Err(SealError::TooLarge);
}
let eph = StaticSecret::from(*random::<32>());
let eph_pub = PublicKey::from(&eph).to_bytes();
let shared = eph.diffie_hellman(&PublicKey::from(recipient));
// A low-order "public key" would give a shared secret anyone knows.
if !shared.was_contributory() {
return Err(SealError::BadKey);
}
let key = derive(shared.as_bytes(), &[eph_pub.as_slice(), &recipient].concat(), &[b"custos seal v1", context]);
let nonce = random::<NONCE>();
let aad = [MAGIC.as_slice(), &eph_pub, context].concat();
let ct = cipher(&key)
.encrypt(&xnonce(nonce.as_ref()), Payload { msg: plaintext, aad: &aad })
.expect("encryption cannot fail for in-memory buffers");
Ok([MAGIC.as_slice(), &eph_pub, nonce.as_ref(), &ct].concat())
}
/// Six digits from a public key: what the requesting screen and the approving screen both show.
pub fn match_code(public: &[u8]) -> String {
let h = Sha256::new().chain_update(b"custos match v1").chain_update(public).finalize();
let n = u32::from_be_bytes([h[0], h[1], h[2], h[3]]) % 1_000_000;
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]);
let nonce = random::<NONCE>();
let aad = [REST.as_slice(), context].concat();
let ct = cipher(&k)
.encrypt(&xnonce(nonce.as_ref()), Payload { msg: plaintext, aad: &aad })
.expect("encryption cannot fail for in-memory buffers");
[REST.as_slice(), nonce.as_ref(), &ct].concat()
}
pub fn open_at_rest(key: &[u8; 32], context: &[u8], sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>, SealError> {
if sealed.len() < 4 + NONCE + TAG || &sealed[..4] != REST {
return Err(SealError::Malformed);
}
let k = derive(key, b"", &[b"custos rest v1", context]);
let aad = [REST.as_slice(), context].concat();
cipher(&k)
.decrypt(&xnonce(&sealed[4..4 + NONCE]), Payload { msg: &sealed[4 + NONCE..], aad: &aad })
.map(Zeroizing::new)
.map_err(|_| SealError::Rejected)
}
/// 32 random bytes from the OS (factor material, tokens).
pub fn random_bytes() -> Zeroizing<[u8; 32]> {
random()
}
+74
View File
@@ -0,0 +1,74 @@
//! Mandatory tests for sealed boxes (docs/SEAL.md).
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() {
let r = Recipient::generate();
let other = Recipient::generate();
let b = seal(&r.public(), b"approval:f1:r1", b"factor material").unwrap();
assert_eq!(r.open(&b, b"approval:f1:r1").unwrap().as_slice(), b"factor material");
assert_eq!(other.open(&b, b"approval:f1:r1"), Err(SealError::Rejected));
// The same box for another request or factor does not open.
assert_eq!(r.open(&b, b"approval:f1:r2"), Err(SealError::Rejected));
// Two seals of the same secret differ (fresh ephemeral key and nonce).
assert_ne!(b, seal(&r.public(), b"approval:f1:r1", b"factor material").unwrap());
assert!(!b.windows(15).any(|w| w == b"factor material"));
}
#[test]
fn every_changed_byte_is_refused() {
let r = Recipient::generate();
let b = seal(&r.public(), b"c", b"secret").unwrap();
for i in 0..b.len() {
let mut bad = b.clone();
bad[i] ^= 1;
assert!(r.open(&bad, b"c").is_err(), "byte {i}");
}
assert_eq!(r.open(&b[..b.len() - 1], b"c"), Err(SealError::Rejected));
assert_eq!(r.open(&b[..20], b"c"), Err(SealError::Malformed));
}
#[test]
fn bad_public_keys_are_refused() {
assert_eq!(seal(&[1u8; 31], b"c", b"s"), Err(SealError::BadKey));
// The all-zero point (low order) would give a shared secret everyone knows.
assert_eq!(seal(&[0u8; 32], b"c", b"s"), Err(SealError::BadKey));
assert_eq!(seal(&Recipient::generate().public(), b"c", &vec![0u8; 40_000]), Err(SealError::TooLarge));
}
#[test]
fn the_match_code_is_six_digits_and_follows_the_key() {
let r = Recipient::generate();
assert_eq!(r.match_code(), match_code(&r.public()));
assert_eq!(r.match_code().len(), 6);
assert!(r.match_code().bytes().all(|b| b.is_ascii_digit()));
// A known vector, so every implementation (the web app's wasm too) shows the same digits.
assert_eq!(match_code(&[7u8; 32]), KNOWN_MATCH_CODE);
let codes: std::collections::HashSet<String> = (0..50).map(|_| Recipient::generate().match_code()).collect();
assert!(codes.len() > 45);
assert!(!format!("{r:?}").contains(&format!("{:?}", r.public())));
}
/// 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];
let b = seal_at_rest(&key, b"totp:f1", b"share");
assert_eq!(open_at_rest(&key, b"totp:f1", &b).unwrap().as_slice(), b"share");
assert_eq!(open_at_rest(&[8u8; 32], b"totp:f1", &b), Err(SealError::Rejected));
assert_eq!(open_at_rest(&key, b"totp:f2", &b), Err(SealError::Rejected));
assert_eq!(open_at_rest(&key, b"totp:f1", b"CSR1"), Err(SealError::Malformed));
}
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "custos-share"
description = "Custos private share links: the secret encrypted in the sender's app, the key in the link fragment"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-vault = { path = "../custos-vault" }
argon2.workspace = true
chacha20poly1305.workspace = true
hkdf.workspace = true
sha2.workspace = true
rand.workspace = true
zeroize.workspace = true
serde.workspace = true
serde_json.workspace = true
data-encoding.workspace = true
thiserror.workspace = true
+296
View File
@@ -0,0 +1,296 @@
//! Private share links (docs/SHARE.md): a secret encrypted in the sender's app with a random key that
//! travels only in the link's fragment, optionally combined with a password told separately. The share
//! server stores the blob and never sees a key.
use argon2::{Algorithm, Argon2, Params, Version};
use chacha20poly1305::aead::{Aead, KeyInit, Payload as AeadPayload};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use custos_vault::{Item, SecretString};
use data_encoding::BASE64URL_NOPAD;
use hkdf::Hkdf;
use rand::Rng;
use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::fmt;
use zeroize::{Zeroize, Zeroizing};
pub use custos_vault::Field;
const MAGIC: &[u8; 4] = b"CSH1";
const FLAG_PASSWORD: u8 = 0x01;
const KEY_LEN: usize = 32;
const SALT_LEN: usize = 16;
const NONCE_LEN: usize = 24;
const TAG_LEN: usize = 16;
const KDF_LEN: usize = 12;
const INFO: &[u8] = b"custos-share v1";
/// The largest blob a share may be (the server enforces the same limit).
pub const MAX_BLOB: usize = 64 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ShareError {
#[error("this is not a Custos share")]
Malformed,
#[error("the link is incomplete: the part after # is missing or damaged")]
BadLink,
#[error("this share needs a password")]
PasswordRequired,
#[error("the share's password settings are not supported")]
UnsupportedKdf,
#[error("wrong password, or the link or the share is damaged; nothing was decrypted")]
DecryptFailed,
#[error("the secret is too large to share (at most 64 KB)")]
TooLarge,
}
/// Argon2id parameters for a password share.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ShareKdf {
pub m_cost_kib: u32,
pub t_cost: u32,
pub p_cost: u32,
}
impl ShareKdf {
/// 19 MiB, 2 passes, 1 lane: OWASP's Argon2id minimum, about a second in a phone browser.
pub const DEFAULT: ShareKdf = ShareKdf { m_cost_kib: 19_456, t_cost: 2, p_cost: 1 };
fn check(&self) -> Result<(), ShareError> {
let ok = (8 * 1024..=256 * 1024).contains(&self.m_cost_kib)
&& (1..=16).contains(&self.t_cost)
&& (1..=4).contains(&self.p_cost);
if ok { Ok(()) } else { Err(ShareError::UnsupportedKdf) }
}
}
/// What a share carries: a title and the fields to show, with secret ones hidden until revealed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Payload {
pub title: String,
/// The item type (`web-login`, `wifi`, …), only for the recipient page's label.
pub kind: Option<String>,
pub fields: Vec<Field>,
pub notes: Option<SecretString>,
}
/// Fields never put into a share.
const NEVER_SHARED: [&str; 4] = ["totp", "autotype-match", "autotype-sequence", "domi-ref"];
impl Payload {
/// The item's non-empty fields and notes, without its TOTP seed (that would hand over the second
/// factor too) and its auto-type settings.
pub fn from_item(item: &Item) -> Payload {
let kind = serde_json::to_value(item.kind).ok().and_then(|v| v.as_str().map(str::to_owned));
Payload {
title: item.title.clone(),
kind,
fields: item
.fields
.iter()
.filter(|f| !f.value.is_empty() && !NEVER_SHARED.contains(&f.name.as_str()))
.cloned()
.collect(),
notes: (!item.notes.is_empty()).then(|| item.notes.clone()),
}
}
}
#[derive(Serialize)]
struct WireOut<'a> {
v: u32,
title: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
kind: Option<&'a str>,
fields: &'a [Field],
#[serde(skip_serializing_if = "Option::is_none")]
notes: Option<&'a SecretString>,
}
#[derive(Deserialize)]
struct WireIn {
v: u32,
title: String,
#[serde(default)]
kind: Option<String>,
#[serde(default)]
fields: Vec<Field>,
#[serde(default)]
notes: Option<SecretString>,
}
/// A sealed share: the blob to upload and the link fragment (`k=…` or `k=…&p=1`) to put after `#`.
pub struct Sealed {
pub blob: Vec<u8>,
pub fragment: String,
}
impl Sealed {
pub fn needs_password(&self) -> bool {
fragment_needs_password(&self.fragment)
}
/// `https://host/s/<id>#<fragment>`.
pub fn link(&self, base_url: &str, id: &str) -> String {
format!("{}/s/{id}#{}", base_url.trim_end_matches('/'), self.fragment)
}
}
impl fmt::Debug for Sealed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Sealed").field("blob_len", &self.blob.len()).field("fragment", &"[redacted]").finish()
}
}
impl Drop for Sealed {
fn drop(&mut self) {
self.fragment.zeroize();
}
}
/// Whether a link fragment says the recipient needs a password (only a hint for the page; the blob decides).
pub fn fragment_needs_password(fragment: &str) -> bool {
fragment.trim_start_matches('#').split('&').any(|p| p == "p=1")
}
fn rng() -> UnwrapErr<SysRng> {
UnwrapErr(SysRng)
}
fn link_key(fragment: &str) -> Result<Zeroizing<[u8; KEY_LEN]>, ShareError> {
let k =
fragment.trim_start_matches('#').split('&').find_map(|p| p.strip_prefix("k=")).ok_or(ShareError::BadLink)?;
let bytes = Zeroizing::new(BASE64URL_NOPAD.decode(k.as_bytes()).map_err(|_| ShareError::BadLink)?);
let mut key = Zeroizing::new([0u8; KEY_LEN]);
if bytes.len() != KEY_LEN {
return Err(ShareError::BadLink);
}
key.copy_from_slice(&bytes);
Ok(key)
}
fn message_key(
link: &[u8; KEY_LEN],
password: Option<(&SecretString, ShareKdf, &[u8])>,
) -> Result<Zeroizing<[u8; KEY_LEN]>, ShareError> {
let Some((pw, kdf, salt)) = password else {
return Ok(Zeroizing::new(*link));
};
kdf.check()?;
let params =
Params::new(kdf.m_cost_kib, kdf.t_cost, kdf.p_cost, Some(KEY_LEN)).map_err(|_| ShareError::UnsupportedKdf)?;
let mut ikm = Zeroizing::new([0u8; 2 * KEY_LEN]);
ikm[..KEY_LEN].copy_from_slice(link);
Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
.hash_password_into(pw.expose().as_bytes(), salt, &mut ikm[KEY_LEN..])
.map_err(|_| ShareError::UnsupportedKdf)?;
let mut key = Zeroizing::new([0u8; KEY_LEN]);
Hkdf::<Sha256>::new(Some(salt), ikm.as_ref()).expand(INFO, key.as_mut()).map_err(|_| ShareError::UnsupportedKdf)?;
Ok(key)
}
fn cipher(key: &[u8; KEY_LEN]) -> XChaCha20Poly1305 {
XChaCha20Poly1305::new_from_slice(key).expect("32-byte key")
}
/// Seals `payload` with a fresh link key and, if given, a password (default KDF).
pub fn seal(payload: &Payload, password: Option<&SecretString>) -> Result<Sealed, ShareError> {
seal_with_kdf(payload, password, ShareKdf::DEFAULT)
}
pub fn seal_with_kdf(payload: &Payload, password: Option<&SecretString>, kdf: ShareKdf) -> Result<Sealed, ShareError> {
let wire = WireOut {
v: 1,
title: &payload.title,
kind: payload.kind.as_deref(),
fields: &payload.fields,
notes: payload.notes.as_ref(),
};
let plaintext = Zeroizing::new(serde_json::to_vec(&wire).map_err(|_| ShareError::Malformed)?);
let overhead = 5 + KDF_LEN + SALT_LEN + NONCE_LEN + TAG_LEN;
if plaintext.len() + overhead > MAX_BLOB {
return Err(ShareError::TooLarge);
}
let mut link = Zeroizing::new([0u8; KEY_LEN]);
rng().fill_bytes(link.as_mut());
let mut blob = Vec::with_capacity(plaintext.len() + overhead);
blob.extend_from_slice(MAGIC);
let mut salt = [0u8; SALT_LEN];
if password.is_some() {
kdf.check()?;
rng().fill_bytes(&mut salt);
blob.push(FLAG_PASSWORD);
for v in [kdf.m_cost_kib, kdf.t_cost, kdf.p_cost] {
blob.extend_from_slice(&v.to_le_bytes());
}
blob.extend_from_slice(&salt);
} else {
blob.push(0);
}
let mut nonce = [0u8; NONCE_LEN];
rng().fill_bytes(&mut nonce);
blob.extend_from_slice(&nonce);
let key = message_key(&link, password.map(|p| (p, kdf, &salt[..])))?;
let ct = cipher(&key)
.encrypt(
&XNonce::try_from(&nonce[..]).map_err(|_| ShareError::Malformed)?,
AeadPayload { msg: &plaintext, aad: &blob },
)
.map_err(|_| ShareError::Malformed)?;
blob.extend_from_slice(&ct);
let mut fragment = format!("k={}", BASE64URL_NOPAD.encode(link.as_ref()));
if password.is_some() {
fragment.push_str("&p=1");
}
Ok(Sealed { blob, fragment })
}
/// Opens a blob with the link fragment (with or without its leading `#`) and the password, if the
/// share has one. Any change to the blob, a wrong key or a wrong password gives `DecryptFailed`.
pub fn open(blob: &[u8], fragment: &str, password: Option<&SecretString>) -> Result<Payload, ShareError> {
if blob.len() > MAX_BLOB || blob.len() < 5 || &blob[..4] != MAGIC || blob[4] & !FLAG_PASSWORD != 0 {
return Err(ShareError::Malformed);
}
let has_password = blob[4] & FLAG_PASSWORD != 0;
let mut at = 5;
let mut kdf = ShareKdf::DEFAULT;
let mut salt: &[u8] = &[];
if has_password {
if blob.len() < at + KDF_LEN + SALT_LEN {
return Err(ShareError::Malformed);
}
let u = |i: usize| u32::from_le_bytes(blob[at + i..at + i + 4].try_into().unwrap());
kdf = ShareKdf { m_cost_kib: u(0), t_cost: u(4), p_cost: u(8) };
at += KDF_LEN;
salt = &blob[at..at + SALT_LEN];
at += SALT_LEN;
}
if blob.len() < at + NONCE_LEN + TAG_LEN {
return Err(ShareError::Malformed);
}
let (header, ct) = blob.split_at(at + NONCE_LEN);
let nonce = &header[at..];
let link = link_key(fragment)?;
let pw = match (has_password, password) {
(true, None) => return Err(ShareError::PasswordRequired),
(true, Some(p)) => Some((p, kdf, salt)),
(false, _) => None,
};
let key = message_key(&link, pw)?;
let plaintext = Zeroizing::new(
cipher(&key)
.decrypt(&XNonce::try_from(nonce).map_err(|_| ShareError::Malformed)?, AeadPayload { msg: ct, aad: header })
.map_err(|_| ShareError::DecryptFailed)?,
);
let w: WireIn = serde_json::from_slice(&plaintext).map_err(|_| ShareError::Malformed)?;
if w.v != 1 {
return Err(ShareError::Malformed);
}
Ok(Payload { title: w.title, kind: w.kind, fields: w.fields, notes: w.notes })
}
+163
View File
@@ -0,0 +1,163 @@
//! The mandatory share tests (Day 2, tests 5 and 6) and the format checks from docs/SHARE.md.
use custos_share::{Field, Payload, ShareError, ShareKdf, open, seal, seal_with_kdf};
use custos_vault::{Item, ItemType, SecretString};
/// Fast parameters for tests; the format and the code path are the same as the default's.
const TEST_KDF: ShareKdf = ShareKdf { m_cost_kib: 8 * 1024, t_cost: 1, p_cost: 1 };
fn payload() -> Payload {
Payload {
title: "Router".into(),
kind: Some("wifi".into()),
fields: vec![Field::text("ssid", "Home"), Field::secret("password", "correct-horse-ž!")],
notes: None,
}
}
fn pw(s: &str) -> SecretString {
SecretString::from(s)
}
#[test]
fn round_trip_without_password() {
let s = seal(&payload(), None).unwrap();
assert!(s.fragment.starts_with("k=") && s.fragment.len() == 45, "{}", s.fragment);
assert!(!s.needs_password());
let got = open(&s.blob, &s.fragment, None).unwrap();
assert_eq!(got, payload());
}
#[test]
fn tamper_any_byte_or_wrong_key_fails_with_a_clear_error() {
let s = seal(&payload(), None).unwrap();
for i in 0..s.blob.len() {
let mut bad = s.blob.clone();
bad[i] ^= 0x01;
let e = open(&bad, &s.fragment, None).unwrap_err();
// Flipping the password flag on asks for a password; everything else fails to decrypt or parse.
assert!(
matches!(e, ShareError::DecryptFailed | ShareError::Malformed | ShareError::PasswordRequired),
"byte {i}: {e:?}"
);
}
// A different, well-formed key.
let other = seal(&payload(), None).unwrap();
assert_eq!(open(&s.blob, &other.fragment, None).unwrap_err(), ShareError::DecryptFailed);
// Truncated or extended.
assert!(open(&s.blob[..s.blob.len() - 1], &s.fragment, None).is_err());
let mut longer = s.blob.clone();
longer.push(0);
assert_eq!(open(&longer, &s.fragment, None).unwrap_err(), ShareError::DecryptFailed);
// The message is plain and never contains the secret.
let msg = ShareError::DecryptFailed.to_string();
assert!(msg.contains("damaged") && !msg.contains("correct-horse"), "{msg}");
}
#[test]
fn password_share_wrong_password_fails_right_one_works() {
let s = seal_with_kdf(&payload(), Some(&pw("tell-them-by-phone")), TEST_KDF).unwrap();
assert!(s.fragment.ends_with("&p=1") && s.needs_password());
assert_eq!(open(&s.blob, &s.fragment, None).unwrap_err(), ShareError::PasswordRequired);
assert_eq!(open(&s.blob, &s.fragment, Some(&pw("tell-them-by-phone!"))).unwrap_err(), ShareError::DecryptFailed);
assert_eq!(open(&s.blob, &s.fragment, Some(&pw(""))).unwrap_err(), ShareError::DecryptFailed);
assert_eq!(open(&s.blob, &s.fragment, Some(&pw("tell-them-by-phone"))).unwrap(), payload());
// The link alone is not enough even with the hint removed: the blob decides.
let bare = s.fragment.trim_end_matches("&p=1");
assert_eq!(open(&s.blob, bare, None).unwrap_err(), ShareError::PasswordRequired);
// The password alone is not enough: a different link key with the right password fails.
let other = seal(&payload(), None).unwrap();
let wrong_key = format!("{}&p=1", other.fragment);
assert_eq!(open(&s.blob, &wrong_key, Some(&pw("tell-them-by-phone"))).unwrap_err(), ShareError::DecryptFailed);
}
#[test]
fn default_kdf_is_the_documented_one_and_works() {
assert_eq!(ShareKdf::DEFAULT, ShareKdf { m_cost_kib: 19_456, t_cost: 2, p_cost: 1 });
let s = seal(&payload(), Some(&pw("pw"))).unwrap();
assert_eq!(&s.blob[5..17], [0x00, 0x4c, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0]);
assert_eq!(open(&s.blob, &s.fragment, Some(&pw("pw"))).unwrap(), payload());
}
#[test]
fn layout_matches_docs() {
let s = seal(&payload(), None).unwrap();
assert_eq!(&s.blob[..4], b"CSH1");
assert_eq!(s.blob[4], 0);
let p = seal_with_kdf(&payload(), Some(&pw("x")), TEST_KDF).unwrap();
assert_eq!(p.blob[4], 1);
// magic + flags + kdf (12) + salt (16) + nonce (24) + tag (16) + plaintext
assert_eq!(p.blob.len(), s.blob.len() + 28);
// Unknown flags are rejected before any crypto.
let mut bad = s.blob.clone();
bad[4] = 0x02;
assert_eq!(open(&bad, &s.fragment, None).unwrap_err(), ShareError::Malformed);
}
#[test]
fn kdf_limits_are_checked_before_argon2() {
let s = seal_with_kdf(&payload(), Some(&pw("x")), TEST_KDF).unwrap();
for (offset, value) in [(5usize, 300 * 1024u32), (5, 1024), (9, 17), (9, 0), (13, 5), (13, 0)] {
let mut bad = s.blob.clone();
bad[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
assert_eq!(
open(&bad, &s.fragment, Some(&pw("x"))).unwrap_err(),
ShareError::UnsupportedKdf,
"{offset}={value}"
);
}
}
#[test]
fn bad_links_are_rejected() {
let s = seal(&payload(), None).unwrap();
for frag in
["", "k=", "k=abc", "x=1", &s.fragment[..44], &format!("{}A", s.fragment), &s.fragment.replace('k', "K")]
{
assert_eq!(open(&s.blob, frag, None).unwrap_err(), ShareError::BadLink, "{frag:?}");
}
// A leading '#' (location.hash) is accepted.
assert!(open(&s.blob, &format!("#{}", s.fragment), None).is_ok());
}
#[test]
fn size_limit() {
let big = Payload { notes: Some(SecretString::new("x".repeat(70_000))), ..payload() };
assert_eq!(seal(&big, None).unwrap_err(), ShareError::TooLarge);
let mut blob = seal(&payload(), None).unwrap().blob.clone();
blob.resize(64 * 1024 + 1, 0);
assert_eq!(open(&blob, "k=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", None).unwrap_err(), ShareError::Malformed);
}
#[test]
fn every_link_key_and_nonce_is_fresh() {
let a = seal(&payload(), None).unwrap();
let b = seal(&payload(), None).unwrap();
assert_ne!(a.fragment, b.fragment);
assert_ne!(a.blob[5..29], b.blob[5..29]);
}
#[test]
fn payload_from_item_leaves_out_empty_fields_totp_and_autotype() {
let mut item = Item::new(ItemType::WebLogin, "GitHub", 0);
item.set("username", "mark", 0);
item.set("password", "hunter2", 0);
item.set("totp", "JBSWY3DPEHPK3PXP", 0);
item.set("autotype-match", "exe:firefox.exe", 0);
item.notes = "recovery codes in the safe".into();
let p = Payload::from_item(&item);
assert_eq!(p.title, "GitHub");
assert_eq!(p.kind.as_deref(), Some("web-login"));
let names: Vec<_> = p.fields.iter().map(|f| f.name.as_str()).collect();
assert_eq!(names, ["username", "password"]);
assert!(p.fields[1].secret && !p.fields[0].secret);
assert_eq!(p.notes.as_ref().map(|n| n.expose()), Some("recovery codes in the safe"));
}
#[test]
fn secrets_are_redacted_in_debug() {
let s = seal(&payload(), Some(&pw("pw"))).unwrap();
let out = format!("{:?} {:?}", s, payload());
assert!(!out.contains("correct-horse") && !out.contains(&s.fragment[2..]), "{out}");
assert!(out.contains("[redacted]"), "{out}");
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "custos-totp"
description = "Custos TOTP (RFC 6238) and HOTP (RFC 4226), otpauth:// URIs"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-vault = { path = "../custos-vault" }
hmac.workspace = true
sha1.workspace = true
sha2.workspace = true
data-encoding.workspace = true
percent-encoding.workspace = true
zeroize.workspace = true
+221
View File
@@ -0,0 +1,221 @@
//! TOTP (RFC 6238) and HOTP (RFC 4226) on RustCrypto's HMAC, and `otpauth://` URIs.
//!
//! ```
//! use custos_totp::Totp;
//! let t = Totp::parse("otpauth://totp/GitHub:mark?secret=JBSWY3DPEHPK3PXP&issuer=GitHub")?;
//! assert_eq!(t.code_at(1_700_000_000).len(), 6);
//! # Ok::<(), custos_totp::TotpError>(())
//! ```
use data_encoding::BASE32_NOPAD;
use hmac::{Hmac, KeyInit, Mac};
use percent_encoding::{NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
use std::fmt;
use zeroize::Zeroizing;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Algorithm {
Sha1,
Sha256,
Sha512,
}
impl Algorithm {
fn name(self) -> &'static str {
match self {
Algorithm::Sha1 => "SHA1",
Algorithm::Sha256 => "SHA256",
Algorithm::Sha512 => "SHA512",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TotpError(String);
impl fmt::Display for TotpError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for TotpError {}
fn err<T>(msg: &str) -> Result<T, TotpError> {
Err(TotpError(msg.into()))
}
fn mac(alg: Algorithm, key: &[u8], msg: &[u8]) -> Vec<u8> {
// HMAC accepts keys of any length; `new_from_slice` cannot fail for it.
match alg {
Algorithm::Sha1 => {
let mut m = <Hmac<sha1::Sha1> as KeyInit>::new_from_slice(key).expect("any key length");
m.update(msg);
m.finalize().into_bytes().to_vec()
}
Algorithm::Sha256 => {
let mut m = <Hmac<sha2::Sha256> as KeyInit>::new_from_slice(key).expect("any key length");
m.update(msg);
m.finalize().into_bytes().to_vec()
}
Algorithm::Sha512 => {
let mut m = <Hmac<sha2::Sha512> as KeyInit>::new_from_slice(key).expect("any key length");
m.update(msg);
m.finalize().into_bytes().to_vec()
}
}
}
/// RFC 4226: HMAC of the 8-byte big-endian counter, dynamic truncation, `digits` decimal digits.
pub fn hotp(secret: &[u8], counter: u64, digits: u32, alg: Algorithm) -> String {
let h = mac(alg, secret, &counter.to_be_bytes());
let off = (h[h.len() - 1] & 0x0f) as usize;
let bin = u32::from_be_bytes([h[off] & 0x7f, h[off + 1], h[off + 2], h[off + 3]]);
format!("{:0width$}", bin % 10u32.pow(digits), width = digits as usize)
}
/// A TOTP generator. The secret is wiped on drop and never printed.
#[derive(Clone)]
pub struct Totp {
secret: Zeroizing<Vec<u8>>,
algorithm: Algorithm,
digits: u32,
period: u64,
issuer: Option<String>,
account: Option<String>,
}
impl fmt::Debug for Totp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Totp")
.field("secret", &"[redacted]")
.field("algorithm", &self.algorithm)
.field("digits", &self.digits)
.field("period", &self.period)
.field("issuer", &self.issuer)
.finish_non_exhaustive()
}
}
fn decode_base32(s: &str) -> Result<Zeroizing<Vec<u8>>, TotpError> {
let clean: Zeroizing<String> = Zeroizing::new(
s.chars().filter(|c| !c.is_whitespace() && *c != '-' && *c != '=').collect::<String>().to_uppercase(),
);
if clean.is_empty() {
return err("the 2FA secret is empty");
}
BASE32_NOPAD
.decode(clean.as_bytes())
.map(Zeroizing::new)
.map_err(|_| TotpError("the 2FA secret is not valid base32".into()))
}
impl Totp {
/// `digits` 6..=8, `period` in seconds (at least 1).
pub fn new(secret: Vec<u8>, algorithm: Algorithm, digits: u32, period: u64) -> Result<Totp, TotpError> {
if !(6..=8).contains(&digits) {
return err("a 2FA code has 6 to 8 digits");
}
if period == 0 {
return err("the 2FA period must be at least one second");
}
if secret.is_empty() {
return err("the 2FA secret is empty");
}
Ok(Totp { secret: Zeroizing::new(secret), algorithm, digits, period, issuer: None, account: None })
}
/// An `otpauth://totp/…` URI, or a bare base32 secret (spaces, lower case and `=` are fine).
pub fn parse(input: &str) -> Result<Totp, TotpError> {
let input = input.trim();
let Some(rest) = input.strip_prefix("otpauth://") else {
return Totp::new(decode_base32(input)?.to_vec(), Algorithm::Sha1, 6, 30);
};
let Some(rest) = rest.strip_prefix("totp/") else {
return err("only time-based codes (otpauth://totp) are supported");
};
let (label, query) = rest.split_once('?').unwrap_or((rest, ""));
let label = percent_decode_str(label).decode_utf8_lossy().into_owned();
let (mut issuer, account) = match label.split_once(':') {
Some((i, a)) => (Some(i.trim().to_owned()), Some(a.trim().to_owned())),
None if label.is_empty() => (None, None),
None => (None, Some(label.trim().to_owned())),
};
let (mut secret, mut alg, mut digits, mut period) = (None, Algorithm::Sha1, 6u32, 30u64);
for pair in query.split('&').filter(|p| !p.is_empty()) {
let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
let v = Zeroizing::new(percent_decode_str(v).decode_utf8_lossy().into_owned());
match k.to_ascii_lowercase().as_str() {
"secret" => secret = Some(decode_base32(&v)?),
"issuer" => issuer = Some(v.to_string()),
"algorithm" => {
alg = match v.to_ascii_uppercase().as_str() {
"SHA1" => Algorithm::Sha1,
"SHA256" => Algorithm::Sha256,
"SHA512" => Algorithm::Sha512,
_ => return err("unsupported 2FA algorithm (use SHA1, SHA256 or SHA512)"),
}
}
"digits" => digits = v.parse().map_err(|_| TotpError("digits is not a number".into()))?,
"period" => period = v.parse().map_err(|_| TotpError("period is not a number".into()))?,
_ => {}
}
}
let secret = secret.ok_or_else(|| TotpError("the otpauth URI has no secret".into()))?;
let mut t = Totp::new(secret.to_vec(), alg, digits, period)?;
t.issuer = issuer.filter(|s| !s.is_empty());
t.account = account.filter(|s| !s.is_empty());
Ok(t)
}
/// The code for Unix time `unix_secs`.
pub fn code_at(&self, unix_secs: u64) -> String {
hotp(&self.secret, unix_secs / self.period, self.digits, self.algorithm)
}
/// Seconds until the code at `unix_secs` changes (1..=period).
pub fn seconds_left(&self, unix_secs: u64) -> u64 {
self.period - unix_secs % self.period
}
pub fn to_uri(&self) -> String {
let enc = |s: &str| utf8_percent_encode(s, NON_ALPHANUMERIC).to_string();
let label = match (&self.issuer, &self.account) {
(Some(i), Some(a)) => format!("{}:{}", enc(i), enc(a)),
(None, Some(a)) => enc(a),
(Some(i), None) => enc(i),
(None, None) => String::new(),
};
let mut uri = format!(
"otpauth://totp/{label}?secret={}&algorithm={}&digits={}&period={}",
BASE32_NOPAD.encode(&self.secret),
self.algorithm.name(),
self.digits,
self.period
);
if let Some(i) = &self.issuer {
uri.push_str(&format!("&issuer={}", enc(i)));
}
uri
}
pub fn issuer(&self) -> Option<&str> {
self.issuer.as_deref()
}
pub fn account(&self) -> Option<&str> {
self.account.as_deref()
}
pub fn digits(&self) -> u32 {
self.digits
}
pub fn period(&self) -> u64 {
self.period
}
pub fn algorithm(&self) -> Algorithm {
self.algorithm
}
}
+93
View File
@@ -0,0 +1,93 @@
//! RFC 6238 Appendix B and RFC 4226 Appendix D test vectors, exactly as published, plus otpauth parsing.
use custos_totp::{Algorithm, Totp, hotp};
const SEED_SHA1: &[u8] = b"12345678901234567890";
const SEED_SHA256: &[u8] = b"12345678901234567890123456789012";
const SEED_SHA512: &[u8] = b"1234567890123456789012345678901234567890123456789012345678901234";
#[test]
fn rfc6238_appendix_b() {
// Time (s), SHA1, SHA256, SHA512 — 8 digits, period 30, T0 = 0.
let table: [(u64, &str, &str, &str); 6] = [
(59, "94287082", "46119246", "90693936"),
(1111111109, "07081804", "68084774", "25091201"),
(1111111111, "14050471", "67062674", "99943326"),
(1234567890, "89005924", "91819424", "93441116"),
(2000000000, "69279037", "90698825", "38618901"),
(20000000000, "65353130", "77737706", "47863826"),
];
for (t, sha1, sha256, sha512) in table {
for (seed, alg, want) in [
(SEED_SHA1, Algorithm::Sha1, sha1),
(SEED_SHA256, Algorithm::Sha256, sha256),
(SEED_SHA512, Algorithm::Sha512, sha512),
] {
let totp = Totp::new(seed.to_vec(), alg, 8, 30).unwrap();
assert_eq!(totp.code_at(t), want, "T={t} {alg:?}");
}
}
}
#[test]
fn rfc4226_appendix_d() {
let want = ["755224", "287082", "359152", "969429", "338314", "254676", "287922", "162583", "399871", "520489"];
for (counter, code) in want.iter().enumerate() {
assert_eq!(hotp(SEED_SHA1, counter as u64, 6, Algorithm::Sha1), *code, "counter {counter}");
}
}
#[test]
fn otpauth_uri_and_base32() {
// "12345678901234567890" in base32.
let b32 = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
let t = Totp::parse(&format!(
"otpauth://totp/Example%20Co:alice%40example.com?secret={b32}&issuer=Example%20Co&algorithm=SHA1&digits=8&period=30"
))
.unwrap();
assert_eq!(t.code_at(59), "94287082");
assert_eq!(t.issuer(), Some("Example Co"));
assert_eq!(t.account(), Some("alice@example.com"));
assert_eq!((t.digits(), t.period(), t.algorithm()), (8, 30, Algorithm::Sha1));
// Defaults: SHA1, 6 digits, 30 s. A bare secret (lower case, spaces, padding) works too.
let bare = Totp::parse("gezd gnbv gy3t qojq gezd gnbv gy3t qojq").unwrap();
assert_eq!(bare.code_at(59), "287082");
assert_eq!((bare.digits(), bare.period()), (6, 30));
assert_eq!(Totp::parse(&format!("{b32}====")).unwrap().code_at(59), "287082");
let sha256 = Totp::parse(
"otpauth://totp/x?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA&algorithm=SHA256&digits=8",
)
.unwrap();
assert_eq!(sha256.code_at(59), "46119246");
for bad in [
"otpauth://hotp/x?secret=GEZDGNBV&counter=1",
"otpauth://totp/x?digits=6",
"otpauth://totp/x?secret=not*base32",
"otpauth://totp/x?secret=GEZDGNBV&digits=9",
"otpauth://totp/x?secret=GEZDGNBV&period=0",
"otpauth://totp/x?secret=GEZDGNBV&algorithm=MD5",
"",
] {
assert!(Totp::parse(bad).is_err(), "{bad} was accepted");
}
}
#[test]
fn round_trip_through_uri_and_countdown() {
let t = Totp::parse("otpauth://totp/GitHub:mark?secret=JBSWY3DPEHPK3PXP&issuer=GitHub").unwrap();
let back = Totp::parse(&t.to_uri()).unwrap();
assert_eq!(back.code_at(1_700_000_000), t.code_at(1_700_000_000));
assert_eq!(back.issuer(), Some("GitHub"));
assert_eq!(t.seconds_left(1_700_000_000), 30 - 1_700_000_000 % 30);
assert_eq!(t.seconds_left(60), 30);
}
#[test]
fn secret_is_redacted_in_debug() {
let t = Totp::parse("otpauth://totp/x?secret=JBSWY3DPEHPK3PXP").unwrap();
let out = format!("{t:?}");
assert!(!out.contains("JBSWY3DPEHPK3PXP") && !out.contains("72, 101") && out.contains("[redacted]"), "{out}");
}
+6
View File
@@ -14,6 +14,12 @@ rand.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
thiserror.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] [dev-dependencies]
tempfile = "3" tempfile = "3"
data-encoding.workspace = true
+22
View File
@@ -55,7 +55,29 @@ pub fn seal(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], plaintext: &[u8], aad: &[u
.expect("encryption cannot fail for in-memory buffers") .expect("encryption cannot fail for in-memory buffers")
} }
/// HKDF-SHA256(ikm, salt, info) → 32-byte key: the factor, pair and single KEKs (docs/FACTORS.md).
pub fn hkdf(ikm: &[u8], salt: &[u8], info: &[u8]) -> Zeroizing<[u8; KEY_LEN]> {
let mut k = Zeroizing::new([0u8; KEY_LEN]);
hkdf::Hkdf::<sha2::Sha256>::new(Some(salt), ikm).expand(info, k.as_mut()).expect("32 bytes is a valid HKDF length");
k
}
/// `None` when the tag does not verify: wrong key, or changed ciphertext, nonce or AAD. /// `None` when the tag does not verify: wrong key, or changed ciphertext, nonce or AAD.
pub fn open(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], ciphertext: &[u8], aad: &[u8]) -> Option<Zeroizing<Vec<u8>>> { 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) 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()
}
+45
View File
@@ -0,0 +1,45 @@
//! Device unlock (docs/FORMAT.md, "Device key wrap"): the vault key wrapped with a key derived from
//! material only this device can produce (the desktop app uses a Windows Hello signature). The blob is
//! kept on that device, never in the vault file.
use crate::Error;
use crate::crypto::{self, KEY_LEN, NONCE_LEN, TAG_LEN};
use hkdf::Hkdf;
use sha2::Sha256;
use zeroize::Zeroizing;
const MAGIC: &[u8; 4] = b"CDW1";
const SALT_LEN: usize = 32;
const INFO: &[u8] = b"custos device wrap v1";
pub const BLOB_LEN: usize = 4 + SALT_LEN + NONCE_LEN + KEY_LEN + TAG_LEN;
fn kek(material: &[u8], salt: &[u8]) -> Zeroizing<[u8; KEY_LEN]> {
let mut k = Zeroizing::new([0u8; KEY_LEN]);
Hkdf::<Sha256>::new(Some(salt), material).expand(INFO, k.as_mut()).expect("32 bytes is a valid HKDF length");
k
}
/// `CDW1 ‖ salt ‖ nonce ‖ XChaCha20-Poly1305(HKDF-SHA256(material, salt), vault key, aad = CDW1 ‖ salt ‖ nonce)`.
pub fn wrap(key: &[u8; KEY_LEN], material: &[u8]) -> Vec<u8> {
let mut salt = [0u8; SALT_LEN];
crypto::fill_random(&mut salt);
let nonce = crypto::random_nonce();
let mut blob = Vec::with_capacity(BLOB_LEN);
blob.extend_from_slice(MAGIC);
blob.extend_from_slice(&salt);
blob.extend_from_slice(&nonce);
let sealed = crypto::seal(&kek(material, &salt), &nonce, key, &blob);
blob.extend_from_slice(&sealed);
blob
}
pub fn unwrap(blob: &[u8], material: &[u8]) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
if blob.len() != BLOB_LEN || &blob[..4] != MAGIC {
return Err(Error::DeviceKeyRejected);
}
let salt = &blob[4..4 + SALT_LEN];
let nonce: [u8; NONCE_LEN] = blob[4 + SALT_LEN..4 + SALT_LEN + NONCE_LEN].try_into().unwrap();
let head = 4 + SALT_LEN + NONCE_LEN;
let k = crypto::open(&kek(material, salt), &nonce, &blob[head..], &blob[..head]).ok_or(Error::DeviceKeyRejected)?;
Ok(Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::DeviceKeyRejected)?))
}
+245 -8
View File
@@ -1,19 +1,29 @@
//! Reading and writing the header of a `.custos` file (docs/FORMAT.md, "Layout"). //! Reading and writing the header of a `.custos` file (docs/FORMAT.md, "Layout"; version 2 in
//! docs/FACTORS.md).
use crate::crypto::{KEY_LEN, NONCE_LEN, TAG_LEN}; use crate::crypto::{KEY_LEN, NONCE_LEN, TAG_LEN};
use crate::{Error, KdfParams}; use crate::{Error, KdfParams};
pub const MAGIC: &[u8; 6] = b"CUSTOS"; pub const MAGIC: &[u8; 6] = b"CUSTOS";
pub const VERSION: u16 = 1; pub const VERSION: u16 = 1;
/// Two factors (docs/FACTORS.md).
pub const VERSION_2: u16 = 2;
pub const MAX_SLOTS: usize = 8; pub const MAX_SLOTS: usize = 8;
pub const MAX_SLOTS_V2: usize = 64;
pub const MAX_FACTORS: usize = 8;
pub const SLOT_PASSWORD: u8 = 1; pub const SLOT_PASSWORD: u8 = 1;
pub const SLOT_FACTOR: u8 = 2;
pub const SLOT_PAIR: u8 = 3;
pub const SLOT_SINGLE: u8 = 4;
const KDF_ARGON2ID: u8 = 1; const KDF_ARGON2ID: u8 = 1;
pub const SALT_LEN: usize = 32; pub const SALT_LEN: usize = 32;
pub const ID_LEN: usize = 16;
/// kdf(1) m(4) t(4) p(4) salt(32) nonce(24): the part of a password slot that is its own AAD. /// kdf(1) m(4) t(4) p(4) salt(32) nonce(24): the part of a password slot that is its own AAD.
const PW_AAD_LEN: usize = 1 + 12 + SALT_LEN + NONCE_LEN; const PW_AAD_LEN: usize = 1 + 12 + SALT_LEN + NONCE_LEN;
const PW_PAYLOAD_LEN: usize = PW_AAD_LEN + KEY_LEN + TAG_LEN; const PW_PAYLOAD_LEN: usize = PW_AAD_LEN + KEY_LEN + TAG_LEN;
const WRAPPED_LEN: usize = KEY_LEN + TAG_LEN;
/// One key slot as stored. Unknown kinds are kept and written back unchanged. /// One key slot as stored. Unknown kinds are kept and written back unchanged (version 1).
#[derive(Clone)] #[derive(Clone)]
pub struct RawSlot { pub struct RawSlot {
pub kind: u8, pub kind: u8,
@@ -73,7 +83,169 @@ impl PasswordSlot {
} }
} }
fn v2_aad(kind: u8, head: &[u8]) -> Vec<u8> {
let mut a = Vec::with_capacity(9 + head.len());
a.extend_from_slice(MAGIC);
a.extend_from_slice(&VERSION_2.to_le_bytes());
a.push(kind);
a.extend_from_slice(head);
a
}
/// A factor slot (kind 2): the factor key `F`, wrapped by a KEK from the factor's material.
pub struct FactorSlot {
pub id: [u8; ID_LEN],
pub kind: u8,
/// Argon2id parameters; password factors only.
pub kdf: Option<KdfParams>,
pub salt: [u8; SALT_LEN],
pub nonce: [u8; NONCE_LEN],
pub wrapped: Vec<u8>,
}
impl FactorSlot {
fn head(&self) -> Vec<u8> {
let mut p = Vec::with_capacity(ID_LEN + 1 + 13 + SALT_LEN + NONCE_LEN);
p.extend_from_slice(&self.id);
p.push(self.kind);
if let Some(k) = self.kdf {
p.push(KDF_ARGON2ID);
p.extend_from_slice(&k.m_cost_kib.to_le_bytes());
p.extend_from_slice(&k.t_cost.to_le_bytes());
p.extend_from_slice(&k.p_cost.to_le_bytes());
}
p.extend_from_slice(&self.salt);
p.extend_from_slice(&self.nonce);
p
}
pub fn aad(&self) -> Vec<u8> {
v2_aad(SLOT_FACTOR, &self.head())
}
pub fn raw(&self) -> RawSlot {
let mut p = self.head();
p.extend_from_slice(&self.wrapped);
RawSlot { kind: SLOT_FACTOR, payload: p }
}
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
let kind = *payload.get(ID_LEN).ok_or(Error::Malformed)?;
let id: [u8; ID_LEN] = payload[..ID_LEN].try_into().unwrap();
let mut at = ID_LEN + 1;
let kdf = match kind {
1 => {
if payload.len() != at + 13 + SALT_LEN + NONCE_LEN + WRAPPED_LEN {
return Err(Error::Malformed);
}
if payload[at] != KDF_ARGON2ID {
return Err(Error::UnsupportedKdf);
}
let u32_at = |i: usize| u32::from_le_bytes(payload[i..i + 4].try_into().unwrap());
let k = KdfParams { m_cost_kib: u32_at(at + 1), t_cost: u32_at(at + 5), p_cost: u32_at(at + 9) };
k.check()?;
at += 13;
Some(k)
}
2..=5 => {
if payload.len() != at + SALT_LEN + NONCE_LEN + WRAPPED_LEN {
return Err(Error::Malformed);
}
None
}
_ => return Err(Error::Malformed),
};
Ok(FactorSlot {
id,
kind,
kdf,
salt: payload[at..at + SALT_LEN].try_into().unwrap(),
nonce: payload[at + SALT_LEN..at + SALT_LEN + NONCE_LEN].try_into().unwrap(),
wrapped: payload[at + SALT_LEN + NONCE_LEN..].to_vec(),
})
}
}
/// A pair slot (kind 3): the vault key, wrapped by a KEK from two factor keys. `a < b` bytewise.
pub struct PairSlot {
pub a: [u8; ID_LEN],
pub b: [u8; ID_LEN],
pub nonce: [u8; NONCE_LEN],
pub wrapped: Vec<u8>,
}
impl PairSlot {
pub fn aad(&self) -> Vec<u8> {
let mut h = Vec::with_capacity(2 * ID_LEN + NONCE_LEN);
h.extend_from_slice(&self.a);
h.extend_from_slice(&self.b);
h.extend_from_slice(&self.nonce);
v2_aad(SLOT_PAIR, &h)
}
pub fn raw(&self) -> RawSlot {
let mut p = Vec::with_capacity(2 * ID_LEN + NONCE_LEN + WRAPPED_LEN);
p.extend_from_slice(&self.a);
p.extend_from_slice(&self.b);
p.extend_from_slice(&self.nonce);
p.extend_from_slice(&self.wrapped);
RawSlot { kind: SLOT_PAIR, payload: p }
}
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
if payload.len() != 2 * ID_LEN + NONCE_LEN + WRAPPED_LEN {
return Err(Error::Malformed);
}
let s = PairSlot {
a: payload[..ID_LEN].try_into().unwrap(),
b: payload[ID_LEN..2 * ID_LEN].try_into().unwrap(),
nonce: payload[2 * ID_LEN..2 * ID_LEN + NONCE_LEN].try_into().unwrap(),
wrapped: payload[2 * ID_LEN + NONCE_LEN..].to_vec(),
};
if s.a >= s.b {
return Err(Error::Malformed);
}
Ok(s)
}
}
/// A single slot (kind 4, machine stores only): the vault key, wrapped by one factor key.
pub struct SingleSlot {
pub id: [u8; ID_LEN],
pub nonce: [u8; NONCE_LEN],
pub wrapped: Vec<u8>,
}
impl SingleSlot {
pub fn aad(&self) -> Vec<u8> {
let mut h = Vec::with_capacity(ID_LEN + NONCE_LEN);
h.extend_from_slice(&self.id);
h.extend_from_slice(&self.nonce);
v2_aad(SLOT_SINGLE, &h)
}
pub fn raw(&self) -> RawSlot {
let mut p = Vec::with_capacity(ID_LEN + NONCE_LEN + WRAPPED_LEN);
p.extend_from_slice(&self.id);
p.extend_from_slice(&self.nonce);
p.extend_from_slice(&self.wrapped);
RawSlot { kind: SLOT_SINGLE, payload: p }
}
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
if payload.len() != ID_LEN + NONCE_LEN + WRAPPED_LEN {
return Err(Error::Malformed);
}
Ok(SingleSlot {
id: payload[..ID_LEN].try_into().unwrap(),
nonce: payload[ID_LEN..ID_LEN + NONCE_LEN].try_into().unwrap(),
wrapped: payload[ID_LEN + NONCE_LEN..].to_vec(),
})
}
}
pub struct Header { pub struct Header {
pub version: u16,
pub slots: Vec<RawSlot>, pub slots: Vec<RawSlot>,
pub body_nonce: [u8; NONCE_LEN], pub body_nonce: [u8; NONCE_LEN],
} }
@@ -82,7 +254,7 @@ impl Header {
pub fn to_bytes(&self) -> Vec<u8> { pub fn to_bytes(&self) -> Vec<u8> {
let mut h = Vec::new(); let mut h = Vec::new();
h.extend_from_slice(MAGIC); h.extend_from_slice(MAGIC);
h.extend_from_slice(&VERSION.to_le_bytes()); h.extend_from_slice(&self.version.to_le_bytes());
h.push(self.slots.len() as u8); h.push(self.slots.len() as u8);
for s in &self.slots { for s in &self.slots {
h.push(s.kind); h.push(s.kind);
@@ -99,11 +271,13 @@ impl Header {
return Err(Error::NotAVault); return Err(Error::NotAVault);
} }
let version = u16::from_le_bytes([bytes[6], bytes[7]]); let version = u16::from_le_bytes([bytes[6], bytes[7]]);
if version != VERSION { let max = match version {
return Err(Error::UnsupportedVersion(version)); VERSION => MAX_SLOTS,
} VERSION_2 => MAX_SLOTS_V2,
v => return Err(Error::UnsupportedVersion(v)),
};
let count = bytes[8] as usize; let count = bytes[8] as usize;
if count == 0 || count > MAX_SLOTS { if count == 0 || count > max {
return Err(Error::Malformed); return Err(Error::Malformed);
} }
let mut at = 9; let mut at = 9;
@@ -120,6 +294,69 @@ impl Header {
if bytes.len() < at + TAG_LEN { if bytes.len() < at + TAG_LEN {
return Err(Error::Malformed); return Err(Error::Malformed);
} }
Ok((Header { slots, body_nonce }, at)) let header = Header { version, slots, body_nonce };
if version == VERSION_2 {
header.check_v2()?;
}
Ok((header, at))
}
/// Structural rules of a v2 header (docs/FACTORS.md, "Limits a reader enforces").
fn check_v2(&self) -> Result<(), Error> {
let mut ids = Vec::new();
for s in self.slots.iter().filter(|s| s.kind == SLOT_FACTOR) {
ids.push(FactorSlot::parse(&s.payload)?.id);
}
if ids.is_empty() || ids.len() > MAX_FACTORS {
return Err(Error::Malformed);
}
let mut seen = ids.clone();
seen.sort();
seen.dedup();
if seen.len() != ids.len() {
return Err(Error::Malformed);
}
let mut singles = 0;
for s in &self.slots {
match s.kind {
SLOT_FACTOR => {}
SLOT_PAIR => {
let p = PairSlot::parse(&s.payload)?;
if !ids.contains(&p.a) || !ids.contains(&p.b) {
return Err(Error::Malformed);
}
}
SLOT_SINGLE => {
let p = SingleSlot::parse(&s.payload)?;
if !ids.contains(&p.id) {
return Err(Error::Malformed);
}
singles += 1;
}
// A v1 password slot, or an unknown kind, has no place in a v2 header.
_ => return Err(Error::Malformed),
}
}
// A machine store is exactly one factor and its single slot.
if singles > 0 && (singles != 1 || ids.len() != 1) {
return Err(Error::Malformed);
}
Ok(())
}
pub fn factor_slots(&self) -> Vec<FactorSlot> {
self.slots.iter().filter(|s| s.kind == SLOT_FACTOR).filter_map(|s| FactorSlot::parse(&s.payload).ok()).collect()
}
pub fn pair_slots(&self) -> Vec<PairSlot> {
self.slots.iter().filter(|s| s.kind == SLOT_PAIR).filter_map(|s| PairSlot::parse(&s.payload).ok()).collect()
}
pub fn single_slot(&self) -> Option<SingleSlot> {
self.slots.iter().find(|s| s.kind == SLOT_SINGLE).and_then(|s| SingleSlot::parse(&s.payload).ok())
}
pub fn is_machine_store(&self) -> bool {
self.slots.iter().any(|s| s.kind == SLOT_SINGLE)
} }
} }
+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() })
}
}
+14 -1
View File
@@ -16,16 +16,19 @@ pub enum ItemType {
Wifi, Wifi,
SecureNote, SecureNote,
Card, Card,
/// A signing or SSH key pair (docs/FACTORS.md, "The key-pair item type").
KeyPair,
} }
impl ItemType { impl ItemType {
pub const ALL: [ItemType; 6] = [ pub const ALL: [ItemType; 7] = [
ItemType::WebLogin, ItemType::WebLogin,
ItemType::ApiCredential, ItemType::ApiCredential,
ItemType::LocalApp, ItemType::LocalApp,
ItemType::Wifi, ItemType::Wifi,
ItemType::SecureNote, ItemType::SecureNote,
ItemType::Card, ItemType::Card,
ItemType::KeyPair,
]; ];
pub fn label(self) -> &'static str { pub fn label(self) -> &'static str {
@@ -36,6 +39,7 @@ impl ItemType {
ItemType::Wifi => "Wi-Fi", ItemType::Wifi => "Wi-Fi",
ItemType::SecureNote => "Secure note", ItemType::SecureNote => "Secure note",
ItemType::Card => "Card", ItemType::Card => "Card",
ItemType::KeyPair => "Key pair",
} }
} }
@@ -59,6 +63,15 @@ impl ItemType {
ItemType::Card => { ItemType::Card => {
&[("cardholder", false), ("number", true), ("expiry", false), ("cvv", true), ("pin", true)] &[("cardholder", false), ("number", true), ("expiry", false), ("cvv", true), ("pin", true)]
} }
ItemType::KeyPair => &[
("algorithm", false),
("public-key", false),
("public-pem", false),
("private-key", true),
("private-openssh", true),
("fingerprint", false),
("comment", false),
],
} }
} }
} }
+598 -27
View File
@@ -1,18 +1,25 @@
//! The Custos vault: one `.custos` file, Argon2id + XChaCha20-Poly1305, documented in docs/FORMAT.md. //! The Custos vault: one `.custos` file, Argon2id + XChaCha20-Poly1305, documented in docs/FORMAT.md
//! (version 1) and docs/FACTORS.md (version 2: any two factors).
//! //!
//! ``` //! ```
//! use custos_vault::{Item, ItemType, KdfParams, SecretString, Vault}; //! use custos_vault::{FactorKind, Item, ItemType, KdfParams, SecretString, Unlock, Vault};
//! let password = SecretString::from("Orbit7-Fable3-Quartz9-Lumen2"); //! let password = SecretString::from("Orbit7-Fable3-Quartz9-Lumen2");
//! let device_key = [7u8; 32]; // in the app: a key file only this Windows account can read
//! # let kdf = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }; //! # let kdf = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
//! let mut vault = Vault::create(&password, kdf)?; //! let mut vault = Vault::create_with(
//! Unlock::Password(&password), "Master password",
//! Unlock::Material(FactorKind::Device, &device_key), "This PC", kdf)?;
//! vault.add(Item::new(ItemType::WebLogin, "GitHub", custos_vault::now_ms())); //! vault.add(Item::new(ItemType::WebLogin, "GitHub", custos_vault::now_ms()));
//! let bytes = vault.to_bytes()?; //! let bytes = vault.to_bytes()?;
//! assert_eq!(Vault::open(&bytes, &password)?.items().len(), 1); //! let back = Vault::open_with(&bytes, Unlock::Password(&password), Unlock::Material(FactorKind::Device, &device_key))?;
//! assert_eq!(back.items().len(), 1);
//! # Ok::<(), custos_vault::Error>(()) //! # Ok::<(), custos_vault::Error>(())
//! ``` //! ```
mod crypto; mod crypto;
mod device;
mod format; mod format;
pub mod identity;
mod item; mod item;
mod save; mod save;
mod secret; mod secret;
@@ -22,7 +29,10 @@ pub use save::{CrashPoint, save_atomic, save_atomic_crashing};
pub use secret::SecretString; pub use secret::SecretString;
use crypto::KEY_LEN; use crypto::KEY_LEN;
use format::{Header, PasswordSlot, RawSlot, SALT_LEN, SLOT_PASSWORD}; use format::{
FactorSlot, Header, ID_LEN, MAX_FACTORS, PairSlot, PasswordSlot, RawSlot, SALT_LEN, SLOT_FACTOR, SLOT_PAIR,
SLOT_PASSWORD, SingleSlot, VERSION, VERSION_2,
};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt; use std::fmt;
use std::path::Path; use std::path::Path;
@@ -42,6 +52,24 @@ pub enum Error {
WrongPassword, WrongPassword,
#[error("the vault file was changed or damaged after it was written")] #[error("the vault file was changed or damaged after it was written")]
Corrupted, Corrupted,
#[error("this device's unlock key no longer opens the vault; use the master password")]
DeviceKeyRejected,
#[error("this vault opens with two different factors")]
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}")] #[error("{0}")]
Io(#[from] std::io::Error), Io(#[from] std::io::Error),
} }
@@ -77,12 +105,162 @@ impl Default for KdfParams {
} }
} }
/// What kind of secret a factor is (docs/FACTORS.md, "Factor KEKs").
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FactorKind {
/// The master password.
Password,
/// A key one device keeps (a DPAPI-protected key file, a key in the phone's storage).
Device,
/// A share the TOTP service releases after a valid code.
Totp,
/// A secret another paired device sends after you approve there.
Approval,
/// A WebAuthn PRF output (Face ID, Touch ID, Windows Hello passkey).
Passkey,
}
impl FactorKind {
fn code(self) -> u8 {
match self {
FactorKind::Password => 1,
FactorKind::Device => 2,
FactorKind::Totp => 3,
FactorKind::Approval => 4,
FactorKind::Passkey => 5,
}
}
fn from_code(c: u8) -> Option<Self> {
Some(match c {
1 => FactorKind::Password,
2 => FactorKind::Device,
3 => FactorKind::Totp,
4 => FactorKind::Approval,
5 => FactorKind::Passkey,
_ => return None,
})
}
}
/// One factor given to open a vault. `Debug` never prints the password or the material.
#[derive(Clone, Copy)]
pub enum Unlock<'a> {
Password(&'a SecretString),
/// Any other factor: its kind and 32..=64 bytes of material.
Material(FactorKind, &'a [u8]),
}
impl Unlock<'_> {
fn kind(&self) -> FactorKind {
match self {
Unlock::Password(_) => FactorKind::Password,
Unlock::Material(k, _) => *k,
}
}
/// Material for types 2..5 must be 32..=64 bytes, and a password is never passed as material.
fn check(&self) -> Result<(), Error> {
match self {
Unlock::Password(_) => Ok(()),
Unlock::Material(FactorKind::Password, _) => Err(Error::FactorRejected),
Unlock::Material(_, m) if (32..=64).contains(&m.len()) => Ok(()),
Unlock::Material(..) => Err(Error::FactorRejected),
}
}
}
impl fmt::Debug for Unlock<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Unlock::Password(_) => f.write_str("Password([redacted])"),
Unlock::Material(k, _) => write!(f, "Material({k:?}, [redacted])"),
}
}
}
/// A factor of an unlocked vault, as the app lists it. Never carries the factor key.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FactorInfo {
/// 32 hex digits.
pub id: String,
pub kind: FactorKind,
pub label: String,
pub created: i64,
}
/// A factor as the body keeps it: its key `F` is what lets an unlocked vault add pairs.
#[derive(Clone)]
struct FactorRec {
id: [u8; ID_LEN],
kind: FactorKind,
label: String,
created: i64,
key: Zeroizing<[u8; KEY_LEN]>,
}
#[derive(Serialize, Deserialize)]
struct FactorJson {
id: String,
#[serde(rename = "type")]
kind: FactorKind,
label: String,
created: i64,
key: SecretString,
}
fn hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{x:02x}")).collect()
}
fn unhex<const N: usize>(s: &str) -> Option<[u8; N]> {
if s.len() != 2 * N {
return None;
}
let mut out = [0u8; N];
for (i, o) in out.iter_mut().enumerate() {
*o = u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()?;
}
Some(out)
}
impl FactorRec {
fn json(&self) -> FactorJson {
FactorJson {
id: hex(&self.id),
kind: self.kind,
label: self.label.clone(),
created: self.created,
key: SecretString::new(hex(self.key.as_ref())),
}
}
fn from_json(j: &FactorJson) -> Option<FactorRec> {
Some(FactorRec {
id: unhex(&j.id)?,
kind: j.kind,
label: j.label.clone(),
created: j.created,
key: Zeroizing::new(unhex(j.key.expose())?),
})
}
}
const BODY_FORMAT: u32 = 1; const BODY_FORMAT: u32 = 1;
const BODY_FORMAT_2: u32 = 2;
const INFO_FACTOR: &[u8] = b"custos factor v2";
const INFO_PAIR: &[u8] = b"custos pair v2";
const INFO_SINGLE: &[u8] = b"custos single v2";
#[derive(Deserialize)] #[derive(Deserialize)]
struct Body { struct Body {
format: u32, format: u32,
items: Vec<Item>, 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. /// What `to_bytes` serializes: borrows the items instead of cloning every secret.
@@ -90,18 +268,34 @@ struct Body {
struct BodyRef<'a> { struct BodyRef<'a> {
format: u32, format: u32,
items: &'a [Item], 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. /// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
pub struct Vault { pub struct Vault {
key: Zeroizing<[u8; KEY_LEN]>, key: Zeroizing<[u8; KEY_LEN]>,
version: u16,
slots: Vec<RawSlot>, slots: Vec<RawSlot>,
items: Vec<Item>, items: Vec<Item>,
/// Version 2 only.
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 { impl fmt::Debug for Vault {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Vault").field("items", &self.items.len()).finish_non_exhaustive() f.debug_struct("Vault")
.field("version", &self.version)
.field("items", &self.items.len())
.field("factors", &self.factors.len())
.field("identity", &self.identity.is_some())
.finish_non_exhaustive()
} }
} }
@@ -115,21 +309,144 @@ fn password_slot(key: &[u8; KEY_LEN], password: &SecretString, kdf: KdfParams) -
Ok(slot) Ok(slot)
} }
/// The KEK a factor's material gives for one factor slot.
fn factor_kek(u: &Unlock, salt: &[u8], kdf: Option<KdfParams>) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
match (u, kdf) {
(Unlock::Password(p), Some(k)) => crypto::derive_kek(p.expose().as_bytes(), salt, k),
(Unlock::Material(_, m), None) => Ok(crypto::hkdf(m, salt, INFO_FACTOR)),
_ => Err(Error::FactorRejected),
}
}
/// A new factor slot wrapping `key` (the factor key `F`) with `u`'s material.
fn factor_slot(id: [u8; ID_LEN], key: &[u8; KEY_LEN], u: &Unlock, kdf: KdfParams) -> Result<FactorSlot, Error> {
u.check()?;
let kdf = matches!(u, Unlock::Password(_)).then_some(kdf);
if let Some(k) = kdf {
k.check()?;
}
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 kek = factor_kek(u, &slot.salt, slot.kdf)?;
slot.wrapped = crypto::seal(&kek, &slot.nonce, key, &slot.aad());
Ok(slot)
}
fn pair_kek(a: &FactorRec, b: &FactorRec) -> Zeroizing<[u8; KEY_LEN]> {
let (x, y) = if a.id < b.id { (a, b) } else { (b, a) };
let mut ikm = Zeroizing::new([0u8; 2 * KEY_LEN]);
ikm[..KEY_LEN].copy_from_slice(x.key.as_ref());
ikm[KEY_LEN..].copy_from_slice(y.key.as_ref());
let mut salt = [0u8; 2 * ID_LEN];
salt[..ID_LEN].copy_from_slice(&x.id);
salt[ID_LEN..].copy_from_slice(&y.id);
crypto::hkdf(ikm.as_ref(), &salt, INFO_PAIR)
}
fn pair_slot(vault_key: &[u8; KEY_LEN], a: &FactorRec, b: &FactorRec) -> PairSlot {
let (x, y) = if a.id < b.id { (a.id, b.id) } else { (b.id, a.id) };
let mut slot = PairSlot { a: x, b: y, nonce: crypto::random_nonce(), wrapped: Vec::new() };
slot.wrapped = crypto::seal(&pair_kek(a, b), &slot.nonce, vault_key, &slot.aad());
slot
}
fn single_kek(f: &FactorRec) -> Zeroizing<[u8; KEY_LEN]> {
crypto::hkdf(f.key.as_ref(), &f.id, INFO_SINGLE)
}
fn key32(k: Zeroizing<Vec<u8>>) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
Ok(Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::Malformed)?))
}
/// The first factor slot of `u`'s kind that `u` unwraps: its id and factor key.
fn unwrap_factor(header: &Header, u: &Unlock) -> Result<FactorRec, Error> {
u.check()?;
for slot in header.factor_slots().into_iter().filter(|s| s.kind == u.kind().code()) {
let kek = factor_kek(u, &slot.salt, slot.kdf)?;
if let Some(k) = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()) {
return Ok(FactorRec { id: slot.id, kind: u.kind(), label: String::new(), created: 0, key: key32(k)? });
}
}
Err(if matches!(u, Unlock::Password(_)) { Error::WrongPassword } else { Error::FactorRejected })
}
impl Vault { impl Vault {
/// A new, empty vault with a fresh random vault key wrapped by `password`. /// A new, empty version-1 vault with a fresh random vault key wrapped by `password`.
pub fn create(password: &SecretString, kdf: KdfParams) -> Result<Vault, Error> { pub fn create(password: &SecretString, kdf: KdfParams) -> Result<Vault, Error> {
let key = crypto::random_key(); let key = crypto::random_key();
let slot = password_slot(&key, password, kdf)?; let slot = password_slot(&key, password, kdf)?;
Ok(Vault { key, slots: vec![slot.raw()], items: Vec::new() }) 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).
pub fn create_with(a: Unlock, label_a: &str, b: Unlock, label_b: &str, kdf: KdfParams) -> Result<Vault, Error> {
if a.kind() == FactorKind::Password && b.kind() == FactorKind::Password {
return Err(Error::NeedTwoFactors);
}
let mut v = Vault {
key: crypto::random_key(),
version: VERSION_2,
slots: Vec::new(),
items: Vec::new(),
factors: Vec::new(),
kdf_new: kdf,
identity: None,
};
v.add_factor(a, label_a)?;
v.add_factor(b, label_b)?;
Ok(v)
}
/// A machine store: a separate vault that one device key opens alone, for a program that must
/// open it unattended (the Claude Code store). Never for the user's own secrets.
pub fn create_machine_store(material: &[u8], label: &str) -> Result<Vault, Error> {
let u = Unlock::Material(FactorKind::Device, material);
u.check()?;
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 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());
Ok(Vault {
key,
version: VERSION_2,
slots: vec![fslot.raw(), single.raw()],
items: Vec::new(),
factors: vec![rec],
kdf_new: KdfParams::DEFAULT,
identity: None,
})
} }
pub fn open_file(path: &Path, password: &SecretString) -> Result<Vault, Error> { pub fn open_file(path: &Path, password: &SecretString) -> Result<Vault, Error> {
Vault::open(&std::fs::read(path)?, password) Vault::open(&std::fs::read(path)?, password)
} }
/// Unlocks a vault. Returns no data at all unless both the key slot and the body authenticate. /// Unlocks a version-1 vault with its password. A version-2 vault needs [`Vault::open_with`].
/// Returns no data at all unless both the key slot and the body authenticate.
pub fn open(bytes: &[u8], password: &SecretString) -> Result<Vault, Error> { pub fn open(bytes: &[u8], password: &SecretString) -> Result<Vault, Error> {
let (header, body_at) = Header::parse(bytes)?; let (header, body_at) = Header::parse(bytes)?;
if header.version == VERSION_2 {
return Err(Error::NeedTwoFactors);
}
let pw_slots: Vec<PasswordSlot> = header let pw_slots: Vec<PasswordSlot> = header
.slots .slots
.iter() .iter()
@@ -142,30 +459,136 @@ impl Vault {
for slot in &pw_slots { for slot in &pw_slots {
let kek = crypto::derive_kek(password.expose().as_bytes(), &slot.salt, slot.kdf)?; let kek = crypto::derive_kek(password.expose().as_bytes(), &slot.salt, slot.kdf)?;
if let Some(k) = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()) { if let Some(k) = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()) {
let key: Zeroizing<[u8; KEY_LEN]> = let kdf = slot.kdf;
Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::Malformed)?); let mut v = Vault::open_body(bytes, header, body_at, key32(k)?)?;
return Vault::open_body(bytes, header, body_at, key); v.kdf_new = kdf;
return Ok(v);
} }
} }
Err(Error::WrongPassword) Err(Error::WrongPassword)
} }
/// Unlocks a version-2 vault with two different factors, in any order (docs/FACTORS.md, "Opening").
pub fn open_with(bytes: &[u8], a: Unlock, b: Unlock) -> Result<Vault, Error> {
let (header, body_at) = Header::parse(bytes)?;
if header.version != VERSION_2 || header.is_machine_store() {
return Err(Error::NeedTwoFactors);
}
// Refuse bad material before any Argon2 work.
a.check()?;
b.check()?;
let fa = unwrap_factor(&header, &a)?;
let fb = unwrap_factor(&header, &b)?;
if fa.id == fb.id {
return Err(Error::NeedTwoFactors);
}
let (x, y) = if fa.id < fb.id { (fa.id, fb.id) } else { (fb.id, fa.id) };
// 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)?)
}
/// Opens a machine store with its one device key. A user vault is never opened this way.
pub fn open_machine_store(bytes: &[u8], material: &[u8]) -> Result<Vault, Error> {
let (header, body_at) = Header::parse(bytes)?;
if header.version != VERSION_2 || !header.is_machine_store() {
return Err(Error::NeedTwoFactors);
}
let f = unwrap_factor(&header, &Unlock::Material(FactorKind::Device, material))?;
let slot = header.single_slot().filter(|s| s.id == f.id).ok_or(Error::Corrupted)?;
let k = crypto::open(&single_kek(&f), &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::Corrupted)?;
Vault::open_body(bytes, header, body_at, key32(k)?)
}
/// The format version of a vault file (1 or 2), from its header alone.
pub fn version_of(bytes: &[u8]) -> Result<u16, Error> {
Ok(Header::parse(bytes)?.0.version)
}
/// The kinds of factor a vault opens with, from its header alone: what the unlock screen offers.
pub fn factor_kinds(bytes: &[u8]) -> Result<Vec<FactorKind>, Error> {
let (header, _) = Header::parse(bytes)?;
if header.version == VERSION {
return Ok(vec![FactorKind::Password]);
}
Ok(header.factor_slots().iter().filter_map(|s| FactorKind::from_code(s.kind)).collect())
}
/// The factors a vault file has, from its header (no key needed): id (32 hex digits) and type. The app
/// asks the TOTP service and paired devices for a factor by this id.
pub fn factor_ids(bytes: &[u8]) -> Result<Vec<(String, FactorKind)>, Error> {
let (header, _) = Header::parse(bytes)?;
if header.version == VERSION {
return Ok(Vec::new());
}
Ok(header.factor_slots().iter().filter_map(|s| Some((hex(&s.id), FactorKind::from_code(s.kind)?))).collect())
}
pub fn is_machine_store(bytes: &[u8]) -> Result<bool, Error> {
Ok(Header::parse(bytes)?.0.is_machine_store())
}
fn open_body(bytes: &[u8], header: Header, body_at: usize, key: Zeroizing<[u8; KEY_LEN]>) -> Result<Vault, Error> { fn open_body(bytes: &[u8], header: Header, body_at: usize, key: Zeroizing<[u8; KEY_LEN]>) -> Result<Vault, Error> {
let json = let json =
crypto::open(&key, &header.body_nonce, &bytes[body_at..], &bytes[..body_at]).ok_or(Error::Corrupted)?; crypto::open(&key, &header.body_nonce, &bytes[body_at..], &bytes[..body_at]).ok_or(Error::Corrupted)?;
let body: Body = serde_json::from_slice(&json).map_err(|_| Error::Corrupted)?; let body: Body = serde_json::from_slice(&json).map_err(|_| Error::Corrupted)?;
if body.format != BODY_FORMAT { let want = if header.version == VERSION_2 { BODY_FORMAT_2 } else { BODY_FORMAT };
if body.format != want {
return Err(Error::Corrupted); return Err(Error::Corrupted);
} }
Ok(Vault { key, slots: header.slots, items: body.items }) 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();
let mut in_body: Vec<_> = factors.iter().map(|f| f.id).collect();
in_header.sort();
in_body.sort();
if in_header != in_body {
return Err(Error::Corrupted);
}
}
let kdf_new = header.factor_slots().iter().find_map(|s| s.kdf).unwrap_or(KdfParams::DEFAULT);
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
/// Windows Hello signature). Version 1 only: a version-2 vault never opens with one secret.
pub fn wrap_for_device(&self, material: &[u8]) -> Result<Vec<u8>, Error> {
if self.version == VERSION_2 {
return Err(Error::NeedTwoFactors);
}
Ok(device::wrap(&self.key, material))
}
/// Unlocks with a device blob instead of the password (version 1). Fails with `DeviceKeyRejected`
/// when the material is wrong or the blob was changed, and with `Corrupted` when it belongs to another vault.
pub fn open_with_device(bytes: &[u8], blob: &[u8], material: &[u8]) -> Result<Vault, Error> {
let (header, body_at) = Header::parse(bytes)?;
if header.version == VERSION_2 {
return Err(Error::NeedTwoFactors);
}
let key = device::unwrap(blob, material)?;
Vault::open_body(bytes, header, body_at, key)
} }
/// The encrypted file contents, with a fresh body nonce. /// The encrypted file contents, with a fresh body nonce.
pub fn to_bytes(&self) -> Result<Vec<u8>, Error> { pub fn to_bytes(&self) -> Result<Vec<u8>, Error> {
let body_nonce = crypto::random_nonce(); let body_nonce = crypto::random_nonce();
let mut out = Header { slots: self.slots.clone(), body_nonce }.to_bytes(); let mut out = Header { version: self.version, slots: self.slots.clone(), body_nonce }.to_bytes();
let mut json = Zeroizing::new(Vec::with_capacity(4096 + 1024 * self.items.len())); let mut json = Zeroizing::new(Vec::with_capacity(4096 + 1024 * self.items.len()));
let body = BodyRef { format: BODY_FORMAT, items: &self.items }; let v2 = self.version == VERSION_2;
let body = BodyRef {
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())))?; 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); let sealed = crypto::seal(&self.key, &body_nonce, &json, &out);
out.extend_from_slice(&sealed); out.extend_from_slice(&sealed);
@@ -177,28 +600,147 @@ impl Vault {
save_atomic(path, &self.to_bytes()?) save_atomic(path, &self.to_bytes()?)
} }
/// Wraps the same vault key with a new password (new salt and nonce). The items are untouched; /// Changes the master password. Version 1: a new password slot. Version 2: the password factor's
/// the old password stops working at the next save. /// key is rewrapped, so its pairs keep working (also after a forgotten password: open with two
/// other factors, then set a new one). The old password stops working at the next save.
pub fn change_password(&mut self, new_password: &SecretString, kdf: KdfParams) -> Result<(), Error> { pub fn change_password(&mut self, new_password: &SecretString, kdf: KdfParams) -> Result<(), Error> {
let slot = password_slot(&self.key, new_password, kdf)?; if self.version == VERSION {
self.slots.retain(|s| s.kind != SLOT_PASSWORD); let slot = password_slot(&self.key, new_password, kdf)?;
self.slots.insert(0, slot.raw()); self.slots.retain(|s| s.kind != SLOT_PASSWORD);
self.slots.insert(0, slot.raw());
self.kdf_new = kdf;
return Ok(());
}
if self.is_store() {
return Err(Error::FactorRejected);
}
self.kdf_new = kdf;
let Some(rec) = self.factors.iter().find(|f| f.kind == FactorKind::Password).cloned() else {
self.add_factor(Unlock::Password(new_password), "Master password")?;
return Ok(());
};
let slot = factor_slot(rec.id, &rec.key, &Unlock::Password(new_password), kdf)?;
let at = self.factor_slot_index(&rec.id).ok_or(Error::Corrupted)?;
self.slots[at] = slot.raw();
Ok(()) Ok(())
} }
fn is_store(&self) -> bool {
self.slots.iter().any(|s| s.kind == format::SLOT_SINGLE)
}
fn factor_slot_index(&self, id: &[u8; ID_LEN]) -> Option<usize> {
self.slots.iter().position(|s| s.kind == SLOT_FACTOR && s.payload.get(..ID_LEN) == Some(&id[..]))
}
/// 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);
}
if self.is_store() {
return Err(Error::FactorRejected);
}
u.check()?;
if self.factors.len() >= MAX_FACTORS
|| (u.kind() == FactorKind::Password && self.factors.iter().any(|f| f.kind == FactorKind::Password))
{
return Err(Error::TooManyFactors);
}
let mut id = [0u8; ID_LEN];
crypto::fill_random(&mut id);
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.iter().filter(|f| !apart.contains(&f.id)) {
self.slots.push(pair_slot(&self.key, &rec, other).raw());
}
self.factors.push(rec);
Ok(hex(&id))
}
/// Removes a factor (a lost phone, an old PC) and every pair it is part of. A vault keeps at least two.
pub fn remove_factor(&mut self, id: &str) -> Result<(), Error> {
let id: [u8; ID_LEN] = unhex(id).ok_or(Error::FactorRejected)?;
if !self.factors.iter().any(|f| f.id == id) {
return Err(Error::FactorRejected);
}
if self.factors.len() <= 2 {
return Err(Error::NeedTwoFactors);
}
self.factors.retain(|f| f.id != id);
self.slots.retain(|s| match s.kind {
SLOT_FACTOR => s.payload.get(..ID_LEN) != Some(&id[..]),
SLOT_PAIR => s.payload.get(..ID_LEN) != Some(&id[..]) && s.payload.get(ID_LEN..2 * ID_LEN) != Some(&id[..]),
_ => true,
});
Ok(())
}
/// 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> {
if self.version != VERSION {
return Err(Error::UnsupportedVersion(self.version));
}
if second.kind() == FactorKind::Password {
return Err(Error::NeedTwoFactors);
}
second.check()?;
self.version = VERSION_2;
self.slots.clear();
self.factors.clear();
self.kdf_new = kdf;
self.add_factor(Unlock::Password(password), "Master password")?;
self.add_factor(second, label)?;
Ok(())
}
/// The factors of a version-2 vault, oldest first. Empty for version 1.
pub fn factors(&self) -> Vec<FactorInfo> {
self.factors
.iter()
.map(|f| FactorInfo { id: hex(&f.id), kind: f.kind, label: f.label.clone(), created: f.created })
.collect()
}
/// 1 or 2.
pub fn version(&self) -> u16 {
self.version
}
/// Whether two unlocked vaults share a vault key (tests: a password change keeps the key). /// Whether two unlocked vaults share a vault key (tests: a password change keeps the key).
#[doc(hidden)] #[doc(hidden)]
pub fn same_key_as(&self, other: &Vault) -> bool { pub fn same_key_as(&self, other: &Vault) -> bool {
self.key[..] == other.key[..] self.key[..] == other.key[..]
} }
/// The KDF parameters of the first password slot. /// The KDF parameters of the (first) password slot or password factor.
pub fn kdf(&self) -> Option<KdfParams> { pub fn kdf(&self) -> Option<KdfParams> {
self.slots self.slots.iter().find_map(|s| match s.kind {
.iter() SLOT_PASSWORD => PasswordSlot::parse(&s.payload).ok().map(|p| p.kdf),
.filter(|s| s.kind == SLOT_PASSWORD) SLOT_FACTOR => FactorSlot::parse(&s.payload).ok().and_then(|f| f.kdf),
.find_map(|s| PasswordSlot::parse(&s.payload).ok()) _ => None,
.map(|s| s.kdf) })
} }
pub fn items(&self) -> &[Item] { pub fn items(&self) -> &[Item] {
@@ -229,4 +771,33 @@ impl Vault {
let i = self.items.iter().position(|it| it.id == id)?; let i = self.items.iter().position(|it| it.id == id)?;
Some(self.items.remove(i)) 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(())
}
} }
+241
View File
@@ -0,0 +1,241 @@
//! Mandatory tests for format version 2 (docs/FACTORS.md): any two factors open the vault, one never
//! does, factors come and go without the others, v1 upgrades, tampering fails, machine stores.
use custos_vault::{Error, FactorKind, Item, ItemType, KdfParams, SecretString, Unlock, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
fn pw(s: &str) -> SecretString {
SecretString::from(s)
}
const DEVICE: [u8; 32] = [7; 32];
const TOTP: [u8; 32] = [9; 32];
const PHONE: [u8; 32] = [11; 32];
fn two_factor_vault() -> Vault {
let mut v = Vault::create_with(
Unlock::Password(&pw("Orbit7-Fable3")),
"Master password",
Unlock::Material(FactorKind::Device, &DEVICE),
"MARK-PC",
FAST,
)
.unwrap();
v.add(Item::new(ItemType::WebLogin, "GitHub", 1_000));
v
}
fn open(bytes: &[u8], a: Unlock, b: Unlock) -> Result<Vault, Error> {
Vault::open_with(bytes, a, b)
}
#[test]
fn any_two_factors_open_and_one_never_does() {
let mut v = two_factor_vault();
v.add_factor(Unlock::Material(FactorKind::Totp, &TOTP), "TOTP backup").unwrap();
let bytes = v.to_bytes().unwrap();
let p = pw("Orbit7-Fable3");
let pairs = [
(Unlock::Password(&p), Unlock::Material(FactorKind::Device, &DEVICE)),
(Unlock::Password(&p), Unlock::Material(FactorKind::Totp, &TOTP)),
(Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Totp, &TOTP)),
// Order does not matter.
(Unlock::Material(FactorKind::Totp, &TOTP), Unlock::Password(&p)),
];
for (a, b) in pairs {
assert_eq!(open(&bytes, a, b).unwrap().items().len(), 1);
}
// One factor, alone or twice, is never enough.
assert!(matches!(open(&bytes, Unlock::Password(&p), Unlock::Password(&p)), Err(Error::NeedTwoFactors)));
assert!(matches!(
open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Device, &DEVICE)),
Err(Error::NeedTwoFactors)
));
// The v1 entry point refuses a v2 vault rather than guessing.
assert!(matches!(Vault::open(&bytes, &p), Err(Error::NeedTwoFactors)));
}
#[test]
fn wrong_factors_are_named() {
let bytes = two_factor_vault().to_bytes().unwrap();
let dev = Unlock::Material(FactorKind::Device, &DEVICE);
assert!(matches!(open(&bytes, Unlock::Password(&pw("wrong")), dev), Err(Error::WrongPassword)));
let bad = [8u8; 32];
assert!(matches!(
open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &bad)),
Err(Error::FactorRejected)
));
// A factor of a type the vault does not have.
assert!(matches!(
open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Passkey, &PHONE)),
Err(Error::FactorRejected)
));
// Material outside 32..=64 bytes is refused before any work.
assert!(matches!(
open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &[1; 31])),
Err(Error::FactorRejected)
));
}
#[test]
fn a_factor_is_added_and_removed_without_the_others() {
let p = pw("Orbit7-Fable3");
let bytes = two_factor_vault().to_bytes().unwrap();
let mut v = open(&bytes, Unlock::Password(&p), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
// Only the new factor's material is needed: its pairs come from the factor keys in the body.
let phone = v.add_factor(Unlock::Material(FactorKind::Approval, &PHONE), "Phone").unwrap();
let bytes = v.to_bytes().unwrap();
let mut v = open(&bytes, Unlock::Material(FactorKind::Approval, &PHONE), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
let kinds: Vec<_> = v.factors().iter().map(|f| f.kind).collect();
assert_eq!(kinds, [FactorKind::Password, FactorKind::Device, FactorKind::Approval]);
// A lost device: drop its factor; the other two still open, the device no longer helps.
let device = v.factors()[1].id.clone();
v.remove_factor(&device).unwrap();
let bytes = v.to_bytes().unwrap();
assert!(open(&bytes, Unlock::Password(&p), Unlock::Material(FactorKind::Approval, &PHONE)).is_ok());
assert!(matches!(
open(&bytes, Unlock::Password(&p), Unlock::Material(FactorKind::Device, &DEVICE)),
Err(Error::FactorRejected)
));
// Never below two factors.
let mut v = open(&bytes, Unlock::Password(&p), Unlock::Material(FactorKind::Approval, &PHONE)).unwrap();
assert!(matches!(v.remove_factor(&phone), Err(Error::NeedTwoFactors)));
}
#[test]
fn a_forgotten_password_is_replaced_with_two_other_factors() {
let mut v = two_factor_vault();
v.add_factor(Unlock::Material(FactorKind::Totp, &TOTP), "TOTP backup").unwrap();
let bytes = v.to_bytes().unwrap();
let mut v = open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Totp, &TOTP)).unwrap();
v.change_password(&pw("New9-Password4"), FAST).unwrap();
let bytes2 = v.to_bytes().unwrap();
let dev = || Unlock::Material(FactorKind::Device, &DEVICE);
assert!(open(&bytes2, Unlock::Password(&pw("New9-Password4")), dev()).is_ok());
assert!(matches!(open(&bytes2, Unlock::Password(&pw("Orbit7-Fable3")), dev()), Err(Error::WrongPassword)));
// The vault key and the pair slots stayed: same key before and after.
let before = open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), dev()).unwrap();
let after = open(&bytes2, Unlock::Password(&pw("New9-Password4")), dev()).unwrap();
assert!(before.same_key_as(&after));
}
#[test]
fn a_v1_vault_upgrades_and_its_password_alone_stops_working() {
let p = pw("Orbit7-Fable3");
let mut v1 = Vault::create(&p, FAST).unwrap();
v1.add(Item::new(ItemType::SecureNote, "note", 1));
let old = v1.to_bytes().unwrap();
assert_eq!(Vault::version_of(&old).unwrap(), 1);
let mut v = Vault::open(&old, &p).unwrap();
v.upgrade_to_two_factors(&p, FAST, Unlock::Material(FactorKind::Device, &DEVICE), "MARK-PC").unwrap();
let new = v.to_bytes().unwrap();
assert_eq!(Vault::version_of(&new).unwrap(), 2);
assert_eq!(Vault::factor_kinds(&new).unwrap(), [FactorKind::Password, FactorKind::Device]);
// The header names each factor by the id the unlocked vault lists; a v1 file has none.
let ids = Vault::factor_ids(&new).unwrap();
let listed: Vec<(String, FactorKind)> = v.factors().into_iter().map(|f| (f.id, f.kind)).collect();
assert_eq!(ids, listed);
assert!(Vault::factor_ids(&old).unwrap().is_empty());
assert!(matches!(Vault::open(&new, &p), Err(Error::NeedTwoFactors)));
let back = open(&new, Unlock::Password(&p), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
assert_eq!(back.items().len(), 1);
assert!(back.same_key_as(&v1));
}
#[test]
fn flipping_any_header_byte_fails() {
let bytes = two_factor_vault().to_bytes().unwrap();
let header_len = bytes.len() - 16 - 30; // well inside the header + body; every byte is checked below
for i in 0..header_len {
let mut t = bytes.clone();
t[i] ^= 0x01;
let r = open(&t, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &DEVICE));
assert!(r.is_err(), "byte {i} flipped and the vault still opened");
}
}
#[test]
fn a_machine_store_opens_with_its_device_key_alone() {
const STORE: [u8; 32] = [42; 32];
let mut s = Vault::create_machine_store(&STORE, "Claude Code store").unwrap();
s.add(Item::new(ItemType::ApiCredential, "deploy key", 1));
let bytes = s.to_bytes().unwrap();
assert!(Vault::is_machine_store(&bytes).unwrap());
assert_eq!(Vault::open_machine_store(&bytes, &STORE).unwrap().items().len(), 1);
assert!(matches!(Vault::open_machine_store(&bytes, &[43; 32]), Err(Error::FactorRejected)));
// A user vault is never opened as a machine store, nor a store as a user vault.
let user = two_factor_vault().to_bytes().unwrap();
assert!(!Vault::is_machine_store(&user).unwrap());
assert!(matches!(Vault::open_machine_store(&user, &DEVICE), Err(Error::NeedTwoFactors)));
assert!(Vault::open_with(&bytes, Unlock::Material(FactorKind::Device, &STORE), Unlock::Material(FactorKind::Device, &STORE)).is_err());
}
#[test]
fn limits_are_enforced() {
let mut v = two_factor_vault();
for i in 0..6u8 {
v.add_factor(Unlock::Material(FactorKind::Device, &[100 + i; 32]), "extra").unwrap();
}
assert_eq!(v.factors().len(), 8);
assert!(matches!(v.add_factor(Unlock::Material(FactorKind::Device, &[1; 32]), "ninth"), Err(Error::TooManyFactors)));
// Every pair still opens with 8 factors (8 factor slots + 28 pair slots).
let bytes = v.to_bytes().unwrap();
assert!(open(&bytes, Unlock::Material(FactorKind::Device, &[100; 32]), Unlock::Material(FactorKind::Device, &[105; 32])).is_ok());
}
#[test]
fn no_factor_material_in_debug_output() {
let secret = [0xAB; 32];
let u = Unlock::Material(FactorKind::Device, &secret);
let p = pw("Orbit7-Fable3");
let printed = format!("{u:?} {:?}", Unlock::Password(&p));
assert!(!printed.contains("171") && !printed.to_lowercase().contains("ab, ab") && !printed.contains("Orbit7"), "{printed}");
let v = two_factor_vault();
let printed = format!("{v:?} {:?}", v.factors());
for f in v.factors() {
assert!(!printed.contains(&f.id[..8]) || !printed.contains("key"), "{printed}");
}
assert!(!printed.contains("0707070707"));
}
#[test]
fn the_key_pair_item_type_round_trips() {
let mut v = two_factor_vault();
let mut k = Item::new(ItemType::KeyPair, "deploy@home", 5);
k.set("algorithm", "ed25519", 5);
k.set("private-key", "-----BEGIN PRIVATE KEY-----\n…", 5);
v.add(k);
let bytes = v.to_bytes().unwrap();
let back = open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
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");
}
+28 -1
View File
@@ -104,8 +104,11 @@ fn tampered_kdf_params_are_refused_before_argon2_runs() {
fn not_a_vault_and_future_versions_are_refused() { fn not_a_vault_and_future_versions_are_refused() {
assert!(matches!(Vault::open(b"hello world, not a vault at all", &pw("x")), Err(Error::NotAVault))); assert!(matches!(Vault::open(b"hello world, not a vault at all", &pw("x")), Err(Error::NotAVault)));
let mut bytes = sample_vault("pw").to_bytes().unwrap(); let mut bytes = sample_vault("pw").to_bytes().unwrap();
// Version 2 exists now (docs/FACTORS.md); a v1 file relabelled as 2 is malformed, 3 is unknown.
bytes[6] = 2; bytes[6] = 2;
assert!(matches!(Vault::open(&bytes, &pw("pw")), Err(Error::UnsupportedVersion(2)))); assert!(matches!(Vault::open(&bytes, &pw("pw")), Err(Error::Malformed)));
bytes[6] = 3;
assert!(matches!(Vault::open(&bytes, &pw("pw")), Err(Error::UnsupportedVersion(3))));
} }
fn opens_with(path: &Path, password: &str, title: &str) -> bool { fn opens_with(path: &Path, password: &str, title: &str) -> bool {
@@ -202,3 +205,27 @@ fn no_secret_in_debug_or_display() {
// Non-secret fields stay readable in Debug, which is what makes it useful. // Non-secret fields stay readable in Debug, which is what makes it useful.
assert!(format!("{item:?}").contains("Example")); assert!(format!("{item:?}").contains("Example"));
} }
#[test]
fn device_wrap_opens_the_same_vault_and_nothing_else() {
// Windows Hello gives the desktop app a signature; the core turns it into a key wrap.
let v = sample_vault("pw");
let bytes = v.to_bytes().unwrap();
let material = b"signature bytes from the device key";
let blob = v.wrap_for_device(material).unwrap();
assert_ne!(v.wrap_for_device(material).unwrap(), blob, "fresh salt and nonce each time");
let back = Vault::open_with_device(&bytes, &blob, material).unwrap();
assert_eq!(back.items(), v.items());
assert!(matches!(Vault::open_with_device(&bytes, &blob, b"other signature"), Err(Error::DeviceKeyRejected)));
for i in 0..blob.len() {
let mut t = blob.clone();
t[i] ^= 1;
assert!(Vault::open_with_device(&bytes, &t, material).is_err(), "blob byte {i}");
}
// A blob made for another vault does not open this one.
let other = sample_vault("pw").wrap_for_device(material).unwrap();
assert!(Vault::open_with_device(&bytes, &other, material).is_err());
assert!(!format!("{:?}", Error::DeviceKeyRejected).contains("signature"));
}
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "custos-wasm"
description = "Custos in the browser: the web vault's and the share page's crypto, compiled to WebAssembly"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
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
zeroize.workspace = true
qrcode = { version = "0.14", default-features = false, features = ["svg"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
getrandom = "0.4"
+46
View File
@@ -0,0 +1,46 @@
// The whole JavaScript side of custos-wasm (see src/lib.rs, "ABI"): load the module, give it the
// browser's CSPRNG, and pass JSON requests in and out. The vault key never leaves WebAssembly memory.
/** @param {BufferSource | Response | Promise<Response>} source the custos_wasm.wasm bytes or a fetch of them */
export async function loadCustos(source) {
let memory;
const env = {
random_fill(ptr, len) {
// getRandomValues fills at most 65,536 bytes per call.
for (let off = 0; off < len; off += 65536) {
crypto.getRandomValues(new Uint8Array(memory.buffer, ptr + off, Math.min(65536, len - off)));
}
},
};
const { instance } =
source instanceof Response || source instanceof Promise
? await WebAssembly.instantiateStreaming(source, { env })
: await WebAssembly.instantiate(source, { env });
const x = instance.exports;
memory = x.memory;
const enc = new TextEncoder();
const dec = new TextDecoder();
/** Sends one request; resolves to the parsed response ({ok: true, …} or {ok: false, error}). */
function call(request) {
const bytes = enc.encode(JSON.stringify(request));
const ptr = x.alloc(bytes.length);
new Uint8Array(memory.buffer, ptr, bytes.length).set(bytes);
bytes.fill(0);
const packed = x.call(ptr, bytes.length); // frees and zeroes the request
const outPtr = Number(packed >> 32n);
const outLen = Number(packed & 0xffffffffn);
const out = new Uint8Array(memory.buffer, outPtr, outLen);
const text = dec.decode(out);
x.dealloc(outPtr, outLen); // zeroes the response in WebAssembly memory
return JSON.parse(text);
}
return { call };
}
/** Base64 of bytes, for the `open` and `share_open` requests. */
export function toBase64(bytes) {
let s = '';
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
return btoa(s);
}
+32
View File
@@ -0,0 +1,32 @@
// node test.mjs <custos_wasm.wasm> [<vault file> <password>]: the JS loader against the real build.
import fs from 'node:fs';
import { loadCustos, toBase64 } from './custos.mjs';
const [wasmPath, vaultPath, password] = process.argv.slice(2);
const c = await loadCustos(fs.readFileSync(wasmPath));
const assert = (ok, msg) => { if (!ok) { console.error('FAIL', msg); process.exit(1); } };
const bad = c.call({ op: 'share_open', blob: 'Q1NIMQA=', fragment: 'k=x' });
assert(!bad.ok && bad.code === 'Malformed', JSON.stringify(bad));
assert(c.call({ op: 'items' }).error === 'The vault is locked.', 'locked');
if (vaultPath) {
const t0 = performance.now();
const r = c.call({ op: 'open', vault: toBase64(fs.readFileSync(vaultPath)), password });
const ms = Math.round(performance.now() - t0);
assert(r.ok, r.error);
console.log(`unlocked ${r.items.length} items in ${ms} ms (WebAssembly, default KDF)`);
const item = r.items.find((i) => i.hasMainSecret);
for (const pw of [null, 'by-phone']) {
const t1 = performance.now();
const s = c.call({ op: 'share_seal', id: item.id, password: pw });
assert(s.ok, s.error);
const o = c.call({ op: 'share_open', blob: s.blob, fragment: s.fragment, password: pw });
assert(o.ok && o.payload.title === item.title, JSON.stringify(o.error));
console.log(`share ${pw ? 'with' : 'without'} password: sealed and opened in ${Math.round(performance.now() - t1)} ms`);
}
const fresh = new Set(Array.from({ length: 100 }, () => c.call({ op: 'share_seal', id: item.id }).fragment));
assert(fresh.size === 100, 'link keys repeat: random_fill is broken');
c.call({ op: 'lock' });
}
console.log('ok');
+514
View File
@@ -0,0 +1,514 @@
//! Custos in the browser. The web vault and the share recipient page load this crate compiled to
//! `wasm32-unknown-unknown`; everything that touches a key or plaintext happens here, in code from this
//! public repository. The page's JavaScript only moves JSON in and out.
//!
//! # ABI (no wasm-bindgen)
//! Exports:
//! - `memory`
//! - `alloc(len) -> ptr` and `dealloc(ptr, len)`; `dealloc` zeroes the bytes before freeing them.
//! - `call(ptr, len) -> u64`: takes a JSON request the caller wrote into an `alloc`ed buffer (and frees it,
//! zeroed), returns `(response_ptr << 32) | response_len`. The caller reads the JSON response and gives it
//! back with `dealloc`.
//!
//! Import: `env.random_fill(ptr, len)`, which must fill the bytes from `crypto.getRandomValues`
//! (getrandom's custom backend; `.cargo/config.toml` selects it for this target).
//!
//! 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::{FactorKind, Item, ItemType, SecretString, Unlock, Vault};
use data_encoding::BASE64;
use qrcode::render::svg;
use qrcode::{EcLevel, QrCode};
use serde::Deserialize;
use serde_json::{Value, json};
use std::cell::RefCell;
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)]
#[serde(tag = "op", rename_all = "snake_case", rename_all_fields = "camelCase")]
enum Request {
/// `vault`: the `.custos` file, base64.
Open {
vault: String,
password: SecretString,
},
Lock,
Items,
/// A field's value by name and index among fields of that name, or `name: "notes"`.
Reveal {
id: String,
name: String,
#[serde(default)]
index: usize,
},
/// `now`: Unix seconds (WebAssembly has no clock of its own).
Totp {
id: String,
now: u64,
},
/// A Wi-Fi item gives its join code, anything else its main secret.
Qr {
id: String,
},
ShareSeal {
id: String,
password: Option<SecretString>,
},
/// `blob`: base64, as the share server returned it.
ShareOpen {
blob: String,
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 {
json!({ "ok": false, "error": msg.to_string() })
}
/// The field *Copy* and the QR code use for each type (the desktop app's choice).
pub fn primary_secret(kind: ItemType) -> &'static str {
match kind {
ItemType::WebLogin | ItemType::LocalApp | ItemType::Wifi => "password",
ItemType::ApiCredential => "secret",
ItemType::Card => "number",
ItemType::SecureNote => "notes",
ItemType::KeyPair => "private-key",
}
}
fn primary_user(kind: ItemType) -> Option<&'static str> {
match kind {
ItemType::WebLogin | ItemType::LocalApp => Some("username"),
ItemType::ApiCredential => Some("key-id"),
ItemType::Wifi => Some("ssid"),
ItemType::Card => Some("cardholder"),
ItemType::SecureNote => None,
ItemType::KeyPair => Some("public-key"),
}
}
fn plain<'a>(item: &'a Item, name: &str) -> Option<&'a str> {
item.field(name).filter(|f| !f.secret).map(|f| f.value.expose()).filter(|v| !v.is_empty())
}
fn value<'a>(item: &'a Item, name: &str, index: usize) -> Option<&'a SecretString> {
if name == "notes" {
return Some(&item.notes);
}
item.fields.iter().filter(|f| f.name == name).nth(index).map(|f| &f.value)
}
/// An item for the page: non-secret field values, secret ones only as "has a value".
fn view(item: &Item) -> Value {
let urls: Vec<&str> =
item.fields.iter().filter(|f| f.name == "url" && !f.value.is_empty()).map(|f| f.value.expose()).collect();
let subtitle = primary_user(item.kind)
.and_then(|n| plain(item, n))
.or(plain(item, "service"))
.or(plain(item, "target"))
.or(urls.first().copied())
.unwrap_or("");
let mut seen = std::collections::HashMap::<&str, usize>::new();
let fields: Vec<Value> = item
.fields
.iter()
.map(|f| {
let n = seen.entry(f.name.as_str()).or_default();
let index = *n;
*n += 1;
json!({
"name": f.name,
"index": index,
"secret": f.secret,
"hasValue": !f.value.is_empty(),
"value": if f.secret { Value::Null } else { Value::from(f.value.expose()) },
})
})
.collect();
let main = primary_secret(item.kind);
json!({
"id": item.id,
"kind": item.kind,
"title": item.title,
"subtitle": subtitle,
"urls": urls,
"tags": item.tags,
"fields": fields,
"hasNotes": !item.notes.is_empty(),
"mainSecret": main,
"hasMainSecret": value(item, main, 0).is_some_and(|v| !v.is_empty()),
"hasTotp": item.field("totp").is_some_and(|f| !f.value.is_empty()),
"modified": item.modified,
})
}
fn items(v: &Vault) -> Value {
json!({ "ok": true, "items": v.items().iter().map(view).collect::<Vec<_>>() })
}
fn with_item(id: &str, f: impl FnOnce(&Item) -> Value) -> Value {
VAULT.with_borrow(|v| match v {
None => err("The vault is locked."),
Some(v) => match v.item(id) {
None => err("Item not found."),
Some(item) => f(item),
},
})
}
fn qr_svg(payload: &str) -> Result<String, String> {
let code = QrCode::with_error_correction_level(payload.as_bytes(), EcLevel::M).map_err(|e| e.to_string())?;
Ok(code.render::<svg::Color>().min_dimensions(320, 320).quiet_zone(true).build())
}
fn payload_json(p: &Payload) -> Value {
json!({
"title": p.title,
"kind": p.kind,
"fields": p.fields.iter().map(|f| json!({ "name": f.name, "value": f.value.expose(), "secret": f.secret })).collect::<Vec<_>>(),
"notes": p.notes.as_ref().map(|n| n.expose()),
})
}
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:?}") })
}
/// Handles one request. Native code (and the tests) call this directly; the browser goes through `call`.
pub fn handle(request: &[u8]) -> Value {
let req: Request = match serde_json::from_slice(request) {
Ok(r) => r,
// serde's message can quote the input, which may hold a password: say only what failed.
Err(_) => return err("Bad request."),
};
match req {
Request::Open { vault, password } => {
let Ok(bytes) = BASE64.decode(vault.as_bytes()) else { return err("The vault file is damaged.") };
match Vault::open(&bytes, &password) {
Ok(v) => {
let out = items(&v);
VAULT.set(Some(v));
out
}
Err(e) => err(e),
}
}
Request::Lock => {
VAULT.set(None);
json!({ "ok": true })
}
Request::Items => VAULT.with_borrow(|v| v.as_ref().map(items).unwrap_or_else(|| err("The vault is locked."))),
Request::Reveal { id, name, index } => with_item(&id, |item| match value(item, &name, index) {
Some(v) => json!({ "ok": true, "value": v.expose() }),
None => err("No such field."),
}),
Request::Totp { id, now } => with_item(&id, |item| {
let Some(f) = item.field("totp").filter(|f| !f.value.is_empty()) else { return err("No 2FA code here.") };
match custos_totp::Totp::parse(f.value.expose()) {
Ok(t) => {
json!({ "ok": true, "code": t.code_at(now), "secondsLeft": t.seconds_left(now), "period": t.period() })
}
Err(e) => err(e),
}
}),
Request::Qr { id } => with_item(&id, |item| {
let f = |n: &str| item.field(n).map(|f| f.value.expose()).unwrap_or("");
let (payload, wifi) = if item.kind == ItemType::Wifi {
let p = custos_qr::wifi_payload(
f("ssid"),
f("password"),
custos_qr::WifiSecurity::parse(f("security")),
f("hidden") == "true",
);
(Zeroizing::new(p), true)
} else {
match value(item, primary_secret(item.kind), 0).filter(|v| !v.is_empty()) {
Some(v) => (Zeroizing::new(custos_qr::secret_payload(v.expose())), false),
None => return err("Nothing to show."),
}
};
match qr_svg(&payload) {
Ok(svg) => json!({ "ok": true, "svg": svg, "wifi": wifi }),
Err(e) => err(e),
}
}),
Request::ShareSeal { id, password } => with_item(&id, |item| {
let password = password.filter(|p| !p.is_empty());
match custos_share::seal(&Payload::from_item(item), password.as_ref()) {
Ok(s) => json!({ "ok": true, "blob": BASE64.encode(&s.blob), "fragment": s.fragment.as_str() }),
Err(e) => share_error(e),
}
}),
Request::ShareOpen { blob, fragment, password } => {
let Ok(bytes) = BASE64.decode(blob.as_bytes()) else { return share_error(ShareError::Malformed) };
match custos_share::open(&bytes, &fragment, password.as_ref()) {
Ok(p) => json!({ "ok": true, "payload": payload_json(&p) }),
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),
}
}
}
}
// ---------- the WebAssembly ABI ----------
#[cfg(target_arch = "wasm32")]
mod abi {
use std::alloc::{Layout, alloc as raw_alloc, dealloc as raw_dealloc};
use zeroize::Zeroize;
#[link(wasm_import_module = "env")]
unsafe extern "C" {
fn random_fill(ptr: *mut u8, len: usize);
}
/// getrandom's custom backend: the browser's CSPRNG.
#[unsafe(no_mangle)]
unsafe extern "Rust" fn __getrandom_v03_custom(dest: *mut u8, len: usize) -> Result<(), getrandom::Error> {
unsafe { random_fill(dest, len) };
Ok(())
}
#[unsafe(no_mangle)]
pub extern "C" fn alloc(len: usize) -> *mut u8 {
if len == 0 {
return std::ptr::NonNull::dangling().as_ptr();
}
unsafe { raw_alloc(Layout::from_size_align(len, 1).expect("layout")) }
}
/// # Safety
/// `ptr` and `len` must come from `alloc` or `call`, and be given back once.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn dealloc(ptr: *mut u8, len: usize) {
if len == 0 {
return;
}
unsafe {
std::slice::from_raw_parts_mut(ptr, len).zeroize();
raw_dealloc(ptr, Layout::from_size_align(len, 1).expect("layout"));
}
}
/// # Safety
/// `ptr`/`len` must be a buffer from `alloc` holding the request; `call` frees it.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn call(ptr: *mut u8, len: usize) -> u64 {
let response = {
let request = unsafe { std::slice::from_raw_parts(ptr, len) };
super::handle(request)
};
unsafe { dealloc(ptr, len) };
let mut bytes = serde_json::to_vec(&response).unwrap_or_else(|_| b"{\"ok\":false}".to_vec());
drop(response);
let out = alloc(bytes.len());
unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), out, bytes.len()) };
let packed = ((out as u64) << 32) | bytes.len() as u64;
bytes.zeroize();
packed
}
}
+112
View File
@@ -0,0 +1,112 @@
//! The JSON operations the browser calls, run natively.
use custos_vault::{Field, Item, ItemType, KdfParams, SecretString, 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())
}
fn vault_b64() -> (String, String, String) {
let mut v = Vault::create(&SecretString::from(PASSWORD), FAST).unwrap();
let mut login = Item::new(ItemType::WebLogin, "GitHub", 0);
login.set("username", "mark", 0);
login.set("password", SECRET, 0);
login.set("url", "https://github.com", 0);
login.set("totp", "JBSWY3DPEHPK3PXP", 0);
let login_id = login.id.clone();
let mut wifi = Item::new(ItemType::Wifi, "Home", 0);
wifi.set("ssid", "Domov", 0);
wifi.set("password", SECRET, 0);
wifi.set("security", "WPA", 0);
wifi.add_field(Field::text("note", "2.4 GHz"));
let wifi_id = wifi.id.clone();
v.add(login);
v.add(wifi);
(BASE64.encode(&v.to_bytes().unwrap()), login_id, wifi_id)
}
#[test]
fn open_list_reveal_lock() {
let (vault, login, _) = vault_b64();
let bad = call(json!({ "op": "open", "vault": vault, "password": "wrong" }));
assert_eq!(bad["ok"], false);
assert_eq!(bad["error"], "wrong password");
let r = call(json!({ "op": "open", "vault": vault, "password": PASSWORD }));
assert_eq!(r["ok"], true, "{r}");
let text = r.to_string();
assert!(!text.contains(SECRET) && !text.contains("JBSWY3DP"), "the list holds no secret values");
let items = r["items"].as_array().unwrap();
assert_eq!(items.len(), 2);
let gh = items.iter().find(|i| i["id"] == login.as_str()).unwrap();
assert_eq!(
(gh["subtitle"].as_str(), gh["hasTotp"].as_bool(), gh["mainSecret"].as_str()),
(Some("mark"), Some(true), Some("password"))
);
let rv = call(json!({ "op": "reveal", "id": login, "name": "password" }));
assert_eq!(rv["value"], SECRET);
assert_eq!(call(json!({ "op": "reveal", "id": login, "name": "password", "index": 1 }))["ok"], false);
assert_eq!(call(json!({ "op": "lock" }))["ok"], true);
let locked = call(json!({ "op": "reveal", "id": login, "name": "password" }));
assert_eq!(locked["error"], "The vault is locked.");
assert_eq!(call(json!({ "op": "items" }))["ok"], false);
}
#[test]
fn totp_and_qr() {
let (vault, login, wifi) = vault_b64();
call(json!({ "op": "open", "vault": vault, "password": PASSWORD }));
let now = 1_800_000_000u64;
let t = call(json!({ "op": "totp", "id": login, "now": now }));
let expected = custos_totp::Totp::parse("JBSWY3DPEHPK3PXP").unwrap();
assert_eq!(t["code"], expected.code_at(now));
assert_eq!(t["secondsLeft"], expected.seconds_left(now));
let q = call(json!({ "op": "qr", "id": wifi }));
assert_eq!((q["ok"].as_bool(), q["wifi"].as_bool()), (Some(true), Some(true)));
assert!(q["svg"].as_str().unwrap().starts_with("<?xml"));
let q = call(json!({ "op": "qr", "id": login }));
assert_eq!(q["wifi"], false);
}
#[test]
fn share_seal_and_open() {
let (vault, login, _) = vault_b64();
call(json!({ "op": "open", "vault": vault, "password": PASSWORD }));
for password in [None, Some("by-phone")] {
let s = call(json!({ "op": "share_seal", "id": login, "password": password }));
assert_eq!(s["ok"], true, "{s}");
let (blob, fragment) = (s["blob"].as_str().unwrap(), s["fragment"].as_str().unwrap());
assert!(!blob.contains(SECRET));
let o = call(json!({ "op": "share_open", "blob": blob, "fragment": fragment, "password": password }));
assert_eq!(o["ok"], true, "{o}");
let fields = o["payload"]["fields"].as_array().unwrap();
let names: Vec<_> = fields.iter().map(|f| f["name"].as_str().unwrap()).collect();
assert_eq!(names, ["username", "password", "url"], "no TOTP seed in a share");
assert_eq!(fields[1]["value"], SECRET);
if password.is_some() {
let w = call(json!({ "op": "share_open", "blob": blob, "fragment": fragment, "password": "nope" }));
assert_eq!(w["code"], "DecryptFailed");
let w = call(json!({ "op": "share_open", "blob": blob, "fragment": fragment }));
assert_eq!(w["code"], "PasswordRequired");
}
}
// An empty password means none.
let s = call(json!({ "op": "share_seal", "id": login, "password": "" }));
assert!(!s["fragment"].as_str().unwrap().contains("p=1"));
}
#[test]
fn bad_requests_never_echo_their_input() {
let r = custos_wasm::handle(br#"{"op":"open","vault":"x","password":"hunter2","extra":"#);
assert_eq!(r["error"], "Bad request.");
let r = call(json!({ "op": "share_open", "blob": "!!", "fragment": "k=hunter2" }));
assert!(!r.to_string().contains("hunter2"));
}
+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);
}
+147
View File
@@ -0,0 +1,147 @@
# Two factors: vault format version 2
A version-2 vault never opens with one secret. It opens with **any two of its factors**: the master
password, a key kept by one device, a share released by a TOTP check, a secret held by another device that
it releases after you approve, a passkey's PRF output. Each pair of factors wraps the vault key.
Version 1 (`docs/FORMAT.md`) stays readable. A v1 vault becomes v2 when a second factor is added; from then
on, Custos writes it as v2 only.
A **machine store** (the Claude Code store) is the one exception: a separate file whose vault key is
wrapped by one device key alone, so a program can open it unattended. It never holds the user's secrets.
## Keys
```
factor material ──KDF──► factor KEK ──unwraps──► factor key F (32 random bytes, one per factor)
F_a ‖ F_b ──HKDF-SHA256(salt = id_a ‖ id_b, info "custos pair v2")──► pair KEK ──unwraps──► vault key
```
- Every factor has a random 16-byte **id** and a random 32-byte **factor key** `F`. The factor's material
(the password, a device key, a released share…) only unwraps `F`.
- A **pair slot** for every pair of factors wraps the vault key with a key derived from both factor keys.
Two factors of the same vault always have a pair slot; one factor never unwraps the vault key by itself.
- The factor keys are also stored **inside the encrypted body**. An unlocked vault can therefore add a
factor (only the new factor's material is needed) or drop one, without the other factors present.
Changing the password rewraps the password factor's `F`; the pair slots stay as they are.
Factor KEKs:
| Type | Code | Material | KEK |
|:--|:--|:--|:--|
| password | 1 | the master password | Argon2id(password, salt, m, t, p), limits as in v1 |
| device | 2 | 32..=64 bytes the device keeps (a key file protected by Windows DPAPI, a key in the phone's storage) | HKDF-SHA256(material, salt, "custos factor v2") |
| totp | 3 | 32 bytes the TOTP service releases after a valid code | same |
| approval | 4 | 32 bytes another paired device sends after you approve there | same |
| passkey | 5 | a WebAuthn PRF output (32 bytes) | same |
The type only tells the app which material to ask for; the cryptography is the same for 2..5.
## Layout
The v1 layout with `version = 2`, up to 64 slots and these slot kinds (`docs/FORMAT.md`, "Layout"):
```
kind 2, factor slot
16 factor id
1 type 1..=5 (table above)
13 kdf type 1 only: kdf(1) = 1 (Argon2id), m_cost, t_cost, p_cost (u32 each)
32 salt
24 wrap nonce
48 wrapped F 32-byte factor key + 16-byte tag
AAD = magic ‖ version ‖ kind ‖ everything in the payload before the wrapped F
kind 3, pair slot
16 id a the smaller of the two ids (bytewise)
16 id b
24 wrap nonce
48 wrapped vault key
AAD = magic ‖ version ‖ kind ‖ id a ‖ id b ‖ nonce
kind 4, single slot (machine stores only)
16 factor id
24 wrap nonce
48 wrapped vault key KEK = HKDF-SHA256(F, salt = id, info "custos single v2")
AAD = magic ‖ version ‖ kind ‖ id ‖ nonce
```
Kind 1 (the v1 password slot) does not occur in a v2 file; a reader treats one as malformed. The body AAD
is the whole header, as in v1.
### Limits a reader enforces
- 1 ..= 64 slots; at most 8 factor slots; a factor type outside 1..=5 is malformed.
- A pair slot whose two ids are equal, or not in order, or name a factor that has no factor slot, is malformed.
- Argon2 limits as in v1, checked before any work.
- Material for types 2..5: 32 ..= 64 bytes, else `FactorRejected` before any work.
### Opening
The app passes two factors (a password, or a type and its material). For each one, the reader tries the
factor slots of that type; the first that unwraps gives `(id, F)`. With two distinct ids it opens their pair
slot, then the body.
| Situation | Error |
|:--|:--|
| Fewer than two different factors given, or two of the same factor | `NeedTwoFactors` |
| A given factor unwraps no factor slot of its type | `FactorRejected` (a wrong password says so: `WrongPassword`) |
| Both unwrap, but their pair slot is missing or fails | `Corrupted` |
| A machine store: its one device factor unwraps, then the single slot | — |
## Which factors a file has
`Vault::factor_ids(bytes)` reads the header alone and returns each factor's id and type. No key is needed,
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`:
```json
"factors": [
{ "id": "9f2c…(32 hex)", "type": "password", "label": "Master password", "created": 1793600000000, "key": "…(64 hex)" },
{ "id": "41aa…", "type": "device", "label": "MARK-PC", "created": 1793600000000, "key": "…" }
]
```
`key` is the factor key `F`. It is inside the body's encryption like every secret in the vault.
### The key-pair item type
`key-pair` (new in body format 2): `algorithm` (`ed25519`, `ecdsa-p256`, `rsa-3072`, `rsa-4096`),
`public-key` (OpenSSH line), `public-pem` (SPKI PEM), `private-key`* (PKCS#8 PEM), `private-openssh`* (OpenSSH
private key), `fingerprint` (SHA256:… as `ssh-keygen -l` prints it), `comment`.
## What it protects
- The vault file plus one factor opens nothing: a stolen password, a copied key file, a compromised TOTP
service or one lost phone each give one factor key, never the vault key.
- A device factor is only as private as the device: Windows DPAPI binds the key file to the Windows account
on that machine, so a copy of the file does not work elsewhere, but malware running as that account can
use it. That is one factor, which is why it is never enough alone.
- Losing a factor is not losing the vault: any other two open it, and the lost one can then be removed.
+24
View File
@@ -1,5 +1,7 @@
# The `.custos` vault file, format version 1 # The `.custos` vault file, format version 1
Version 2 (two factors, the machine store) is in `docs/FACTORS.md`; it reuses this layout.
One file holds one vault. Everything after the header is one XChaCha20-Poly1305 ciphertext. One file holds one vault. Everything after the header is one XChaCha20-Poly1305 ciphertext.
The header is not secret, but it is authenticated: changing any byte of it makes the body fail to open. The header is not secret, but it is authenticated: changing any byte of it makes the body fail to open.
All integers are little-endian. The code is `crates/custos-vault/src/format.rs`. All integers are little-endian. The code is `crates/custos-vault/src/format.rs`.
@@ -117,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. - `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). - `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. - 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) ### Item types and their fields (v1)
@@ -162,6 +166,22 @@ become *protected* strings.
| `created`, `modified` | `Times/CreationTime`, `Times/LastModificationTime` | | `created`, `modified` | `Times/CreationTime`, `Times/LastModificationTime` |
| `history` entries | `History` entries (one per change, with that old password) | | `history` entries | `History` entries (one per change, with that old password) |
## Device key wrap (not part of the file)
Quick unlock on one machine (the desktop app uses Windows Hello) keeps a separate 108-byte blob **on that
machine**, never in the vault file:
```
"CDW1" (4) ‖ salt (32) ‖ nonce (24) ‖ XChaCha20-Poly1305(KEK, vault key, aad = "CDW1" ‖ salt ‖ nonce) (48)
KEK = HKDF-SHA256(ikm = device material, salt, info = "custos device wrap v1")
```
The device material is something only that device can produce on request (for Windows Hello: the RSA
signature of a fixed challenge by a TPM-held key, which only Hello can unlock). A wrong material or a
changed blob gives `DeviceKeyRejected`; a blob from another vault unwraps a key that fails the body tag
(`Corrupted`). Changing the master password does not change the vault key, so the app deletes the blob
itself when the password changes.
## Saving ## Saving
`custos-vault::save_atomic` never leaves a half-written vault in place of the old one: `custos-vault::save_atomic` never leaves a half-written vault in place of the old one:
@@ -180,3 +200,7 @@ and an identical `.bak`. Leftover `.tmp` files are ignored and overwritten by th
A change that old readers would misread bumps `version`. Readers refuse versions they do not know rather A change that old readers would misread bumps `version`. Readers refuse versions they do not know rather
than guess. Adding JSON members or new slot kinds does not need a bump. than guess. Adding JSON members or new slot kinds does not need a bump.
## Share links
Shares are not vault files; their blob and link format is in `docs/SHARE.md`.
+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.
+61
View File
@@ -0,0 +1,61 @@
# Keys, API keys and key pairs
What `custos-gen` and `custos-keys` generate besides passwords. All randomness comes from the OS CSPRNG.
## Secret keys (`custos_gen::secret_key`)
16 ..= 128 random bytes (default 32 = 256 bits), written as lowercase hex, base64url without padding, or
standard base64 with padding. For symmetric keys, HMAC and JWT secrets, encryption passphrases for tools.
## API keys (`custos_gen::api_key`)
```
<prefix>_<32 base62 characters><6 base62 characters of checksum> e.g. domi_7Kq…Zx41aP0c
```
- `prefix`: empty, or a lowercase letter then up to 15 lowercase letters or digits. It says what the key is
for at a glance, and lets leak scanners find it. No prefix: the key starts with the 32 characters.
- 32 base62 characters: 190.5 bits, each character uniform (rejection sampling, no modulo bias).
- The checksum is CRC-32 (IEEE) of everything before it, in base62, padded to 6 characters. It catches typos
and lets a scanner tell a real key from random text. It is not a security feature.
## Key pairs (`custos_keys::generate`)
| Algorithm | Name in the item | Notes |
|:--|:--|:--|
| Ed25519 | `ed25519` | the default: SSH, signing, minisign-style tools |
| ECDSA P-256 | `ecdsa-p256` | where Ed25519 is not accepted (some cloud KMS, older hardware) |
| RSA 3072 / 4096 | `rsa-3072`, `rsa-4096` | for systems that accept nothing else; generation takes seconds |
Each gives:
- `public-key`: the OpenSSH public line (`ssh-ed25519 AAAA… comment`), for `authorized_keys`;
- `public-pem`: the SubjectPublicKeyInfo PEM;
- `private-key`*: the PKCS#8 PEM (unencrypted; the vault is its encryption);
- `private-openssh`*: the OpenSSH private key (unencrypted, same reason), for `ssh -i`;
- `fingerprint`: `SHA256:…`, exactly as `ssh-keygen -l` prints it.
The crates are RustCrypto's: `ssh-key`, `ed25519-dalek` (its Ed25519 backend), `p256`, `rsa`.
## Importing (`custos_keys::import`)
An existing private key becomes the same kind of item. Accepted formats:
| Input | Header | Algorithms |
|:--|:--|:--|
| OpenSSH private key | `BEGIN OPENSSH PRIVATE KEY` | Ed25519, ECDSA P-256, RSA |
| PKCS#8 | `BEGIN PRIVATE KEY` | Ed25519, ECDSA P-256, RSA |
| PKCS#1 | `BEGIN RSA PRIVATE KEY` | RSA |
| SEC1 | `BEGIN EC PRIVATE KEY` | ECDSA P-256 |
- **The public line, the PEMs and the fingerprint are derived from the private key**, never copied from the
input. A pasted public key therefore cannot disagree with its private key.
- **RSA:** 2048 to 4096 bits. An imported 2048-bit key is named `rsa-2048`; Custos never generates one.
- **A passphrase-protected key is refused** (`Encrypted`): OpenSSH with a cipher, `ENCRYPTED PRIVATE KEY`,
or PKCS#1 with `Proc-Type: 4,ENCRYPTED`. Remove the passphrase first (`ssh-keygen -p`); the vault is the
key's encryption.
- **Comment:** an OpenSSH key keeps its own comment; the other formats take the item's name.
- **Line ends:** CRLF and surrounding whitespace are accepted, as in a paste or a Windows file.
- **Errors never repeat the input.**
- **ssh-key 0.6.7 conversion bug:** its `TryFrom<&RsaKeypair> for rsa::RsaPrivateKey` uses `p` twice. Custos
rebuilds the key from `n, e, d, p, q` and validates it instead.
+62
View File
@@ -0,0 +1,62 @@
# Sealed boxes (`custos-seal`)
The two-factor services (`docs/FACTORS.md`, types 3 and 4) pass factor material through a mailbox on the
home server. The mailbox must never be able to read it. So the device that wants a secret makes a
**one-time X25519 key pair**, sends only the public half, and whoever releases the secret seals it to that
key. The same box carries a secret from the user's PC to a Claude Code cloud session.
## The box, version 1
```
sealed = "CSL1" ‖ E (32) ‖ nonce (24) ‖ XChaCha20-Poly1305(K, nonce, plaintext, aad)
E the sender's ephemeral X25519 public key (a fresh one per box)
R the recipient's one-time public key
K HKDF-SHA256(ikm = X25519(e, R), salt = E ‖ R, info = "custos seal v1" ‖ context)
aad "CSL1" ‖ E ‖ context
```
- **`context`** names the purpose, for example `approval:<factor id>:<request id>` or `cloud:<request id>`.
A box opens only with the context it was sealed for, so a box for one request does not work as another.
- **A low-order public key is refused** on both sides: the shared secret must be contributory.
- **Plaintext limit:** 32 KiB.
- **The recipient's secret half** lives only in memory, as `x25519_dalek::StaticSecret` with `zeroize`,
and is wiped on drop. Nothing writes it to disk.
## The match code
Six digits that the requesting screen and the approving screen both show:
```
match = u32_be(SHA-256("custos match v1" ‖ R)[0..4]) mod 1 000 000, zero-padded to 6 digits
```
If they differ, someone else's request is waiting: deny it. The code is not a secret. It only ties the
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
that is not in its state directory:
```
at rest = "CSR1" ‖ nonce (24) ‖ XChaCha20-Poly1305(HKDF-SHA256(key, salt = "", info = "custos rest v1" ‖ context),
nonce, plaintext, "CSR1" ‖ context)
```
What this protects: a leaked copy of `/var/lib/custos-factors` without the credential gives nothing.
What it does not protect: anyone who controls the running server. That is one factor, which is why a
factor is never enough alone.
## Crates
`x25519-dalek` 2 (dalek-cryptography, the X25519 sibling of the `ed25519-dalek` used for key pairs),
`chacha20poly1305`, `hkdf`, `sha2`, and `rand`'s `SysRng`.
+71
View File
@@ -0,0 +1,71 @@
# Private share links (`custos-share`), format version 1
A share link hands one secret to someone who has no Custos. The sender's app (desktop or web) encrypts it;
the share server stores only ciphertext; the key travels in the link's fragment, which browsers never send
to a server.
```
https://custos.example/s/<id>#k=<link key> no password
https://custos.example/s/<id>#k=<link key>&p=1 the recipient also needs a password, told separately
```
- `<id>`: chosen by the server (128 random bits, base64url, 22 characters). It is not secret.
- `<link key>`: 32 random bytes from the OS CSPRNG, base64url without padding (43 characters).
- `p=1` only tells the recipient page to ask for a password before it fetches anything. The blob's own
flag decides; a link with `p=1` removed still needs the password.
## Keys
```
no password: K = link key
with password: P = Argon2id(password (UTF-8), salt, m, t, p) → 32 bytes
K = HKDF-SHA256(salt = salt, ikm = link key ‖ P, info = "custos-share v1") → 32 bytes
```
Both the link and the password are needed; neither alone gives anything, and the server has neither.
Default share KDF: m = 19 MiB (19,456 KiB), t = 2, p = 1 (OWASP's Argon2id minimum; it runs in a phone
browser in about a second). It only has to slow down guessing by someone who already holds the link.
## Blob (what the server stores), all integers little-endian
| Offset | Size | Field |
|:--|:--|:--|
| 0 | 4 | magic `CSH1` |
| 4 | 1 | flags: bit 0 = password; other bits must be 0 |
| 5 | 28 | only if bit 0: `m_cost_kib` u32, `t_cost` u32, `p_cost` u32, salt (16 bytes) |
| … | 24 | nonce |
| … | rest | XChaCha20-Poly1305 ciphertext and 16-byte tag; AAD = every byte before it (magic to nonce) |
Limits a reader enforces before running Argon2: m from 8 MiB to 256 MiB, t from 1 to 16, p from 1 to 4.
A whole blob is at most 64 KiB.
## Plaintext
UTF-8 JSON, `{"v":1,"title":"…","kind":"web-login","fields":[{"name":"password","value":"…","secret":true}],"notes":"…"}`.
`kind` and `notes` may be missing. Built from an item by `Payload::from_item`, which leaves out empty
fields, the TOTP seed (sharing it would hand over the second factor too) and the auto-type settings.
## Errors (none contains secret material)
| Error | When | Says |
|:--|:--|:--|
| `Malformed` | wrong magic, too short, unknown flags, too large | not a Custos share |
| `BadLink` | fragment missing, not `k=` + 43 base64url characters | the link is incomplete |
| `PasswordRequired` | the blob has the password flag and no password was given | — |
| `UnsupportedKdf` | parameters outside the limits | — |
| `DecryptFailed` | the tag does not verify: wrong key, wrong password, or any byte changed | never garbage: nothing is returned |
A wrong password and a tampered blob give the same `DecryptFailed`; the page says "wrong password, or the
link or share is damaged".
## Server rules (the private app's share service implements them)
- Stores the blob, an expiry (1 hour, 1 day or 7 days; default 1 day) and a view count (default 1).
- `open` returns the blob and counts one view; the last view deletes it. Expired, used up and unknown ids
answer the same 404.
- Logs only the id, the time and the status code. Never a body, never a full URL.
## The browser build (`custos-wasm`)
The web vault and the recipient page run this repository's code compiled to `wasm32-unknown-unknown`,
with no wasm-bindgen: a JSON-in/JSON-out `call` export and a `random_fill` import backed by
`crypto.getRandomValues` (getrandom's custom backend). The ABI is documented in `crates/custos-wasm/src/lib.rs`.
+30
View File
@@ -14,8 +14,12 @@ just as plainly, what it does not.
| Attacker | Has | Gets | Why | | Attacker | Has | Gets | Why |
|:--|:--|:--|:--| |:--|:--|:--|:--|
| Thief or sync server | The `.custos` file (any number of old versions) | Item count and sizes roughly (the ciphertext length), the KDF parameters. Nothing else. | XChaCha20-Poly1305 over the whole body; titles, URLs and usernames are inside it too. | | Thief or sync server | The `.custos` file (any number of old versions) | Item count and sizes roughly (the ciphertext length), the KDF parameters. Nothing else. | XChaCha20-Poly1305 over the whole body; titles, URLs and usernames are inside it too. |
| Thief with one factor (v2) | The file plus the master password, or a copied key file, or a lost phone | Nothing | A version-2 vault opens only with two different factors (docs/FACTORS.md); one factor unwraps one factor key, never the vault key. |
| Offline guesser | The file and a GPU farm | One Argon2id evaluation (64 MiB, 20 passes by default, ≈ 0.75 s on a desktop CPU) per guess | A 4-word memorable password with digits (~65 bits) is out of reach; a weak master password is not. **The master password is the whole defence here.** | | Offline guesser | The file and a GPU farm | One Argon2id evaluation (64 MiB, 20 passes by default, ≈ 0.75 s on a desktop CPU) per guess | A 4-word memorable password with digits (~65 bits) is out of reach; a weak master password is not. **The master password is the whole defence here.** |
| Tamperer | Write access to the file | Can destroy it, or roll it back to an older version they saw. Cannot change, reorder, add or remove items unnoticed. | The header is the body's AAD; each slot's parameters are its wrap's AAD. | | Tamperer | Write access to the file | Can destroy it, or roll it back to an older version they saw. Cannot change, reorder, add or remove items unnoticed. | The header is the body's AAD; each slot's parameters are its wrap's AAD. |
| Share server operator | Every share blob, its id, size, expiry, view count, the uploader's login and the recipients' IP addresses | Nothing of the secret | The key is in the link's `#fragment`, which browsers never send; the server stores ciphertext only (docs/SHARE.md). |
| Someone who gets a share link | The link (chat history, a forwarded mail) | The secret, if the share still has views left; with a password share, also one Argon2id evaluation (19 MiB) per password guess | That is what a link is. Use 1 view (the default): once it is opened, it is gone, and the sender learns about interception when the recipient finds it used. |
| Link-preview bot | The link, fetched by a chat app | Nothing; the view is not used | The page asks for a click on *Reveal* before it fetches the share. |
| Someone who crashes the machine mid-save | — | Nothing | Atomic save: temp file, fsync, rename; the previous version is kept as `.bak`. | | Someone who crashes the machine mid-save | — | Nothing | Atomic save: temp file, fsync, rename; the previous version is kept as `.bak`. |
## What is NOT protected ## What is NOT protected
@@ -31,6 +35,13 @@ just as plainly, what it does not.
desktop app), and by any clipboard manager that ignores the "exclude from history" marker. desktop app), and by any clipboard manager that ignores the "exclude from history" marker.
- **Auto-type** sends keystrokes to whatever window has focus. The app re-checks the target window before - **Auto-type** sends keystrokes to whatever window has focus. The app re-checks the target window before
typing, but a window that steals focus at the wrong moment can receive them. typing, but a window that steals focus at the wrong moment can receive them.
- **A device factor (v2) on its own device.** The key file is bound to one Windows account by DPAPI; malware
running as that account can use it. That is one factor, and a v2 vault never opens with one.
- **The machine store** (the Claude Code store) opens with its device key alone, by design: anything running as
the user can open it. It must hold only what that program generated, never the user's own secrets.
- **Device unlock (Windows Hello, version 1 only).** The blob on disk is only as strong as the device key behind it: anyone
who can make Windows Hello sign as you on that machine (your PIN, your face, or malware running while
you approve a prompt) can unlock the vault there. It does not help an attacker who has only the vault file.
- **Rollback.** Someone with write access to the synced file can replace it with an older version. - **Rollback.** Someone with write access to the synced file can replace it with an older version.
Custos does not detect that (there is no trusted counter to compare against). Custos does not detect that (there is no trusted counter to compare against).
- **Shoulder surfing and QR codes.** A revealed password or a shown QR code is readable by anyone who - **Shoulder surfing and QR codes.** A revealed password or a shown QR code is readable by anyone who
@@ -38,6 +49,25 @@ just as plainly, what it does not.
- **Metadata.** File size and modification times reveal roughly how much is stored and when it changed. - **Metadata.** File size and modification times reveal roughly how much is stored and when it changed.
- **Side channels.** No effort beyond what the RustCrypto crates provide (constant-time tag comparison). - **Side channels.** No effort beyond what the RustCrypto crates provide (constant-time tag comparison).
- **The web vault trusts the server that serves its code.** In the browser, the page, its JavaScript and the
WebAssembly come from the home server on every visit. Whoever controls that server (or its TLS
certificate) can serve a modified page that sends the master password away the next time someone unlocks
in the browser. The desktop app does not have this problem. Authelia keeps strangers out; it does not
protect against the server itself. The same holds for the share page and the recipient.
- **Browser memory.** In the web vault the key and the decrypted items live in WebAssembly memory, and a
revealed or copied value passes through JavaScript strings, which cannot be wiped. Lock (or close the tab)
when done.
- **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.
## Design rules that follow from this ## Design rules that follow from this
- No custom cryptography: Argon2id (`argon2`), XChaCha20-Poly1305 (`chacha20poly1305`), the OS CSPRNG - No custom cryptography: Argon2id (`argon2`), XChaCha20-Poly1305 (`chacha20poly1305`), the OS CSPRNG