From 4daffdff73cd8a5f59a7dcb24bccbf6685cd780b Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 2 Nov 2026 15:39:47 +0100 Subject: [PATCH 1/5] [docs] Factors: format version 2, any two of password, device, TOTP, approval, passkey; machine store --- docs/FACTORS.md | 118 ++++++++++++++++++++++++++++++++++++++++++++++++ docs/FORMAT.md | 2 + 2 files changed, 120 insertions(+) create mode 100644 docs/FACTORS.md diff --git a/docs/FACTORS.md b/docs/FACTORS.md new file mode 100644 index 0000000..aef7ba2 --- /dev/null +++ b/docs/FACTORS.md @@ -0,0 +1,118 @@ +# 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 | — | + +## 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. diff --git a/docs/FORMAT.md b/docs/FORMAT.md index 1dc905d..f9818f2 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -1,5 +1,7 @@ # 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. 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`. From df6565941e7017e343f636fd1dc8734dece8a7c3 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 2 Nov 2026 15:45:54 +0100 Subject: [PATCH 2/5] [vault] Tests: any two factors, never one; factors added and removed alone; v1 upgrade; tamper; machine store --- crates/custos-vault/tests/factors.rs | 208 +++++++++++++++++++++++++ crates/custos-vault/tests/mandatory.rs | 5 +- 2 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 crates/custos-vault/tests/factors.rs diff --git a/crates/custos-vault/tests/factors.rs b/crates/custos-vault/tests/factors.rs new file mode 100644 index 0000000..34afbd1 --- /dev/null +++ b/crates/custos-vault/tests/factors.rs @@ -0,0 +1,208 @@ +//! 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::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]); + 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)); +} diff --git a/crates/custos-vault/tests/mandatory.rs b/crates/custos-vault/tests/mandatory.rs index 78490c2..d97896e 100644 --- a/crates/custos-vault/tests/mandatory.rs +++ b/crates/custos-vault/tests/mandatory.rs @@ -104,8 +104,11 @@ fn tampered_kdf_params_are_refused_before_argon2_runs() { 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))); 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; - 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 { From 02c6795f53fd915b0553040aa421ae2de7441676 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 2 Nov 2026 15:45:55 +0100 Subject: [PATCH 3/5] [vault] Format v2: factor, pair and single slots; open_with any two factors; upgrade from v1; key-pair item type --- crates/custos-vault/src/crypto.rs | 7 + crates/custos-vault/src/format.rs | 253 ++++++++++++++- crates/custos-vault/src/item.rs | 15 +- crates/custos-vault/src/lib.rs | 515 ++++++++++++++++++++++++++++-- crates/custos-wasm/src/lib.rs | 2 + 5 files changed, 753 insertions(+), 39 deletions(-) diff --git a/crates/custos-vault/src/crypto.rs b/crates/custos-vault/src/crypto.rs index e817b2e..6c9fb93 100644 --- a/crates/custos-vault/src/crypto.rs +++ b/crates/custos-vault/src/crypto.rs @@ -55,6 +55,13 @@ pub fn seal(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], plaintext: &[u8], aad: &[u .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::::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. pub fn open(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], ciphertext: &[u8], aad: &[u8]) -> Option>> { cipher(key).decrypt(&nonce(n), Payload { msg: ciphertext, aad }).ok().map(Zeroizing::new) diff --git a/crates/custos-vault/src/format.rs b/crates/custos-vault/src/format.rs index 0952a82..cea9a0e 100644 --- a/crates/custos-vault/src/format.rs +++ b/crates/custos-vault/src/format.rs @@ -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::{Error, KdfParams}; pub const MAGIC: &[u8; 6] = b"CUSTOS"; 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_V2: usize = 64; +pub const MAX_FACTORS: usize = 8; 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; 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. const PW_AAD_LEN: usize = 1 + 12 + SALT_LEN + NONCE_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)] pub struct RawSlot { pub kind: u8, @@ -73,7 +83,169 @@ impl PasswordSlot { } } +fn v2_aad(kind: u8, head: &[u8]) -> Vec { + 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, + pub salt: [u8; SALT_LEN], + pub nonce: [u8; NONCE_LEN], + pub wrapped: Vec, +} + +impl FactorSlot { + fn head(&self) -> Vec { + 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 { + 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 { + 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, +} + +impl PairSlot { + pub fn aad(&self) -> Vec { + 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 { + 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, +} + +impl SingleSlot { + pub fn aad(&self) -> Vec { + 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 { + 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 version: u16, pub slots: Vec, pub body_nonce: [u8; NONCE_LEN], } @@ -82,7 +254,7 @@ impl Header { pub fn to_bytes(&self) -> Vec { let mut h = Vec::new(); 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); for s in &self.slots { h.push(s.kind); @@ -99,11 +271,13 @@ impl Header { return Err(Error::NotAVault); } let version = u16::from_le_bytes([bytes[6], bytes[7]]); - if version != VERSION { - return Err(Error::UnsupportedVersion(version)); - } + let max = match version { + VERSION => MAX_SLOTS, + VERSION_2 => MAX_SLOTS_V2, + v => return Err(Error::UnsupportedVersion(v)), + }; let count = bytes[8] as usize; - if count == 0 || count > MAX_SLOTS { + if count == 0 || count > max { return Err(Error::Malformed); } let mut at = 9; @@ -120,6 +294,69 @@ impl Header { if bytes.len() < at + TAG_LEN { 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 { + self.slots.iter().filter(|s| s.kind == SLOT_FACTOR).filter_map(|s| FactorSlot::parse(&s.payload).ok()).collect() + } + + pub fn pair_slots(&self) -> Vec { + self.slots.iter().filter(|s| s.kind == SLOT_PAIR).filter_map(|s| PairSlot::parse(&s.payload).ok()).collect() + } + + pub fn single_slot(&self) -> Option { + 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) } } diff --git a/crates/custos-vault/src/item.rs b/crates/custos-vault/src/item.rs index e009a62..0851ee7 100644 --- a/crates/custos-vault/src/item.rs +++ b/crates/custos-vault/src/item.rs @@ -16,16 +16,19 @@ pub enum ItemType { Wifi, SecureNote, Card, + /// A signing or SSH key pair (docs/FACTORS.md, "The key-pair item type"). + KeyPair, } impl ItemType { - pub const ALL: [ItemType; 6] = [ + pub const ALL: [ItemType; 7] = [ ItemType::WebLogin, ItemType::ApiCredential, ItemType::LocalApp, ItemType::Wifi, ItemType::SecureNote, ItemType::Card, + ItemType::KeyPair, ]; pub fn label(self) -> &'static str { @@ -36,6 +39,7 @@ impl ItemType { ItemType::Wifi => "Wi-Fi", ItemType::SecureNote => "Secure note", ItemType::Card => "Card", + ItemType::KeyPair => "Key pair", } } @@ -59,6 +63,15 @@ impl ItemType { ItemType::Card => { &[("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), + ], } } } diff --git a/crates/custos-vault/src/lib.rs b/crates/custos-vault/src/lib.rs index d4ab090..bba2b7f 100644 --- a/crates/custos-vault/src/lib.rs +++ b/crates/custos-vault/src/lib.rs @@ -1,13 +1,18 @@ -//! 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 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 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())); //! 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>(()) //! ``` @@ -23,7 +28,10 @@ pub use save::{CrashPoint, save_atomic, save_atomic_crashing}; pub use secret::SecretString; 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 std::fmt; use std::path::Path; @@ -45,6 +53,12 @@ pub enum Error { 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("a vault has at most 8 factors and one master password")] + TooManyFactors, #[error("{0}")] Io(#[from] std::io::Error), } @@ -80,12 +94,160 @@ 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 { + 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(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 { + 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_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)] struct Body { format: u32, items: Vec, + #[serde(default)] + factors: Vec, } /// What `to_bytes` serializes: borrows the items instead of cloning every secret. @@ -93,18 +255,29 @@ struct Body { struct BodyRef<'a> { format: u32, items: &'a [Item], + #[serde(skip_serializing_if = "Vec::is_empty")] + factors: Vec, } /// An unlocked vault: the vault key and the decrypted items, both wiped on drop. pub struct Vault { key: Zeroizing<[u8; KEY_LEN]>, + version: u16, slots: Vec, items: Vec, + /// Version 2 only. + factors: Vec, + /// Argon2 parameters for a password factor added later. + kdf_new: KdfParams, } impl fmt::Debug for Vault { 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()) + .finish_non_exhaustive() } } @@ -118,21 +291,127 @@ fn password_slot(key: &[u8; KEY_LEN], password: &SecretString, kdf: KdfParams) - Ok(slot) } +/// The KEK a factor's material gives for one factor slot. +fn factor_kek(u: &Unlock, salt: &[u8], kdf: Option) -> Result, 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 { + 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>) -> Result, 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 { + 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 { - /// 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 { let key = crypto::random_key(); 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 }) + } + + /// 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 { + 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, + }; + 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 { + 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, + }) } pub fn open_file(path: &Path, password: &SecretString) -> Result { 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 { let (header, body_at) = Header::parse(bytes)?; + if header.version == VERSION_2 { + return Err(Error::NeedTwoFactors); + } let pw_slots: Vec = header .slots .iter() @@ -145,34 +424,104 @@ impl Vault { for slot in &pw_slots { 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()) { - let key: Zeroizing<[u8; KEY_LEN]> = - Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::Malformed)?); - return Vault::open_body(bytes, header, body_at, key); + let kdf = slot.kdf; + let mut v = Vault::open_body(bytes, header, body_at, key32(k)?)?; + v.kdf_new = kdf; + return Ok(v); } } 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 { + 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) }; + let slot = header.pair_slots().into_iter().find(|p| p.a == x && p.b == y).ok_or(Error::Corrupted)?; + 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 { + 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 { + 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, 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()) + } + + pub fn is_machine_store(bytes: &[u8]) -> Result { + Ok(Header::parse(bytes)?.0.is_machine_store()) + } + fn open_body(bytes: &[u8], header: Header, body_at: usize, key: Zeroizing<[u8; KEY_LEN]>) -> Result { let json = 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)?; - 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); } - Ok(Vault { key, slots: header.slots, items: body.items }) + let factors: Vec = body.factors.iter().map(FactorRec::from_json).collect::>().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); + Ok(Vault { key, version: header.version, slots: header.slots, items: body.items, factors, kdf_new }) } /// Wraps the vault key for device unlock with key material only this device can produce (e.g. a - /// Windows Hello signature). Keep the blob on the device; see docs/FORMAT.md, "Device key wrap". + /// Windows Hello signature). Version 1 only: a version-2 vault never opens with one secret. pub fn wrap_for_device(&self, material: &[u8]) -> Result, 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. Fails with `DeviceKeyRejected` when the - /// material is wrong or the blob was changed, and with `Corrupted` when it belongs to another vault. + /// 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 { 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) } @@ -180,9 +529,14 @@ impl Vault { /// The encrypted file contents, with a fresh body nonce. pub fn to_bytes(&self) -> Result, Error> { 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 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(), + }; 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); out.extend_from_slice(&sealed); @@ -194,28 +548,129 @@ impl Vault { save_atomic(path, &self.to_bytes()?) } - /// Wraps the same vault key with a new password (new salt and nonce). The items are untouched; - /// the old password stops working at the next save. + /// Changes the master password. Version 1: a new password slot. Version 2: the password factor's + /// 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> { - let slot = password_slot(&self.key, new_password, kdf)?; - self.slots.retain(|s| s.kind != SLOT_PASSWORD); - self.slots.insert(0, slot.raw()); + if self.version == VERSION { + let slot = password_slot(&self.key, new_password, kdf)?; + 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(()) } + 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 { + 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 { + 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 { + 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 { + 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). #[doc(hidden)] pub fn same_key_as(&self, other: &Vault) -> bool { 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 { - self.slots - .iter() - .filter(|s| s.kind == SLOT_PASSWORD) - .find_map(|s| PasswordSlot::parse(&s.payload).ok()) - .map(|s| s.kdf) + self.slots.iter().find_map(|s| match s.kind { + SLOT_PASSWORD => PasswordSlot::parse(&s.payload).ok().map(|p| p.kdf), + SLOT_FACTOR => FactorSlot::parse(&s.payload).ok().and_then(|f| f.kdf), + _ => None, + }) } pub fn items(&self) -> &[Item] { diff --git a/crates/custos-wasm/src/lib.rs b/crates/custos-wasm/src/lib.rs index 14320ec..7ba9b21 100644 --- a/crates/custos-wasm/src/lib.rs +++ b/crates/custos-wasm/src/lib.rs @@ -80,6 +80,7 @@ pub fn primary_secret(kind: ItemType) -> &'static str { ItemType::ApiCredential => "secret", ItemType::Card => "number", ItemType::SecureNote => "notes", + ItemType::KeyPair => "private-key", } } @@ -90,6 +91,7 @@ fn primary_user(kind: ItemType) -> Option<&'static str> { ItemType::Wifi => Some("ssid"), ItemType::Card => Some("cardholder"), ItemType::SecureNote => None, + ItemType::KeyPair => Some("public-key"), } } From 12783c9b928bea0e9991581f69e04060ca48af9c Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 2 Nov 2026 15:46:44 +0100 Subject: [PATCH 4/5] [docs] Keys: secret keys, API keys, key pairs; tests first --- crates/custos-gen/tests/keys.rs | 50 +++++++++++++++++++++++++++ crates/custos-keys/tests/mandatory.rs | 50 +++++++++++++++++++++++++++ docs/KEYS.md | 38 ++++++++++++++++++++ 3 files changed, 138 insertions(+) create mode 100644 crates/custos-gen/tests/keys.rs create mode 100644 crates/custos-keys/tests/mandatory.rs create mode 100644 docs/KEYS.md diff --git a/crates/custos-gen/tests/keys.rs b/crates/custos-gen/tests/keys.rs new file mode 100644 index 0000000..e905ff5 --- /dev/null +++ b/crates/custos-gen/tests/keys.rs @@ -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 = 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::())); + // 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}"); +} diff --git a/crates/custos-keys/tests/mandatory.rs b/crates/custos-keys/tests/mandatory.rs new file mode 100644 index 0000000..fe8556f --- /dev/null +++ b/crates/custos-keys/tests/mandatory.rs @@ -0,0 +1,50 @@ +//! 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); +} diff --git a/docs/KEYS.md b/docs/KEYS.md new file mode 100644 index 0000000..5bd51fb --- /dev/null +++ b/docs/KEYS.md @@ -0,0 +1,38 @@ +# 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`) + +``` +_<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`. From 3f3cd26590829437e8314ae42e2045c1171093f8 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 2 Nov 2026 15:49:07 +0100 Subject: [PATCH 5/5] [keys] Key pairs and API keys: custos-keys (Ed25519, ECDSA P-256, RSA), secret_key, api_key; threat model; v0.4.0 --- CLAUDE.md | 12 +- Cargo.lock | 701 ++++++++++++++++++++++++++++++++-- Cargo.toml | 2 +- crates/custos-gen/Cargo.toml | 1 + crates/custos-gen/src/lib.rs | 80 ++++ crates/custos-keys/Cargo.toml | 17 + crates/custos-keys/src/lib.rs | 142 +++++++ docs/THREAT_MODEL.md | 7 +- 8 files changed, 914 insertions(+), 48 deletions(-) create mode 100644 crates/custos-keys/Cargo.toml create mode 100644 crates/custos-keys/src/lib.rs diff --git a/CLAUDE.md b/CLAUDE.md index 53bd5ff..4a1d1c2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,12 +7,15 @@ The Windows app lives in the private `Custos` repo and depends on this one by gi ## Layout ``` 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 +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-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 (versioned; change it before the code) +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/SHARE.md the share blob and link format (versioned like FORMAT.md) docs/THREAT_MODEL.md what is and is not protected ``` @@ -33,8 +36,9 @@ On the dev machine set `CARGO_HOME=F:\C-Drive-Migration\future-caches\cargo` (C: - Commits: `[] : `, 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 binaries in git. -- **No custom crypto.** Only RustCrypto / rust-random crates (`argon2`, `chacha20poly1305`, `zeroize`, - `rand` with `SysRng`). Randomness from the OS CSPRNG only. +- **No custom crypto.** Only RustCrypto / rust-random crates (`argon2`, `chacha20poly1305`, `hkdf`, `zeroize`, + `rand` with `SysRng`; for key pairs `ssh-key`, `p256`, `rsa` and `ed25519-dalek`, RustCrypto's Ed25519 + backend). Randomness from the OS CSPRNG only. - **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. - Tests here are mandatory (it is public and holds the crypto). A format change updates `docs/FORMAT.md` diff --git a/Cargo.lock b/Cargo.lock index 4053f2c..e4c0948 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,8 +8,8 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" dependencies = [ - "crypto-common", - "inout", + "crypto-common 0.2.2", + "inout 0.2.5", ] [[package]] @@ -29,11 +29,23 @@ checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c" dependencies = [ "base64ct", "blake2", - "cpufeatures", + "cpufeatures 0.3.1", "password-hash", "zeroize", ] +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base64ct" version = "1.8.3" @@ -52,7 +64,16 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" dependencies = [ - "digest", + "digest 0.11.3", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", ] [[package]] @@ -77,9 +98,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", - "cipher", - "cpufeatures", - "rand_core", + "cipher 0.5.2", + "cpufeatures 0.3.1", + "rand_core 0.10.1", ] [[package]] @@ -90,19 +111,29 @@ checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb" dependencies = [ "aead", "chacha20", - "cipher", + "cipher 0.5.2", "poly1305", ] +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.6", + "inout 0.1.4", +] + [[package]] name = "cipher" version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ - "block-buffer", - "crypto-common", - "inout", + "block-buffer 0.12.1", + "crypto-common 0.2.2", + "inout 0.2.5", ] [[package]] @@ -111,12 +142,27 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "cpufeatures" version = "0.3.1" @@ -126,15 +172,37 @@ dependencies = [ "libc", ] +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "crypto-common" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ - "getrandom", + "getrandom 0.4.3", "hybrid-array", - "rand_core", + "rand_core 0.10.1", ] [[package]] @@ -146,62 +214,103 @@ dependencies = [ "cmov", ] +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "custos-gen" -version = "0.3.0" +version = "0.4.0" dependencies = [ "custos-vault", - "rand", + "data-encoding", + "rand 0.10.3", "regex", "unicode-normalization", "zeroize", ] +[[package]] +name = "custos-keys" +version = "0.4.0" +dependencies = [ + "custos-vault", + "ed25519-dalek", + "p256", + "rand_core 0.6.4", + "rsa", + "ssh-key", + "thiserror", +] + [[package]] name = "custos-qr" -version = "0.3.0" +version = "0.4.0" [[package]] name = "custos-share" -version = "0.3.0" +version = "0.4.0" dependencies = [ "argon2", "chacha20poly1305", "custos-vault", "data-encoding", "hkdf", - "rand", + "rand 0.10.3", "serde", "serde_json", - "sha2", + "sha2 0.11.1", "thiserror", "zeroize", ] [[package]] name = "custos-totp" -version = "0.3.0" +version = "0.4.0" dependencies = [ "custos-vault", "data-encoding", - "hmac", + "hmac 0.13.0", "percent-encoding", "sha1", - "sha2", + "sha2 0.11.1", "zeroize", ] [[package]] name = "custos-vault" -version = "0.3.0" +version = "0.4.0" dependencies = [ "argon2", "chacha20poly1305", "hkdf", - "rand", + "rand 0.10.3", "serde", "serde_json", - "sha2", + "sha2 0.11.1", "tempfile", "thiserror", "zeroize", @@ -209,14 +318,14 @@ dependencies = [ [[package]] name = "custos-wasm" -version = "0.3.0" +version = "0.4.0" dependencies = [ "custos-qr", "custos-share", "custos-totp", "custos-vault", "data-encoding", - "getrandom", + "getrandom 0.4.3", "qrcode", "serde", "serde_json", @@ -229,18 +338,100 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "const-oid 0.9.6", + "crypto-common 0.1.6", + "subtle", +] + [[package]] name = "digest" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "block-buffer", - "const-oid", - "crypto-common", + "block-buffer 0.12.1", + "const-oid 0.10.2", + "crypto-common 0.2.2", "ctutils", ] +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest 0.10.7", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "rand_core 0.6.4", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", +] + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest 0.10.7", + "ff", + "generic-array", + "group", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "errno" version = "0.3.14" @@ -257,6 +448,44 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "generic-array" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -266,7 +495,18 @@ dependencies = [ "cfg-if", "libc", "r-efi", - "rand_core", + "rand_core 0.10.1", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", ] [[package]] @@ -275,7 +515,16 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" dependencies = [ - "hmac", + "hmac 0.13.0", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", ] [[package]] @@ -284,7 +533,7 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" dependencies = [ - "digest", + "digest 0.11.3", ] [[package]] @@ -296,6 +545,15 @@ dependencies = [ "typenum", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + [[package]] name = "inout" version = "0.2.5" @@ -311,12 +569,27 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] + [[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -329,12 +602,95 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + +[[package]] +name = "p521" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fc9e2161f1f215afdfce23677034ae137bbd45016a880c2eb3ba8eb95f085b2" +dependencies = [ + "base16ct", + "ecdsa", + "elliptic-curve", + "primeorder", + "rand_core 0.6.4", + "sha2 0.10.9", +] + [[package]] name = "password-hash" version = "0.6.1" @@ -344,6 +700,15 @@ dependencies = [ "phc", ] +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -360,16 +725,55 @@ dependencies = [ "ctutils", ] +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "poly1305" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c" dependencies = [ - "cpufeatures", + "cpufeatures 0.3.1", "universal-hash", ] +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -400,6 +804,16 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_chacha", + "rand_core 0.6.4", +] + [[package]] name = "rand" version = "0.10.3" @@ -407,8 +821,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ "chacha20", - "getrandom", - "rand_core", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", ] [[package]] @@ -446,6 +879,46 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac 0.12.1", + "subtle", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "sha2 0.10.9", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" version = "1.1.6" @@ -459,6 +932,26 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -509,8 +1002,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", ] [[package]] @@ -520,10 +1024,91 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.3.1", + "digest 0.11.3", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "ssh-cipher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caac132742f0d33c3af65bfcde7f6aa8f62f0e991d80db99149eb9d44708784f" +dependencies = [ + "cipher 0.4.4", + "ssh-encoding", +] + +[[package]] +name = "ssh-encoding" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb9242b9ef4108a78e8cd1a2c98e193ef372437f8c22be363075233321dd4a15" +dependencies = [ + "base64ct", + "pem-rfc7468", + "sha2 0.10.9", +] + +[[package]] +name = "ssh-key" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b86f5297f0f04d08cabaa0f6bff7cb6aec4d9c3b49d87990d63da9d9156a8c3" +dependencies = [ + "ed25519-dalek", + "num-bigint-dig", + "p256", + "p384", + "p521", + "rand_core 0.6.4", + "rsa", + "sec1", + "sha2 0.10.9", + "signature", + "ssh-cipher", + "ssh-encoding", + "subtle", + "zeroize", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -553,7 +1138,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom", + "getrandom 0.4.3", "once_cell", "rustix", "windows-sys", @@ -612,10 +1197,22 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" dependencies = [ - "crypto-common", + "crypto-common 0.2.2", "ctutils", ] +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "windows-link" version = "0.2.1" @@ -631,6 +1228,26 @@ dependencies = [ "windows-link", ] +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zeroize" version = "1.9.1" diff --git a/Cargo.toml b/Cargo.toml index d3bb352..7518b53 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.3.0" +version = "0.4.0" edition = "2024" license = "MPL-2.0" repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic" diff --git a/crates/custos-gen/Cargo.toml b/crates/custos-gen/Cargo.toml index 72bab71..7e47695 100644 --- a/crates/custos-gen/Cargo.toml +++ b/crates/custos-gen/Cargo.toml @@ -11,6 +11,7 @@ custos-vault = { path = "../custos-vault" } rand.workspace = true zeroize.workspace = true unicode-normalization.workspace = true +data-encoding.workspace = true [dev-dependencies] regex = "1" diff --git a/crates/custos-gen/src/lib.rs b/crates/custos-gen/src/lib.rs index 9a2148a..a3938c7 100644 --- a/crates/custos-gen/src/lib.rs +++ b/crates/custos-gen/src/lib.rs @@ -514,3 +514,83 @@ pub fn pin(length: u8) -> Generated { let value: String = (0..len).map(|_| digit()).collect(); 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 { + 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") +} + +/// `_` + 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 { + 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 + } +} diff --git a/crates/custos-keys/Cargo.toml b/crates/custos-keys/Cargo.toml new file mode 100644 index 0000000..f593dae --- /dev/null +++ b/crates/custos-keys/Cargo.toml @@ -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"] } diff --git a/crates/custos-keys/src/lib.rs b/crates/custos-keys/src/lib.rs new file mode 100644 index 0000000..29666ac --- /dev/null +++ b/crates/custos-keys/src/lib.rs @@ -0,0 +1,142 @@ +//! 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, +} + +#[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 { + 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(r: Result) -> Result { + r.map_err(|_| KeyError::Encode) +} + +/// A new key pair. RSA takes a few seconds (prime generation). +pub fn generate(alg: Algorithm, comment: &str) -> Result { + let (data, private_pem, public_pem) = match alg { + Algorithm::Ed25519 => { + use ed25519_dalek::pkcs8::{EncodePrivateKey, EncodePublicKey}; + let sk = ed25519_dalek::SigningKey::generate(&mut OsRng); + 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))?; + (KeypairData::Ed25519(Ed25519Keypair::from(&sk)), private_pem, public_pem) + } + Algorithm::EcdsaP256 => { + use p256::pkcs8::{EncodePrivateKey, EncodePublicKey}; + let sk = p256::SecretKey::random(&mut OsRng); + 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(); + (KeypairData::Ecdsa(EcdsaKeypair::NistP256 { private: sk.into(), public: public.into() }), private_pem, public_pem) + } + Algorithm::Rsa3072 | Algorithm::Rsa4096 => { + use rsa::pkcs8::{EncodePrivateKey, EncodePublicKey}; + let bits = if alg == Algorithm::Rsa3072 { 3072 } else { 4096 }; + let sk = enc(rsa::RsaPrivateKey::new(&mut OsRng, bits))?; + 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))?; + (KeypairData::Rsa(enc(RsaKeypair::try_from(sk))?), private_pem, public_pem) + } + }; + let private = enc(PrivateKey::new(data, comment))?; + let public = private.public_key(); + Ok(KeyPair { + algorithm: alg.name().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 { + 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, 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 { + 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()) +} diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index a1529af..3699ad7 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -14,6 +14,7 @@ just as plainly, what it does not. | 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 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.** | | 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). | @@ -34,7 +35,11 @@ just as plainly, what it does not. 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 typing, but a window that steals focus at the wrong moment can receive them. -- **Device unlock (Windows Hello).** The blob on disk is only as strong as the device key behind it: anyone +- **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.