Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ff14c8902f | |||
| 2b4a78644b | |||
| 8d5d08afcb | |||
| 61b98ee9b0 | |||
| 2c2d56b856 | |||
| 95613f4ed0 | |||
| 2d04f32f57 |
Generated
+12
-12
@@ -329,14 +329,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-browser"
|
||||
version = "0.15.0"
|
||||
version = "0.17.0"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "custos-gen"
|
||||
version = "0.15.0"
|
||||
version = "0.17.0"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"data-encoding",
|
||||
@@ -348,7 +348,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-kdbx"
|
||||
version = "0.15.0"
|
||||
version = "0.17.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"argon2",
|
||||
@@ -369,7 +369,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-keys"
|
||||
version = "0.15.0"
|
||||
version = "0.17.0"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"ed25519-dalek",
|
||||
@@ -382,7 +382,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-native"
|
||||
version = "0.15.0"
|
||||
version = "0.17.0"
|
||||
dependencies = [
|
||||
"custos-browser",
|
||||
"serde_json",
|
||||
@@ -392,11 +392,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-qr"
|
||||
version = "0.15.0"
|
||||
version = "0.17.0"
|
||||
|
||||
[[package]]
|
||||
name = "custos-seal"
|
||||
version = "0.15.0"
|
||||
version = "0.17.0"
|
||||
dependencies = [
|
||||
"chacha20poly1305",
|
||||
"hkdf",
|
||||
@@ -409,7 +409,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-share"
|
||||
version = "0.15.0"
|
||||
version = "0.17.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"chacha20poly1305",
|
||||
@@ -426,7 +426,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-sign"
|
||||
version = "0.15.0"
|
||||
version = "0.17.0"
|
||||
dependencies = [
|
||||
"blake2 0.10.6",
|
||||
"data-encoding",
|
||||
@@ -445,7 +445,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-totp"
|
||||
version = "0.15.0"
|
||||
version = "0.17.0"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"data-encoding",
|
||||
@@ -458,7 +458,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-vault"
|
||||
version = "0.15.0"
|
||||
version = "0.17.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"bip39",
|
||||
@@ -482,7 +482,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-wasm"
|
||||
version = "0.15.0"
|
||||
version = "0.17.0"
|
||||
dependencies = [
|
||||
"custos-qr",
|
||||
"custos-seal",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.15.0"
|
||||
version = "0.17.0"
|
||||
edition = "2024"
|
||||
license = "MPL-2.0"
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
|
||||
|
||||
@@ -15,6 +15,9 @@ 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;
|
||||
const KDF_ARGON2ID: u8 = 1;
|
||||
pub const SALT_LEN: usize = 32;
|
||||
pub const ID_LEN: usize = 16;
|
||||
@@ -244,6 +247,48 @@ impl SingleSlot {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<u8>,
|
||||
}
|
||||
|
||||
impl RecoverySlot {
|
||||
fn head(&self) -> Vec<u8> {
|
||||
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<u8> {
|
||||
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<Self, Error> {
|
||||
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(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Header {
|
||||
pub version: u16,
|
||||
pub slots: Vec<RawSlot>,
|
||||
@@ -317,6 +362,7 @@ impl Header {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
let mut singles = 0;
|
||||
let mut recoveries = 0;
|
||||
for s in &self.slots {
|
||||
match s.kind {
|
||||
SLOT_FACTOR => {}
|
||||
@@ -333,6 +379,10 @@ impl Header {
|
||||
}
|
||||
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),
|
||||
}
|
||||
@@ -341,6 +391,10 @@ impl Header {
|
||||
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(())
|
||||
}
|
||||
|
||||
@@ -356,6 +410,10 @@ impl Header {
|
||||
self.slots.iter().find(|s| s.kind == SLOT_SINGLE).and_then(|s| SingleSlot::parse(&s.payload).ok())
|
||||
}
|
||||
|
||||
pub fn recovery_slot(&self) -> Option<RecoverySlot> {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -22,12 +22,14 @@ mod format;
|
||||
pub mod identity;
|
||||
mod item;
|
||||
pub mod provision;
|
||||
mod recovery;
|
||||
mod save;
|
||||
mod secret;
|
||||
pub mod security;
|
||||
pub mod signing;
|
||||
|
||||
pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
|
||||
pub use recovery::RecoveryKey;
|
||||
pub use save::{CrashPoint, save_atomic, save_atomic_crashing};
|
||||
pub use secret::{SecretBytes, SecretString};
|
||||
|
||||
@@ -63,6 +65,12 @@ pub enum Error {
|
||||
FactorRejected,
|
||||
#[error("these two factors are kept on the same device; use one of them with another factor")]
|
||||
SameDevice,
|
||||
#[error("this is not a recovery key as Custos prints it: check each group of characters")]
|
||||
RecoveryKeyMistyped,
|
||||
#[error("this recovery key does not open this vault: it is another vault's, or an older one that was replaced")]
|
||||
WrongRecoveryKey,
|
||||
#[error("this vault has no recovery key")]
|
||||
NoRecoveryKey,
|
||||
#[error("a vault has at most 8 factors and one master password")]
|
||||
TooManyFactors,
|
||||
#[error("this vault has no Domi identity yet")]
|
||||
@@ -271,6 +279,7 @@ 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";
|
||||
const INFO_RECOVERY: &[u8] = b"custos recovery v2";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Body {
|
||||
@@ -721,6 +730,106 @@ impl Vault {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the recovery key (docs/FACTORS.md, "The recovery key") ----
|
||||
|
||||
/// Which recovery key a vault file has (its id, 8 hex characters), from the header alone.
|
||||
pub fn recovery_id_of(bytes: &[u8]) -> Result<Option<String>, Error> {
|
||||
Ok(Header::parse(bytes)?.0.recovery_slot().map(|s| recovery::id_hex(&s.id)))
|
||||
}
|
||||
|
||||
/// Which recovery key this vault has.
|
||||
pub fn recovery_id(&self) -> Option<String> {
|
||||
self.slots
|
||||
.iter()
|
||||
.find(|s| s.kind == format::SLOT_RECOVERY)
|
||||
.and_then(|s| format::RecoverySlot::parse(&s.payload).ok())
|
||||
.map(|s| recovery::id_hex(&s.id))
|
||||
}
|
||||
|
||||
fn recovery_put(&mut self) -> RecoveryKey {
|
||||
let mut id = [0u8; recovery::ID_LEN];
|
||||
crypto::fill_random(&mut id);
|
||||
let material = crypto::random_key();
|
||||
let mut salt = [0u8; SALT_LEN];
|
||||
crypto::fill_random(&mut salt);
|
||||
let mut slot = format::RecoverySlot { id, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() };
|
||||
let kek = crypto::hkdf(material.as_ref(), &slot.salt, INFO_RECOVERY);
|
||||
slot.wrapped = crypto::seal(&kek, &slot.nonce, self.key.as_ref(), &slot.aad());
|
||||
self.slots.retain(|s| s.kind != format::SLOT_RECOVERY);
|
||||
self.slots.push(slot.raw());
|
||||
recovery::encode(&id, &material)
|
||||
}
|
||||
|
||||
/// Makes the vault's recovery key and returns it, once: it is in no file and no log, so what the caller does
|
||||
/// not show or print is lost. A key the vault already had stops working. Only a two-factor vault has one
|
||||
/// (not version 1, not a machine-key vault). The caller saves.
|
||||
pub fn recovery_create(&mut self, now: i64) -> Result<RecoveryKey, Error> {
|
||||
if self.version != VERSION_2 {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
if self.is_store() {
|
||||
return Err(Error::FactorRejected);
|
||||
}
|
||||
let key = self.recovery_put();
|
||||
self.security.recovery_note(security::Action::RecoveryCreated, key.id(), now);
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
/// Removes the recovery key: from the next save on, only the factors open the vault. The caller saves.
|
||||
pub fn recovery_remove(&mut self, now: i64) -> Result<(), Error> {
|
||||
let id = self.recovery_id().ok_or(Error::NoRecoveryKey)?;
|
||||
self.slots.retain(|s| s.kind != format::SLOT_RECOVERY);
|
||||
self.security.recovery_note(security::Action::RecoveryRemoved, &id, now);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Opens a vault with its recovery key and, before handing it back, replaces what opened it until now: every
|
||||
/// factor is dropped, `new_password` and `second` (anything but a password) become its two factors, and the
|
||||
/// used recovery key is replaced by the new one returned here. The items and everything else stay. Nothing is
|
||||
/// written: the caller saves, and until it does the file is as it was.
|
||||
///
|
||||
/// This is the only call that takes a recovery key, so the key is never an everyday unlock.
|
||||
pub fn recover(
|
||||
bytes: &[u8],
|
||||
key: &SecretString,
|
||||
new_password: &SecretString,
|
||||
kdf: KdfParams,
|
||||
second: Unlock,
|
||||
label: &str,
|
||||
now: i64,
|
||||
) -> Result<(Vault, RecoveryKey), Error> {
|
||||
// What was typed is checked first: a typing mistake is not a wrong key.
|
||||
let (id, material) = recovery::decode(key)?;
|
||||
if second.kind() == FactorKind::Password {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
second.check()?;
|
||||
if new_password.expose().is_empty() {
|
||||
return Err(Error::WrongPassword);
|
||||
}
|
||||
kdf.check()?;
|
||||
let (header, body_at) = Header::parse(bytes)?;
|
||||
if header.version != VERSION_2 {
|
||||
return Err(Error::NoRecoveryKey);
|
||||
}
|
||||
let slot = header.recovery_slot().ok_or(Error::NoRecoveryKey)?;
|
||||
if slot.id != id {
|
||||
return Err(Error::WrongRecoveryKey);
|
||||
}
|
||||
let kek = crypto::hkdf(material.as_ref(), &slot.salt, INFO_RECOVERY);
|
||||
let k = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::WrongRecoveryKey)?;
|
||||
let mut v = Vault::open_body(bytes, header, body_at, key32(k)?)?;
|
||||
// Whoever held the old factors holds nothing of this vault from the next save on.
|
||||
v.slots.clear();
|
||||
v.factors.clear();
|
||||
v.kdf_new = kdf;
|
||||
v.add_factor(Unlock::Password(new_password), "Master password")?;
|
||||
v.add_factor(second, label)?;
|
||||
let new_key = v.recovery_put();
|
||||
v.security.recovery_note(security::Action::Recovered, &recovery::id_hex(&id), now);
|
||||
Ok((v, new_key))
|
||||
}
|
||||
|
||||
fn is_store(&self) -> bool {
|
||||
self.slots.iter().any(|s| s.kind == format::SLOT_SINGLE)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
//! The recovery key (docs/FACTORS.md, "The recovery key"): one long random key per vault that opens it alone, for
|
||||
//! the day the factors are gone. It is printed once and kept on paper. It is never an everyday unlock:
|
||||
//! [`crate::Vault::recover`] is the only call that takes it, and it replaces every factor before it returns.
|
||||
|
||||
use crate::Error;
|
||||
use crate::secret::SecretString;
|
||||
use data_encoding::BASE32_NOPAD;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::fmt;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
pub(crate) const ID_LEN: usize = 4;
|
||||
pub(crate) const MATERIAL_LEN: usize = 32;
|
||||
const CHECK_LEN: usize = 4;
|
||||
const CHECK_CONTEXT: &[u8] = b"custos recovery key v1";
|
||||
/// 40 bytes as base32: 64 characters, written as 8 groups of 8.
|
||||
const TEXT_LEN: usize = 64;
|
||||
const GROUP: usize = 8;
|
||||
|
||||
/// A recovery key as it is printed. `Debug` never shows it.
|
||||
pub struct RecoveryKey {
|
||||
id: String,
|
||||
text: Zeroizing<String>,
|
||||
}
|
||||
|
||||
impl RecoveryKey {
|
||||
/// Which key this is (8 hex characters): not secret, shown in Settings and printed next to the key.
|
||||
pub fn id(&self) -> &str {
|
||||
&self.id
|
||||
}
|
||||
|
||||
/// The key: 8 groups of 8 characters, `A-Z` and `2-7`.
|
||||
pub fn expose(&self) -> &str {
|
||||
&self.text
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for RecoveryKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "RecoveryKey({}, [redacted])", self.id)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn id_hex(id: &[u8; ID_LEN]) -> String {
|
||||
id.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
fn check(id: &[u8; ID_LEN], material: &[u8; MATERIAL_LEN]) -> [u8; CHECK_LEN] {
|
||||
let mut h = Sha256::new();
|
||||
h.update(CHECK_CONTEXT);
|
||||
h.update(id);
|
||||
h.update(material);
|
||||
let d = h.finalize();
|
||||
[d[0], d[1], d[2], d[3]]
|
||||
}
|
||||
|
||||
pub(crate) fn encode(id: &[u8; ID_LEN], material: &[u8; MATERIAL_LEN]) -> RecoveryKey {
|
||||
let mut raw = Zeroizing::new([0u8; ID_LEN + MATERIAL_LEN + CHECK_LEN]);
|
||||
raw[..ID_LEN].copy_from_slice(id);
|
||||
raw[ID_LEN..ID_LEN + MATERIAL_LEN].copy_from_slice(material);
|
||||
raw[ID_LEN + MATERIAL_LEN..].copy_from_slice(&check(id, material));
|
||||
let flat = Zeroizing::new(BASE32_NOPAD.encode(raw.as_ref()));
|
||||
let mut text = Zeroizing::new(String::with_capacity(TEXT_LEN + TEXT_LEN / GROUP));
|
||||
for (i, c) in flat.chars().enumerate() {
|
||||
if i > 0 && i % GROUP == 0 {
|
||||
text.push('-');
|
||||
}
|
||||
text.push(c);
|
||||
}
|
||||
RecoveryKey { id: id_hex(id), text }
|
||||
}
|
||||
|
||||
/// The id and the material of a typed key. Case, spaces and hyphens do not matter; a key that is too short, too
|
||||
/// long, has another character or fails its check is `RecoveryKeyMistyped`, before any vault is touched.
|
||||
pub(crate) fn decode(text: &SecretString) -> Result<([u8; ID_LEN], Zeroizing<[u8; MATERIAL_LEN]>), Error> {
|
||||
let mut flat = Zeroizing::new(String::with_capacity(TEXT_LEN));
|
||||
for c in text.expose().chars() {
|
||||
match c {
|
||||
' ' | '-' | '\t' | '\r' | '\n' => {}
|
||||
c if c.is_ascii_alphanumeric() && flat.len() < TEXT_LEN + 1 => flat.push(c.to_ascii_uppercase()),
|
||||
_ => return Err(Error::RecoveryKeyMistyped),
|
||||
}
|
||||
}
|
||||
if flat.len() != TEXT_LEN {
|
||||
return Err(Error::RecoveryKeyMistyped);
|
||||
}
|
||||
let raw = Zeroizing::new(BASE32_NOPAD.decode(flat.as_bytes()).map_err(|_| Error::RecoveryKeyMistyped)?);
|
||||
if raw.len() != ID_LEN + MATERIAL_LEN + CHECK_LEN {
|
||||
return Err(Error::RecoveryKeyMistyped);
|
||||
}
|
||||
let id: [u8; ID_LEN] = raw[..ID_LEN].try_into().expect("checked");
|
||||
let mut material = Zeroizing::new([0u8; MATERIAL_LEN]);
|
||||
material.copy_from_slice(&raw[ID_LEN..ID_LEN + MATERIAL_LEN]);
|
||||
if raw[ID_LEN + MATERIAL_LEN..] != check(&id, &material) {
|
||||
return Err(Error::RecoveryKeyMistyped);
|
||||
}
|
||||
Ok((id, material))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_printed_key_reads_back_however_it_is_typed() {
|
||||
let key = encode(&[0xa1, 0xb2, 0xc3, 0xd4], &[9; 32]);
|
||||
assert_eq!(key.id(), "a1b2c3d4");
|
||||
let text = key.expose().to_owned();
|
||||
assert_eq!(text.len(), 64 + 7);
|
||||
assert!(
|
||||
text.split('-')
|
||||
.all(|g| g.len() == 8 && g.bytes().all(|b| b.is_ascii_uppercase() || (b'2'..=b'7').contains(&b)))
|
||||
);
|
||||
for typed in
|
||||
[text.clone(), text.to_lowercase(), text.replace('-', " "), text.replace('-', ""), format!(" {text}\r\n")]
|
||||
{
|
||||
let (id, material) = decode(&SecretString::from(typed.as_str())).unwrap();
|
||||
assert_eq!((id, *material), ([0xa1, 0xb2, 0xc3, 0xd4], [9; 32]));
|
||||
}
|
||||
assert_eq!(format!("{key:?}"), "RecoveryKey(a1b2c3d4, [redacted])");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mistyped_key_is_told_apart_before_any_vault_is_touched() {
|
||||
let text = encode(&[1, 2, 3, 4], &[9; 32]).expose().to_owned();
|
||||
let mistyped = |s: String| matches!(decode(&SecretString::from(s.as_str())), Err(Error::RecoveryKeyMistyped));
|
||||
// One character changed, anywhere: the check catches it.
|
||||
for at in [0usize, 7, 40, 70] {
|
||||
let mut chars: Vec<char> = text.chars().collect();
|
||||
if chars[at] == '-' {
|
||||
continue;
|
||||
}
|
||||
chars[at] = if chars[at] == 'A' { 'B' } else { 'A' };
|
||||
assert!(mistyped(chars.into_iter().collect()), "position {at}");
|
||||
}
|
||||
// Two groups swapped, a group missing, one too many, a character that is never in a key.
|
||||
let groups: Vec<&str> = text.split('-').collect();
|
||||
let mut swapped = groups.clone();
|
||||
swapped.swap(2, 6);
|
||||
if swapped != groups {
|
||||
assert!(mistyped(swapped.join("-")));
|
||||
}
|
||||
assert!(mistyped(groups[1..].join("-")));
|
||||
assert!(mistyped(format!("{text}-AAAAAAAA")));
|
||||
assert!(mistyped(text.replacen(|c: char| c != '-', "1", 1)));
|
||||
assert!(mistyped(text.replacen('-', "_", 1)));
|
||||
assert!(mistyped(String::new()));
|
||||
assert!(mistyped("A".repeat(100_000)));
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,19 @@ pub enum Action {
|
||||
UnattendedSigned,
|
||||
/// *Take over the vault*: a master password added, the PC-only access removed.
|
||||
TakenOver,
|
||||
/// A standing approval was granted on a card (core 0.16.0; `detail`: the rule's repository, key, kind, pipeline
|
||||
/// and origin). Written by [`Vault::standing_grant`] only.
|
||||
StandingGranted,
|
||||
/// A standing approval was revoked (`detail`: the same). Written by [`Vault::standing_revoke`] only.
|
||||
StandingRevoked,
|
||||
/// A recovery key was made (core 0.17.0; `detail`: the key's id, never the key). Written by
|
||||
/// [`Vault::recovery_create`] only.
|
||||
RecoveryCreated,
|
||||
/// The recovery key was removed (`detail`: its id). Written by [`Vault::recovery_remove`] only.
|
||||
RecoveryRemoved,
|
||||
/// The vault was opened with its recovery key: every factor and the key were replaced (`detail`: the used
|
||||
/// key's id). Written by [`Vault::recover`] only.
|
||||
Recovered,
|
||||
}
|
||||
|
||||
/// What *Connect via SSH* needs.
|
||||
@@ -232,6 +245,28 @@ impl State {
|
||||
trim(&mut self.audit);
|
||||
}
|
||||
|
||||
/// Whether a checklist item is ticked.
|
||||
pub(crate) fn is_ticked(&self, item: Item) -> bool {
|
||||
self.ticked.contains(&item)
|
||||
}
|
||||
|
||||
/// `standing-granted` or `standing-revoked`, with the rule as its detail (cut to what a note may hold).
|
||||
pub(crate) fn standing_note(&mut self, action: Action, detail: &str, now: i64) {
|
||||
debug_assert!(matches!(action, Action::StandingGranted | Action::StandingRevoked));
|
||||
let detail: String = detail.chars().filter(|c| !c.is_control()).take(500).collect();
|
||||
self.notice_expiry(now);
|
||||
self.audit.push(SecurityEntry { at: now, action, item: None, auth: None, detail: Some(detail) });
|
||||
trim(&mut self.audit);
|
||||
}
|
||||
|
||||
/// `recovery-created`, `recovery-removed` or `recovered`, with the key's id as its detail.
|
||||
pub(crate) fn recovery_note(&mut self, action: Action, id: &str, now: i64) {
|
||||
debug_assert!(matches!(action, Action::RecoveryCreated | Action::RecoveryRemoved | Action::Recovered));
|
||||
self.notice_expiry(now);
|
||||
self.audit.push(SecurityEntry { at: now, action, item: None, auth: None, detail: Some(id.to_owned()) });
|
||||
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) {
|
||||
@@ -724,6 +759,108 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A vault whose release key has signed once and has one standing approval, used once (core 0.16.0).
|
||||
fn vault_with_a_standing_approval() -> Vault {
|
||||
use crate::signing::{Approval, Context, Request, Role, SignKind, Via};
|
||||
let mut v = vault();
|
||||
v.signing_create(Role::Release, &["release".to_string()], &["Arca".to_string()], NOW).unwrap();
|
||||
let r = Request {
|
||||
key: "domi-release".into(),
|
||||
kind: SignKind::Minisign,
|
||||
digest: vec![1; 64],
|
||||
manifest: None,
|
||||
approval: None,
|
||||
run: Some("r-42".into()),
|
||||
context: Context {
|
||||
repo: "Arca".into(),
|
||||
pipeline: "release".into(),
|
||||
file: "a.exe".into(),
|
||||
..Default::default()
|
||||
},
|
||||
via: Via::Local,
|
||||
};
|
||||
v.signing_sign(&r, Approval::Mark, NOW).unwrap();
|
||||
v.standing_grant(&r, NOW + 1).unwrap();
|
||||
v.signing_sign(&r, Approval::Standing, NOW + 2).unwrap();
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_reader_refuses_a_vault_in_which_a_standing_approval_was_granted() {
|
||||
let v = vault_with_a_standing_approval();
|
||||
let json = body_json(&v);
|
||||
assert!(json.contains(r#""standing":[{"id":""#) && json.contains(r#""outcome":"standing""#), "{json}");
|
||||
assert!(json.contains(r#""action":"standing-granted""#), "{json}");
|
||||
// Core 0.11.0 does not know the outcome or the action: it refuses the file rather than misread it.
|
||||
assert!(serde_json::from_str::<BodyV0_11>(&json).is_err());
|
||||
// The rules alone it would ignore: with the outcome it knows, its signing parser takes the member.
|
||||
let plain = json.replace(r#""outcome":"standing""#, r#""outcome":"approved""#);
|
||||
let body: serde_json::Value = serde_json::from_str(&plain).unwrap();
|
||||
let old: SigningV0_11 = serde_json::from_value(body["signing"].clone()).unwrap();
|
||||
assert_eq!(old.audit.len(), 2);
|
||||
// This core reads it back the same.
|
||||
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
|
||||
assert_eq!(back.standing_rules(), v.standing_rules());
|
||||
assert_eq!(back.standing_rules()[0].uses, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rule_whose_count_is_at_its_end_still_signs() {
|
||||
use crate::signing::{Approval, Context, Request, SignKind, Via};
|
||||
let v = vault_with_a_standing_approval();
|
||||
let json = body_json(&v).replace(r#""uses":1"#, r#""uses":18446744073709551615"#);
|
||||
let mut full = Vault::open(&with_body(&v, &json), &SecretString::from("pw")).unwrap();
|
||||
let r = Request {
|
||||
key: "domi-release".into(),
|
||||
kind: SignKind::Minisign,
|
||||
digest: vec![1; 64],
|
||||
manifest: None,
|
||||
approval: None,
|
||||
run: Some("r-43".into()),
|
||||
context: Context {
|
||||
repo: "Arca".into(),
|
||||
pipeline: "release".into(),
|
||||
file: "a.exe".into(),
|
||||
..Default::default()
|
||||
},
|
||||
via: Via::Local,
|
||||
};
|
||||
full.signing_sign(&r, Approval::Standing, NOW + 9).expect("signed, not a panic");
|
||||
assert_eq!(full.standing_rules()[0].uses, u64::MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_standing_approval_makes_the_vault_refuse_to_open() {
|
||||
let v = vault_with_a_standing_approval();
|
||||
let json = body_json(&v);
|
||||
assert!(Vault::open(&with_body(&v, &json), &SecretString::from("pw")).is_ok());
|
||||
let id = v.standing_rules()[0].id.clone();
|
||||
let shape = r#""kind":"minisign","pipeline":"release","via":"local""#;
|
||||
let cases = [
|
||||
// A rule edited to name another repository, pipeline, kind or origin no longer has its id.
|
||||
(
|
||||
r#""repo":"Arca","key":"domi-release","keyCreated""#.to_string(),
|
||||
r#""repo":"Fabrica","key":"domi-release","keyCreated""#.to_string(),
|
||||
),
|
||||
(shape.to_string(), r#""kind":"minisign","pipeline":"deploy","via":"local""#.to_string()),
|
||||
(shape.to_string(), r#""kind":"apk","pipeline":"release","via":"local""#.to_string()),
|
||||
(shape.to_string(), r#""kind":"minisign","pipeline":"release","via":"remote""#.to_string()),
|
||||
(shape.to_string(), r#""kind":"sigstore","pipeline":"release","via":"local""#.to_string()),
|
||||
(format!(r#""id":"{id}""#), r#""id":"0000000000000000""#.to_string()),
|
||||
// Targets belong to approvals only.
|
||||
(
|
||||
r#""via":"local","granted""#.to_string(),
|
||||
r#""via":"local","targets":["deploy to nixos-vm"],"granted""#.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:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_or_broken_security_values_make_the_vault_refuse_to_open() {
|
||||
let mut v = vault();
|
||||
|
||||
@@ -116,12 +116,16 @@ pub enum Approval {
|
||||
Mark,
|
||||
/// Nobody was asked: allowed for test keys only.
|
||||
Auto,
|
||||
/// Nobody was asked: a standing approval Mark granted fits the request (core 0.16.0). Refused when none does.
|
||||
Standing,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Outcome {
|
||||
Approved,
|
||||
/// Signed without asking: a standing approval fitted (core 0.16.0).
|
||||
Standing,
|
||||
Auto,
|
||||
Refused,
|
||||
Expired,
|
||||
@@ -151,6 +155,34 @@ pub struct AuditEntry {
|
||||
pub run: Option<String>,
|
||||
}
|
||||
|
||||
/// A standing approval (core 0.16.0, docs/SIGNING.md): what Mark allowed for good, when, and how often it was used.
|
||||
/// Nothing in it is secret.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StandingRule {
|
||||
/// 16 hex characters: the SHA-256 of repo, key, kind, pipeline and via, joined by newlines, cut short.
|
||||
pub id: String,
|
||||
pub repo: String,
|
||||
pub key: String,
|
||||
/// The key's `created`: a key made later under the same id does not inherit the rule.
|
||||
pub key_created: i64,
|
||||
pub kind: SignKind,
|
||||
pub pipeline: String,
|
||||
pub via: Via,
|
||||
/// For an approval: the deploy targets the rule was granted for.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub targets: Vec<String>,
|
||||
/// Unix milliseconds.
|
||||
pub granted: i64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_used: Option<i64>,
|
||||
#[serde(default)]
|
||||
pub uses: u64,
|
||||
}
|
||||
|
||||
/// At most this many standing approvals in a vault.
|
||||
pub const STANDING_MAX: usize = 256;
|
||||
|
||||
/// A signature handed back to the build.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Signed {
|
||||
@@ -213,6 +245,7 @@ impl fmt::Debug for Key {
|
||||
pub(crate) struct Store {
|
||||
keys: Vec<Key>,
|
||||
audit: Vec<AuditEntry>,
|
||||
standing: Vec<StandingRule>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -244,6 +277,9 @@ pub(crate) struct StoreJson {
|
||||
keys: Vec<KeyJson>,
|
||||
#[serde(default)]
|
||||
audit: Vec<AuditEntry>,
|
||||
/// Standing approvals (core 0.16.0); absent while there are none.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
standing: Vec<StandingRule>,
|
||||
}
|
||||
|
||||
fn b64(bytes: &[u8]) -> String {
|
||||
@@ -271,7 +307,7 @@ fn unhex8(s: &str) -> Option<[u8; 8]> {
|
||||
|
||||
impl Store {
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.keys.is_empty() && self.audit.is_empty()
|
||||
self.keys.is_empty() && self.audit.is_empty() && self.standing.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) fn from_json(j: StoreJson) -> Option<Store> {
|
||||
@@ -323,7 +359,10 @@ impl Store {
|
||||
repos: k.repos,
|
||||
});
|
||||
}
|
||||
Some(Store { keys, audit: j.audit })
|
||||
if j.standing.len() > STANDING_MAX || !j.standing.iter().all(rule_ok) {
|
||||
return None;
|
||||
}
|
||||
Some(Store { keys, audit: j.audit, standing: j.standing })
|
||||
}
|
||||
|
||||
pub(crate) fn json(&self) -> Option<StoreJson> {
|
||||
@@ -351,7 +390,7 @@ impl Store {
|
||||
repos: k.repos.clone(),
|
||||
})
|
||||
.collect();
|
||||
Some(StoreJson { keys, audit: self.audit.clone() })
|
||||
Some(StoreJson { keys, audit: self.audit.clone(), standing: self.standing.clone() })
|
||||
}
|
||||
|
||||
fn get(&self, id: &str) -> Option<&Key> {
|
||||
@@ -399,6 +438,52 @@ pub struct AndroidKey {
|
||||
pub repos: Vec<String>,
|
||||
}
|
||||
|
||||
/// A name in a rule: 1 to 100 characters, no control characters (as a key's scope lists hold them).
|
||||
fn name_ok(x: &str) -> bool {
|
||||
(1..=100).contains(&x.chars().count()) && !x.chars().any(char::is_control)
|
||||
}
|
||||
|
||||
fn kind_word(kind: SignKind) -> &'static str {
|
||||
match kind {
|
||||
SignKind::Minisign => "minisign",
|
||||
SignKind::Manifest => "manifest",
|
||||
SignKind::Authenticode => "authenticode",
|
||||
SignKind::Approval => "approval",
|
||||
SignKind::Apk => "apk",
|
||||
}
|
||||
}
|
||||
|
||||
fn via_word(via: Via) -> &'static str {
|
||||
match via {
|
||||
Via::Local => "local",
|
||||
Via::Remote => "remote",
|
||||
}
|
||||
}
|
||||
|
||||
/// A rule's id: one per repository, key, kind, pipeline and origin.
|
||||
fn rule_id(repo: &str, key: &str, kind: SignKind, pipeline: &str, via: Via) -> String {
|
||||
let joined = [repo, key, kind_word(kind), pipeline, via_word(via)].join("\n");
|
||||
custos_sign::sha256_hex(joined.as_bytes())[..16].to_string()
|
||||
}
|
||||
|
||||
/// A stored rule is what [`Vault::standing_grant`] could have written; anything else makes the vault refuse to open.
|
||||
fn rule_ok(r: &StandingRule) -> bool {
|
||||
r.id == rule_id(&r.repo, &r.key, r.kind, &r.pipeline, r.via)
|
||||
&& name_ok(&r.repo)
|
||||
&& name_ok(&r.pipeline)
|
||||
&& (1..=64).contains(&r.key.len())
|
||||
&& (r.via == Via::Local || r.kind == SignKind::Approval)
|
||||
&& (r.kind == SignKind::Approval) == !r.targets.is_empty()
|
||||
&& r.targets.len() <= 64
|
||||
&& r.targets.iter().all(|t| (1..=80).contains(&t.chars().count()) && !t.chars().any(char::is_control))
|
||||
}
|
||||
|
||||
/// What a rule says, for the security audit: names only.
|
||||
fn rule_words(r: &StandingRule) -> String {
|
||||
let targets = if r.targets.is_empty() { String::new() } else { format!(" ({} targets)", r.targets.len()) };
|
||||
format!("{} {} {} pipeline {} {}{targets}", r.repo, r.key, kind_word(r.kind), r.pipeline, via_word(r.via))
|
||||
}
|
||||
|
||||
fn in_scope(list: &[String], what: &str) -> bool {
|
||||
list.iter().any(|x| x == "*" || x == what)
|
||||
}
|
||||
@@ -726,6 +811,12 @@ impl Vault {
|
||||
self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now);
|
||||
return Err(r);
|
||||
}
|
||||
let rule = self.standing_rule_for(req, now).map(|r| r.id);
|
||||
if approval == Approval::Standing && rule.is_none() {
|
||||
let r = Refusal::NeedsApproval(req.key.clone());
|
||||
self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now);
|
||||
return Err(r);
|
||||
}
|
||||
let k = self.signing.get(&req.key).expect("checked");
|
||||
let seconds = seconds(now);
|
||||
let bytes = match (&k.secret, req.kind) {
|
||||
@@ -765,15 +856,25 @@ impl Vault {
|
||||
}
|
||||
};
|
||||
let sha256 = custos_sign::sha256_hex(&bytes);
|
||||
let outcome = if approval == Approval::Auto { Outcome::Auto } else { Outcome::Approved };
|
||||
let outcome = match approval {
|
||||
Approval::Auto => Outcome::Auto,
|
||||
Approval::Mark => Outcome::Approved,
|
||||
Approval::Standing => Outcome::Standing,
|
||||
};
|
||||
self.signing_record(req, outcome, None, Some(sha256.clone()), now);
|
||||
if let (Approval::Standing, Some(id)) = (approval, rule)
|
||||
&& let Some(r) = self.signing.standing.iter_mut().find(|r| r.id == id)
|
||||
{
|
||||
r.uses = r.uses.saturating_add(1);
|
||||
r.last_used = Some(now);
|
||||
}
|
||||
Ok(Signed { bytes, sha256 })
|
||||
}
|
||||
|
||||
/// Records a request that was not signed: Mark refused it, or nobody answered in time. The caller saves.
|
||||
pub fn signing_refuse(&mut self, req: &Request, outcome: Outcome, reason: Option<String>, now: i64) {
|
||||
let outcome = match outcome {
|
||||
Outcome::Approved | Outcome::Auto => Outcome::Refused,
|
||||
Outcome::Approved | Outcome::Auto | Outcome::Standing => Outcome::Refused,
|
||||
o => o,
|
||||
};
|
||||
self.signing_record(req, outcome, reason, None, now);
|
||||
@@ -827,6 +928,131 @@ impl Vault {
|
||||
});
|
||||
}
|
||||
|
||||
/// What a rule for `req` would name, when `req` could be signed and may be covered by one at all: the key's
|
||||
/// `created`, the repository and pipeline as the scope check reads them, and an approval's targets.
|
||||
fn standing_shape(&self, req: &Request, now: i64) -> Result<(i64, String, String, Vec<String>), Error> {
|
||||
let no = |why: &str| Error::Signing(why.into());
|
||||
let (view, approval) = self.check(req, now).map_err(|r| Error::Signing(r.to_string()))?;
|
||||
if req.run.is_none() {
|
||||
return Err(no("a standing approval is for requests that name a run"));
|
||||
}
|
||||
if req.via == Via::Remote && req.kind != SignKind::Approval {
|
||||
return Err(no("a release signature the server runner asks for always needs a card"));
|
||||
}
|
||||
if self.security.is_ticked(crate::security::Item::CardSigning) {
|
||||
return Err(no("Sign only with a card is ticked"));
|
||||
}
|
||||
let (repo, pipeline, targets) = match approval {
|
||||
Some(a) => (a.repo, a.pipeline, a.targets),
|
||||
None => (req.context.repo.clone(), req.context.pipeline.clone(), Vec::new()),
|
||||
};
|
||||
if !name_ok(&repo) || !name_ok(&pipeline) {
|
||||
return Err(no("the repository or pipeline is not a usable name"));
|
||||
}
|
||||
Ok((view.created, repo, pipeline, targets))
|
||||
}
|
||||
|
||||
/// Whether `req`, which Mark is approving on a card, may start a standing approval (docs/SIGNING.md, "Standing
|
||||
/// approvals"); the error says why not, in words for the card.
|
||||
pub fn standing_can_grant(&self, req: &Request, now: i64) -> Result<(), Error> {
|
||||
self.standing_shape(req, now)?;
|
||||
let k = self.signing.get(&req.key).expect("checked");
|
||||
if k.role != Role::Release {
|
||||
return Err(Error::Signing("a test key signs without asking: it needs no standing approval".into()));
|
||||
}
|
||||
// A key's first signature is never the one that starts a rule.
|
||||
let signed = |e: &AuditEntry| {
|
||||
e.key == k.id && e.at >= k.created && matches!(e.outcome, Outcome::Approved | Outcome::Standing)
|
||||
};
|
||||
if !self.signing.audit.iter().any(signed) {
|
||||
return Err(Error::Signing(format!(
|
||||
"`{}` has never signed: its first signature needs a card of its own",
|
||||
k.id
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stores the standing approval for `req` (or adds an approval's targets to the one there is) and writes
|
||||
/// `standing-granted` to the security audit. Call it before signing the request Mark approved. The caller saves.
|
||||
pub fn standing_grant(&mut self, req: &Request, now: i64) -> Result<StandingRule, Error> {
|
||||
self.standing_can_grant(req, now)?;
|
||||
let (key_created, repo, pipeline, targets) = self.standing_shape(req, now)?;
|
||||
let id = rule_id(&repo, &req.key, req.kind, &pipeline, req.via);
|
||||
let at = self.signing.standing.iter().position(|r| r.id == id);
|
||||
// The same combination again keeps its rule (and its count) unless the key under that id is another one.
|
||||
let mut rule = match at.map(|i| self.signing.standing[i].clone()).filter(|r| r.key_created == key_created) {
|
||||
Some(r) => r,
|
||||
None => StandingRule {
|
||||
id,
|
||||
repo,
|
||||
key: req.key.clone(),
|
||||
key_created,
|
||||
kind: req.kind,
|
||||
pipeline,
|
||||
via: req.via,
|
||||
targets: Vec::new(),
|
||||
granted: now,
|
||||
last_used: None,
|
||||
uses: 0,
|
||||
},
|
||||
};
|
||||
// Any target Mark sees on this card joins the ones he allowed before.
|
||||
for t in targets {
|
||||
if !rule.targets.contains(&t) {
|
||||
rule.targets.push(t);
|
||||
}
|
||||
}
|
||||
// Never stored in a form this core would refuse to read back; what was there stays as it was.
|
||||
if !rule_ok(&rule) {
|
||||
return Err(Error::Signing("this request cannot be written as a standing approval".into()));
|
||||
}
|
||||
match at {
|
||||
Some(i) => self.signing.standing[i] = rule.clone(),
|
||||
None if self.signing.standing.len() >= STANDING_MAX => {
|
||||
return Err(Error::Signing("there are 256 standing approvals already: revoke one first".into()));
|
||||
}
|
||||
None => self.signing.standing.push(rule.clone()),
|
||||
}
|
||||
self.security.standing_note(crate::security::Action::StandingGranted, &rule_words(&rule), now);
|
||||
Ok(rule)
|
||||
}
|
||||
|
||||
/// The standing approval `req` fits, if one does: the request passes [`Vault::signing_check_at`], names a run,
|
||||
/// and equals the rule in repository, pipeline, key, kind and origin (an approval: its targets are the rule's).
|
||||
pub fn standing_rule_for(&self, req: &Request, now: i64) -> Option<StandingRule> {
|
||||
let (key_created, repo, pipeline, targets) = self.standing_shape(req, now).ok()?;
|
||||
let id = rule_id(&repo, &req.key, req.kind, &pipeline, req.via);
|
||||
self.signing
|
||||
.standing
|
||||
.iter()
|
||||
.find(|r| {
|
||||
r.id == id
|
||||
&& r.repo == repo
|
||||
&& r.key == req.key
|
||||
&& r.key_created == key_created
|
||||
&& r.kind == req.kind
|
||||
&& r.pipeline == pipeline
|
||||
&& r.via == req.via
|
||||
&& targets.iter().all(|t| r.targets.contains(t))
|
||||
})
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// The standing approvals, oldest first.
|
||||
pub fn standing_rules(&self) -> Vec<StandingRule> {
|
||||
self.signing.standing.clone()
|
||||
}
|
||||
|
||||
/// Removes a standing approval, audited `standing-revoked`. False when there is none with this id. The caller
|
||||
/// saves.
|
||||
pub fn standing_revoke(&mut self, id: &str, now: i64) -> bool {
|
||||
let Some(i) = self.signing.standing.iter().position(|r| r.id == id) else { return false };
|
||||
let rule = self.signing.standing.remove(i);
|
||||
self.security.standing_note(crate::security::Action::StandingRevoked, &rule_words(&rule), now);
|
||||
true
|
||||
}
|
||||
|
||||
/// Every request any key was named in, oldest first.
|
||||
pub fn signing_audit(&self) -> &[AuditEntry] {
|
||||
&self.signing.audit
|
||||
@@ -883,6 +1109,27 @@ mod tests {
|
||||
assert_eq!(back.signing_keys(), views);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_made_again_under_the_same_id_does_not_inherit_the_rule() {
|
||||
let mut v =
|
||||
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
|
||||
v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), 1).unwrap();
|
||||
let r = Request { run: Some("r-1".into()), ..req("domi-release", SignKind::Minisign, 64) };
|
||||
v.signing_sign(&r, Approval::Mark, 2).unwrap();
|
||||
v.standing_grant(&r, 3).unwrap();
|
||||
assert!(v.standing_rule_for(&r, 4).is_some());
|
||||
// The same id, made at another time (no API does this; a rule must not depend on that).
|
||||
v.signing.keys.iter_mut().find(|k| k.id == "domi-release").unwrap().created = 10;
|
||||
assert!(v.standing_rule_for(&r, 11).is_none(), "the rule names the key it was granted for");
|
||||
assert!(matches!(v.signing_sign(&r, Approval::Standing, 11), Err(Refusal::NeedsApproval(_))));
|
||||
// The old key's signatures do not count as the new key's first one either.
|
||||
assert!(v.standing_grant(&r, 12).is_err());
|
||||
v.signing_sign(&r, Approval::Mark, 13).unwrap();
|
||||
let again = v.standing_grant(&r, 14).unwrap();
|
||||
assert_eq!((again.key_created, again.granted, again.uses), (10, 14, 0));
|
||||
assert_eq!(v.standing_rules().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_api_path_returns_a_private_key() {
|
||||
let mut v =
|
||||
@@ -942,13 +1189,20 @@ mod tests {
|
||||
reqs.push(req("domi-code-signing", SignKind::Apk, 64));
|
||||
for r in &reqs {
|
||||
out += &format!("{:?}", v.signing_check(r));
|
||||
for approval in [Approval::Mark, Approval::Auto] {
|
||||
for approval in [Approval::Mark, Approval::Auto, Approval::Standing] {
|
||||
match v.signing_sign(r, approval, 2) {
|
||||
Ok(signed) => out += &format!("{signed:?}{}", data_encoding::HEXLOWER.encode(&signed.bytes)),
|
||||
Err(e) => out += &format!("{e:?}{e}"),
|
||||
}
|
||||
// A standing approval for the same request with a run, once the key has signed (core 0.16.0).
|
||||
let with_run = Request { run: r.run.clone().or(Some("r-1".into())), ..r.clone() };
|
||||
out += &format!("{:?}{:?}", v.standing_can_grant(&with_run, 2), v.standing_grant(&with_run, 2));
|
||||
out += &format!("{:?}", v.standing_rule_for(&with_run, 2));
|
||||
}
|
||||
}
|
||||
assert!(v.standing_rules().len() >= 3, "rules were granted: {:?}", v.standing_rules());
|
||||
out += &serde_json::to_string(&v.standing_rules()).unwrap();
|
||||
out += &format!("{:?}{:?}", v.standing_rules(), v.security_view(3).audit);
|
||||
assert!(
|
||||
v.signing_audit().iter().any(|e| e.kind == SignKind::Approval && e.outcome == Outcome::Approved),
|
||||
"an approval was signed too"
|
||||
|
||||
@@ -86,7 +86,9 @@ fn a_factor_is_added_and_removed_without_the_others() {
|
||||
// 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 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.
|
||||
@@ -108,7 +110,8 @@ 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();
|
||||
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);
|
||||
@@ -168,7 +171,14 @@ fn a_machine_store_opens_with_its_device_key_alone() {
|
||||
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());
|
||||
assert!(
|
||||
Vault::open_with(
|
||||
&bytes,
|
||||
Unlock::Material(FactorKind::Device, &STORE),
|
||||
Unlock::Material(FactorKind::Device, &STORE)
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -178,10 +188,20 @@ fn limits_are_enforced() {
|
||||
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)));
|
||||
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());
|
||||
assert!(
|
||||
open(
|
||||
&bytes,
|
||||
Unlock::Material(FactorKind::Device, &[100; 32]),
|
||||
Unlock::Material(FactorKind::Device, &[105; 32])
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -190,7 +210,10 @@ fn no_factor_material_in_debug_output() {
|
||||
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}");
|
||||
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() {
|
||||
@@ -207,7 +230,8 @@ fn the_key_pair_item_type_round_trips() {
|
||||
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 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));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
//! The recovery key (docs/FACTORS.md, "The recovery key"): made on request, printed once, and taken by
|
||||
//! `Vault::recover` only, which replaces every factor and the key itself before it hands the vault back.
|
||||
|
||||
use custos_vault::security::Action;
|
||||
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 };
|
||||
const NOW: i64 = 1_793_750_000_000;
|
||||
const PC: [u8; 32] = [7; 32];
|
||||
const NEW_PC: [u8; 32] = [8; 32];
|
||||
const PHONE: [u8; 32] = [9; 32];
|
||||
|
||||
fn pw(s: &str) -> SecretString {
|
||||
SecretString::from(s)
|
||||
}
|
||||
|
||||
fn device(m: &[u8; 32]) -> Unlock<'_> {
|
||||
Unlock::Material(FactorKind::Device, m)
|
||||
}
|
||||
|
||||
/// A two-factor vault (password, this PC, a phone's approval) with one item.
|
||||
fn vault() -> Vault {
|
||||
let old = pw("the old master password");
|
||||
let mut v = Vault::create_with(Unlock::Password(&old), "Master password", device(&PC), "MARK-PC", FAST).unwrap();
|
||||
v.add_factor(Unlock::Material(FactorKind::Approval, &PHONE), "Phone").unwrap();
|
||||
let mut item = Item::new(ItemType::WebLogin, "Gitea", NOW);
|
||||
item.set("password", "item-secret-value", NOW);
|
||||
v.add(item);
|
||||
v
|
||||
}
|
||||
|
||||
fn actions(v: &Vault) -> Vec<Action> {
|
||||
v.security_view(NOW + 60_000).audit.iter().map(|e| e.action).collect()
|
||||
}
|
||||
|
||||
fn recover(bytes: &[u8], key: &str, new_password: &str) -> Result<(Vault, custos_vault::RecoveryKey), Error> {
|
||||
Vault::recover(bytes, &pw(key), &pw(new_password), FAST, device(&NEW_PC), "MARK-PC", NOW + 5000)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vault_without_a_recovery_key_is_as_before_and_making_one_changes_only_the_header() {
|
||||
let v = vault();
|
||||
let before = v.to_bytes().unwrap();
|
||||
assert_eq!(Vault::recovery_id_of(&before).unwrap(), None);
|
||||
assert_eq!(v.recovery_id(), None);
|
||||
assert!(matches!(recover(&before, &"A".repeat(64), "a new master password"), Err(Error::RecoveryKeyMistyped)));
|
||||
|
||||
let mut v = v;
|
||||
let key = v.recovery_create(NOW).unwrap();
|
||||
assert_eq!(v.recovery_id().as_deref(), Some(key.id()));
|
||||
let after = v.to_bytes().unwrap();
|
||||
assert_eq!(Vault::recovery_id_of(&after).unwrap().as_deref(), Some(key.id()));
|
||||
// The factors still open it, exactly as before, and the item is there.
|
||||
let old = pw("the old master password");
|
||||
let w = Vault::open_with(&after, Unlock::Password(&old), device(&PC)).unwrap();
|
||||
assert_eq!((w.items().len(), w.factors().len()), (1, 3));
|
||||
assert_eq!(actions(&w), [Action::RecoveryCreated]);
|
||||
assert_eq!(w.security_view(NOW).audit[0].detail.as_deref(), Some(key.id()));
|
||||
// The key is in neither the file nor the audit.
|
||||
let flat = key.expose().replace('-', "");
|
||||
let text = String::from_utf8_lossy(&after).into_owned();
|
||||
assert!(!text.contains(&flat) && !text.contains(key.expose()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovering_forces_a_new_password_new_factors_and_a_new_key() {
|
||||
let mut v = vault();
|
||||
let key = v.recovery_create(NOW).unwrap();
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
|
||||
let (r, new_key) = recover(&bytes, key.expose(), "a new master password").expect("recovered");
|
||||
// Everything in the vault is still there.
|
||||
assert_eq!(r.items().len(), 1);
|
||||
assert_eq!(r.item(&r.items()[0].id).unwrap().field("password").unwrap().value.expose(), "item-secret-value");
|
||||
// Exactly the two new factors; the old password, the old PC key and the phone are gone.
|
||||
let kinds: Vec<FactorKind> = r.factors().iter().map(|f| f.kind).collect();
|
||||
assert_eq!(kinds, [FactorKind::Password, FactorKind::Device]);
|
||||
assert_ne!(new_key.id(), key.id());
|
||||
assert_ne!(new_key.expose(), key.expose());
|
||||
assert_eq!(r.recovery_id().as_deref(), Some(new_key.id()));
|
||||
assert_eq!(actions(&r), [Action::RecoveryCreated, Action::Recovered]);
|
||||
let last = r.security_view(NOW + 5000).audit[1].clone();
|
||||
assert_eq!((last.at, last.detail.as_deref()), (NOW + 5000, Some(key.id())));
|
||||
|
||||
let saved = r.to_bytes().unwrap();
|
||||
let (old, new) = (pw("the old master password"), pw("a new master password"));
|
||||
assert!(Vault::open_with(&saved, Unlock::Password(&new), device(&NEW_PC)).is_ok());
|
||||
assert!(matches!(Vault::open_with(&saved, Unlock::Password(&old), device(&NEW_PC)), Err(Error::WrongPassword)));
|
||||
assert!(matches!(Vault::open_with(&saved, Unlock::Password(&new), device(&PC)), Err(Error::FactorRejected)));
|
||||
assert!(Vault::open_with(&saved, device(&PC), Unlock::Material(FactorKind::Approval, &PHONE)).is_err());
|
||||
// The used key is spent; the new one works, once more.
|
||||
assert!(matches!(recover(&saved, key.expose(), "yet another password"), Err(Error::WrongRecoveryKey)));
|
||||
assert!(recover(&saved, new_key.expose(), "yet another password").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recovery_key_is_never_an_everyday_unlock() {
|
||||
let mut v = vault();
|
||||
let key = v.recovery_create(NOW).unwrap();
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
let text = pw(key.expose());
|
||||
let (_, material) = (key.id(), key.expose().replace('-', ""));
|
||||
// It is not a password and not a factor: no ordinary way of opening takes it, alone or with a real factor.
|
||||
assert!(Vault::open(&bytes, &text).is_err());
|
||||
let old = pw("the old master password");
|
||||
assert!(matches!(Vault::open_with(&bytes, Unlock::Password(&text), device(&PC)), Err(Error::WrongPassword)));
|
||||
for kind in [FactorKind::Device, FactorKind::Totp, FactorKind::Approval, FactorKind::Passkey] {
|
||||
let as_material = Unlock::Material(kind, &material.as_bytes()[..32]);
|
||||
assert!(Vault::open_with(&bytes, Unlock::Password(&old), as_material).is_err(), "{kind:?}");
|
||||
}
|
||||
assert!(Vault::open_machine_store(&bytes, &PC).is_err());
|
||||
assert_eq!(Vault::is_machine_store(&bytes).unwrap(), false);
|
||||
// It does not count as a factor: two are still needed and it is not listed.
|
||||
assert_eq!(Vault::factor_ids(&bytes).unwrap().len(), 3);
|
||||
// Recovering needs a real second factor and a password worth the name.
|
||||
let two_passwords =
|
||||
Vault::recover(&bytes, &text, &pw("a new master password"), FAST, Unlock::Password(&old), "x", NOW);
|
||||
assert!(matches!(two_passwords, Err(Error::NeedTwoFactors)));
|
||||
let short = Vault::recover(&bytes, &text, &pw(""), FAST, device(&NEW_PC), "x", NOW);
|
||||
assert!(matches!(short, Err(Error::WrongPassword) | Err(Error::FactorRejected)));
|
||||
// A refused recovery changed nothing: the key still works.
|
||||
assert!(recover(&bytes, key.expose(), "a new master password").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_an_old_or_another_vaults_key_opens_nothing() {
|
||||
let mut v = vault();
|
||||
let first = v.recovery_create(NOW).unwrap();
|
||||
// A second key replaces the first: one key per vault.
|
||||
let second = v.recovery_create(NOW + 1000).unwrap();
|
||||
assert_ne!(first.id(), second.id());
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
assert!(matches!(recover(&bytes, first.expose(), "a new master password"), Err(Error::WrongRecoveryKey)));
|
||||
|
||||
let mut other = vault();
|
||||
let others = other.recovery_create(NOW).unwrap();
|
||||
assert!(matches!(recover(&bytes, others.expose(), "a new master password"), Err(Error::WrongRecoveryKey)));
|
||||
// The right key with its last character changed: the check says so before the vault is tried.
|
||||
let forged: String = {
|
||||
let mut flat: Vec<char> = second.expose().chars().collect();
|
||||
let last = flat.len() - 1;
|
||||
flat[last] = if flat[last] == 'A' { 'B' } else { 'A' };
|
||||
flat.into_iter().collect()
|
||||
};
|
||||
assert!(matches!(recover(&bytes, &forged, "a new master password"), Err(Error::RecoveryKeyMistyped)));
|
||||
assert!(recover(&bytes, second.expose(), "a new master password").is_ok());
|
||||
assert_eq!(actions(&v), [Action::RecoveryCreated, Action::RecoveryCreated]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_key_closes_that_door_and_is_audited() {
|
||||
let mut v = vault();
|
||||
assert!(matches!(v.recovery_remove(NOW), Err(Error::NoRecoveryKey)));
|
||||
let key = v.recovery_create(NOW).unwrap();
|
||||
v.recovery_remove(NOW + 1000).unwrap();
|
||||
assert_eq!(v.recovery_id(), None);
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
assert_eq!(Vault::recovery_id_of(&bytes).unwrap(), None);
|
||||
assert!(matches!(recover(&bytes, key.expose(), "a new master password"), Err(Error::NoRecoveryKey)));
|
||||
assert_eq!(actions(&v), [Action::RecoveryCreated, Action::RecoveryRemoved]);
|
||||
// The file is an ordinary two-factor vault again: byte for byte the slots an older reader knows.
|
||||
let old = pw("the old master password");
|
||||
assert!(Vault::open_with(&bytes, Unlock::Password(&old), device(&PC)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_two_factor_vault_gets_a_recovery_key() {
|
||||
// Version 1: one password. A recovery key would be its second way in without a second factor to replace.
|
||||
let mut v1 = Vault::create(&pw("a version one password"), FAST).unwrap();
|
||||
assert!(matches!(v1.recovery_create(NOW), Err(Error::NeedTwoFactors)));
|
||||
// A machine store opens itself; it has nothing to recover and must stay exactly one factor and its slot.
|
||||
let mut store = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
|
||||
assert!(matches!(store.recovery_create(NOW), Err(Error::FactorRejected)));
|
||||
assert!(Vault::open_machine_store(&store.to_bytes().unwrap(), &PC).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_with_a_broken_or_a_second_recovery_slot_is_malformed() {
|
||||
let mut v = vault();
|
||||
v.recovery_create(NOW).unwrap();
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
let plain = vault().to_bytes().unwrap();
|
||||
// The slot count is the byte after magic (6) and version (2); slots follow as kind, length (u16 LE), payload.
|
||||
let count = bytes[8] as usize;
|
||||
assert_eq!(count, plain[8] as usize + 1);
|
||||
let mut at = 9;
|
||||
let mut found = None;
|
||||
for _ in 0..count {
|
||||
let len = u16::from_le_bytes([bytes[at + 1], bytes[at + 2]]) as usize;
|
||||
if bytes[at] == 5 {
|
||||
found = Some((at, len));
|
||||
}
|
||||
at += 3 + len;
|
||||
}
|
||||
let (at, len) = found.expect("a recovery slot, kind 5");
|
||||
assert_eq!(len, 4 + 32 + 24 + 48);
|
||||
// A kind this reader does not know.
|
||||
let mut unknown = bytes.clone();
|
||||
unknown[at] = 6;
|
||||
assert!(matches!(Vault::factor_ids(&unknown), Err(Error::Malformed)));
|
||||
// The slot twice.
|
||||
let mut twice = bytes[..at + 3 + len].to_vec();
|
||||
twice.extend_from_slice(&bytes[at..at + 3 + len]);
|
||||
twice.extend_from_slice(&bytes[at + 3 + len..]);
|
||||
twice[8] += 1;
|
||||
assert!(matches!(Vault::factor_ids(&twice), Err(Error::Malformed)));
|
||||
// A changed byte in the slot: the header is the body's AAD, so the vault does not open at all.
|
||||
let mut flipped = bytes.clone();
|
||||
flipped[at + 3 + 10] ^= 1;
|
||||
let old = pw("the old master password");
|
||||
assert!(matches!(Vault::open_with(&flipped, Unlock::Password(&old), device(&PC)), Err(Error::Corrupted)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_key_and_the_audit_survive_a_reopen_and_ordinary_changes() {
|
||||
let mut v = vault();
|
||||
let key = v.recovery_create(NOW).unwrap();
|
||||
let old = pw("the old master password");
|
||||
let mut w = Vault::open_with(&v.to_bytes().unwrap(), Unlock::Password(&old), device(&PC)).unwrap();
|
||||
// Changing the password, adding and removing a factor: none of them touches the recovery key.
|
||||
w.change_password(&pw("a changed master password"), FAST).unwrap();
|
||||
let id = w.add_factor(Unlock::Material(FactorKind::Totp, &[5; 32]), "TOTP").unwrap();
|
||||
w.remove_factor(&id).unwrap();
|
||||
assert_eq!(w.recovery_id().as_deref(), Some(key.id()));
|
||||
let bytes = w.to_bytes().unwrap();
|
||||
assert!(recover(&bytes, key.expose(), "a new master password").is_ok());
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
//! Standing approvals (core 0.16.0, docs/SIGNING.md "Standing approvals"): a rule Mark grants from a request he is
|
||||
//! approving, for one repository, key, kind, pipeline and origin. A later request that fits is signed without
|
||||
//! asking and recorded as `standing`; everything else still needs him.
|
||||
|
||||
use custos_vault::security::{Action, Auth, Item};
|
||||
use custos_vault::signing::{AndroidKey, Approval, Context, Outcome, Refusal, Request, Role, SignKind, Via};
|
||||
use custos_vault::{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 COMMIT: &str = "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1";
|
||||
|
||||
fn s(v: &[&str]) -> Vec<String> {
|
||||
v.iter().map(|x| x.to_string()).collect()
|
||||
}
|
||||
|
||||
/// The release set for the pipelines `release` and `deploy` of Arca, Aula and Fabrica, and the test set.
|
||||
fn vault() -> Vault {
|
||||
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
v.signing_create(Role::Release, &s(&["release", "deploy"]), &s(&["Arca", "Aula", "Fabrica"]), NOW).unwrap();
|
||||
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap();
|
||||
v
|
||||
}
|
||||
|
||||
fn ctx(pipeline: &str, repo: &str) -> Context {
|
||||
Context {
|
||||
repo: repo.into(),
|
||||
commit: COMMIT.into(),
|
||||
pipeline: pipeline.into(),
|
||||
step: "sign".into(),
|
||||
trigger: "tag".into(),
|
||||
file: "Arca_0.7.0_x64-setup.exe".into(),
|
||||
size: 25_145_977,
|
||||
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
|
||||
version: "0.7.0".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn minisign(repo: &str, pipeline: &str, run: &str) -> Request {
|
||||
Request {
|
||||
key: "domi-release".into(),
|
||||
kind: SignKind::Minisign,
|
||||
digest: vec![7; 64],
|
||||
manifest: None,
|
||||
approval: None,
|
||||
run: Some(run.into()),
|
||||
context: ctx(pipeline, repo),
|
||||
via: Via::Local,
|
||||
}
|
||||
}
|
||||
|
||||
fn authenticode(repo: &str, run: &str) -> Request {
|
||||
Request {
|
||||
key: "domi-code-signing".into(),
|
||||
kind: SignKind::Authenticode,
|
||||
digest: vec![9; 32],
|
||||
..minisign(repo, "release", run)
|
||||
}
|
||||
}
|
||||
|
||||
fn approval(repo: &str, run: &str, targets: &[&str], via: Via) -> Request {
|
||||
let targets = targets.iter().map(|t| format!("\"{t}\"")).collect::<Vec<_>>().join(",");
|
||||
let text = format!(
|
||||
r#"{{"v":1,"run":"{run}","repo":"{repo}","commit":"{COMMIT}","pipeline":"deploy","version":"0.7.0","targets":[{targets}],"expires":{}}}"#,
|
||||
NOW / 1000 + 600
|
||||
);
|
||||
Request {
|
||||
key: "domi-approve".into(),
|
||||
kind: SignKind::Approval,
|
||||
digest: vec![],
|
||||
manifest: None,
|
||||
approval: Some(text),
|
||||
run: Some(run.into()),
|
||||
context: Context {
|
||||
repo: repo.into(),
|
||||
pipeline: "deploy".into(),
|
||||
trigger: "manual".into(),
|
||||
..Default::default()
|
||||
},
|
||||
via,
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark approves `req` on a card (the key's signature that must come before any rule).
|
||||
fn mark_signs(v: &mut Vault, req: &Request) {
|
||||
v.signing_sign(req, Approval::Mark, NOW).expect("signed with Mark's click");
|
||||
}
|
||||
|
||||
/// Mark approves `req` with *Always allow*: the rule first, then the signature.
|
||||
fn always(v: &mut Vault, req: &Request) -> String {
|
||||
let rule = v.standing_grant(req, NOW + 1).expect("granted");
|
||||
v.signing_sign(req, Approval::Mark, NOW + 1).unwrap();
|
||||
rule.id
|
||||
}
|
||||
|
||||
fn outcomes(v: &Vault) -> Vec<Outcome> {
|
||||
v.signing_audit().iter().map(|e| e.outcome).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_granted_rule_signs_the_next_matching_request_and_records_it() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
assert!(v.standing_rules().is_empty());
|
||||
assert!(v.standing_rule_for(&minisign("Arca", "release", "r-2"), NOW).is_none(), "nothing fits before a grant");
|
||||
|
||||
let id = always(&mut v, &minisign("Arca", "release", "r-2"));
|
||||
let rules = v.standing_rules();
|
||||
assert_eq!(rules.len(), 1);
|
||||
let r = &rules[0];
|
||||
assert_eq!(
|
||||
(r.id.as_str(), r.repo.as_str(), r.key.as_str(), r.pipeline.as_str()),
|
||||
(id.as_str(), "Arca", "domi-release", "release")
|
||||
);
|
||||
assert_eq!((r.kind, r.via, r.granted, r.uses, r.last_used), (SignKind::Minisign, Via::Local, NOW + 1, 0, None));
|
||||
|
||||
// The next run: it fits, and signing with the rule records everything an approved entry holds.
|
||||
let next = minisign("Arca", "release", "r-3");
|
||||
assert_eq!(v.standing_rule_for(&next, NOW + 5).map(|r| r.id), Some(id.clone()));
|
||||
let signed = v.signing_sign(&next, Approval::Standing, NOW + 5).expect("signed by the rule");
|
||||
assert_eq!(outcomes(&v), [Outcome::Approved, Outcome::Approved, Outcome::Standing]);
|
||||
let e = v.signing_audit().last().unwrap().clone();
|
||||
assert_eq!(e.context, ctx("release", "Arca"));
|
||||
assert_eq!(
|
||||
(e.key.as_str(), e.kind, e.via, e.run.as_deref(), e.at),
|
||||
("domi-release", SignKind::Minisign, Via::Local, Some("r-3"), NOW + 5)
|
||||
);
|
||||
assert_eq!(e.signature.as_deref(), Some(signed.sha256.as_str()));
|
||||
let r = &v.standing_rules()[0];
|
||||
assert_eq!((r.uses, r.last_used), (1, Some(NOW + 5)));
|
||||
|
||||
// Granting the same thing again makes no second rule and keeps the count.
|
||||
assert_eq!(v.standing_grant(&minisign("Arca", "release", "r-4"), NOW + 9).unwrap().id, id);
|
||||
assert_eq!(v.standing_rules().len(), 1);
|
||||
assert_eq!(v.standing_rules()[0].uses, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_repository_key_kind_pipeline_or_origin_does_not_fit() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
mark_signs(&mut v, &authenticode("Arca", "r-1"));
|
||||
always(&mut v, &minisign("Arca", "release", "r-2"));
|
||||
assert!(v.standing_rule_for(&minisign("Arca", "release", "r-3"), NOW).is_some());
|
||||
|
||||
let sums = format!("{} Arca_0.7.0_x64-setup.exe\n", "c".repeat(64));
|
||||
let cases: [(&str, Request); 5] = [
|
||||
("another repository", minisign("Fabrica", "release", "r-3")),
|
||||
("another pipeline", minisign("Arca", "deploy", "r-3")),
|
||||
("another key and kind", authenticode("Arca", "r-3")),
|
||||
(
|
||||
"another kind of the same key",
|
||||
Request {
|
||||
kind: SignKind::Manifest,
|
||||
digest: vec![],
|
||||
manifest: Some(sums),
|
||||
..minisign("Arca", "release", "r-3")
|
||||
},
|
||||
),
|
||||
("the server runner", Request { via: Via::Remote, ..minisign("Arca", "release", "r-3") }),
|
||||
];
|
||||
for (what, req) in cases {
|
||||
assert!(v.signing_check_at(&req, NOW).is_ok(), "{what}: the key itself would sign it");
|
||||
assert!(v.standing_rule_for(&req, NOW).is_none(), "{what}");
|
||||
let r = v.signing_sign(&req, Approval::Standing, NOW);
|
||||
assert!(matches!(r, Err(Refusal::NeedsApproval(_))), "{what}: {r:?}");
|
||||
}
|
||||
assert_eq!(v.standing_rules()[0].uses, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_out_of_the_keys_scope_never_fits_and_narrowing_the_scope_stops_the_rule() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
// Out of scope today: no rule can be made for it.
|
||||
assert!(v.standing_grant(&minisign("Postea", "release", "r-2"), NOW).is_err());
|
||||
assert!(v.standing_grant(&minisign("Arca", "nightly", "r-2"), NOW).is_err());
|
||||
assert!(v.standing_rules().is_empty());
|
||||
|
||||
always(&mut v, &minisign("Arca", "release", "r-2"));
|
||||
// Mark narrows the key: Arca may no longer use it. The rule is still listed and no longer fits.
|
||||
v.signing_set_scope("domi-release", &s(&["release"]), &s(&["Fabrica"])).unwrap();
|
||||
let req = minisign("Arca", "release", "r-3");
|
||||
assert!(v.standing_rule_for(&req, NOW).is_none());
|
||||
assert!(matches!(v.signing_sign(&req, Approval::Standing, NOW), Err(Refusal::OutOfScope(_))));
|
||||
assert_eq!(v.standing_rules().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_without_a_run_never_fits() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
let no_run = Request { run: None, ..minisign("Arca", "release", "x") };
|
||||
assert!(v.standing_grant(&no_run, NOW).is_err(), "and cannot start a rule");
|
||||
always(&mut v, &minisign("Arca", "release", "r-2"));
|
||||
assert!(v.standing_rule_for(&no_run, NOW).is_none());
|
||||
assert!(matches!(v.signing_sign(&no_run, Approval::Standing, NOW), Err(Refusal::NeedsApproval(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keys_first_signature_cannot_start_a_rule() {
|
||||
let mut v = vault();
|
||||
let first = minisign("Arca", "release", "r-1");
|
||||
assert!(v.standing_can_grant(&first, NOW).is_err());
|
||||
assert!(v.standing_grant(&first, NOW).is_err(), "the key has never signed");
|
||||
assert!(v.standing_rules().is_empty());
|
||||
// A refused or expired card is not a signature either.
|
||||
v.signing_refuse(&first, Outcome::Refused, None, NOW);
|
||||
assert!(v.standing_grant(&first, NOW).is_err());
|
||||
// Mark signs once on the card; from then on the key can have a rule.
|
||||
mark_signs(&mut v, &first);
|
||||
assert!(v.standing_can_grant(&minisign("Arca", "release", "r-2"), NOW).is_ok());
|
||||
// Another key of the same vault has still never signed.
|
||||
assert!(v.standing_grant(&authenticode("Arca", "r-2"), NOW).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_test_key_and_a_server_runners_release_signature_cannot_start_a_rule() {
|
||||
let mut v = vault();
|
||||
let test = Request {
|
||||
key: "domi-test".into(),
|
||||
context: Context { trigger: "push".into(), ..ctx("ci", "Arca") },
|
||||
..minisign("Arca", "ci", "r-1")
|
||||
};
|
||||
v.signing_sign(&test, Approval::Auto, NOW).unwrap();
|
||||
assert!(v.standing_grant(&test, NOW).is_err(), "a test key signs without asking anyway");
|
||||
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
let remote = Request { via: Via::Remote, ..minisign("Arca", "release", "r-2") };
|
||||
assert!(v.standing_can_grant(&remote, NOW).is_err());
|
||||
assert!(v.standing_grant(&remote, NOW).is_err(), "a release signature asked through the mailbox");
|
||||
assert!(v.standing_rules().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_approval_rule_holds_only_for_the_targets_it_was_granted_for() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &approval("Aula", "r-1", &["deploy to nixos-vm"], Via::Remote));
|
||||
let id = always(&mut v, &approval("Aula", "r-2", &["deploy to nixos-vm"], Via::Remote));
|
||||
let r = &v.standing_rules()[0];
|
||||
assert_eq!((r.repo.as_str(), r.pipeline.as_str(), r.via), ("Aula", "deploy", Via::Remote));
|
||||
assert_eq!(r.targets, s(&["deploy to nixos-vm"]));
|
||||
|
||||
assert!(v.standing_rule_for(&approval("Aula", "r-3", &["deploy to nixos-vm"], Via::Remote), NOW).is_some());
|
||||
// A target Mark has not seen, alone or next to the known one; another repository; the same from this PC.
|
||||
for (what, req) in [
|
||||
("a new target", approval("Aula", "r-3", &["publish to Aula"], Via::Remote)),
|
||||
(
|
||||
"a new target next to the old",
|
||||
approval("Aula", "r-3", &["deploy to nixos-vm", "publish to Aula"], Via::Remote),
|
||||
),
|
||||
("another repository", approval("Arca", "r-3", &["deploy to nixos-vm"], Via::Remote)),
|
||||
("this PC's pipe", approval("Aula", "r-3", &["deploy to nixos-vm"], Via::Local)),
|
||||
] {
|
||||
assert!(v.signing_check_at(&req, NOW).is_ok(), "{what}");
|
||||
assert!(v.standing_rule_for(&req, NOW).is_none(), "{what}");
|
||||
}
|
||||
// Granting again on a card that shows the new target adds it to the same rule.
|
||||
let wider = approval("Aula", "r-4", &["deploy to nixos-vm", "publish to Aula"], Via::Remote);
|
||||
assert_eq!(always(&mut v, &wider), id);
|
||||
assert_eq!(v.standing_rules().len(), 1);
|
||||
assert_eq!(v.standing_rules()[0].targets, s(&["deploy to nixos-vm", "publish to Aula"]));
|
||||
let signed =
|
||||
v.signing_sign(&approval("Aula", "r-5", &["publish to Aula"], Via::Remote), Approval::Standing, NOW + 9);
|
||||
assert!(signed.is_ok(), "{signed:?}");
|
||||
assert_eq!(v.signing_audit().last().unwrap().context.file, "approval-r-5.json");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sign_only_with_a_card_pauses_every_rule() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
always(&mut v, &minisign("Arca", "release", "r-2"));
|
||||
let req = minisign("Arca", "release", "r-3");
|
||||
|
||||
v.security_tick(Item::CardSigning, NOW + 2);
|
||||
assert!(v.standing_rule_for(&req, NOW + 3).is_none());
|
||||
assert!(matches!(v.signing_sign(&req, Approval::Standing, NOW + 3), Err(Refusal::NeedsApproval(_))));
|
||||
assert!(v.standing_can_grant(&req, NOW + 3).is_err(), "and no new rule while it is ticked");
|
||||
assert_eq!(v.standing_rules().len(), 1, "the rule is kept, paused");
|
||||
// Other checklist items do not pause it.
|
||||
v.security_untick(Item::CardSigning, Auth::Hello, NOW + 4);
|
||||
v.security_tick(Item::NoAutoConnect, NOW + 4);
|
||||
assert!(v.standing_rule_for(&req, NOW + 5).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_revoked_rule_no_longer_fits_and_both_are_in_the_security_audit() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
let id = always(&mut v, &minisign("Arca", "release", "r-2"));
|
||||
assert!(!v.standing_revoke("0000000000000000", NOW + 2), "no such rule");
|
||||
assert!(v.standing_revoke(&id, NOW + 3));
|
||||
assert!(!v.standing_revoke(&id, NOW + 4), "once");
|
||||
assert!(v.standing_rules().is_empty());
|
||||
|
||||
let req = minisign("Arca", "release", "r-3");
|
||||
assert!(v.standing_rule_for(&req, NOW + 5).is_none());
|
||||
assert!(matches!(v.signing_sign(&req, Approval::Standing, NOW + 5), Err(Refusal::NeedsApproval(_))));
|
||||
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Refused);
|
||||
|
||||
let notes: Vec<(Action, String)> = v
|
||||
.security_view(NOW + 6)
|
||||
.audit
|
||||
.into_iter()
|
||||
.filter(|e| matches!(e.action, Action::StandingGranted | Action::StandingRevoked))
|
||||
.map(|e| (e.action, e.detail.unwrap_or_default()))
|
||||
.collect();
|
||||
assert_eq!(notes.len(), 2, "{notes:?}");
|
||||
assert_eq!(notes[0].0, Action::StandingGranted);
|
||||
assert_eq!(notes[1].0, Action::StandingRevoked);
|
||||
for (_, d) in ¬es {
|
||||
assert!(
|
||||
d.contains("Arca") && d.contains("domi-release") && d.contains("minisign") && d.contains("release"),
|
||||
"{d}"
|
||||
);
|
||||
}
|
||||
// The public note call cannot write them.
|
||||
assert!(v.security_note(Action::StandingGranted, "x", NOW).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_and_the_standing_outcome_survive_a_reopen() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
mark_signs(&mut v, &approval("Aula", "r-1", &["deploy to nixos-vm"], Via::Remote));
|
||||
always(&mut v, &minisign("Arca", "release", "r-2"));
|
||||
always(&mut v, &approval("Aula", "r-2", &["deploy to nixos-vm"], Via::Remote));
|
||||
v.signing_sign(&minisign("Arca", "release", "r-3"), Approval::Standing, NOW + 5).unwrap();
|
||||
|
||||
let mut back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
|
||||
assert_eq!(back.standing_rules(), v.standing_rules());
|
||||
assert_eq!(back.standing_rules().len(), 2);
|
||||
assert_eq!(back.signing_audit(), v.signing_audit());
|
||||
// After the restart the rule still answers, and still only what it was granted for.
|
||||
assert!(back.signing_sign(&minisign("Arca", "release", "r-4"), Approval::Standing, NOW + 9).is_ok());
|
||||
assert!(back.standing_rule_for(&minisign("Fabrica", "release", "r-4"), NOW + 9).is_none());
|
||||
assert_eq!(back.standing_rules().iter().find(|r| r.repo == "Arca").unwrap().uses, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_with_standing_and_no_rule_is_refused_and_recorded() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
let req = minisign("Arca", "release", "r-2");
|
||||
let r = v.signing_sign(&req, Approval::Standing, NOW);
|
||||
assert!(matches!(r, Err(Refusal::NeedsApproval(_))), "{r:?}");
|
||||
assert_eq!(outcomes(&v), [Outcome::Approved, Outcome::Refused]);
|
||||
assert!(v.signing_audit()[1].signature.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_android_keys_rule_signs_its_apks_and_nothing_else() {
|
||||
let spec = AndroidKey {
|
||||
id: "postea-android".into(),
|
||||
name: "Postea Android".into(),
|
||||
cn: "Postea".into(),
|
||||
o: "Marek Novak".into(),
|
||||
c: "CZ".into(),
|
||||
role: Role::Release,
|
||||
pipelines: s(&["release"]),
|
||||
repos: s(&["mnovak/Postea"]),
|
||||
};
|
||||
let apk = |run: &str| Request {
|
||||
key: "postea-android".into(),
|
||||
kind: SignKind::Apk,
|
||||
digest: vec![3; 128],
|
||||
context: Context { file: "Postea-1.0.0.apk".into(), ..ctx("release", "mnovak/Postea") },
|
||||
..minisign("mnovak/Postea", "release", run)
|
||||
};
|
||||
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
v.signing_create_android(&spec, NOW).unwrap();
|
||||
// The first signature (the card says so) cannot be the one that starts the rule.
|
||||
assert!(v.standing_grant(&apk("r-1"), NOW).is_err());
|
||||
mark_signs(&mut v, &apk("r-1"));
|
||||
always(&mut v, &apk("r-2"));
|
||||
let signed = v.signing_sign(&apk("r-3"), Approval::Standing, NOW + 2).expect("an APK fits its rule");
|
||||
assert_eq!(signed.bytes.len(), 2 * 512, "v2 and v3, RSA-4096");
|
||||
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Standing);
|
||||
// Postea's rule says nothing about another repository: that is out of the key's scope, as before.
|
||||
let other = Request {
|
||||
context: Context { file: "Postea-1.0.0.apk".into(), ..ctx("release", "mnovak/Other") },
|
||||
..apk("r-4")
|
||||
};
|
||||
assert!(matches!(v.signing_sign(&other, Approval::Standing, NOW + 3), Err(Refusal::OutOfScope(_))));
|
||||
}
|
||||
@@ -79,6 +79,7 @@ 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.
|
||||
- At most one recovery slot (kind 5, core 0.17.0), of exactly 108 bytes, and none in a machine store.
|
||||
- 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.
|
||||
@@ -96,6 +97,54 @@ slot, then the body.
|
||||
| Both unwrap, but their pair slot is missing or fails | `Corrupted` |
|
||||
| A machine store: its one device factor unwraps, then the single slot | — |
|
||||
|
||||
## The recovery key (core 0.17.0)
|
||||
|
||||
A two-factor vault can have **one recovery key**: 32 random bytes that open the vault alone, for the day the
|
||||
factors are gone (a forgotten password and a dead PC, a lost phone and a reinstalled Windows). It is the one
|
||||
deliberate exception to "never one secret", and it is hedged accordingly:
|
||||
|
||||
- **It is made on request and returned once** (`Vault::recovery_create`). It is in no file and no log. The app
|
||||
shows or prints it and keeps nothing. Making a new one replaces the old one.
|
||||
- **It is never an everyday unlock.** `Vault::recover` is the only call that takes it. Before it returns the vault
|
||||
it drops **every** factor, makes the new master password and one new second factor the vault's two factors, and
|
||||
replaces the recovery key (the new one is returned, once). Whoever held the old password, an old PC key or a
|
||||
phone holds nothing of the vault from the next save on. No `open` or `open_with` accepts a recovery key, as a
|
||||
password or as material.
|
||||
- **It is audited** in the security member: `recovery-created`, `recovery-removed`, `recovered`, each with the
|
||||
key's id (never the key).
|
||||
- A version-1 vault and a machine-key vault have none (`NeedTwoFactors`, `FactorRejected`).
|
||||
- `recover` writes nothing. Until the caller saves, the file is as it was and the old factors still open it.
|
||||
- The vault key stays the same across a recovery: a **copy of the file from before** still opens with the old
|
||||
factors and the old recovery key. A recovery takes back the vault, not its old copies.
|
||||
|
||||
**As printed:** `id (4 bytes) ‖ key (32 bytes) ‖ check (4 bytes)` in base32 without padding, 64 characters in 8
|
||||
groups of 8 (`A–Z`, `2–7`). The check is the first 4 bytes of `SHA-256("custos recovery key v1" ‖ id ‖ key)`.
|
||||
A reader ignores case, spaces and hyphens; any other character, another length or a failed check is
|
||||
`RecoveryKeyMistyped`, told apart from `WrongRecoveryKey` (a well-formed key that is not this vault's current one)
|
||||
before the vault is touched. The **id** (8 hex characters) is not secret: it is in the header, shown in Settings
|
||||
and printed next to the key, so the paper can be matched to the vault.
|
||||
|
||||
```
|
||||
kind 5, recovery slot (at most one; never together with a single slot)
|
||||
4 id
|
||||
32 salt
|
||||
24 wrap nonce
|
||||
48 wrapped vault key KEK = HKDF-SHA256(key, salt, info "custos recovery v2")
|
||||
AAD = magic ‖ version ‖ kind ‖ id ‖ salt ‖ nonce
|
||||
```
|
||||
|
||||
It is not a factor: it has no factor slot, no pair slots and no entry in the body's `factors`, it does not count
|
||||
toward the two factors or the limit of 8, and `factor_ids` does not list it. `Vault::recovery_id_of(bytes)` reads
|
||||
its id from the header.
|
||||
|
||||
**Older readers.** A reader before core 0.17.0 knows slot kinds 2 to 4 and treats kind 5 as malformed: a vault
|
||||
with a recovery key does not open in an older Custos ("the vault file is malformed"), and is not rewritten by
|
||||
one. Removing the key (`recovery_remove`) makes the file readable by older readers again, apart from the three
|
||||
audit actions, which they refuse like any unknown action (docs/FORMAT.md, "The security member").
|
||||
|
||||
**What it costs.** The paper is a complete way in. It is 256 bits, so it is not guessed; it is stolen, copied or
|
||||
photographed. Keep it away from the PC and from the other vault's paper. Losing it loses nothing: make a new one.
|
||||
|
||||
## Which factors a file has
|
||||
|
||||
`Vault::factor_ids(bytes)` reads the header alone and returns each factor's id and type. No key is needed,
|
||||
|
||||
+5
-2
@@ -142,7 +142,10 @@ member), so these values, new in core 0.12.0, make a vault unreadable for a core
|
||||
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. Core 0.14.0 adds two more: a `signing` key
|
||||
of kind `android` and an audit entry of kind `apk` (docs/SIGNING.md); a vault that holds either does not open in a
|
||||
core before 0.14.0.
|
||||
core before 0.14.0. Core 0.16.0 adds the `signing` audit outcome `standing` and the `security` actions
|
||||
`standing-granted` and `standing-revoked` (docs/SIGNING.md, "Standing approvals"): a vault in which a standing
|
||||
approval was ever granted does not open in a core before 0.16.0. The rules themselves (`signing.standing`) are a
|
||||
member older cores ignore and drop.
|
||||
|
||||
### The provision audit (core 0.11.0)
|
||||
|
||||
@@ -206,7 +209,7 @@ an outcome; a code the server then refuses (its exit 10) is not seen by Custos,
|
||||
| `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`, and (core 0.13.0) `no-auto-connect`, `no-unattended`, `card-signing` |
|
||||
| `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?, detail?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected`, `totp-moved`, or (core 0.13.0) `auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`, `taken-over`; `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`); `detail` (core 0.13.0, the four notes) names what happened, never a value: 1–500 characters, no control characters |
|
||||
| `audit` | `{at, action, item?, auth?, detail?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected`, `totp-moved`, or (core 0.13.0) `auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`, `taken-over`, or (core 0.16.0) `standing-granted`, `standing-revoked`, or (core 0.17.0) `recovery-created`, `recovery-removed`, `recovered` (docs/FACTORS.md, "The recovery key"; their `detail` is the key's id); `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`); `detail` (core 0.13.0, the four notes; core 0.16.0, the two standing actions) names what happened, never a value: 1–500 characters, no control characters |
|
||||
|
||||
The **level** is computed, never stored:
|
||||
|
||||
|
||||
+58
-2
@@ -1,4 +1,4 @@
|
||||
# Signing keys (core 0.9.0; deploy approvals 0.12.0; Android APKs 0.14.0)
|
||||
# Signing keys (core 0.9.0; deploy approvals 0.12.0; Android APKs 0.14.0; standing approvals 0.16.0)
|
||||
|
||||
Custos signs releases for Fabrica Domi · Artifex without a private key ever leaving the vault. A build asks for a
|
||||
signature over a **digest**; Custos checks who may ask, Mark approves with a match code, and the vault signs and
|
||||
@@ -195,6 +195,51 @@ the digests and answers with placeholder signatures (the signed data does not de
|
||||
Custos's answer, again with a signer that hands each recorded digest its signature, and refuses any digest it did
|
||||
not record. It verifies the result with apksig's verifier before it writes the APK.
|
||||
|
||||
## Standing approvals (core 0.16.0)
|
||||
|
||||
A release key always asks. A **standing approval** is Mark's answer kept: "always allow this, for this repository".
|
||||
It is a rule in `signing.standing`, made only from a request Mark is approving on a card, and a later request that
|
||||
fits it is signed without a card.
|
||||
|
||||
```json
|
||||
"standing": [
|
||||
{ "id": "5b0c1e0f6a2d4c11", "repo": "mnovak/Postea", "key": "postea-android", "keyCreated": 1793750000000,
|
||||
"kind": "apk", "pipeline": "release", "via": "local", "granted": 1794000000000, "lastUsed": 1794100000000, "uses": 3 },
|
||||
{ "id": "9d3e…", "repo": "Aula", "key": "domi-approve", "keyCreated": 1793750000000, "kind": "approval",
|
||||
"pipeline": "deploy", "via": "remote", "targets": ["deploy to nixos-vm"], "granted": 1794000000000, "uses": 0 }
|
||||
]
|
||||
```
|
||||
|
||||
**What a rule is.** Five things, all compared exactly (no `*`, no prefix): the repository and the pipeline as the
|
||||
scope check reads them (an approval's own `repo` and `pipeline`), the key (its id and its `created` time, so a key
|
||||
made later under the same id never inherits a rule), the kind, and `via` (the Domi pipe or the factor service's
|
||||
mailbox). A rule for an `approval` also keeps the targets it was granted for. `id` is the first 16 hex characters
|
||||
of the SHA-256 of `repo`, `key`, `kind`, `pipeline` and `via` joined by newlines, so one rule exists per
|
||||
combination. The trigger and the step are not part of a rule; they are in every audit entry.
|
||||
|
||||
**A request fits a rule** (`standing_rule_for`) when all of these hold:
|
||||
|
||||
- `signing_check` passes: a rule never widens a key's scope, and narrowing the scope afterwards stops the rule;
|
||||
- the request names a run;
|
||||
- repository, pipeline, key (id and `created`), kind and `via` equal the rule's;
|
||||
- for an approval, every target of the request is one of the rule's targets;
|
||||
- `via` is `local`, or the kind is `approval`: a release signature asked through the mailbox never fits a rule;
|
||||
- the checklist item `card-signing` (*Sign only with a card*) is not ticked.
|
||||
|
||||
**A rule is made** (`standing_grant`) only when the request would itself fit the rule being made, the key is a
|
||||
release key (a test key needs none), and **the key has signed before** (an `approved` or `standing` audit entry):
|
||||
a key's first signature is never the one that starts a rule. Granting again for an approval adds its targets to
|
||||
the rule. At most 256 rules. `standing_revoke` removes one. Granting and revoking are written to the security audit
|
||||
(`standing-granted`, `standing-revoked`, with the rule's fields as the detail).
|
||||
|
||||
**Signing with a rule** is `signing_sign(req, Approval::Standing, now)`: it checks the request, finds the rule
|
||||
(refusing with `NeedsApproval` when none fits), signs, records the outcome `standing` with everything an `approved`
|
||||
entry holds, and counts the use on the rule (`uses`, `lastUsed`).
|
||||
|
||||
Never covered by a rule, by construction: another repository, key, kind, pipeline or origin; a request out of the
|
||||
key's scope; a request without a run; a key's first signature; a deploy to a target the rule was not granted for;
|
||||
a release signature the server runner asks for; creating a key.
|
||||
|
||||
## The audit log
|
||||
|
||||
`audit` is append-only: there is no function that edits or removes an entry. Every request a key is named in gets
|
||||
@@ -203,6 +248,7 @@ one entry, whatever happened:
|
||||
| `outcome` | |
|
||||
| :-- | :-- |
|
||||
| `approved` | Mark approved; signed |
|
||||
| `standing` | (core 0.16.0) a standing approval fitted; signed without asking |
|
||||
| `auto` | a test key; signed without asking |
|
||||
| `refused` | Mark refused |
|
||||
| `expired` | nobody answered within 5 minutes |
|
||||
@@ -214,6 +260,11 @@ one entry, whatever happened:
|
||||
(core 0.12.0) is the context's version, absent when empty. The entry is part of the vault, so it survives a reopen
|
||||
and travels with it.
|
||||
|
||||
**Compatibility (core 0.16.0).** A core before 0.16.0 ignores `standing` when it reads and drops it when it saves
|
||||
(the rules are gone and every request asks again). The audit outcome `standing` and the security actions
|
||||
`standing-granted` and `standing-revoked` are values it does not know: once a rule was granted, every Custos that
|
||||
opens the vault must be on core 0.16.0 or later (an older one refuses it as `Corrupted`).
|
||||
|
||||
**Compatibility.** A key of kind `android` and an audit entry of kind `apk` (core 0.14.0) are values a core
|
||||
before 0.14.0 does not know: once the vault holds an Android key, every Custos that opens it must be on core 0.14.0
|
||||
or later (an older one refuses the vault as `Corrupted`; the web vault, which never reads `signing`, is unaffected).
|
||||
@@ -234,9 +285,14 @@ Vault::signing_export_cert(id) -> DER //
|
||||
Vault::signing_minisign_public(id) -> minisign.pub text
|
||||
Vault::signing_check(&request) -> Ok | Refusal // before asking Mark (the clock: now_ms)
|
||||
Vault::signing_check_at(&request, now) -> Ok | Refusal // the same at `now` (an approval's expiry)
|
||||
Vault::signing_sign(&request, Approval::{Mark, Auto}, now) -> Signed // checks again, signs, records
|
||||
Vault::signing_sign(&request, Approval::{Mark, Auto, Standing}, now) -> Signed // checks again, signs, records
|
||||
Vault::signing_refuse(&request, outcome, now) // records refused / expired
|
||||
Vault::signing_audit() -> [AuditEntry]
|
||||
Vault::standing_can_grant(&request, now) -> Ok | why not // may the card offer "always"? (0.16.0)
|
||||
Vault::standing_grant(&request, now) -> StandingRule // before signing the approved request
|
||||
Vault::standing_rule_for(&request, now) -> Option<StandingRule>
|
||||
Vault::standing_rules() -> [StandingRule]
|
||||
Vault::standing_revoke(id, now) -> bool
|
||||
```
|
||||
|
||||
No function returns a `secret`. The views and the audit entries print and serialise without one; there is a test.
|
||||
|
||||
Reference in New Issue
Block a user