[vault] Signing: the signing body member (release and test key sets, scope, sign-only API, append-only audit log); custos-sign draws from SysRng; the wasm build links getrandom 0.2 to the browser CSPRNG

This commit is contained in:
2026-11-04 00:26:11 +01:00
parent cd2963392d
commit 06410ab3be
13 changed files with 373 additions and 52 deletions
Generated
+7
View File
@@ -415,6 +415,7 @@ dependencies = [
"data-encoding",
"ed25519-dalek",
"minisign-verify",
"rand 0.10.3",
"rand_core 0.6.4",
"rsa",
"sha2 0.10.9",
@@ -443,15 +444,20 @@ dependencies = [
"argon2",
"bip39",
"chacha20poly1305",
"custos-sign",
"data-encoding",
"ed25519-dalek",
"hkdf",
"minisign-verify",
"rand 0.10.3",
"rsa",
"serde",
"serde_json",
"sha2 0.10.9",
"sha2 0.11.1",
"tempfile",
"thiserror",
"x509-cert",
"zeroize",
]
@@ -465,6 +471,7 @@ dependencies = [
"custos-totp",
"custos-vault",
"data-encoding",
"getrandom 0.2.17",
"getrandom 0.4.3",
"qrcode",
"serde",
+21 -6
View File
@@ -84,9 +84,11 @@ pub fn generate(alg: Algorithm, comment: &str) -> Result<KeyPair, KeyError> {
/// An OpenSSH key keeps its own comment unless it has none.
pub fn import(text: &str, comment: &str) -> Result<KeyPair, KeyError> {
// Pasted or read from a Windows file: CRLF line ends.
let text = text.replace("
let text = text.replace(
"
", "
");
",
);
let text = text.trim();
let has = |label: &str| text.contains(&format!("-----BEGIN {label}-----"));
if has("ENCRYPTED PRIVATE KEY") || text.contains("Proc-Type: 4,ENCRYPTED") {
@@ -99,7 +101,9 @@ pub fn import(text: &str, comment: &str) -> Result<KeyPair, KeyError> {
}
let comment = if key.comment().is_empty() { comment.to_owned() } else { key.comment().to_owned() };
return match key.key_data() {
KeypairData::Ed25519(k) => from_ed25519(ed25519_dalek::SigningKey::from_bytes(&k.private.to_bytes()), &comment),
KeypairData::Ed25519(k) => {
from_ed25519(ed25519_dalek::SigningKey::from_bytes(&k.private.to_bytes()), &comment)
}
KeypairData::Ecdsa(EcdsaKeypair::NistP256 { private, .. }) => {
from_p256(p256::SecretKey::from_slice(private.as_slice()).map_err(|_| KeyError::Invalid)?, &comment)
}
@@ -135,8 +139,13 @@ pub fn import(text: &str, comment: &str) -> Result<KeyPair, KeyError> {
/// rebuilt from its components here.
fn rsa_from_openssh(k: &RsaKeypair) -> Result<rsa::RsaPrivateKey, KeyError> {
let n = |m: &ssh_key::Mpint| rsa::BigUint::try_from(m).map_err(|_| KeyError::Invalid);
let sk = rsa::RsaPrivateKey::from_components(n(&k.public.n)?, n(&k.public.e)?, n(&k.private.d)?, vec![n(&k.private.p)?, n(&k.private.q)?])
.map_err(|_| KeyError::Invalid)?;
let sk = rsa::RsaPrivateKey::from_components(
n(&k.public.n)?,
n(&k.public.e)?,
n(&k.private.d)?,
vec![n(&k.private.p)?, n(&k.private.q)?],
)
.map_err(|_| KeyError::Invalid)?;
sk.validate().map_err(|_| KeyError::Invalid)?;
Ok(sk)
}
@@ -169,7 +178,13 @@ fn from_rsa(sk: rsa::RsaPrivateKey, comment: &str) -> Result<KeyPair, KeyError>
assemble(&format!("rsa-{bits}"), KeypairData::Rsa(enc(RsaKeypair::try_from(sk))?), private_pem, public_pem, comment)
}
fn assemble(algorithm: &str, data: KeypairData, private_pem: String, public_pem: String, comment: &str) -> Result<KeyPair, KeyError> {
fn assemble(
algorithm: &str,
data: KeypairData,
private_pem: String,
public_pem: String,
comment: &str,
) -> Result<KeyPair, KeyError> {
let private = enc(PrivateKey::new(data, comment))?;
let public = private.public_key();
Ok(KeyPair {
+2 -1
View File
@@ -87,7 +87,8 @@ fn every_private_key_format_imports_to_the_same_key() {
for text in inputs {
// Surrounding whitespace (a paste, a file with CRLF line ends) does not matter.
let pasted = format!("\r\n {}\r\n", text.replace('\n', "\r\n"));
let i = custos_keys::import(&pasted, "deploy").unwrap_or_else(|e| panic!("{alg:?} {}: {e:?}", text.lines().next().unwrap()));
let i = custos_keys::import(&pasted, "deploy")
.unwrap_or_else(|e| panic!("{alg:?} {}: {e:?}", text.lines().next().unwrap()));
assert_eq!((i.algorithm.as_str(), i.fingerprint.as_str()), (alg.name(), k.fingerprint.as_str()), "{alg:?}");
assert_eq!(i.public_pem, k.public_pem);
}
+3 -1
View File
@@ -52,7 +52,9 @@ fn random<const N: usize>() -> Zeroizing<[u8; N]> {
fn derive(ikm: &[u8], salt: &[u8], info: &[&[u8]]) -> Zeroizing<[u8; 32]> {
let mut k = Zeroizing::new([0u8; 32]);
hkdf::Hkdf::<Sha256>::new(Some(salt), ikm).expand(&info.concat(), k.as_mut()).expect("32 bytes is a valid HKDF length");
hkdf::Hkdf::<Sha256>::new(Some(salt), ikm)
.expand(&info.concat(), k.as_mut())
.expect("32 bytes is a valid HKDF length");
k
}
+5 -3
View File
@@ -11,12 +11,14 @@ thiserror.workspace = true
zeroize.workspace = true
data-encoding.workspace = true
# The RustCrypto generation custos-keys already uses (digest 0.10, signature 2).
ed25519-dalek = { version = "2", features = ["rand_core"] }
rsa = { version = "0.9", features = ["sha2"] }
ed25519-dalek = "2"
rsa = { version = "0.9", default-features = false, features = ["sha2", "u64_digit"] }
sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] }
blake2 = "0.10"
x509-cert = { version = "0.2.5", features = ["builder"] }
rand_core = { version = "0.6", features = ["getrandom"] }
# rsa 0.9 generates keys through rand_core 0.6; the bytes come from `rand`'s SysRng (lib.rs, `OsRng06`).
rand_core = "0.6"
rand.workspace = true
[dev-dependencies]
minisign-verify = "0.3"
+37 -5
View File
@@ -15,7 +15,8 @@ use std::time::Duration;
use blake2::{Blake2b512, Digest};
use data_encoding::BASE64;
use ed25519_dalek::{Signer as _, SigningKey};
use rand_core::{OsRng, RngCore};
use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use rsa::RsaPrivateKey;
use rsa::pkcs1v15;
use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey, EncodePublicKey};
@@ -103,6 +104,37 @@ impl fmt::Debug for RsaSecret {
}
}
/// Fills `buf` from the OS CSPRNG through `rand`'s `SysRng`, as the rest of the workspace does (the browser build
/// routes it to `crypto.getRandomValues`).
fn fill(buf: &mut [u8]) {
rand::Rng::fill_bytes(&mut UnwrapErr(SysRng), buf);
}
/// rand_core 0.6's interface, which `rsa` 0.9 generates keys with, over [`fill`].
struct OsRng06;
impl rand_core::RngCore for OsRng06 {
fn next_u32(&mut self) -> u32 {
let mut b = [0u8; 4];
fill(&mut b);
u32::from_le_bytes(b)
}
fn next_u64(&mut self) -> u64 {
let mut b = [0u8; 8];
fill(&mut b);
u64::from_le_bytes(b)
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
fill(dest);
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
fill(dest);
Ok(())
}
}
impl rand_core::CryptoRng for OsRng06 {}
// ---- minisign ----
/// A new Ed25519 key with a random minisign key id.
@@ -114,9 +146,9 @@ pub struct NewEd25519 {
pub fn new_ed25519() -> NewEd25519 {
let mut seed = Zeroizing::new([0u8; 32]);
OsRng.fill_bytes(&mut *seed);
fill(&mut *seed);
let mut key_id = [0u8; 8];
OsRng.fill_bytes(&mut key_id);
fill(&mut key_id);
let secret = Ed25519Secret(seed);
let public = secret.public();
NewEd25519 { secret, public, key_id }
@@ -257,14 +289,14 @@ pub struct NewCert {
}
fn new_rsa() -> Result<(RsaPrivateKey, RsaSecret), Error> {
let key = RsaPrivateKey::new(&mut OsRng, RSA_BITS).map_err(|_| Error::BadKey)?;
let key = RsaPrivateKey::new(&mut OsRng06, RSA_BITS).map_err(|_| Error::BadKey)?;
let der = key.to_pkcs8_der().map_err(|_| Error::BadKey)?.as_bytes().to_vec();
Ok((key, RsaSecret(Zeroizing::new(der))))
}
fn serial() -> Result<SerialNumber, Error> {
let mut bytes = [0u8; 16];
OsRng.fill_bytes(&mut bytes);
fill(&mut bytes);
bytes[0] &= 0x7f; // positive
bytes[0] |= 0x01; // and without a leading zero byte
SerialNumber::new(&bytes).map_err(|_| Error::Certificate)
+2 -1
View File
@@ -65,7 +65,8 @@ fn minisign_verify_accepts_our_signatures_and_rejects_a_changed_file() {
#[test]
fn a_manifest_is_signed_over_its_own_text() {
let (secret, key_id) = minisign_key();
let sums = format!("{} Arca_0.2.0_x64-setup.exe\n{} Arca_0.2.0_x64-setup.exe.sig\n", "a".repeat(64), "0".repeat(64));
let sums =
format!("{} Arca_0.2.0_x64-setup.exe\n{} Arca_0.2.0_x64-setup.exe.sig\n", "a".repeat(64), "0".repeat(64));
let sig = manifest(&secret, &key_id, &sums, 1_793_750_000).unwrap();
let public = minisign_verify::PublicKey::decode(&text("minisign.pub")).unwrap();
public.verify(sums.as_bytes(), &minisign_verify::Signature::decode(&sig).unwrap(), false).unwrap();
+29 -1
View File
@@ -23,6 +23,7 @@ pub mod identity;
mod item;
mod save;
mod secret;
pub mod signing;
pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
pub use save::{CrashPoint, save_atomic, save_atomic_crashing};
@@ -70,6 +71,10 @@ pub enum Error {
NotACert,
#[error("those words are not the ones in the recovery phrase")]
WrongWords,
#[error("this vault already has {0} signing keys")]
SigningExists(&'static str),
#[error("signing keys: {0}")]
Signing(String),
#[error("{0}")]
Io(#[from] std::io::Error),
}
@@ -261,6 +266,8 @@ struct Body {
factors: Vec<FactorJson>,
#[serde(default)]
identity: Option<identity::RootJson>,
#[serde(default)]
signing: Option<signing::StoreJson>,
}
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
@@ -272,6 +279,8 @@ struct BodyRef<'a> {
factors: Vec<FactorJson>,
#[serde(skip_serializing_if = "Option::is_none")]
identity: Option<identity::RootJson>,
#[serde(skip_serializing_if = "Option::is_none")]
signing: Option<signing::StoreJson>,
}
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
@@ -286,6 +295,8 @@ pub struct Vault {
kdf_new: KdfParams,
/// The Domi identity's root key (docs/IDENTITY.md), never handed out.
identity: Option<identity::Root>,
/// Signing keys and their audit log (docs/SIGNING.md); no key is ever handed out.
signing: signing::Store,
}
impl fmt::Debug for Vault {
@@ -385,6 +396,7 @@ impl Vault {
factors: Vec::new(),
kdf_new: kdf,
identity: None,
signing: signing::Store::default(),
})
}
@@ -401,6 +413,7 @@ impl Vault {
factors: Vec::new(),
kdf_new: kdf,
identity: None,
signing: signing::Store::default(),
};
v.add_factor(a, label_a)?;
v.add_factor(b, label_b)?;
@@ -433,6 +446,7 @@ impl Vault {
factors: vec![rec],
kdf_new: KdfParams::DEFAULT,
identity: None,
signing: signing::Store::default(),
})
}
@@ -554,7 +568,20 @@ impl Vault {
Some(j) => Some(identity::Root::from_json(j).ok_or(Error::Corrupted)?),
None => None,
};
Ok(Vault { key, version: header.version, slots: header.slots, items: body.items, factors, kdf_new, identity })
let signing = match body.signing {
Some(j) => signing::Store::from_json(j).ok_or(Error::Corrupted)?,
None => signing::Store::default(),
};
Ok(Vault {
key,
version: header.version,
slots: header.slots,
items: body.items,
factors,
kdf_new,
identity,
signing,
})
}
/// Wraps the vault key for device unlock with key material only this device can produce (e.g. a
@@ -588,6 +615,7 @@ impl Vault {
items: &self.items,
factors: self.factors.iter().map(FactorRec::json).collect(),
identity: self.identity.as_ref().map(identity::Root::json),
signing: self.signing.json(),
};
serde_json::to_writer(&mut *json, &body).map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?;
let sealed = crypto::seal(&self.key, &body_nonce, &json, &out);
+170 -12
View File
@@ -353,7 +353,13 @@ fn clean_list(list: &[String]) -> Result<Vec<String>, Error> {
impl Vault {
/// Creates the release set (`domi-release`, `domi-root`, `domi-code-signing`) or the test set (`domi-test`,
/// `domi-test-root`, `domi-test-code-signing`). The caller saves. Slow: two RSA-3072 keys.
pub fn signing_create(&mut self, role: Role, pipelines: &[String], repos: &[String], now: i64) -> Result<Vec<String>, Error> {
pub fn signing_create(
&mut self,
role: Role,
pipelines: &[String],
repos: &[String],
now: i64,
) -> Result<Vec<String>, Error> {
if self.signing.keys.iter().any(|k| k.role == role) {
return Err(Error::SigningExists(match role {
Role::Release => "release",
@@ -363,8 +369,22 @@ impl Vault {
let pipelines = clean_list(pipelines)?;
let repos = clean_list(repos)?;
let (ed_id, root_id, leaf_id, ed_name, root_name, leaf_name) = match role {
Role::Release => ("domi-release", "domi-root", "domi-code-signing", "Domi release", "Domi Household Root CA", "Domi Code Signing"),
Role::Test => ("domi-test", "domi-test-root", "domi-test-code-signing", "Domi test", "Domi Test Root (never trusted)", "Domi Test Code Signing"),
Role::Release => (
"domi-release",
"domi-root",
"domi-code-signing",
"Domi release",
"Domi Household Root CA",
"Domi Code Signing",
),
Role::Test => (
"domi-test",
"domi-test-root",
"domi-test-code-signing",
"Domi test",
"Domi Test Root (never trusted)",
"Domi Test Code Signing",
),
};
let ed = custos_sign::new_ed25519();
let root = custos_sign::new_root(root_name, 10).map_err(|e| Error::Signing(e.to_string()))?;
@@ -387,8 +407,17 @@ impl Vault {
let mut ed_key = key(ed_id, KeyKind::Ed25519, ed_name, Secret::Ed25519(ed.secret), None, None, true);
ed_key.public = Some(ed.public);
ed_key.key_id = Some(ed.key_id);
let root_key = key(root_id, KeyKind::RootCa, root_name, Secret::Rsa(root.secret), Some(root.cert_der), None, false);
let leaf_key = key(leaf_id, KeyKind::CodeSigning, leaf_name, Secret::Rsa(leaf.secret), Some(leaf.cert_der), Some(root_id), true);
let root_key =
key(root_id, KeyKind::RootCa, root_name, Secret::Rsa(root.secret), Some(root.cert_der), None, false);
let leaf_key = key(
leaf_id,
KeyKind::CodeSigning,
leaf_name,
Secret::Rsa(leaf.secret),
Some(leaf.cert_der),
Some(root_id),
true,
);
self.signing.keys.extend([ed_key, root_key, leaf_key]);
Ok(vec![ed_id.into(), root_id.into(), leaf_id.into()])
}
@@ -421,7 +450,12 @@ impl Vault {
/// Changes who may ask for a key. The caller saves.
pub fn signing_set_scope(&mut self, id: &str, pipelines: &[String], repos: &[String]) -> Result<(), Error> {
let (pipelines, repos) = (clean_list(pipelines)?, clean_list(repos)?);
let k = self.signing.keys.iter_mut().find(|k| k.id == id).ok_or_else(|| Error::Signing(format!("no key `{id}`")))?;
let k = self
.signing
.keys
.iter_mut()
.find(|k| k.id == id)
.ok_or_else(|| Error::Signing(format!("no key `{id}`")))?;
if k.kind == KeyKind::RootCa {
return Err(Error::Signing("a root CA signs no requests, so it has no scope".into()));
}
@@ -442,7 +476,8 @@ impl Vault {
let k = self.signing.get(&req.key).ok_or_else(|| Refusal::NoKey(req.key.clone()))?;
let fits = matches!(
(k.kind, req.kind),
(KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest) | (KeyKind::CodeSigning, SignKind::Authenticode)
(KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest)
| (KeyKind::CodeSigning, SignKind::Authenticode)
);
if k.kind == KeyKind::RootCa {
return Err(Refusal::Invalid(format!("`{}` is a root CA: it signs only the certificate it issued", k.id)));
@@ -499,10 +534,14 @@ impl Vault {
let k = self.signing.get(&req.key).expect("checked");
let seconds = (now.max(0) / 1000) as u64;
let bytes = match (&k.secret, req.kind) {
(Secret::Ed25519(s), SignKind::Minisign) => {
custos_sign::minisign(s, &k.key_id.expect("ed25519 keys have an id"), &req.digest, &req.context.file, seconds)
.map(String::into_bytes)
}
(Secret::Ed25519(s), SignKind::Minisign) => custos_sign::minisign(
s,
&k.key_id.expect("ed25519 keys have an id"),
&req.digest,
&req.context.file,
seconds,
)
.map(String::into_bytes),
(Secret::Ed25519(s), SignKind::Manifest) => custos_sign::manifest(
s,
&k.key_id.expect("ed25519 keys have an id"),
@@ -536,7 +575,14 @@ impl Vault {
self.signing_record(req, outcome, reason, None, now);
}
fn signing_record(&mut self, req: &Request, outcome: Outcome, reason: Option<String>, signature: Option<String>, now: i64) {
fn signing_record(
&mut self,
req: &Request,
outcome: Outcome,
reason: Option<String>,
signature: Option<String>,
now: i64,
) {
let mut context = req.context.clone();
if req.kind == SignKind::Manifest {
context.file = "SHA256SUMS".into();
@@ -558,3 +604,115 @@ impl Vault {
&self.signing.audit
}
}
#[cfg(test)]
mod tests {
//! Mandatory test 2 for the core: no API path returns a private key. It lives here because only this module can
//! see the secrets to look for.
use super::*;
use crate::{KdfParams, SecretString};
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
fn req(key: &str, kind: SignKind, digest: usize) -> Request {
Request {
key: key.into(),
kind,
digest: vec![5; digest],
manifest: None,
context: Context {
repo: "Arca".into(),
pipeline: "release".into(),
trigger: "tag".into(),
file: "a.exe".into(),
..Default::default()
},
via: Via::Local,
}
}
#[test]
fn no_api_path_returns_a_private_key() {
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(&["*"]), &s(&["*"]), 1).unwrap();
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), 1).unwrap();
let secrets: Vec<Vec<u8>> = v
.signing
.keys
.iter()
.map(|k| match &k.secret {
Secret::Ed25519(s) => s.expose().to_vec(),
Secret::Rsa(s) => s.expose().to_vec(),
})
.collect();
assert_eq!(secrets.len(), 6);
// Every public way out: views (serialised and printed), certificates, minisign public keys, checks,
// signatures of every kind, refusals, the audit log, errors, and the Debug of the vault's own store.
let mut out = String::new();
let views = v.signing_keys();
out += &serde_json::to_string(&views).unwrap();
out += &format!("{views:?}{:?}", v.signing);
for k in &views {
if let Ok(c) = v.signing_export_cert(&k.id) {
out += &data_encoding::HEXLOWER.encode(&c);
}
}
let mut reqs =
vec![req("domi-release", SignKind::Minisign, 64), req("domi-code-signing", SignKind::Authenticode, 32)];
reqs.push(req("domi-root", SignKind::Authenticode, 32));
reqs.push(req("domi-test", SignKind::Minisign, 64));
for r in &reqs {
out += &format!("{:?}", v.signing_check(r));
for approval in [Approval::Mark, Approval::Auto] {
match v.signing_sign(r, approval, 2) {
Ok(signed) => out += &format!("{signed:?}{}", data_encoding::HEXLOWER.encode(&signed.bytes)),
Err(e) => out += &format!("{e:?}{e}"),
}
}
}
out += &serde_json::to_string(v.signing_audit()).unwrap();
out += &format!("{:?}", v.signing_audit());
out += &format!("{:?}", v.signing_create(Role::Release, &[], &[], 3));
for secret in &secrets {
for enc in [
data_encoding::HEXLOWER.encode(secret),
data_encoding::HEXUPPER.encode(secret),
data_encoding::BASE64.encode(secret),
data_encoding::BASE64URL_NOPAD.encode(secret),
] {
assert!(!out.contains(&enc), "a secret appears in an output");
}
}
// Partial copies too: every 16-byte window of the numbers that are actually private. (A PKCS#8 RSA key
// also holds the public modulus and DER headers, which the certificate rightly shows.)
for private in private_parts(&secrets) {
for w in private.windows(16).step_by(8) {
assert!(!out.contains(&data_encoding::HEXLOWER.encode(w)), "part of a secret appears in an output");
assert!(!out.contains(&data_encoding::BASE64.encode(w)[..20]), "part of a secret appears in an output");
}
}
}
/// Ed25519 seeds as they are; for RSA the private exponent and the primes.
fn private_parts(secrets: &[Vec<u8>]) -> Vec<Vec<u8>> {
use rsa::pkcs8::DecodePrivateKey;
use rsa::traits::PrivateKeyParts;
let mut out = Vec::new();
for s in secrets {
if s.len() == 32 {
out.push(s.clone());
} else {
let k = rsa::RsaPrivateKey::from_pkcs8_der(s).unwrap();
out.push(k.d().to_bytes_be());
out.extend(k.primes().iter().map(|p| p.to_bytes_be()));
}
}
assert!(out.len() >= 2 + 4 * 3, "seeds, exponents and primes");
out
}
}
+31 -7
View File
@@ -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));
}
+2
View File
@@ -23,3 +23,5 @@ qrcode = { version = "0.14", default-features = false, features = ["svg"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
getrandom = "0.4"
# rand_core 0.6 (custos-sign, through custos-vault) uses getrandom 0.2: the same browser CSPRNG (lib.rs, `fill_v02`).
getrandom02 = { package = "getrandom", version = "0.2", features = ["custom"] }
+27 -5
View File
@@ -48,11 +48,21 @@ const PHONE_APPROVAL: &[u8] = b"custos phone approval v1";
#[derive(Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", rename_all_fields = "camelCase")]
enum FactorIn {
Password { password: SecretString },
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 },
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 },
Material {
factor: FactorKind,
material: SecretString,
},
}
#[derive(Deserialize)]
@@ -426,8 +436,12 @@ pub fn handle(request: &[u8]) -> Value {
}
Request::DomiPair { r#pub, id, label, device } => {
let device_ok = data_encoding::BASE64URL_NOPAD.decode(device.as_bytes()).is_ok_and(|d| d.len() == 32);
let id_ok = !id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
let (Some(public), true, true) = (b64(&r#pub), device_ok, id_ok) else { return err("A malformed request.") };
let id_ok = !id.is_empty()
&& id.len() <= 64
&& id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
let (Some(public), true, true) = (b64(&r#pub), device_ok, id_ok) else {
return err("A malformed request.");
};
let label: String = label.trim().chars().filter(|c| !c.is_control()).take(40).collect();
let plain = json!({ "label": label, "device": device }).to_string();
match custos_seal::seal(&public, format!("domi-pair:{id}").as_bytes(), plain.as_bytes()) {
@@ -473,6 +487,14 @@ mod abi {
Ok(())
}
/// The same for getrandom 0.2, which rand_core 0.6 (custos-sign's RSA and X.509 crates) is built on. The
/// browser never makes signing keys, but the crates must link.
fn fill_v02(dest: &mut [u8]) -> Result<(), getrandom02::Error> {
unsafe { random_fill(dest.as_mut_ptr(), dest.len()) };
Ok(())
}
getrandom02::register_custom_getrandom!(fill_v02);
#[unsafe(no_mangle)]
pub extern "C" fn alloc(len: usize) -> *mut u8 {
if len == 0 {
+37 -10
View File
@@ -17,8 +17,14 @@ fn call(v: Value) -> Value {
/// 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 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);
@@ -53,7 +59,8 @@ fn open_with_password_and_a_sealed_totp_release() {
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 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.
@@ -91,7 +98,9 @@ fn a_phone_pairs_then_opens_and_approves() {
// 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 }));
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");
@@ -105,7 +114,8 @@ fn a_phone_pairs_then_opens_and_approves() {
// 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 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.
@@ -130,13 +140,18 @@ fn a_phone_pairs_then_opens_and_approves() {
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 }));
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());
assert!(
Vault::open_with(&v.to_bytes().unwrap(), Unlock::Password(&pw), Unlock::Material(FactorKind::Approval, &m))
.is_ok()
);
}
#[test]
@@ -144,7 +159,9 @@ fn a_phone_pairs_as_a_domi_device() {
// The PC waits with a one-time key; the phone seals its device public key and label to it.
let pc = Recipient::generate();
let device = data_encoding::BASE64URL_NOPAD.encode(&[5u8; 32]);
let r = call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc_-1", "label": " Pixel\n", "device": device }));
let r = call(
json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc_-1", "label": " Pixel\n", "device": device }),
);
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());
@@ -153,6 +170,16 @@ fn a_phone_pairs_as_a_domi_device() {
assert_eq!(plain, json!({ "label": "Pixel", "device": device }));
// Malformed: a device key of the wrong length, an id that would change the context.
let short = data_encoding::BASE64URL_NOPAD.encode(&[5u8; 31]);
assert_eq!(call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc", "label": "x", "device": short }))["ok"], false);
assert_eq!(call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "a:b", "label": "x", "device": device }))["ok"], false);
assert_eq!(
call(
json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc", "label": "x", "device": short })
)["ok"],
false
);
assert_eq!(
call(
json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "a:b", "label": "x", "device": device })
)["ok"],
false
);
}