diff --git a/crates/custos-vault/src/lib.rs b/crates/custos-vault/src/lib.rs index ecc2cd5..ec3cf64 100644 --- a/crates/custos-vault/src/lib.rs +++ b/crates/custos-vault/src/lib.rs @@ -24,6 +24,7 @@ mod item; pub mod provision; mod save; mod secret; +pub mod security; pub mod signing; pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms}; @@ -83,6 +84,9 @@ pub enum Error { /// Names the member that does not fit (docs/FORMAT.md), never its value. #[error("provision audit: {0}")] Provision(&'static str), + /// Names the rule a security change breaks (docs/FORMAT.md, "The security member"), never a value. + #[error("security: {0}")] + Security(&'static str), #[error("signing keys: {0}")] Signing(String), #[error("{0}")] @@ -280,6 +284,8 @@ struct Body { signing: Option, #[serde(default)] provision: Option, + #[serde(default)] + security: Option, } /// What `to_bytes` serializes: borrows the items instead of cloning every secret. @@ -295,6 +301,8 @@ struct BodyRef<'a> { signing: Option, #[serde(skip_serializing_if = "Option::is_none")] provision: Option, + #[serde(skip_serializing_if = "Option::is_none")] + security: Option, } /// An unlocked vault: the vault key and the decrypted items, both wiped on drop. @@ -313,6 +321,8 @@ pub struct Vault { signing: signing::Store, /// The Provisio audit (docs/FORMAT.md), oldest first. provision: Vec, + /// The security level's Setup window, the checklist and their audit (docs/FORMAT.md). + security: security::State, } impl fmt::Debug for Vault { @@ -414,6 +424,7 @@ impl Vault { identity: None, signing: signing::Store::default(), provision: Vec::new(), + security: security::State::default(), }) } @@ -432,6 +443,7 @@ impl Vault { identity: None, signing: signing::Store::default(), provision: Vec::new(), + security: security::State::default(), }; v.add_factor(a, label_a)?; v.add_factor(b, label_b)?; @@ -466,6 +478,7 @@ impl Vault { identity: None, signing: signing::Store::default(), provision: Vec::new(), + security: security::State::default(), }) } @@ -591,6 +604,7 @@ impl Vault { Some(j) => signing::Store::from_json(j).ok_or(Error::Corrupted)?, None => signing::Store::default(), }; + let security = security::State::from_json(body.security).ok_or(Error::Corrupted)?; Ok(Vault { key, version: header.version, @@ -601,6 +615,7 @@ impl Vault { identity, signing, provision: provision::from_json(body.provision), + security, }) } @@ -637,6 +652,7 @@ impl Vault { identity: self.identity.as_ref().map(identity::Root::json), signing: self.signing.json(), provision: provision::json(&self.provision), + security: self.security.json(), }; serde_json::to_writer(&mut *json, &body).map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?; let sealed = crypto::seal(&self.key, &body_nonce, &json, &out); diff --git a/crates/custos-vault/src/security.rs b/crates/custos-vault/src/security.rs new file mode 100644 index 0000000..58a37f6 --- /dev/null +++ b/crates/custos-vault/src/security.rs @@ -0,0 +1,623 @@ +//! The security level and the hardening checklist (docs/FORMAT.md, "The security member"): the vault body member +//! `security`. The level is computed from the Setup window and the ticked items, never stored; every change is in an +//! append-only audit. Nothing here is secret. + +use std::collections::BTreeSet; + +use serde::{Deserialize, Serialize}; + +use crate::{Error, Vault}; + +/// The log keeps the newest this many entries. +pub const AUDIT_LIMIT: usize = 5_000; +/// How long Setup lasts from *Connect via SSH*, in milliseconds: 2 hours. +pub const SETUP_WINDOW: i64 = 2 * 60 * 60 * 1000; + +/// A checklist item. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Item { + /// Move the Authelia TOTP to my phone. + TotpOnPhone, + /// Approve with Windows Hello. + HelloApprovals, + /// Narrow the server scope. + NarrowScope, + /// Rotate what setup made. + RotateSetup, + /// Turn off Connect via SSH. + NoSsh, + /// The phone approves this PC. + PhoneApproves, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Level { + /// From *Connect via SSH* until 2 hours later or *Finish setup*. + Setup, + /// After Setup, and every vault that never had one. + Standard, + /// Not in Setup, and at least one checklist item ticked. + Hardened, +} + +/// How an undo was confirmed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Auth { + Hello, + Password, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Action { + SetupStarted, + SetupFinished, + /// Written by the first change after the window ended on its own. + SetupExpired, + Ticked, + Unticked, + SshConnected, + TotpMoved, +} + +/// What *Connect via SSH* needs. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum SshRule { + /// Offered, one click (Setup). + Allowed, + /// Offered after Windows Hello or the master password. + NeedsAuth, + /// Not offered (*Turn off Connect via SSH* is ticked). + Off, +} + +/// A Setup window, Unix milliseconds: Setup holds for `started <= now < until`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct Window { + pub started: i64, + pub until: i64, +} + +/// The server scope prefixes *Narrow the server scope* replaced, kept for its undo. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct KeptScope { + #[serde(default)] + pub ask: Vec, + #[serde(default)] + pub offer: Vec, +} + +/// One audit entry. Append-only: nothing edits or removes one. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SecurityEntry { + /// Unix milliseconds. + pub at: i64, + pub action: Action, + /// The checklist item, for `ticked` and `unticked`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub item: Option, + /// How an undo was confirmed, for `unticked`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auth: Option, +} + +/// Everything *Settings → Security* shows. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SecurityView { + pub level: Level, + /// The last Setup window, if there was one. + pub setup: Option, + /// When that window ended (Finish setup, or `until` once its expiry was noticed). + pub finished: Option, + /// Milliseconds of Setup left, while in Setup. + pub setup_remaining: Option, + pub ticked: BTreeSet, + pub kept_scope: Option, + /// Oldest first. + pub audit: Vec, +} + +/// The member as the vault keeps it, and as it is written. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct State { + #[serde(default, skip_serializing_if = "Option::is_none")] + setup: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + finished: Option, + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + ticked: BTreeSet, + #[serde(default, skip_serializing_if = "Option::is_none")] + kept_scope: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + audit: Vec, +} + +/// At most this many prefixes on each side of a kept scope. +const KEPT_MAX: usize = 64; + +/// A kept scope prefix: 1 to 200 characters, no control characters. The error names the rule, never the value. +fn kept_ok(list: &[String]) -> Result<(), Error> { + if list.len() > KEPT_MAX { + return Err(Error::Security("a kept scope has at most 64 prefixes on each side")); + } + if list.iter().any(|p| !(1..=200).contains(&p.chars().count()) || p.chars().any(char::is_control)) { + return Err(Error::Security("a kept scope prefix is 1 to 200 characters without control characters")); + } + Ok(()) +} + +fn trim(audit: &mut Vec) { + if audit.len() > AUDIT_LIMIT { + audit.drain(..audit.len() - AUDIT_LIMIT); + } +} + +impl State { + /// The member as read, checked; `None` when it breaks a rule (the vault then does not open). + pub(crate) fn from_json(j: Option) -> Option { + let mut st = j.unwrap_or_default(); + if let Some(w) = st.setup + && w.until <= w.started + { + return None; + } + if st.finished.is_some() && st.setup.is_none() { + return None; + } + if let Some(k) = &st.kept_scope + && (kept_ok(&k.ask).is_err() || kept_ok(&k.offer).is_err()) + { + return None; + } + trim(&mut st.audit); + Some(st) + } + + /// Absent while nothing was ever set, so a vault without it is written exactly as before. + pub(crate) fn json(&self) -> Option { + (*self != State::default()).then(|| self.clone()) + } + + /// Setup holds for `started <= now < until` of a window that has not finished. + fn in_setup(&self, now: i64) -> bool { + self.finished.is_none() && self.setup.is_some_and(|w| w.started <= now && now < w.until) + } + + fn level(&self, now: i64) -> Level { + if self.in_setup(now) { + Level::Setup + } else if self.ticked.is_empty() { + Level::Standard + } else { + Level::Hardened + } + } + + fn push(&mut self, at: i64, action: Action, item: Option, auth: Option) { + self.audit.push(SecurityEntry { at, action, item, auth }); + trim(&mut self.audit); + } + + /// Before any change: a window that ended on its own is written down once, as `setup-expired` at `now` and + /// `finished` = `until`. + fn notice_expiry(&mut self, now: i64) { + if let Some(w) = self.setup + && self.finished.is_none() + && now >= w.until + { + self.finished = Some(w.until); + self.push(now, Action::SetupExpired, None, None); + } + } +} + +/// *Accept all* on a run card: only in Setup, for a setup run (its id starts with `setup-`) that holds Provisio +/// lines only. +pub fn accept_all_allowed(level: Level, run_id: &str, only_provision: bool) -> bool { + level == Level::Setup && run_id.starts_with("setup-") && only_provision +} + +/// Whether a line that replaces a stored item starts ticked: only where *Accept all* applies (a setup run in +/// Setup); otherwise Mark ticks it himself. +pub fn replacing_line_preticked(level: Level, setup_run: bool) -> bool { + level == Level::Setup && setup_run +} + +/// What *Connect via SSH* needs: off when *Turn off Connect via SSH* is ticked, one click in Setup, Windows Hello or +/// the master password otherwise. +pub fn ssh_needs_auth(level: Level, ticked: &BTreeSet) -> SshRule { + if ticked.contains(&Item::NoSsh) { + SshRule::Off + } else if level == Level::Setup { + SshRule::Allowed + } else { + SshRule::NeedsAuth + } +} + +/// Whether a server may offer a TOTP seed into the vault: not once it was moved to the phone. +pub fn totp_offer_allowed(ticked: &BTreeSet) -> bool { + !ticked.contains(&Item::TotpOnPhone) +} + +/// Whether *Sign & release*, *Accept*, *Accept all* and approvals ask for Windows Hello first. +pub fn hello_for_approvals(ticked: &BTreeSet) -> bool { + ticked.contains(&Item::HelloApprovals) +} + +impl Vault { + /// The level at `now` (Unix milliseconds). + pub fn security_level(&self, now: i64) -> Level { + self.security.level(now) + } + + /// The level, the Setup window and what is left of it, the ticked items, the kept scope and the audit. + pub fn security_view(&self, now: i64) -> SecurityView { + let st = &self.security; + SecurityView { + level: st.level(now), + setup: st.setup, + finished: st.finished, + setup_remaining: st.setup.filter(|_| st.in_setup(now)).map(|w| w.until - now), + ticked: st.ticked.clone(), + kept_scope: st.kept_scope.clone(), + audit: st.audit.clone(), + } + } + + /// Starts Setup (*Connect via SSH*): a window of 2 hours from `now`, audited `setup-started`. While in Setup it + /// changes nothing and returns the window that holds. The caller saves. + pub fn security_start_setup(&mut self, now: i64) -> Window { + let st = &mut self.security; + st.notice_expiry(now); + if st.in_setup(now) + && let Some(w) = st.setup + { + return w; + } + let w = Window { started: now, until: now.saturating_add(SETUP_WINDOW) }; + st.setup = Some(w); + st.finished = None; + st.push(now, Action::SetupStarted, None, None); + w + } + + /// *Finish setup*: ends the window at `now`, audited `setup-finished`. False when not in Setup. The caller saves. + pub fn security_finish_setup(&mut self, now: i64) -> bool { + let st = &mut self.security; + st.notice_expiry(now); + if !st.in_setup(now) { + return false; + } + st.finished = Some(now); + st.push(now, Action::SetupFinished, None, None); + true + } + + /// Ticks a checklist item, audited `ticked`. False (and no entry) when it was ticked already. The caller saves. + pub fn security_tick(&mut self, item: Item, now: i64) -> bool { + let st = &mut self.security; + st.notice_expiry(now); + if !st.ticked.insert(item) { + return false; + } + st.push(now, Action::Ticked, Some(item), None); + true + } + + /// Unticks a checklist item after Windows Hello or the master password, audited `unticked` with how. False (and + /// no entry) when it was not ticked. The caller saves. + pub fn security_untick(&mut self, item: Item, auth: Auth, now: i64) -> bool { + let st = &mut self.security; + st.notice_expiry(now); + if !st.ticked.remove(&item) { + return false; + } + st.push(now, Action::Unticked, Some(item), Some(auth)); + true + } + + /// Keeps the scope prefixes *Narrow the server scope* replaces. Refused when a scope is kept already (its undo + /// has not taken it back), so the first prefixes are never lost. The caller saves. + pub fn security_keep_scope(&mut self, ask: &[String], offer: &[String]) -> Result<(), Error> { + if self.security.kept_scope.is_some() { + return Err(Error::Security("a scope is kept already; take it back first")); + } + kept_ok(ask)?; + kept_ok(offer)?; + self.security.kept_scope = Some(KeptScope { ask: ask.to_vec(), offer: offer.to_vec() }); + Ok(()) + } + + /// Takes the kept prefixes back, for the undo. The caller saves. + pub fn security_take_kept_scope(&mut self) -> Option { + self.security.kept_scope.take() + } + + /// Records `ssh-connected` or `totp-moved`; the other actions are written by the calls above. The caller saves. + pub fn security_record(&mut self, action: Action, item: Option, now: i64) -> Result<(), Error> { + if !matches!(action, Action::SshConnected | Action::TotpMoved) { + return Err(Error::Security("only ssh-connected and totp-moved are recorded directly")); + } + let st = &mut self.security; + st.notice_expiry(now); + st.push(now, action, item, None); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + //! An older reader still opens a vault with the member, and unknown values make the vault refuse to open. They + //! live here because only the crate can decrypt the body, change it and seal it again. + use super::*; + use crate::format::Header; + use crate::{FactorJson, Item as VaultItem, ItemType, KdfParams, SecretString, crypto, identity, provision}; + + const NOW: i64 = 1_793_750_000_000; + + fn vault() -> Vault { + Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap() + } + + fn body_json(v: &Vault) -> String { + let bytes = v.to_bytes().unwrap(); + let (header, at) = Header::parse(&bytes).unwrap(); + let json = crypto::open(&v.key, &header.body_nonce, &bytes[at..], &bytes[..at]).unwrap(); + String::from_utf8(json.to_vec()).unwrap() + } + + /// The vault's file with its body replaced by `json`, sealed with the vault's key as `to_bytes` does. + fn with_body(v: &Vault, json: &str) -> Vec { + let bytes = v.to_bytes().unwrap(); + let (header, at) = Header::parse(&bytes).unwrap(); + let mut out = bytes[..at].to_vec(); + out.extend_from_slice(&crypto::seal(&v.key, &header.body_nonce, json.as_bytes(), &bytes[..at])); + out + } + + // ---- the body as core 0.11.0 parsed it (src/lib.rs, src/signing.rs, src/provision.rs at v0.11.0) ---- + + #[derive(Deserialize)] + #[allow(dead_code)] + struct BodyV0_11 { + format: u32, + items: Vec, + #[serde(default)] + factors: Vec, + #[serde(default)] + identity: Option, + #[serde(default)] + signing: Option, + #[serde(default)] + provision: Option, + } + + #[derive(Deserialize)] + #[allow(dead_code)] + struct SigningV0_11 { + #[serde(default)] + keys: Vec, + #[serde(default)] + audit: Vec, + } + + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + #[allow(dead_code)] + struct KeyV0_11 { + id: String, + kind: OldKeyKind, + role: OldRole, + name: String, + created: i64, + } + + #[derive(Deserialize)] + #[serde(rename_all = "kebab-case")] + enum OldKeyKind { + Ed25519, + RootCa, + CodeSigning, + } + + #[derive(Deserialize)] + #[serde(rename_all = "lowercase")] + enum OldRole { + Release, + Test, + } + + #[derive(Deserialize)] + #[allow(dead_code)] + struct SignEntryV0_11 { + at: i64, + key: String, + kind: OldSignKind, + outcome: OldSignOutcome, + via: String, + } + + #[derive(Deserialize)] + #[serde(rename_all = "lowercase")] + enum OldSignKind { + Minisign, + Manifest, + Authenticode, + } + + #[derive(Deserialize)] + #[serde(rename_all = "kebab-case")] + enum OldSignOutcome { + Approved, + Auto, + Refused, + Expired, + OutOfScope, + Invalid, + } + + #[derive(Deserialize)] + #[allow(dead_code)] + struct ProvisionV0_11 { + #[serde(default)] + audit: Vec, + } + + #[derive(Deserialize)] + #[allow(dead_code)] + struct ProvisionEntryV0_11 { + store: OldStore, + outcome: OldProvisionOutcome, + } + + #[derive(Deserialize)] + #[serde(rename_all = "lowercase")] + enum OldStore { + Vault, + Claude, + Cloud, + } + + #[derive(Deserialize)] + #[serde(rename_all = "kebab-case")] + enum OldProvisionOutcome { + Approved, + Generated, + Accepted, + Refused, + OutOfScope, + Invalid, + Expired, + } + + fn display_entry(outcome: provision::Outcome) -> provision::ProvisionEntry { + provision::ProvisionEntry { + at: NOW, + direction: provision::Direction::Offer, + host: "nixos-vm".into(), + item: "arca/authelia-mark".into(), + store: provision::Store::Display, + run: None, + kind: Some("totp".into()), + code: "684361".into(), + outcome, + replaced: false, + } + } + + #[test] + fn an_older_reader_opens_a_vault_with_the_security_member() { + let mut v = vault(); + v.add(VaultItem::new(ItemType::SecureNote, "kept", 1)); + // Never set: the body has no trace of the member, so it is byte-for-byte what 0.11.0 wrote. + assert!(!body_json(&v).contains("security")); + + v.security_start_setup(NOW); + v.security_tick(Item::HelloApprovals, NOW + 1); + v.security_untick(Item::HelloApprovals, Auth::Hello, NOW + 2); + v.security_tick(Item::NoSsh, NOW + 3); + v.security_keep_scope(&["arca/".to_string()], &[]).unwrap(); + v.security_record(Action::SshConnected, None, NOW + 4).unwrap(); + let json = body_json(&v); + assert!(json.contains(r#""security":{"setup":{"started":"#), "{json}"); + assert!(json.contains(r#""ticked":["no-ssh"]"#) && json.contains(r#""keptScope":{"ask":["arca/"]"#), "{json}"); + // Core 0.11.0's parser takes it and keeps everything it knows. + let old: BodyV0_11 = serde_json::from_str(&json).unwrap(); + assert_eq!(old.items.len(), 1); + assert_eq!(old.items[0].title, "kept"); + // And this core reads it back the same. + let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap(); + assert_eq!(back.security_view(NOW + 5), v.security_view(NOW + 5)); + } + + #[test] + fn an_older_reader_opens_a_vault_with_the_approval_key_and_runs_but_not_approval_entries() { + use crate::signing::{Approval, Context, Request, Role, SignKind, Via}; + let mut v = vault(); + v.signing_create(Role::Release, &["*".to_string()], &["*".to_string()], NOW).unwrap(); + let mut r = Request { + key: "domi-release".into(), + kind: SignKind::Minisign, + digest: vec![1; 64], + manifest: None, + approval: None, + run: Some("r-42".into()), + context: Context { file: "a.exe".into(), version: "0.7.0".into(), ..Default::default() }, + via: Via::Local, + }; + v.signing_sign(&r, Approval::Mark, NOW).unwrap(); + v.provision_record(provision::ProvisionEntry { + store: provision::Store::Vault, + outcome: provision::Outcome::Accepted, + ..display_entry(provision::Outcome::Accepted) + }) + .unwrap(); + let json = body_json(&v); + assert!(json.contains(r#""id":"domi-approve""#) && json.contains(r#""run":"r-42""#), "{json}"); + assert!(serde_json::from_str::(&json).is_ok(), "the new key and members are ignored"); + + // An approval entry is a kind 0.11.0 does not know: it refuses the vault (docs/FORMAT.md). + r.key = "domi-approve".into(); + r.kind = SignKind::Approval; + r.digest = vec![]; + v.signing_refuse(&r, crate::signing::Outcome::Refused, None, NOW + 1); + assert!(serde_json::from_str::(&body_json(&v)).is_err()); + } + + #[test] + fn an_older_reader_refuses_display_and_confirmed() { + for (store, outcome) in [ + (provision::Store::Display, provision::Outcome::Refused), + (provision::Store::Display, provision::Outcome::Confirmed), + ] { + let mut v = vault(); + v.provision_record(provision::ProvisionEntry { store, ..display_entry(outcome) }).unwrap(); + assert!(serde_json::from_str::(&body_json(&v)).is_err(), "{store:?} {outcome:?}"); + // This core reads it. + assert!(Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).is_ok()); + } + } + + #[test] + fn unknown_or_broken_security_values_make_the_vault_refuse_to_open() { + let mut v = vault(); + v.security_start_setup(NOW); + v.security_tick(Item::NoSsh, NOW + 1); + v.security_untick(Item::NoSsh, Auth::Password, NOW + 2); + v.security_tick(Item::RotateSetup, NOW + 3); + v.security_keep_scope(&["arca/".to_string()], &["fabrica/".to_string()]).unwrap(); + let json = body_json(&v); + // The file as written opens. + assert!(Vault::open(&with_body(&v, &json), &SecretString::from("pw")).is_ok()); + let until = format!(r#""until":{}"#, NOW + SETUP_WINDOW); + let cases = [ + (r#""ticked":["rotate-setup"]"#, r#""ticked":["rotate-later"]"#.to_string()), + (r#""action":"ticked""#, r#""action":"tocked""#.to_string()), + (r#""auth":"password""#, r#""auth":"pin""#.to_string()), + (r#""item":"no-ssh""#, r#""item":"no-telnet""#.to_string()), + (until.as_str(), format!(r#""until":{NOW}"#)), + (r#""ask":["arca/"]"#, r#""ask":["arca/\n"]"#.to_string()), + (r#""ask":["arca/"]"#, r#""ask":[""]"#.to_string()), + ]; + for (from, to) in cases { + assert!(json.contains(from), "{from} in {json}"); + let bad = json.replacen(from, &to, 1); + let r = Vault::open(&with_body(&v, &bad), &SecretString::from("pw")); + assert!(matches!(r, Err(Error::Corrupted)), "{to}: {r:?}"); + } + // `finished` without a window. + let mut no_window = json.clone(); + let start = no_window.find(r#""setup":{"#).unwrap(); + let end = start + no_window[start..].find('}').unwrap() + 2; + no_window.replace_range(start..end, r#""finished":5,"#); + let r = Vault::open(&with_body(&v, &no_window), &SecretString::from("pw")); + assert!(matches!(r, Err(Error::Corrupted)), "{no_window}"); + } +} diff --git a/crates/custos-vault/tests/security.rs b/crates/custos-vault/tests/security.rs new file mode 100644 index 0000000..2b425c4 --- /dev/null +++ b/crates/custos-vault/tests/security.rs @@ -0,0 +1,269 @@ +//! The security member (docs/FORMAT.md, "The security member"): the level rules, the checklist and its audit, the +//! kept scope, and the rules the app asks before a card. That an older reader still opens such a vault, and that +//! unknown values are refused, are unit tests in src/security.rs, which can see the decrypted body. + +use std::collections::BTreeSet; + +use custos_vault::security::{ + AUDIT_LIMIT, Action, Auth, Item, KeptScope, Level, SETUP_WINDOW, SshRule, Window, accept_all_allowed, + hello_for_approvals, replacing_line_preticked, ssh_needs_auth, totp_offer_allowed, +}; +use custos_vault::{Error, KdfParams, SecretString, Vault}; + +const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }; +const NOW: i64 = 1_793_750_000_000; +const HOUR: i64 = 3_600_000; + +fn vault() -> Vault { + Vault::create(&SecretString::from("pw"), FAST).unwrap() +} + +fn actions(v: &Vault) -> Vec { + v.security_view(NOW).audit.iter().map(|e| e.action).collect() +} + +fn s(v: &[&str]) -> Vec { + v.iter().map(|x| x.to_string()).collect() +} + +#[test] +fn a_vault_that_never_had_setup_is_standard() { + let v = vault(); + assert_eq!(v.security_level(NOW), Level::Standard); + let view = v.security_view(NOW); + assert_eq!(view.level, Level::Standard); + assert!(view.setup.is_none() && view.setup_remaining.is_none()); + assert!(view.ticked.is_empty() && view.audit.is_empty() && view.kept_scope.is_none()); +} + +#[test] +fn setup_lasts_two_hours_from_its_start() { + assert_eq!(SETUP_WINDOW, 2 * HOUR); + let mut v = vault(); + let w = v.security_start_setup(NOW); + assert_eq!(w, Window { started: NOW, until: NOW + 2 * HOUR }); + assert_eq!(v.security_level(NOW), Level::Setup); + assert_eq!(v.security_level(NOW + 2 * HOUR - 1), Level::Setup, "the last millisecond is still Setup"); + assert_eq!(v.security_level(NOW + 2 * HOUR), Level::Standard, "`until` itself is not"); + assert_eq!(v.security_level(NOW - 1), Level::Standard, "a clock set back before the start is not Setup"); + assert_eq!(v.security_view(NOW + HOUR).setup_remaining, Some(HOUR)); + assert_eq!(v.security_view(NOW + 2 * HOUR).setup_remaining, None); + assert_eq!(actions(&v), [Action::SetupStarted]); +} + +#[test] +fn starting_setup_again_while_in_setup_extends_nothing() { + let mut v = vault(); + let w = v.security_start_setup(NOW); + assert_eq!(v.security_start_setup(NOW + HOUR), w); + assert_eq!(v.security_level(NOW + 2 * HOUR), Level::Standard); + assert_eq!(actions(&v), [Action::SetupStarted], "no second entry"); +} + +#[test] +fn finish_setup_ends_it_early_and_is_audited() { + let mut v = vault(); + assert!(!v.security_finish_setup(NOW), "nothing to finish"); + v.security_start_setup(NOW); + assert!(v.security_finish_setup(NOW + 10)); + assert_eq!(v.security_level(NOW + 10), Level::Standard); + assert_eq!(v.security_view(NOW + 10).finished, Some(NOW + 10)); + assert!(!v.security_finish_setup(NOW + 20), "once"); + assert_eq!(actions(&v), [Action::SetupStarted, Action::SetupFinished]); + // A later Connect via SSH starts a new window. + let w = v.security_start_setup(NOW + HOUR); + assert_eq!(w, Window { started: NOW + HOUR, until: NOW + 3 * HOUR }); + assert_eq!(v.security_level(NOW + HOUR), Level::Setup); + assert_eq!(v.security_view(NOW + HOUR).finished, None); + assert_eq!(actions(&v), [Action::SetupStarted, Action::SetupFinished, Action::SetupStarted]); +} + +#[test] +fn expiry_is_audited_once_by_the_first_change_that_notices_it() { + let mut v = vault(); + v.security_start_setup(NOW); + // Reading notices nothing. + assert_eq!(v.security_level(NOW + 3 * HOUR), Level::Standard); + assert_eq!(actions(&v), [Action::SetupStarted]); + v.security_tick(Item::NoSsh, NOW + 3 * HOUR); + v.security_record(Action::SshConnected, None, NOW + 3 * HOUR + 1).unwrap(); + assert!(!v.security_finish_setup(NOW + 3 * HOUR + 2)); + assert_eq!(actions(&v), [Action::SetupStarted, Action::SetupExpired, Action::Ticked, Action::SshConnected]); + let view = v.security_view(NOW + 3 * HOUR); + assert_eq!(view.finished, Some(NOW + 2 * HOUR), "ended at `until`"); + assert_eq!(view.audit[1].at, NOW + 3 * HOUR, "written when noticed"); + // Starting again after expiry opens a new window. + let w = v.security_start_setup(NOW + 4 * HOUR); + assert_eq!(w.started, NOW + 4 * HOUR); + assert_eq!(*actions(&v).last().unwrap(), Action::SetupStarted); +} + +#[test] +fn ticking_hardens_and_undoing_needs_hello_or_the_password_and_is_audited() { + let mut v = vault(); + assert!(v.security_tick(Item::HelloApprovals, NOW)); + assert!(!v.security_tick(Item::HelloApprovals, NOW + 1), "ticked already: no entry"); + assert_eq!(v.security_level(NOW), Level::Hardened); + assert!(v.security_tick(Item::NoSsh, NOW + 2)); + assert!(v.security_untick(Item::NoSsh, Auth::Hello, NOW + 3)); + assert!(!v.security_untick(Item::NoSsh, Auth::Password, NOW + 4), "not ticked: no entry"); + assert_eq!(v.security_level(NOW + 5), Level::Hardened); + assert!(v.security_untick(Item::HelloApprovals, Auth::Password, NOW + 5)); + assert_eq!(v.security_level(NOW + 6), Level::Standard); + + let audit = v.security_view(NOW + 6).audit; + let got: Vec<_> = audit.iter().map(|e| (e.at, e.action, e.item, e.auth)).collect(); + assert_eq!( + got, + [ + (NOW, Action::Ticked, Some(Item::HelloApprovals), None), + (NOW + 2, Action::Ticked, Some(Item::NoSsh), None), + (NOW + 3, Action::Unticked, Some(Item::NoSsh), Some(Auth::Hello)), + (NOW + 5, Action::Unticked, Some(Item::HelloApprovals), Some(Auth::Password)), + ] + ); +} + +#[test] +fn ticked_items_hold_during_setup() { + let mut v = vault(); + v.security_tick(Item::NoSsh, NOW); + v.security_tick(Item::TotpOnPhone, NOW); + v.security_start_setup(NOW + 1); + assert_eq!(v.security_level(NOW + 1), Level::Setup); + let ticked = v.security_view(NOW + 1).ticked; + assert_eq!(ticked, BTreeSet::from([Item::TotpOnPhone, Item::NoSsh])); + assert_eq!(ssh_needs_auth(Level::Setup, &ticked), SshRule::Off, "Setup never undoes hardening"); + assert!(!totp_offer_allowed(&ticked)); + // After Setup the ticks are still there: Hardened. + assert_eq!(v.security_level(NOW + 3 * HOUR), Level::Hardened); +} + +#[test] +fn the_state_survives_a_reopen() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("v.custos"); + let mut v = vault(); + v.security_start_setup(NOW); + v.security_tick(Item::NarrowScope, NOW + 1); + v.security_keep_scope(&s(&["arca/"]), &s(&["arca/", "fabrica/"])).unwrap(); + v.security_record(Action::TotpMoved, Some(Item::TotpOnPhone), NOW + 2).unwrap(); + v.save(&path).unwrap(); + let back = Vault::open_file(&path, &SecretString::from("pw")).unwrap(); + assert_eq!(back.security_view(NOW + 3), v.security_view(NOW + 3)); + assert_eq!(back.security_level(NOW + 3), Level::Setup); + let view = back.security_view(NOW + 3); + assert_eq!(view.kept_scope, Some(KeptScope { ask: s(&["arca/"]), offer: s(&["arca/", "fabrica/"]) })); + assert_eq!(view.audit.last().unwrap().item, Some(Item::TotpOnPhone)); +} + +#[test] +fn the_kept_scope_is_kept_once_and_taken_back() { + let mut v = vault(); + assert!(v.security_take_kept_scope().is_none()); + v.security_keep_scope(&s(&["arca/"]), &s(&["fabrica/"])).unwrap(); + // A second keep would lose the first prefixes: refused. + assert!(matches!(v.security_keep_scope(&s(&["x/"]), &[]), Err(Error::Security(_)))); + let kept = v.security_take_kept_scope().unwrap(); + assert_eq!(kept, KeptScope { ask: s(&["arca/"]), offer: s(&["fabrica/"]) }); + assert!(v.security_take_kept_scope().is_none()); + // The rules for a prefix. + for bad in [s(&[""]), s(&["a\nb"]), vec!["x".repeat(201)], (0..65).map(|i| format!("p{i}/")).collect()] { + assert!(matches!(v.security_keep_scope(&bad, &[]), Err(Error::Security(_))), "{bad:?}"); + assert!(matches!(v.security_keep_scope(&[], &bad), Err(Error::Security(_))), "{bad:?}"); + } + v.security_keep_scope(&[], &[]).unwrap(); + assert_eq!(v.security_take_kept_scope(), Some(KeptScope { ask: vec![], offer: vec![] })); +} + +#[test] +fn only_ssh_connected_and_totp_moved_are_recorded_directly() { + let mut v = vault(); + v.security_record(Action::SshConnected, None, NOW).unwrap(); + v.security_record(Action::TotpMoved, None, NOW + 1).unwrap(); + for a in [Action::SetupStarted, Action::SetupFinished, Action::SetupExpired, Action::Ticked, Action::Unticked] { + assert!(matches!(v.security_record(a, Some(Item::NoSsh), NOW + 2), Err(Error::Security(_))), "{a:?}"); + } + assert_eq!(actions(&v), [Action::SshConnected, Action::TotpMoved]); +} + +#[test] +fn the_audit_keeps_the_newest_5000() { + assert_eq!(AUDIT_LIMIT, 5_000); + let mut v = vault(); + for i in 0..(AUDIT_LIMIT as i64 + 2) { + v.security_record(Action::SshConnected, None, NOW + i).unwrap(); + } + let audit = v.security_view(NOW).audit; + assert_eq!(audit.len(), AUDIT_LIMIT); + assert_eq!(audit[0].at, NOW + 2); + assert_eq!(audit.last().unwrap().at, NOW + AUDIT_LIMIT as i64 + 1); +} + +#[test] +fn the_rules_before_a_card() { + let none = BTreeSet::new(); + // Accept all: only in Setup, only for a setup run with Provisio lines only. + assert!(accept_all_allowed(Level::Setup, "setup-1", true)); + assert!(!accept_all_allowed(Level::Setup, "setup-1", false), "a signing or approval line"); + assert!(!accept_all_allowed(Level::Setup, "r-42", true), "not a setup run"); + assert!(!accept_all_allowed(Level::Setup, "Setup-1", true), "the prefix is exact"); + assert!(!accept_all_allowed(Level::Standard, "setup-1", true)); + assert!(!accept_all_allowed(Level::Hardened, "setup-1", true)); + // A line that replaces a stored item is pre-ticked only where Accept all applies. + assert!(replacing_line_preticked(Level::Setup, true)); + assert!(!replacing_line_preticked(Level::Setup, false)); + assert!(!replacing_line_preticked(Level::Standard, true)); + assert!(!replacing_line_preticked(Level::Hardened, true)); + // Connect via SSH. + assert_eq!(ssh_needs_auth(Level::Setup, &none), SshRule::Allowed); + assert_eq!(ssh_needs_auth(Level::Standard, &none), SshRule::NeedsAuth); + let hello = BTreeSet::from([Item::HelloApprovals]); + assert_eq!(ssh_needs_auth(Level::Hardened, &hello), SshRule::NeedsAuth); + let off = BTreeSet::from([Item::NoSsh]); + for l in [Level::Setup, Level::Standard, Level::Hardened] { + assert_eq!(ssh_needs_auth(l, &off), SshRule::Off); + } + // TOTP offers and Hello for approvals. + assert!(totp_offer_allowed(&none) && totp_offer_allowed(&hello)); + assert!(!totp_offer_allowed(&BTreeSet::from([Item::TotpOnPhone]))); + assert!(hello_for_approvals(&hello) && !hello_for_approvals(&none) && !hello_for_approvals(&off)); +} + +#[test] +fn values_are_spelled_as_docs_format_says() { + let all = [ + Item::TotpOnPhone, + Item::HelloApprovals, + Item::NarrowScope, + Item::RotateSetup, + Item::NoSsh, + Item::PhoneApproves, + ]; + assert_eq!( + serde_json::to_string(&all).unwrap(), + r#"["totp-on-phone","hello-approvals","narrow-scope","rotate-setup","no-ssh","phone-approves"]"# + ); + let actions = [ + Action::SetupStarted, + Action::SetupFinished, + Action::SetupExpired, + Action::Ticked, + Action::Unticked, + Action::SshConnected, + Action::TotpMoved, + ]; + assert_eq!( + serde_json::to_string(&actions).unwrap(), + r#"["setup-started","setup-finished","setup-expired","ticked","unticked","ssh-connected","totp-moved"]"# + ); + assert_eq!(serde_json::to_string(&[Auth::Hello, Auth::Password]).unwrap(), r#"["hello","password"]"#); + assert_eq!( + serde_json::to_string(&[Level::Setup, Level::Standard, Level::Hardened]).unwrap(), + r#"["setup","standard","hardened"]"# + ); + assert_eq!( + serde_json::to_string(&[SshRule::Allowed, SshRule::NeedsAuth, SshRule::Off]).unwrap(), + r#"["allowed","needs-auth","off"]"# + ); +} diff --git a/docs/FORMAT.md b/docs/FORMAT.md index e8117e6..854e599 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -132,6 +132,15 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed: - `provision` (optional, core 0.11.0): the Provisio audit, every outcome of a server's *ask* or *offer* (the app's docs/10_provisio.md). An older Custos ignores it when it reads and drops it when it saves, so every Custos that saves the vault must be 0.11.0 or later. See "The provision audit" below. +- `security` (optional, core 0.12.0): the security level, the hardening checklist and their audit (the app's + docs/11_runs_and_levels.md). An older Custos ignores it when it reads and drops it when it saves (the level falls + back to Standard, the checklist to unticked), so every Custos that saves the vault must be 0.12.0 or later. See + "The security member" below. + +**Values older cores refuse.** A reader refuses a file whose closed lists hold a value it does not know (see each +member), so these values, new in core 0.12.0, make a vault unreadable for a core before 0.12.0 once they are +written: a `signing` audit entry of kind `approval` (docs/SIGNING.md), a `provision` entry with store `display` or +outcome `confirmed`. A vault without them still opens in core 0.11.0. ### The provision audit (core 0.11.0) @@ -151,13 +160,19 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed: | `direction` | `ask` (the server asked for a secret) or `offer` (the server offered one) | | `host` | the name the factor service gave, 1–253 characters `[A-Za-z0-9.-]` | | `item` | `^[a-z0-9][a-z0-9._-]{0,63}(/[a-z0-9][a-z0-9._-]{0,63}){0,3}$`, as the factor service checks it | -| `store` | `vault`, `claude` or `cloud` | +| `store` | `vault`, `claude`, `cloud` or (core 0.12.0) `display`: shown once on the card, stored nowhere | | `run` | optional, `[A-Za-z0-9._-]{1,64}` | | `kind` | optional, at most 200 characters, no control characters (an offer's label; an ask's `--generate` recipe) | | `code` | the match code: six ASCII digits | -| `outcome` | `approved`, `generated`, `accepted`, `refused`, `out-of-scope`, `invalid` or `expired` | +| `outcome` | `approved`, `generated`, `accepted`, `refused`, `out-of-scope`, `invalid`, `expired` or (core 0.12.0) `confirmed` | | `replaced` | `true` when an accepted offer replaced an existing item | +A **display offer** (core 0.12.0; a TOTP seed moved to a phone) is an `offer` with store `display`. Its outcome is +`confirmed` (Mark typed the phone's current code, Custos checked it and sent it to the server), `refused`, `expired`, +`invalid` or `out-of-scope`; never `accepted`, `approved` or `generated`, and never `replaced`, because nothing is +stored. `confirmed` belongs to display offers only. A code Custos's own check refuses stays on the card and is not +an outcome; a code the server then refuses (its exit 10) is not seen by Custos, so there is no `confirmed-wrong`. + - **No value, ever.** There is no member that holds a secret: every member is something the server sent in the clear through the mailbox (host, item, store, run, kind) or derives from a public key (`code`). A recorded entry is checked against the table above; an entry that does not fit is refused, not stored. @@ -166,6 +181,47 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed: - Readers ignore members of an entry they do not know. A file whose `provision` has an `outcome`, `direction` or `store` this core does not know does not open (`Corrupted`), as for `signing`. +### The security member (core 0.12.0) + +```json +"security": { + "setup": { "started": 1793750000000, "until": 1793757200000 }, + "finished": 1793751000000, + "ticked": ["hello-approvals", "no-ssh"], + "keptScope": { "ask": ["arca/"], "offer": ["arca/", "fabrica/"] }, + "audit": [ + { "at": 1793750000000, "action": "setup-started" }, + { "at": 1793751000000, "action": "setup-finished" }, + { "at": 1793752000000, "action": "ticked", "item": "no-ssh" }, + { "at": 1793753000000, "action": "unticked", "item": "no-ssh", "auth": "hello" } + ] +} +``` + +| Member | | +| :-- | :-- | +| `setup` | optional: the last Setup window, Unix milliseconds; `until` is 2 hours after `started` | +| `finished` | optional: when that window ended, by *Finish setup*, or `until` once its expiry was noticed | +| `ticked` | the checklist items that are ticked: `totp-on-phone`, `hello-approvals`, `narrow-scope`, `rotate-setup`, `no-ssh`, `phone-approves` | +| `keptScope` | optional: the server scope prefixes *Narrow the server scope* replaced (`ask`, `offer`: at most 64 each, 1–200 characters, no control characters), kept for its undo | +| `audit` | `{at, action, item?, auth?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected` or `totp-moved`; `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`) | + +The **level** is computed, never stored: + +- **Setup** while there is a `setup` window, it has not `finished`, and `started` ≤ now < `until`; +- otherwise **Hardened** when at least one item is ticked; +- otherwise **Standard** (also every vault without the member). + +Ticked items hold during Setup too: Setup never undoes hardening. Starting Setup while in Setup changes nothing; +after a window ended a new one starts at now. Its expiry is written (`setup-expired`, and `finished` = `until`) by +the first change after it, not by reading. + +- **Append-only** like `provision`: the API adds entries and lists them; the log keeps the newest 5 000. +- Absent while nothing was ever set, so a vault without it is written exactly as before. +- Readers ignore members they do not know. A file whose `security` has an item, action or auth this core does not + know, a window whose `until` is not after `started`, `finished` without `setup`, or a kept scope that breaks the + rules above does not open (`Corrupted`). + ### Item types and their fields (v1) `*` = secret (`"secret": true`: hidden until revealed, copied with clipboard protection).