//! 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; /// The recovery key's slot (core 0.17.0; docs/FACTORS.md, "The recovery key"). pub const SLOT_RECOVERY: u8 = 5; pub const RECOVERY_ID_LEN: usize = 4; /// A team vault's member slot (core 0.18.0; docs/TEAM.md): the team key sealed to one member. pub const SLOT_MEMBER: u8 = 6; /// team id (16) ‖ member id (16) ‖ epoch (4) ‖ sealed team key (108). pub const MEMBER_SLOT_LEN: usize = 16 + 16 + 4 + 108; /// A team has at most this many members. pub const MAX_MEMBER_SLOTS: usize = 32; 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 (version 1). #[derive(Clone)] pub struct RawSlot { pub kind: u8, pub payload: Vec, } pub struct PasswordSlot { pub kdf: KdfParams, pub salt: [u8; SALT_LEN], pub nonce: [u8; NONCE_LEN], pub wrapped: Vec, } impl PasswordSlot { /// The bytes the wrapped key is authenticated against: magic ‖ version ‖ kind ‖ payload before the key. pub fn aad(&self) -> Vec { let mut a = Vec::with_capacity(9 + PW_AAD_LEN); a.extend_from_slice(MAGIC); a.extend_from_slice(&VERSION.to_le_bytes()); a.push(SLOT_PASSWORD); a.extend_from_slice(&self.payload()[..PW_AAD_LEN]); a } pub fn payload(&self) -> Vec { let mut p = Vec::with_capacity(PW_PAYLOAD_LEN); p.push(KDF_ARGON2ID); p.extend_from_slice(&self.kdf.m_cost_kib.to_le_bytes()); p.extend_from_slice(&self.kdf.t_cost.to_le_bytes()); p.extend_from_slice(&self.kdf.p_cost.to_le_bytes()); p.extend_from_slice(&self.salt); p.extend_from_slice(&self.nonce); p.extend_from_slice(&self.wrapped); p } pub fn parse(payload: &[u8]) -> Result { if payload.len() != PW_PAYLOAD_LEN { return Err(Error::Malformed); } if payload[0] != KDF_ARGON2ID { return Err(Error::UnsupportedKdf); } let u32_at = |i: usize| u32::from_le_bytes(payload[i..i + 4].try_into().unwrap()); let kdf = KdfParams { m_cost_kib: u32_at(1), t_cost: u32_at(5), p_cost: u32_at(9) }; kdf.check()?; Ok(PasswordSlot { kdf, salt: payload[13..13 + SALT_LEN].try_into().unwrap(), nonce: payload[13 + SALT_LEN..PW_AAD_LEN].try_into().unwrap(), wrapped: payload[PW_AAD_LEN..].to_vec(), }) } pub fn raw(&self) -> RawSlot { RawSlot { kind: SLOT_PASSWORD, payload: self.payload() } } } 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(), }) } } /// The recovery slot (kind 5): the vault key, wrapped by the recovery key alone. At most one, never in a machine /// store. `id` says which printed key it is and is not secret. pub struct RecoverySlot { pub id: [u8; RECOVERY_ID_LEN], pub salt: [u8; SALT_LEN], pub nonce: [u8; NONCE_LEN], pub wrapped: Vec, } impl RecoverySlot { fn head(&self) -> Vec { let mut h = Vec::with_capacity(RECOVERY_ID_LEN + SALT_LEN + NONCE_LEN); h.extend_from_slice(&self.id); h.extend_from_slice(&self.salt); h.extend_from_slice(&self.nonce); h } pub fn aad(&self) -> Vec { v2_aad(SLOT_RECOVERY, &self.head()) } pub fn raw(&self) -> RawSlot { let mut p = self.head(); p.extend_from_slice(&self.wrapped); RawSlot { kind: SLOT_RECOVERY, payload: p } } pub fn parse(payload: &[u8]) -> Result { const HEAD: usize = RECOVERY_ID_LEN + SALT_LEN + NONCE_LEN; if payload.len() != HEAD + WRAPPED_LEN { return Err(Error::Malformed); } Ok(RecoverySlot { id: payload[..RECOVERY_ID_LEN].try_into().unwrap(), salt: payload[RECOVERY_ID_LEN..RECOVERY_ID_LEN + SALT_LEN].try_into().unwrap(), nonce: payload[RECOVERY_ID_LEN + SALT_LEN..HEAD].try_into().unwrap(), wrapped: payload[HEAD..].to_vec(), }) } } /// A team vault's member slot (kind 6): the box carries its own binding (its context names team, epoch and member). #[derive(Clone)] pub struct MemberSlot { pub team: [u8; ID_LEN], pub member: [u8; ID_LEN], pub epoch: u32, pub sealed: Vec, } impl MemberSlot { pub fn raw(&self) -> RawSlot { let mut p = Vec::with_capacity(MEMBER_SLOT_LEN); p.extend_from_slice(&self.team); p.extend_from_slice(&self.member); p.extend_from_slice(&self.epoch.to_le_bytes()); p.extend_from_slice(&self.sealed); RawSlot { kind: SLOT_MEMBER, payload: p } } pub fn parse(payload: &[u8]) -> Result { if payload.len() != MEMBER_SLOT_LEN { return Err(Error::Malformed); } Ok(MemberSlot { team: payload[..16].try_into().unwrap(), member: payload[16..32].try_into().unwrap(), epoch: u32::from_le_bytes(payload[32..36].try_into().unwrap()), sealed: payload[36..].to_vec(), }) } } pub struct Header { pub version: u16, pub slots: Vec, pub body_nonce: [u8; NONCE_LEN], } impl Header { pub fn to_bytes(&self) -> Vec { let mut h = Vec::new(); h.extend_from_slice(MAGIC); 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); h.extend_from_slice(&(s.payload.len() as u16).to_le_bytes()); h.extend_from_slice(&s.payload); } h.extend_from_slice(&self.body_nonce); h } /// Parses the header; returns it and its length (where the body starts). pub fn parse(bytes: &[u8]) -> Result<(Header, usize), Error> { if bytes.len() < 9 || &bytes[..6] != MAGIC { return Err(Error::NotAVault); } let version = u16::from_le_bytes([bytes[6], bytes[7]]); 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 { return Err(Error::Malformed); } let mut at = 9; let mut slots = Vec::with_capacity(count); for _ in 0..count { let head = bytes.get(at..at + 3).ok_or(Error::Malformed)?; let len = u16::from_le_bytes([head[1], head[2]]) as usize; let payload = bytes.get(at + 3..at + 3 + len).ok_or(Error::Malformed)?; slots.push(RawSlot { kind: head[0], payload: payload.to_vec() }); at += 3 + len; } let body_nonce = bytes.get(at..at + NONCE_LEN).ok_or(Error::Malformed)?.try_into().unwrap(); at += NONCE_LEN; if bytes.len() < at + TAG_LEN { return Err(Error::Malformed); } 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> { if self.slots.iter().any(|s| s.kind == SLOT_MEMBER) { return self.check_team(); } 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; let mut recoveries = 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; } SLOT_RECOVERY => { RecoverySlot::parse(&s.payload)?; recoveries += 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); } // One recovery key at most, and none for a vault that opens by itself. if recoveries > 1 || (recoveries == 1 && singles > 0) { return Err(Error::Malformed); } Ok(()) } /// A team vault (docs/TEAM.md): 1 ..= 32 member slots and nothing else, one team id and epoch, distinct members. fn check_team(&self) -> Result<(), Error> { if self.slots.len() > MAX_MEMBER_SLOTS || self.slots.iter().any(|s| s.kind != SLOT_MEMBER) { return Err(Error::Malformed); } let slots = self.slots.iter().map(|s| MemberSlot::parse(&s.payload)).collect::, _>>()?; let first = &slots[0]; let mut members: Vec<[u8; ID_LEN]> = Vec::with_capacity(slots.len()); for s in &slots { if s.team != first.team || s.epoch != first.epoch || members.contains(&s.member) { return Err(Error::Malformed); } members.push(s.member); } Ok(()) } pub fn is_team(&self) -> bool { self.slots.iter().any(|s| s.kind == SLOT_MEMBER) } pub fn member_slots(&self) -> Vec { self.slots.iter().filter(|s| s.kind == SLOT_MEMBER).filter_map(|s| MemberSlot::parse(&s.payload).ok()).collect() } 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 recovery_slot(&self) -> Option { self.slots.iter().find(|s| s.kind == SLOT_RECOVERY).and_then(|s| RecoverySlot::parse(&s.payload).ok()) } pub fn is_machine_store(&self) -> bool { self.slots.iter().any(|s| s.kind == SLOT_SINGLE) } }