Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e365f21d54 | |||
| df7c149b25 |
Generated
+9
-8
@@ -243,7 +243,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-gen"
|
||||
version = "0.4.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"data-encoding",
|
||||
@@ -255,7 +255,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-keys"
|
||||
version = "0.4.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"ed25519-dalek",
|
||||
@@ -268,11 +268,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-qr"
|
||||
version = "0.4.0"
|
||||
version = "0.6.0"
|
||||
|
||||
[[package]]
|
||||
name = "custos-seal"
|
||||
version = "0.4.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"chacha20poly1305",
|
||||
"hkdf",
|
||||
@@ -285,7 +285,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-share"
|
||||
version = "0.4.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"chacha20poly1305",
|
||||
@@ -302,7 +302,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-totp"
|
||||
version = "0.4.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"data-encoding",
|
||||
@@ -315,7 +315,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-vault"
|
||||
version = "0.4.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"chacha20poly1305",
|
||||
@@ -331,9 +331,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-wasm"
|
||||
version = "0.4.0"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"custos-qr",
|
||||
"custos-seal",
|
||||
"custos-share",
|
||||
"custos-totp",
|
||||
"custos-vault",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.5.0"
|
||||
version = "0.6.0"
|
||||
edition = "2024"
|
||||
license = "MPL-2.0"
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
|
||||
|
||||
@@ -142,6 +142,15 @@ pub fn match_code(public: &[u8]) -> String {
|
||||
format!("{n:06}")
|
||||
}
|
||||
|
||||
/// The match code of the one-time key a box was sealed with. When the receiver must know who sealed a
|
||||
/// box (pairing a phone), the sealing screen shows this code and the receiving screen checks it.
|
||||
pub fn sender_code(sealed: &[u8]) -> Result<String, SealError> {
|
||||
if sealed.len() < 4 + 32 + NONCE + TAG || &sealed[..4] != MAGIC {
|
||||
return Err(SealError::Malformed);
|
||||
}
|
||||
Ok(match_code(&sealed[4..36]))
|
||||
}
|
||||
|
||||
/// Seals data the factor service keeps on disk, with its own key (from a systemd credential).
|
||||
pub fn seal_at_rest(key: &[u8; 32], context: &[u8], plaintext: &[u8]) -> Vec<u8> {
|
||||
let k = derive(key, b"", &[b"custos rest v1", context]);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Mandatory tests for sealed boxes (docs/SEAL.md).
|
||||
|
||||
use custos_seal::{Recipient, SealError, match_code, open_at_rest, seal, seal_at_rest};
|
||||
use custos_seal::{Recipient, SealError, match_code, open_at_rest, seal, seal_at_rest, sender_code};
|
||||
|
||||
#[test]
|
||||
fn only_the_recipient_opens_and_only_for_its_purpose() {
|
||||
@@ -53,6 +53,16 @@ fn the_match_code_is_six_digits_and_follows_the_key() {
|
||||
/// SHA-256("custos match v1" ‖ 0x07 × 32), first four bytes big-endian, mod 1 000 000.
|
||||
const KNOWN_MATCH_CODE: &str = "684361";
|
||||
|
||||
#[test]
|
||||
fn the_sender_code_differs_per_box_and_needs_a_box() {
|
||||
let r = Recipient::generate();
|
||||
let a = seal(&r.public(), b"pair:1", b"x").unwrap();
|
||||
let b = seal(&r.public(), b"pair:1", b"x").unwrap();
|
||||
assert_eq!(sender_code(&a).unwrap(), match_code(&a[4..36]));
|
||||
assert_ne!(a[4..36], b[4..36], "a fresh one-time key per box");
|
||||
assert_eq!(sender_code(&a[..40]), Err(SealError::Malformed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn at_rest_seals_open_with_the_same_key_and_context_only() {
|
||||
let key = [9u8; 32];
|
||||
|
||||
@@ -57,6 +57,8 @@ pub enum Error {
|
||||
NeedTwoFactors,
|
||||
#[error("this factor does not open the vault")]
|
||||
FactorRejected,
|
||||
#[error("these two factors are kept on the same device; use one of them with another factor")]
|
||||
SameDevice,
|
||||
#[error("a vault has at most 8 factors and one master password")]
|
||||
TooManyFactors,
|
||||
#[error("{0}")]
|
||||
@@ -448,7 +450,8 @@ impl Vault {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
let (x, y) = if fa.id < fb.id { (fa.id, fb.id) } else { (fb.id, fa.id) };
|
||||
let slot = header.pair_slots().into_iter().find(|p| p.a == x && p.b == y).ok_or(Error::Corrupted)?;
|
||||
// Both factors opened, so a missing pair is one added apart from the other (one device).
|
||||
let slot = header.pair_slots().into_iter().find(|p| p.a == x && p.b == y).ok_or(Error::SameDevice)?;
|
||||
let k = crypto::open(&pair_kek(&fa, &fb), &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::Corrupted)?;
|
||||
Vault::open_body(bytes, header, body_at, key32(k)?)
|
||||
}
|
||||
@@ -594,6 +597,17 @@ impl Vault {
|
||||
/// Adds a factor to a version-2 vault: only the new factor's material is needed (docs/FACTORS.md).
|
||||
/// Returns its id. A second master password is refused; use [`Vault::change_password`].
|
||||
pub fn add_factor(&mut self, u: Unlock, label: &str) -> Result<String, Error> {
|
||||
self.add_factor_apart(u, label, &[])
|
||||
}
|
||||
|
||||
/// Adds a factor that never pairs with the factors `apart` (ids of factors kept on the same device, such
|
||||
/// as a phone's passkey and its approval key): together they open nothing, so one device is never two
|
||||
/// factors. Returns its id.
|
||||
pub fn add_factor_apart(&mut self, u: Unlock, label: &str, apart: &[&str]) -> Result<String, Error> {
|
||||
let apart: Vec<[u8; ID_LEN]> = apart.iter().map(|a| unhex(a).ok_or(Error::FactorRejected)).collect::<Result<_, _>>()?;
|
||||
if apart.iter().any(|a| !self.factors.iter().any(|f| f.id == *a)) {
|
||||
return Err(Error::FactorRejected);
|
||||
}
|
||||
if self.version != VERSION_2 {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
@@ -611,7 +625,7 @@ impl Vault {
|
||||
let rec = FactorRec { id, kind: u.kind(), label: label.into(), created: now_ms(), key: crypto::random_key() };
|
||||
let slot = factor_slot(id, &rec.key, &u, self.kdf_new)?;
|
||||
self.slots.push(slot.raw());
|
||||
for other in &self.factors {
|
||||
for other in self.factors.iter().filter(|f| !apart.contains(&f.id)) {
|
||||
self.slots.push(pair_slot(&self.key, &rec, other).raw());
|
||||
}
|
||||
self.factors.push(rec);
|
||||
|
||||
@@ -211,3 +211,31 @@ fn the_key_pair_item_type_round_trips() {
|
||||
let item = back.items().iter().find(|i| i.kind == ItemType::KeyPair).unwrap();
|
||||
assert!(item.fields.iter().any(|f| f.name == "private-key" && f.secret));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn factors_on_one_device_never_open_together() {
|
||||
let mut v = two_factor_vault();
|
||||
let passkey = v.add_factor(Unlock::Material(FactorKind::Passkey, &PHONE), "Phone passkey").unwrap();
|
||||
let approval = [12u8; 32];
|
||||
v.add_factor_apart(Unlock::Material(FactorKind::Approval, &approval), "Phone", &[&passkey]).unwrap();
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
let phone = Unlock::Material(FactorKind::Passkey, &PHONE);
|
||||
let phone_approval = Unlock::Material(FactorKind::Approval, &approval);
|
||||
assert!(matches!(open(&bytes, phone, phone_approval), Err(Error::SameDevice)));
|
||||
assert!(matches!(open(&bytes, phone_approval, phone), Err(Error::SameDevice)));
|
||||
// Each still pairs with everything else.
|
||||
let p = pw("Orbit7-Fable3");
|
||||
assert!(open(&bytes, Unlock::Password(&p), phone).is_ok());
|
||||
assert!(open(&bytes, Unlock::Password(&p), phone_approval).is_ok());
|
||||
assert!(open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), phone_approval).is_ok());
|
||||
// A factor added later pairs with both.
|
||||
let mut v = open(&bytes, Unlock::Password(&p), phone).unwrap();
|
||||
v.add_factor(Unlock::Material(FactorKind::Totp, &TOTP), "TOTP backup").unwrap();
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
assert!(open(&bytes, Unlock::Material(FactorKind::Totp, &TOTP), phone_approval).is_ok());
|
||||
// Only existing factors can be named.
|
||||
assert!(matches!(
|
||||
v.add_factor_apart(Unlock::Material(FactorKind::Device, &[13; 32]), "x", &["00112233445566778899aabbccddeeff"]),
|
||||
Err(Error::FactorRejected)
|
||||
));
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ custos-vault = { path = "../custos-vault" }
|
||||
custos-share = { path = "../custos-share" }
|
||||
custos-totp = { path = "../custos-totp" }
|
||||
custos-qr = { path = "../custos-qr" }
|
||||
custos-seal = { path = "../custos-seal" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
data-encoding.workspace = true
|
||||
|
||||
@@ -16,9 +16,15 @@
|
||||
//! Requests are `{"op": …, …}`; responses `{"ok": true, …}` or `{"ok": false, "error": "<message>"}`.
|
||||
//! See [`handle`] for the operations. One vault at a time is held here while unlocked; `lock` drops it
|
||||
//! (and with it the key, wiped).
|
||||
//!
|
||||
//! Two factors (docs/FACTORS.md, docs/SEAL.md): the page asks for a one-time key (`recipient`), sends its
|
||||
//! public half to the factor service, and passes the sealed answer back in `open_with`. The key's secret
|
||||
//! half never leaves this module. A paired phone keeps its approval material wrapped with its passkey's
|
||||
//! PRF output (`phone_enrol`, `phone_approve`); unwrapped, it exists only inside one call.
|
||||
|
||||
use custos_seal::Recipient;
|
||||
use custos_share::{Payload, ShareError};
|
||||
use custos_vault::{Item, ItemType, SecretString, Vault};
|
||||
use custos_vault::{FactorKind, Item, ItemType, SecretString, Unlock, Vault};
|
||||
use data_encoding::BASE64;
|
||||
use qrcode::render::svg;
|
||||
use qrcode::{EcLevel, QrCode};
|
||||
@@ -29,6 +35,24 @@ use zeroize::Zeroizing;
|
||||
|
||||
thread_local! {
|
||||
static VAULT: RefCell<Option<Vault>> = const { RefCell::new(None) };
|
||||
/// One-time keys waiting for a sealed answer, by their public key (base64). Each is used once.
|
||||
static RECIPIENTS: RefCell<Vec<(String, Recipient)>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
/// At most this many one-time keys wait at once; the oldest goes first.
|
||||
const MAX_RECIPIENTS: usize = 8;
|
||||
/// The at-rest context of a phone's approval material, wrapped with its passkey's PRF output.
|
||||
const PHONE_APPROVAL: &[u8] = b"custos phone approval v1";
|
||||
|
||||
/// One factor given to `open_with`.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case", rename_all_fields = "camelCase")]
|
||||
enum FactorIn {
|
||||
Password { password: SecretString },
|
||||
/// A factor service's or a device's answer, sealed to a key from `recipient` (`pub`) for `context`.
|
||||
Sealed { factor: FactorKind, r#pub: String, sealed: String, context: String },
|
||||
/// Material the page holds itself: a passkey's PRF output (base64).
|
||||
Material { factor: FactorKind, material: SecretString },
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -67,6 +91,38 @@ enum Request {
|
||||
fragment: String,
|
||||
password: Option<SecretString>,
|
||||
},
|
||||
/// The format version and the factors (id, type) of a vault, from its header alone.
|
||||
Factors {
|
||||
vault: String,
|
||||
},
|
||||
/// A new one-time key: `{pub, match}`.
|
||||
Recipient,
|
||||
/// The match code of a public key (base64), for example a requesting device's.
|
||||
MatchCode {
|
||||
r#pub: String,
|
||||
},
|
||||
/// Opens a version-2 vault with two different factors.
|
||||
OpenWith {
|
||||
vault: String,
|
||||
factors: Vec<FactorIn>,
|
||||
},
|
||||
/// Pairs this phone with a PC that waits with the one-time key `pub`: makes the phone's approval
|
||||
/// material and seals it with the passkey's PRF output (`prf`, base64) to the PC for `context`.
|
||||
/// Returns the box, its sender code, and the material wrapped with the PRF output (`wrapped`).
|
||||
PhoneEnrol {
|
||||
r#pub: String,
|
||||
context: String,
|
||||
label: String,
|
||||
prf: SecretString,
|
||||
},
|
||||
/// Approves a request: unwraps this phone's approval material with the PRF output and seals it to
|
||||
/// the requester's key for `context` (`approval:<factor>:<request id>`).
|
||||
PhoneApprove {
|
||||
wrapped: String,
|
||||
prf: SecretString,
|
||||
r#pub: String,
|
||||
context: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn err(msg: impl ToString) -> Value {
|
||||
@@ -178,6 +234,48 @@ fn payload_json(p: &Payload) -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
fn b64(s: &str) -> Option<Zeroizing<Vec<u8>>> {
|
||||
BASE64.decode(s.as_bytes()).ok().map(Zeroizing::new)
|
||||
}
|
||||
|
||||
fn key32(s: &SecretString) -> Option<Zeroizing<[u8; 32]>> {
|
||||
let v = b64(s.expose())?;
|
||||
let a: [u8; 32] = v.as_slice().try_into().ok()?;
|
||||
Some(Zeroizing::new(a))
|
||||
}
|
||||
|
||||
fn take_recipient(public: &str) -> Option<Recipient> {
|
||||
RECIPIENTS.with_borrow_mut(|r| r.iter().position(|(p, _)| p == public).map(|i| r.remove(i).1))
|
||||
}
|
||||
|
||||
/// The material for one factor; a password stays a password.
|
||||
enum Given {
|
||||
Password(SecretString),
|
||||
Material(FactorKind, Zeroizing<Vec<u8>>),
|
||||
}
|
||||
|
||||
fn given(f: FactorIn) -> Result<Given, String> {
|
||||
match f {
|
||||
FactorIn::Password { password } => Ok(Given::Password(password)),
|
||||
FactorIn::Material { factor, material } => {
|
||||
Ok(Given::Material(factor, b64(material.expose()).ok_or("A malformed factor.")?))
|
||||
}
|
||||
FactorIn::Sealed { factor, r#pub, sealed, context } => {
|
||||
let me = take_recipient(&r#pub).ok_or("That request expired. Ask again.")?;
|
||||
let sealed = b64(&sealed).ok_or("A malformed answer.")?;
|
||||
let m = me.open(&sealed, context.as_bytes()).map_err(|e| e.to_string())?;
|
||||
Ok(Given::Material(factor, m))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn unlock(g: &Given) -> Unlock<'_> {
|
||||
match g {
|
||||
Given::Password(p) => Unlock::Password(p),
|
||||
Given::Material(k, m) => Unlock::Material(*k, m),
|
||||
}
|
||||
}
|
||||
|
||||
fn share_error(e: ShareError) -> Value {
|
||||
json!({ "ok": false, "error": e.to_string(), "code": format!("{e:?}") })
|
||||
}
|
||||
@@ -254,6 +352,81 @@ pub fn handle(request: &[u8]) -> Value {
|
||||
Err(e) => share_error(e),
|
||||
}
|
||||
}
|
||||
Request::Factors { vault } => {
|
||||
let Some(bytes) = b64(&vault) else { return err("The vault file is damaged.") };
|
||||
match (Vault::version_of(&bytes), Vault::factor_ids(&bytes)) {
|
||||
(Ok(version), Ok(ids)) => json!({
|
||||
"ok": true,
|
||||
"version": version,
|
||||
"factors": ids.iter().map(|(id, kind)| json!({ "id": id, "kind": kind })).collect::<Vec<_>>(),
|
||||
}),
|
||||
(Err(e), _) | (_, Err(e)) => err(e),
|
||||
}
|
||||
}
|
||||
Request::Recipient => {
|
||||
let me = Recipient::generate();
|
||||
let public = BASE64.encode(&me.public());
|
||||
let code = me.match_code();
|
||||
RECIPIENTS.with_borrow_mut(|r| {
|
||||
if r.len() >= MAX_RECIPIENTS {
|
||||
r.remove(0);
|
||||
}
|
||||
r.push((public.clone(), me));
|
||||
});
|
||||
json!({ "ok": true, "pub": public, "match": code })
|
||||
}
|
||||
Request::MatchCode { r#pub } => match b64(&r#pub) {
|
||||
Some(p) if p.len() == 32 => json!({ "ok": true, "match": custos_seal::match_code(&p) }),
|
||||
_ => err("Not a valid public key."),
|
||||
},
|
||||
Request::OpenWith { vault, factors } => {
|
||||
let Some(bytes) = b64(&vault) else { return err("The vault file is damaged.") };
|
||||
let mut factors = factors.into_iter();
|
||||
let (Some(a), Some(b), None) = (factors.next(), factors.next(), factors.next()) else {
|
||||
return err("Choose two different factors.");
|
||||
};
|
||||
let (a, b) = match (given(a), given(b)) {
|
||||
(Ok(a), Ok(b)) => (a, b),
|
||||
(Err(e), _) | (_, Err(e)) => return err(e),
|
||||
};
|
||||
match Vault::open_with(&bytes, unlock(&a), unlock(&b)) {
|
||||
Ok(v) => {
|
||||
let out = items(&v);
|
||||
VAULT.set(Some(v));
|
||||
out
|
||||
}
|
||||
Err(e) => err(e),
|
||||
}
|
||||
}
|
||||
Request::PhoneEnrol { r#pub, context, label, prf } => {
|
||||
let (Some(public), Some(prf_key)) = (b64(&r#pub), key32(&prf)) else { return err("A malformed request.") };
|
||||
let material = custos_seal::random_bytes();
|
||||
let plain = Zeroizing::new(
|
||||
json!({ "label": label, "passkey": prf.expose(), "approval": BASE64.encode(material.as_ref()) })
|
||||
.to_string(),
|
||||
);
|
||||
match custos_seal::seal(&public, context.as_bytes(), plain.as_bytes()) {
|
||||
Ok(sealed) => json!({
|
||||
"ok": true,
|
||||
"code": custos_seal::sender_code(&sealed).unwrap_or_default(),
|
||||
"sealed": BASE64.encode(&sealed),
|
||||
"wrapped": BASE64.encode(&custos_seal::seal_at_rest(&prf_key, PHONE_APPROVAL, material.as_ref())),
|
||||
}),
|
||||
Err(e) => err(e),
|
||||
}
|
||||
}
|
||||
Request::PhoneApprove { wrapped, prf, r#pub, context } => {
|
||||
let (Some(wrapped), Some(prf_key), Some(public)) = (b64(&wrapped), key32(&prf), b64(&r#pub)) else {
|
||||
return err("A malformed request.");
|
||||
};
|
||||
let Ok(material) = custos_seal::open_at_rest(&prf_key, PHONE_APPROVAL, &wrapped) else {
|
||||
return err("This passkey does not belong to this phone's pairing.");
|
||||
};
|
||||
match custos_seal::seal(&public, context.as_bytes(), &material) {
|
||||
Ok(sealed) => json!({ "ok": true, "sealed": BASE64.encode(&sealed) }),
|
||||
Err(e) => err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Two factors in the browser: opening a version-2 vault with a sealed answer or a passkey's PRF output,
|
||||
//! and a phone's pairing and approvals (docs/FACTORS.md, docs/SEAL.md).
|
||||
|
||||
use custos_seal::Recipient;
|
||||
use custos_vault::{FactorKind, Item, ItemType, KdfParams, SecretString, Unlock, Vault};
|
||||
use data_encoding::BASE64;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
|
||||
const PASSWORD: &str = "Test4-Vault7-Only2";
|
||||
const SECRET: &str = "s3cret-Ž!";
|
||||
|
||||
fn call(v: Value) -> Value {
|
||||
custos_wasm::handle(v.to_string().as_bytes())
|
||||
}
|
||||
|
||||
/// A version-2 vault: the master password and a TOTP factor with `totp` as its material.
|
||||
fn vault(totp: &[u8]) -> Vault {
|
||||
let pw = SecretString::from(PASSWORD);
|
||||
let mut v = Vault::create_with(Unlock::Password(&pw), "Master password", Unlock::Material(FactorKind::Totp, totp), "TOTP", FAST)
|
||||
.unwrap();
|
||||
let mut login = Item::new(ItemType::WebLogin, "GitHub", 0);
|
||||
login.set("password", SECRET, 0);
|
||||
v.add(login);
|
||||
v
|
||||
}
|
||||
|
||||
fn b64(v: &Vault) -> String {
|
||||
BASE64.encode(&v.to_bytes().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn factors_from_the_header() {
|
||||
let v = vault(&[3; 32]);
|
||||
let r = call(json!({ "op": "factors", "vault": b64(&v) }));
|
||||
assert_eq!(r["version"], 2, "{r}");
|
||||
let kinds: Vec<&str> = r["factors"].as_array().unwrap().iter().map(|f| f["kind"].as_str().unwrap()).collect();
|
||||
assert_eq!(kinds, ["password", "totp"]);
|
||||
let totp = v.factors().into_iter().find(|f| f.kind == FactorKind::Totp).unwrap();
|
||||
assert_eq!(r["factors"][1]["id"], totp.id.as_str());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_with_password_and_a_sealed_totp_release() {
|
||||
let material = [3u8; 32];
|
||||
let v = vault(&material);
|
||||
let file = b64(&v);
|
||||
let totp = v.factors().into_iter().find(|f| f.kind == FactorKind::Totp).unwrap().id;
|
||||
let context = format!("totp:{totp}");
|
||||
|
||||
let me = call(json!({ "op": "recipient" }));
|
||||
let public = BASE64.decode(me["pub"].as_str().unwrap().as_bytes()).unwrap();
|
||||
assert_eq!(me["match"], custos_seal::match_code(&public));
|
||||
// What the factor service sends back after a valid code.
|
||||
let sealed = BASE64.encode(&custos_seal::seal(&public, context.as_bytes(), &material).unwrap());
|
||||
let sealed_in = |ctx: &str| json!({ "kind": "sealed", "factor": "totp", "pub": me["pub"], "sealed": sealed, "context": ctx });
|
||||
let password = json!({ "kind": "password", "password": PASSWORD });
|
||||
|
||||
// Only the right context opens it.
|
||||
let wrong = call(json!({ "op": "open_with", "vault": file, "factors": [password, sealed_in("totp:other")] }));
|
||||
assert_eq!(wrong["ok"], false);
|
||||
// The key is used once, even when the answer was refused.
|
||||
let again = call(json!({ "op": "open_with", "vault": file, "factors": [password, sealed_in(&context)] }));
|
||||
assert_eq!(again["error"], "That request expired. Ask again.");
|
||||
|
||||
let me = call(json!({ "op": "recipient" }));
|
||||
let public = BASE64.decode(me["pub"].as_str().unwrap().as_bytes()).unwrap();
|
||||
let sealed = BASE64.encode(&custos_seal::seal(&public, context.as_bytes(), &material).unwrap());
|
||||
let ok = call(json!({ "op": "open_with", "vault": file, "factors": [
|
||||
{ "kind": "sealed", "factor": "totp", "pub": me["pub"], "sealed": sealed, "context": context },
|
||||
password,
|
||||
]}));
|
||||
assert_eq!(ok["ok"], true, "{ok}");
|
||||
assert_eq!(ok["items"].as_array().unwrap().len(), 1);
|
||||
assert!(!ok.to_string().contains(SECRET));
|
||||
call(json!({ "op": "lock" }));
|
||||
|
||||
// One factor, or the same one twice, never opens it.
|
||||
for factors in [json!([password]), json!([password, password])] {
|
||||
let r = call(json!({ "op": "open_with", "vault": file, "factors": factors }));
|
||||
assert_eq!(r["ok"], false, "{r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phone_pairs_then_opens_and_approves() {
|
||||
let mut v = vault(&[3; 32]);
|
||||
let prf = [9u8; 32];
|
||||
let prf64 = BASE64.encode(&prf);
|
||||
|
||||
// The PC waits with a one-time key; the phone seals its pairing to it.
|
||||
let pc = Recipient::generate();
|
||||
let context = "pair:abc";
|
||||
let r = call(json!({ "op": "phone_enrol", "pub": BASE64.encode(&pc.public()), "context": context, "label": "Phone", "prf": prf64 }));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap();
|
||||
assert_eq!(r["code"], custos_seal::sender_code(&sealed).unwrap(), "the PC checks the code the phone shows");
|
||||
assert!(pc.open(&sealed, b"pair:other").is_err());
|
||||
let plain: Value = serde_json::from_slice(&pc.open(&sealed, context.as_bytes()).unwrap()).unwrap();
|
||||
assert_eq!((plain["label"].as_str(), plain["passkey"].as_str()), (Some("Phone"), Some(prf64.as_str())));
|
||||
let approval = BASE64.decode(plain["approval"].as_str().unwrap().as_bytes()).unwrap();
|
||||
assert_eq!(approval.len(), 32);
|
||||
let wrapped = r["wrapped"].as_str().unwrap();
|
||||
assert!(!r.to_string().contains(plain["approval"].as_str().unwrap()), "the material leaves only sealed or wrapped");
|
||||
|
||||
// The PC adds both factors.
|
||||
let passkey_id = v.add_factor(Unlock::Material(FactorKind::Passkey, &prf), "Phone passkey").unwrap();
|
||||
let approval_id = v.add_factor_apart(Unlock::Material(FactorKind::Approval, &approval), "Phone", &[&passkey_id]).unwrap();
|
||||
let file = b64(&v);
|
||||
|
||||
// The phone opens it with its passkey and the master password.
|
||||
let r = call(json!({ "op": "open_with", "vault": file, "factors": [
|
||||
{ "kind": "material", "factor": "passkey", "material": prf64 },
|
||||
{ "kind": "password", "password": PASSWORD },
|
||||
]}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
call(json!({ "op": "lock" }));
|
||||
// Its two factors never open it together.
|
||||
let me = call(json!({ "op": "recipient" }));
|
||||
let public = BASE64.decode(me["pub"].as_str().unwrap().as_bytes()).unwrap();
|
||||
let sealed = BASE64.encode(&custos_seal::seal(&public, b"approval:x:y", &approval).unwrap());
|
||||
let r = call(json!({ "op": "open_with", "vault": file, "factors": [
|
||||
{ "kind": "material", "factor": "passkey", "material": prf64 },
|
||||
{ "kind": "sealed", "factor": "approval", "pub": me["pub"], "sealed": sealed, "context": "approval:x:y" },
|
||||
]}));
|
||||
assert_eq!(r["error"], "these two factors are kept on the same device; use one of them with another factor");
|
||||
|
||||
// The PC asks the phone; the phone approves with its passkey.
|
||||
let requester = Recipient::generate();
|
||||
let req_pub = BASE64.encode(&requester.public());
|
||||
assert_eq!(call(json!({ "op": "match_code", "pub": req_pub }))["match"], requester.match_code());
|
||||
let ctx = format!("approval:{approval_id}:r1");
|
||||
let wrong_key = call(json!({ "op": "phone_approve", "wrapped": wrapped, "prf": BASE64.encode(&[8u8; 32]), "pub": req_pub, "context": ctx }));
|
||||
assert_eq!(wrong_key["ok"], false);
|
||||
let r = call(json!({ "op": "phone_approve", "wrapped": wrapped, "prf": prf64, "pub": req_pub, "context": ctx }));
|
||||
let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap();
|
||||
let m = requester.open(&sealed, ctx.as_bytes()).unwrap();
|
||||
let pw = SecretString::from(PASSWORD);
|
||||
assert!(Vault::open_with(&v.to_bytes().unwrap(), Unlock::Password(&pw), Unlock::Material(FactorKind::Approval, &m)).is_ok());
|
||||
}
|
||||
@@ -95,6 +95,29 @@ slot, then the body.
|
||||
because ids and types are not secret. The app uses them to ask the TOTP service or a paired device for a
|
||||
factor. Those services pass material through a mailbox they cannot read; see `docs/SEAL.md`.
|
||||
|
||||
## In the browser and on a phone
|
||||
|
||||
`custos-wasm` opens a version-2 vault with any two factors (`open_with`). A factor that comes from the
|
||||
factor service or from another device arrives as a box sealed to a one-time key the module made
|
||||
(`recipient`); the key's secret half never leaves WebAssembly memory and is used once.
|
||||
|
||||
**Pairing a phone** gives the vault two factors at once, both added by the PC (which writes the file):
|
||||
1. The PC waits with a one-time key and shows its match code; the phone shows the same code.
|
||||
2. On the phone, a passkey is created and evaluated with the WebAuthn PRF extension
|
||||
(salt `SHA-256("custos passkey v1")`). Its 32-byte output is the **passkey** factor's material.
|
||||
3. `phone_enrol` makes 32 random bytes, the phone's **approval** material, and seals both to the PC
|
||||
(context `pair:<pairing id>`). The phone keeps the approval material only wrapped with the PRF output
|
||||
(at-rest sealing, context `custos phone approval v1`), so stolen browser storage is not a factor.
|
||||
4. The phone shows the box's sender code (`docs/SEAL.md`); the PC adds the factors only after you confirm it
|
||||
shows the same code. It adds the approval factor **apart** from the passkey (`add_factor_apart`).
|
||||
|
||||
**Factors on one device never pair.** `add_factor_apart` writes no pair slot between the new factor and the
|
||||
ones named, so those two open nothing together (`Error::SameDevice`) while each still pairs with every other
|
||||
factor. A phone's passkey and its approval key, or a PC's device key and its approval key, are added apart.
|
||||
|
||||
`phone_approve` unwraps the approval material with a fresh PRF output (Face ID, Touch ID) and seals it to a
|
||||
requesting device, for `approval:<factor id>:<request id>`. The material exists unwrapped only inside that call.
|
||||
|
||||
## Body
|
||||
|
||||
`"format": 2`, and a `factors` list next to `items`:
|
||||
|
||||
@@ -36,6 +36,12 @@ approval to the key the box is sealed for.
|
||||
|
||||
Test vector: R = `07` × 32 → `684361`.
|
||||
|
||||
### The sender code
|
||||
|
||||
The match code of a box's ephemeral key E (`sender_code`). When the receiver must know who sealed a box,
|
||||
as when a PC adds a phone's factors, the sealing screen shows this code and the receiving screen asks the
|
||||
person to confirm it. E is fresh for every box, so each box has its own code.
|
||||
|
||||
## At rest
|
||||
|
||||
The factor service keeps each TOTP share sealed with its own key, which comes from a systemd credential
|
||||
|
||||
@@ -61,6 +61,10 @@ just as plainly, what it does not.
|
||||
- **The factor service holds one factor.** It releases the TOTP factor after a valid code, so whoever
|
||||
controls the home server has that factor. It is one factor, never enough alone. Approval material and
|
||||
cloud secrets pass through it only as sealed boxes (`docs/SEAL.md`), which it cannot open.
|
||||
- **A paired phone's browser storage** holds its approval material wrapped with the passkey's PRF output,
|
||||
which the authenticator gives only after Face ID or Touch ID. The passkey and the approval key are added
|
||||
apart (docs/FACTORS.md), so the phone alone is one device and opens nothing: it still needs the master
|
||||
password, the TOTP code or a PC.
|
||||
- **An approval is only as careful as the person approving.** Compare the six-digit match code on both
|
||||
screens; a request you did not start is someone else's.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user