Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6c696ba3a6 | |||
| 1c4bf4b373 | |||
| 680b66cff7 | |||
| 6e4da02351 | |||
| e365f21d54 | |||
| df7c149b25 | |||
| 7a7a628fa5 | |||
| 7893dd199c | |||
| 3f3cd26590 | |||
| 12783c9b92 | |||
| 02c6795f53 | |||
| df6565941e | |||
| 4daffdff73 | |||
| e3128b35aa |
@@ -7,14 +7,20 @@ The Windows app lives in the private `Custos` repo and depends on this one by gi
|
||||
## Layout
|
||||
```
|
||||
crates/custos-vault file format, Argon2id + XChaCha20-Poly1305, atomic save, item model, SecretString
|
||||
crates/custos-gen memorable password, nickname, random, PIN, strict-site generators + wordlists
|
||||
crates/custos-gen memorable password, nickname, random, PIN, strict-site, secret-key and API-key generators
|
||||
crates/custos-keys key pairs (Ed25519, ECDSA P-256, RSA) as OpenSSH and PKCS#8 PEM
|
||||
crates/custos-totp TOTP / HOTP (RFC 6238 / 4226 vectors are tests), otpauth:// parsing
|
||||
crates/custos-qr QR payload strings (Wi-Fi escaping); rendering is the app's job
|
||||
crates/custos-seal sealed boxes (X25519 + XChaCha20-Poly1305) for factor material through a mailbox; at-rest sealing
|
||||
crates/custos-share private share links: XChaCha20-Poly1305 blob, key in the URL fragment, optional password
|
||||
crates/custos-wasm the browser build (web vault + share page): JSON `call` ABI, no wasm-bindgen; js/custos.mjs
|
||||
docs/FORMAT.md the vault file format (versioned; change it before the code)
|
||||
docs/FORMAT.md the vault file format, version 1 (versioned; change it before the code)
|
||||
docs/FACTORS.md version 2: any two factors open the vault; the machine store
|
||||
docs/KEYS.md secret keys, API keys and key pairs
|
||||
docs/SEAL.md sealed boxes and the match code
|
||||
docs/SHARE.md the share blob and link format (versioned like FORMAT.md)
|
||||
docs/THREAT_MODEL.md what is and is not protected
|
||||
docs/IDENTITY.md the Domi identity: the root key in the vault, the mnemonic order, signing certs
|
||||
```
|
||||
|
||||
## Commands
|
||||
@@ -33,8 +39,9 @@ On the dev machine set `CARGO_HOME=F:\C-Drive-Migration\future-caches\cargo` (C:
|
||||
- Commits: `[<crate>] <Feature>: <description>`, e.g. `[vault] Format: authenticate slot parameters`.
|
||||
- **No AI attribution in commits or PRs, ever**: no `Co-Authored-By`, no session links, no "Generated with".
|
||||
- No binaries in git.
|
||||
- **No custom crypto.** Only RustCrypto / rust-random crates (`argon2`, `chacha20poly1305`, `zeroize`,
|
||||
`rand` with `SysRng`). Randomness from the OS CSPRNG only.
|
||||
- **No custom crypto.** Only RustCrypto / rust-random crates (`argon2`, `chacha20poly1305`, `hkdf`, `zeroize`,
|
||||
`rand` with `SysRng`; for key pairs `ssh-key`, `p256`, `rsa` and `ed25519-dalek`, RustCrypto's Ed25519
|
||||
backend; `x25519-dalek` for sealed boxes). Randomness from the OS CSPRNG only.
|
||||
- **Secrets never in logs, panics, error messages, `Debug`/`Display` output or test snapshots.**
|
||||
Secret-holding types print `[redacted]`; there is a test for each one.
|
||||
- Tests here are mandatory (it is public and holds the crypto). A format change updates `docs/FORMAT.md`
|
||||
|
||||
Generated
+724
-42
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.3.0"
|
||||
version = "0.7.0"
|
||||
edition = "2024"
|
||||
license = "MPL-2.0"
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
|
||||
|
||||
@@ -11,6 +11,7 @@ custos-vault = { path = "../custos-vault" }
|
||||
rand.workspace = true
|
||||
zeroize.workspace = true
|
||||
unicode-normalization.workspace = true
|
||||
data-encoding.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
regex = "1"
|
||||
|
||||
@@ -514,3 +514,83 @@ pub fn pin(length: u8) -> Generated {
|
||||
let value: String = (0..len).map(|_| digit()).collect();
|
||||
Generated { value: SecretString::new(value), entropy_bits: len as f64 * 10f64.log2() }
|
||||
}
|
||||
|
||||
// ---------- keys and API keys (docs/KEYS.md) ----------
|
||||
|
||||
/// How a secret key is written out.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum KeyEncoding {
|
||||
/// Lowercase hex.
|
||||
Hex,
|
||||
/// Base64url without padding.
|
||||
Base64Url,
|
||||
/// Standard base64 with padding.
|
||||
Base64,
|
||||
}
|
||||
|
||||
/// `bytes` random bytes (16..=128), encoded: symmetric keys, HMAC and JWT secrets.
|
||||
pub fn secret_key(bytes: usize, encoding: KeyEncoding) -> Result<Generated, GenError> {
|
||||
if !(16..=128).contains(&bytes) {
|
||||
return Err(GenError("a secret key is 16 to 128 bytes".into()));
|
||||
}
|
||||
let mut raw = zeroize::Zeroizing::new(vec![0u8; bytes]);
|
||||
rand::Rng::fill_bytes(&mut rng(), &mut raw);
|
||||
let value = match encoding {
|
||||
KeyEncoding::Hex => data_encoding::HEXLOWER.encode(&raw),
|
||||
KeyEncoding::Base64Url => data_encoding::BASE64URL_NOPAD.encode(&raw),
|
||||
KeyEncoding::Base64 => data_encoding::BASE64.encode(&raw),
|
||||
};
|
||||
Ok(Generated { value: SecretString::new(value), entropy_bits: 8.0 * bytes as f64 })
|
||||
}
|
||||
|
||||
const BASE62: &[u8; 62] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||
const API_KEY_RANDOM: usize = 32;
|
||||
|
||||
/// CRC-32 (IEEE 802.3, reflected, as zlib computes it): the API key checksum. Not a security feature.
|
||||
fn crc32(data: &[u8]) -> u32 {
|
||||
let mut crc = !0u32;
|
||||
for &b in data {
|
||||
crc ^= b as u32;
|
||||
for _ in 0..8 {
|
||||
crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
|
||||
}
|
||||
}
|
||||
!crc
|
||||
}
|
||||
|
||||
fn checksum6(body: &str) -> String {
|
||||
let mut n = crc32(body.as_bytes()) as u64;
|
||||
let mut out = [b'0'; 6];
|
||||
for c in out.iter_mut().rev() {
|
||||
*c = BASE62[(n % 62) as usize];
|
||||
n /= 62;
|
||||
}
|
||||
String::from_utf8(out.to_vec()).expect("base62 is ASCII")
|
||||
}
|
||||
|
||||
/// `<prefix>_` + 32 uniform base62 characters (190.5 bits) + a 6-character CRC-32 checksum.
|
||||
/// The prefix is empty, or a lowercase letter and up to 15 lowercase letters or digits.
|
||||
pub fn api_key(prefix: &str) -> Result<Generated, GenError> {
|
||||
let ok = prefix.is_empty()
|
||||
|| (prefix.len() <= 16
|
||||
&& prefix.starts_with(|c: char| c.is_ascii_lowercase())
|
||||
&& prefix.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()));
|
||||
if !ok {
|
||||
return Err(GenError("the prefix is a lowercase letter and up to 15 lowercase letters or digits".into()));
|
||||
}
|
||||
let mut body = if prefix.is_empty() { String::new() } else { format!("{prefix}_") };
|
||||
for _ in 0..API_KEY_RANDOM {
|
||||
body.push(BASE62[rng().random_range(0..62)] as char);
|
||||
}
|
||||
let sum = checksum6(&body);
|
||||
body.push_str(&sum);
|
||||
Ok(Generated { value: SecretString::new(body), entropy_bits: API_KEY_RANDOM as f64 * 62f64.log2() })
|
||||
}
|
||||
|
||||
/// Whether an API key's last 6 characters are the checksum of the rest (a typo, or not one of ours).
|
||||
pub fn api_key_checksum_ok(key: &str) -> bool {
|
||||
key.len() > 6 && key.is_char_boundary(key.len() - 6) && {
|
||||
let (body, sum) = key.split_at(key.len() - 6);
|
||||
checksum6(body) == sum
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Mandatory tests for the key and API-key generators (docs/KEYS.md).
|
||||
|
||||
use custos_gen::{KeyEncoding, api_key, api_key_checksum_ok, secret_key};
|
||||
|
||||
#[test]
|
||||
fn secret_keys_have_the_asked_length_encoding_and_entropy() {
|
||||
let hex = secret_key(32, KeyEncoding::Hex).unwrap();
|
||||
assert_eq!(hex.value.expose().len(), 64);
|
||||
assert!(hex.value.expose().chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));
|
||||
assert_eq!(hex.entropy_bits, 256.0);
|
||||
let b64 = secret_key(32, KeyEncoding::Base64Url).unwrap();
|
||||
assert_eq!(b64.value.expose().len(), 43);
|
||||
assert!(b64.value.expose().chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'));
|
||||
let std = secret_key(48, KeyEncoding::Base64).unwrap();
|
||||
assert_eq!(std.value.expose().len(), 64);
|
||||
// Never the same twice; refused outside 16..=128 bytes.
|
||||
assert_ne!(secret_key(32, KeyEncoding::Hex).unwrap().value, hex.value);
|
||||
assert!(secret_key(15, KeyEncoding::Hex).is_err());
|
||||
assert!(secret_key(129, KeyEncoding::Hex).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_keys_carry_a_prefix_190_random_bits_and_a_checksum() {
|
||||
let k = api_key("domi").unwrap();
|
||||
let v = k.value.expose();
|
||||
assert!(v.starts_with("domi_"), "{v}");
|
||||
assert_eq!(v.len(), "domi_".len() + 32 + 6);
|
||||
assert!(v["domi_".len()..].chars().all(|c| c.is_ascii_alphanumeric()));
|
||||
assert!((k.entropy_bits - 190.5).abs() < 0.1, "{}", k.entropy_bits);
|
||||
assert!(api_key_checksum_ok(v));
|
||||
// A typo is caught by the checksum.
|
||||
let mut typo: Vec<char> = v.chars().collect();
|
||||
let i = "domi_".len() + 3;
|
||||
typo[i] = if typo[i] == 'a' { 'b' } else { 'a' };
|
||||
assert!(!api_key_checksum_ok(&typo.into_iter().collect::<String>()));
|
||||
// No prefix is allowed; a bad one is refused.
|
||||
let bare = api_key("").unwrap();
|
||||
assert_eq!(bare.value.expose().len(), 38);
|
||||
assert!(api_key_checksum_ok(bare.value.expose()));
|
||||
for bad in ["Domi", "do mi", "1abc", "averyveryverylongprefix"] {
|
||||
assert!(api_key(bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_keys_never_print() {
|
||||
let k = secret_key(32, KeyEncoding::Hex).unwrap();
|
||||
let printed = format!("{k:?}");
|
||||
assert!(!printed.contains(k.value.expose()), "{printed}");
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "custos-keys"
|
||||
description = "Custos key pairs: Ed25519, ECDSA P-256 and RSA, as OpenSSH and PKCS#8 PEM (docs/KEYS.md)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
custos-vault = { path = "../custos-vault" }
|
||||
thiserror.workspace = true
|
||||
# RustCrypto's SSH key formats and the key types they build on (rand_core 0.6 generation API).
|
||||
ssh-key = { version = "0.6", default-features = false, features = ["std", "ed25519", "p256", "rsa", "rand_core"] }
|
||||
ed25519-dalek = { version = "2", features = ["pkcs8", "pem", "rand_core"] }
|
||||
p256 = { version = "0.13", features = ["ecdsa", "pkcs8", "pem"] }
|
||||
rsa = { version = "0.9", features = ["pem"] }
|
||||
rand_core = { version = "0.6", features = ["getrandom"] }
|
||||
@@ -0,0 +1,223 @@
|
||||
//! Key pairs for the `key-pair` item type (docs/KEYS.md): Ed25519, ECDSA P-256 and RSA, written as an
|
||||
//! OpenSSH public line, SPKI PEM, PKCS#8 PEM and an OpenSSH private key. RustCrypto crates only; the
|
||||
//! randomness is the OS CSPRNG (`rand_core::OsRng`).
|
||||
|
||||
use custos_vault::SecretString;
|
||||
use ed25519_dalek::pkcs8::spki::der::pem::LineEnding;
|
||||
use rand_core::OsRng;
|
||||
use ssh_key::private::{EcdsaKeypair, Ed25519Keypair, KeypairData, RsaKeypair};
|
||||
use ssh_key::{HashAlg, PrivateKey};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum KeyError {
|
||||
#[error("the key could not be generated or encoded")]
|
||||
Encode,
|
||||
#[error("not a valid key of this algorithm")]
|
||||
Invalid,
|
||||
#[error("the key is protected with a passphrase; remove it or import the key in the Custos app")]
|
||||
Encrypted,
|
||||
#[error("not a private key Custos can import (Ed25519, ECDSA P-256 or RSA 2048-4096 bits)")]
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Algorithm {
|
||||
Ed25519,
|
||||
EcdsaP256,
|
||||
Rsa3072,
|
||||
Rsa4096,
|
||||
}
|
||||
|
||||
impl Algorithm {
|
||||
pub const ALL: [Algorithm; 4] = [Algorithm::Ed25519, Algorithm::EcdsaP256, Algorithm::Rsa3072, Algorithm::Rsa4096];
|
||||
|
||||
/// The value of the item's `algorithm` field.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Algorithm::Ed25519 => "ed25519",
|
||||
Algorithm::EcdsaP256 => "ecdsa-p256",
|
||||
Algorithm::Rsa3072 => "rsa-3072",
|
||||
Algorithm::Rsa4096 => "rsa-4096",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_name(s: &str) -> Option<Self> {
|
||||
Algorithm::ALL.into_iter().find(|a| a.name() == s)
|
||||
}
|
||||
}
|
||||
|
||||
/// A generated key pair, ready to become a `key-pair` item. `Debug` never shows the private parts.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct KeyPair {
|
||||
pub algorithm: String,
|
||||
/// `ssh-ed25519 AAAA… comment`.
|
||||
pub public_openssh: String,
|
||||
/// SubjectPublicKeyInfo PEM.
|
||||
pub public_pem: String,
|
||||
/// PKCS#8 PEM, unencrypted (the vault is its encryption).
|
||||
pub private_pem: SecretString,
|
||||
/// OpenSSH private key, unencrypted.
|
||||
pub private_openssh: SecretString,
|
||||
/// `SHA256:…`, as `ssh-keygen -l` prints it.
|
||||
pub fingerprint: String,
|
||||
}
|
||||
|
||||
fn enc<T, E>(r: Result<T, E>) -> Result<T, KeyError> {
|
||||
r.map_err(|_| KeyError::Encode)
|
||||
}
|
||||
|
||||
/// A new key pair. RSA takes a few seconds (prime generation).
|
||||
pub fn generate(alg: Algorithm, comment: &str) -> Result<KeyPair, KeyError> {
|
||||
match alg {
|
||||
Algorithm::Ed25519 => from_ed25519(ed25519_dalek::SigningKey::generate(&mut OsRng), comment),
|
||||
Algorithm::EcdsaP256 => from_p256(p256::SecretKey::random(&mut OsRng), comment),
|
||||
Algorithm::Rsa3072 | Algorithm::Rsa4096 => {
|
||||
let bits = if alg == Algorithm::Rsa3072 { 3072 } else { 4096 };
|
||||
from_rsa(enc(rsa::RsaPrivateKey::new(&mut OsRng, bits))?, comment)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An existing private key as a key pair (docs/KEYS.md, "Importing"): an OpenSSH private key, PKCS#8
|
||||
/// (`BEGIN PRIVATE KEY`), PKCS#1 (`BEGIN RSA PRIVATE KEY`) or SEC1 (`BEGIN EC PRIVATE KEY`), unencrypted.
|
||||
/// The public parts and the fingerprint are derived from the private key, never taken from the input.
|
||||
/// 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.trim();
|
||||
let has = |label: &str| text.contains(&format!("-----BEGIN {label}-----"));
|
||||
if has("ENCRYPTED PRIVATE KEY") || text.contains("Proc-Type: 4,ENCRYPTED") {
|
||||
return Err(KeyError::Encrypted);
|
||||
}
|
||||
if has("OPENSSH PRIVATE KEY") {
|
||||
let key = PrivateKey::from_openssh(text).map_err(|_| KeyError::Invalid)?;
|
||||
if key.is_encrypted() {
|
||||
return Err(KeyError::Encrypted);
|
||||
}
|
||||
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::Ecdsa(EcdsaKeypair::NistP256 { private, .. }) => {
|
||||
from_p256(p256::SecretKey::from_slice(private.as_slice()).map_err(|_| KeyError::Invalid)?, &comment)
|
||||
}
|
||||
KeypairData::Rsa(k) => from_rsa(rsa_from_openssh(k)?, &comment),
|
||||
KeypairData::Encrypted(_) => Err(KeyError::Encrypted),
|
||||
_ => Err(KeyError::Unsupported),
|
||||
};
|
||||
}
|
||||
if has("PRIVATE KEY") {
|
||||
use ed25519_dalek::pkcs8::DecodePrivateKey;
|
||||
if let Ok(sk) = ed25519_dalek::SigningKey::from_pkcs8_pem(text) {
|
||||
return from_ed25519(sk, comment);
|
||||
}
|
||||
if let Ok(sk) = p256::SecretKey::from_pkcs8_pem(text) {
|
||||
return from_p256(sk, comment);
|
||||
}
|
||||
if let Ok(sk) = rsa::RsaPrivateKey::from_pkcs8_pem(text) {
|
||||
return from_rsa(sk, comment);
|
||||
}
|
||||
return Err(KeyError::Unsupported);
|
||||
}
|
||||
if has("RSA PRIVATE KEY") {
|
||||
use rsa::pkcs1::DecodeRsaPrivateKey;
|
||||
return from_rsa(rsa::RsaPrivateKey::from_pkcs1_pem(text).map_err(|_| KeyError::Invalid)?, comment);
|
||||
}
|
||||
if has("EC PRIVATE KEY") {
|
||||
return from_p256(p256::SecretKey::from_sec1_pem(text).map_err(|_| KeyError::Unsupported)?, comment);
|
||||
}
|
||||
Err(KeyError::Unsupported)
|
||||
}
|
||||
|
||||
/// ssh-key 0.6.7's own `TryFrom<&RsaKeypair>` passes `p` twice instead of `p` and `q`, so the key is
|
||||
/// 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)?;
|
||||
sk.validate().map_err(|_| KeyError::Invalid)?;
|
||||
Ok(sk)
|
||||
}
|
||||
|
||||
fn from_ed25519(sk: ed25519_dalek::SigningKey, comment: &str) -> Result<KeyPair, KeyError> {
|
||||
use ed25519_dalek::pkcs8::{EncodePrivateKey, EncodePublicKey};
|
||||
let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string();
|
||||
let public_pem = enc(sk.verifying_key().to_public_key_pem(LineEnding::LF))?;
|
||||
assemble("ed25519", KeypairData::Ed25519(Ed25519Keypair::from(&sk)), private_pem, public_pem, comment)
|
||||
}
|
||||
|
||||
fn from_p256(sk: p256::SecretKey, comment: &str) -> Result<KeyPair, KeyError> {
|
||||
use p256::pkcs8::{EncodePrivateKey, EncodePublicKey};
|
||||
let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string();
|
||||
let public_pem = enc(sk.public_key().to_public_key_pem(LineEnding::LF))?;
|
||||
let public = sk.public_key();
|
||||
let data = KeypairData::Ecdsa(EcdsaKeypair::NistP256 { private: sk.into(), public: public.into() });
|
||||
assemble("ecdsa-p256", data, private_pem, public_pem, comment)
|
||||
}
|
||||
|
||||
fn from_rsa(sk: rsa::RsaPrivateKey, comment: &str) -> Result<KeyPair, KeyError> {
|
||||
use rsa::pkcs8::{EncodePrivateKey, EncodePublicKey};
|
||||
use rsa::traits::PublicKeyParts;
|
||||
let bits = sk.size() * 8;
|
||||
if !(2048..=4096).contains(&bits) {
|
||||
return Err(KeyError::Unsupported);
|
||||
}
|
||||
let private_pem = enc(sk.to_pkcs8_pem(LineEnding::LF))?.to_string();
|
||||
let public_pem = enc(sk.to_public_key().to_public_key_pem(LineEnding::LF))?;
|
||||
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> {
|
||||
let private = enc(PrivateKey::new(data, comment))?;
|
||||
let public = private.public_key();
|
||||
Ok(KeyPair {
|
||||
algorithm: algorithm.into(),
|
||||
public_openssh: enc(public.to_openssh())?,
|
||||
public_pem,
|
||||
private_pem: SecretString::new(private_pem),
|
||||
private_openssh: SecretString::new(enc(private.to_openssh(ssh_key::LineEnding::LF))?.to_string()),
|
||||
fingerprint: public.fingerprint(HashAlg::Sha256).to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a PKCS#8 private key and an SPKI public key belong together (tests, and a check before
|
||||
/// importing a key pair someone pasted).
|
||||
pub fn pem_matches(alg: Algorithm, private_pem: &str, public_pem: &str) -> Result<bool, KeyError> {
|
||||
let derived = match alg {
|
||||
Algorithm::Ed25519 => {
|
||||
use ed25519_dalek::pkcs8::{DecodePrivateKey, EncodePublicKey};
|
||||
let sk = ed25519_dalek::SigningKey::from_pkcs8_pem(private_pem).map_err(|_| KeyError::Invalid)?;
|
||||
enc(sk.verifying_key().to_public_key_pem(LineEnding::LF))?
|
||||
}
|
||||
Algorithm::EcdsaP256 => {
|
||||
use p256::pkcs8::{DecodePrivateKey, EncodePublicKey};
|
||||
let sk = p256::SecretKey::from_pkcs8_pem(private_pem).map_err(|_| KeyError::Invalid)?;
|
||||
enc(sk.public_key().to_public_key_pem(LineEnding::LF))?
|
||||
}
|
||||
Algorithm::Rsa3072 | Algorithm::Rsa4096 => {
|
||||
use rsa::pkcs8::{DecodePrivateKey, EncodePublicKey};
|
||||
let sk = rsa::RsaPrivateKey::from_pkcs8_pem(private_pem).map_err(|_| KeyError::Invalid)?;
|
||||
enc(sk.to_public_key().to_public_key_pem(LineEnding::LF))?
|
||||
}
|
||||
};
|
||||
Ok(derived.trim() == public_pem.trim())
|
||||
}
|
||||
|
||||
/// An Ed25519 signature (64 bytes) of `message` with a PKCS#8 private key.
|
||||
pub fn sign_ed25519(private_pem: &str, message: &[u8]) -> Result<Vec<u8>, KeyError> {
|
||||
use ed25519_dalek::Signer;
|
||||
use ed25519_dalek::pkcs8::DecodePrivateKey;
|
||||
let sk = ed25519_dalek::SigningKey::from_pkcs8_pem(private_pem).map_err(|_| KeyError::Invalid)?;
|
||||
Ok(sk.sign(message).to_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// Whether `signature` is a valid Ed25519 signature of `message` under an SPKI public key.
|
||||
pub fn verify_ed25519(public_pem: &str, message: &[u8], signature: &[u8]) -> Result<bool, KeyError> {
|
||||
use ed25519_dalek::Verifier;
|
||||
use ed25519_dalek::pkcs8::DecodePublicKey;
|
||||
let vk = ed25519_dalek::VerifyingKey::from_public_key_pem(public_pem).map_err(|_| KeyError::Invalid)?;
|
||||
let sig = ed25519_dalek::Signature::from_slice(signature).map_err(|_| KeyError::Invalid)?;
|
||||
Ok(vk.verify(message, &sig).is_ok())
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACDt2TW39UZy8qwtg1TjmyyP6tQyICmROg6Ed8wT8LfNMAAAAJDgLH6c4Cx+
|
||||
nAAAAAtzc2gtZWQyNTUxOQAAACDt2TW39UZy8qwtg1TjmyyP6tQyICmROg6Ed8wT8LfNMA
|
||||
AAAEBnrsV5Mk4SOUMLEChNqaRAd2+aSJlQup0lVfIDpgs0ZO3ZNbf1RnLyrC2DVOObLI/q
|
||||
1DIgKZE6DoR3zBPwt80wAAAADGZpeHR1cmVAdGVzdAE=
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
@@ -0,0 +1,8 @@
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABD6DWv11a
|
||||
60wSTEmglCO465AAAAGAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAILvNKbmysLcBtsSO
|
||||
rLTfznA6I1TNJa6UryfZvKCK8m8SAAAAkFMVbzEv6H/wWf5oYKy2l9wRAZzrvy2mqkyLRm
|
||||
DyIuKemJsVxFao1sL84IpcMC809PUX4qHLT5qFb/wOcv3fJKsFluHJS3c26CAqe6pbgP6W
|
||||
pXPKKKedbzrcRxfgVORw36fBNJdMQbFAUsYq2ytId0vHb8JYHCzjO3vSYPAaG+kfwrfRxn
|
||||
7wvt5tz4/9N14Wag==
|
||||
-----END OPENSSH PRIVATE KEY-----
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Mandatory tests for key pairs (docs/KEYS.md): every format parses back to the same key, the
|
||||
//! fingerprint is ssh-keygen's, Ed25519 signs and verifies, nothing private prints.
|
||||
|
||||
use custos_keys::{Algorithm, generate};
|
||||
|
||||
#[test]
|
||||
fn every_algorithm_round_trips_through_every_format() {
|
||||
for alg in [Algorithm::Ed25519, Algorithm::EcdsaP256, Algorithm::Rsa3072] {
|
||||
let k = generate(alg, "deploy@home").unwrap();
|
||||
assert_eq!(k.algorithm, alg.name());
|
||||
// The OpenSSH private key parses back and carries the same public key and comment.
|
||||
let private = ssh_key::PrivateKey::from_openssh(k.private_openssh.expose()).unwrap();
|
||||
assert_eq!(private.public_key().to_openssh().unwrap(), k.public_openssh);
|
||||
assert_eq!(private.comment(), "deploy@home");
|
||||
assert!(k.public_openssh.ends_with(" deploy@home"));
|
||||
// The fingerprint is the one ssh-keygen -l prints.
|
||||
assert_eq!(private.public_key().fingerprint(ssh_key::HashAlg::Sha256).to_string(), k.fingerprint);
|
||||
assert!(k.fingerprint.starts_with("SHA256:"));
|
||||
// PKCS#8 and SPKI PEM have the right headers and parse back to the same public key.
|
||||
assert!(k.private_pem.expose().starts_with("-----BEGIN PRIVATE KEY-----"));
|
||||
assert!(k.public_pem.starts_with("-----BEGIN PUBLIC KEY-----"));
|
||||
assert!(custos_keys::pem_matches(alg, k.private_pem.expose(), &k.public_pem).unwrap(), "{alg:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ed25519_signs_and_verifies() {
|
||||
let k = generate(Algorithm::Ed25519, "").unwrap();
|
||||
let sig = custos_keys::sign_ed25519(k.private_pem.expose(), b"release 1.0").unwrap();
|
||||
assert!(custos_keys::verify_ed25519(&k.public_pem, b"release 1.0", &sig).unwrap());
|
||||
assert!(!custos_keys::verify_ed25519(&k.public_pem, b"release 1.1", &sig).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_are_unique_and_nothing_private_prints() {
|
||||
let a = generate(Algorithm::Ed25519, "a").unwrap();
|
||||
let b = generate(Algorithm::Ed25519, "a").unwrap();
|
||||
assert_ne!(a.public_openssh, b.public_openssh);
|
||||
let printed = format!("{a:?}");
|
||||
assert!(!printed.contains("PRIVATE"), "{printed}");
|
||||
assert!(!printed.contains(a.private_openssh.expose().lines().nth(1).unwrap()), "{printed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn algorithm_names_parse() {
|
||||
for alg in Algorithm::ALL {
|
||||
assert_eq!(Algorithm::from_name(alg.name()), Some(alg));
|
||||
}
|
||||
assert_eq!(Algorithm::from_name("dsa"), None);
|
||||
}
|
||||
|
||||
// ---- importing (docs/KEYS.md, "Importing") ----
|
||||
|
||||
/// A throwaway key made by `ssh-keygen -t ed25519 -C fixture@test` for these tests only.
|
||||
const SSH_KEYGEN_ED25519: &str = include_str!("fixtures/ssh-keygen-ed25519");
|
||||
/// The same kind of key with the passphrase `fixture-pass`.
|
||||
const SSH_KEYGEN_ENCRYPTED: &str = include_str!("fixtures/ssh-keygen-ed25519-passphrase");
|
||||
|
||||
#[test]
|
||||
fn an_ssh_keygen_key_imports_with_its_own_fingerprint_and_comment() {
|
||||
let k = custos_keys::import(SSH_KEYGEN_ED25519, "fallback").unwrap();
|
||||
assert_eq!(k.algorithm, "ed25519");
|
||||
// What `ssh-keygen -l -f` printed for the fixture.
|
||||
assert_eq!(k.fingerprint, "SHA256:IGwHpAF8aVpXvaBckNayqTMlHUvRgN9+w1uS7iyLPGE");
|
||||
assert!(k.public_openssh.ends_with(" fixture@test"));
|
||||
assert!(custos_keys::pem_matches(Algorithm::Ed25519, k.private_pem.expose(), &k.public_pem).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_private_key_format_imports_to_the_same_key() {
|
||||
use p256::pkcs8::DecodePrivateKey as _;
|
||||
use rsa::pkcs1::EncodeRsaPrivateKey;
|
||||
for alg in [Algorithm::Ed25519, Algorithm::EcdsaP256, Algorithm::Rsa3072] {
|
||||
let k = generate(alg, "deploy").unwrap();
|
||||
let mut inputs = vec![k.private_openssh.expose().to_owned(), k.private_pem.expose().to_owned()];
|
||||
match alg {
|
||||
Algorithm::EcdsaP256 => {
|
||||
let sk = p256::SecretKey::from_pkcs8_pem(k.private_pem.expose()).unwrap();
|
||||
inputs.push(sk.to_sec1_pem(p256::pkcs8::LineEnding::LF).unwrap().to_string());
|
||||
}
|
||||
Algorithm::Rsa3072 => {
|
||||
let sk = rsa::RsaPrivateKey::from_pkcs8_pem(k.private_pem.expose()).unwrap();
|
||||
inputs.push(sk.to_pkcs1_pem(rsa::pkcs8::LineEnding::LF).unwrap().to_string());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
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()));
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protected_and_unknown_keys_are_refused() {
|
||||
use custos_keys::KeyError;
|
||||
assert!(matches!(custos_keys::import(SSH_KEYGEN_ENCRYPTED, "x"), Err(KeyError::Encrypted)));
|
||||
let pkcs8_encrypted = "-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIB\n-----END ENCRYPTED PRIVATE KEY-----";
|
||||
assert!(matches!(custos_keys::import(pkcs8_encrypted, "x"), Err(KeyError::Encrypted)));
|
||||
let pkcs1_encrypted = "-----BEGIN RSA PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,00\n\nAAAA\n-----END RSA PRIVATE KEY-----";
|
||||
assert!(matches!(custos_keys::import(pkcs1_encrypted, "x"), Err(KeyError::Encrypted)));
|
||||
// A public key, a password, garbage: nothing to import, and the error never repeats the input.
|
||||
let public = generate(Algorithm::Ed25519, "p").unwrap().public_openssh;
|
||||
for text in [public.as_str(), "hunter2-not-a-key", "-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----"] {
|
||||
let e = custos_keys::import(text, "x").unwrap_err();
|
||||
assert!(!e.to_string().contains("hunter2") && !e.to_string().contains("AAAA"), "{e}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "custos-seal"
|
||||
description = "Custos sealed boxes: a secret encrypted to one device's X25519 key, and at-rest sealing for the factor service (docs/SEAL.md)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
x25519-dalek = { version = "2", features = ["static_secrets", "zeroize"] }
|
||||
chacha20poly1305.workspace = true
|
||||
hkdf.workspace = true
|
||||
sha2.workspace = true
|
||||
rand.workspace = true
|
||||
zeroize.workspace = true
|
||||
thiserror.workspace = true
|
||||
@@ -0,0 +1,180 @@
|
||||
//! Sealed boxes (docs/SEAL.md). A device that wants a secret makes a one-time X25519 key pair and sends
|
||||
//! only its public key; whoever releases the secret seals it to that key, so the mailbox in between (the
|
||||
//! factor service on the home server) carries ciphertext it cannot open. Also the factor service's
|
||||
//! at-rest sealing of the TOTP shares it keeps.
|
||||
//!
|
||||
//! ```text
|
||||
//! sealed = "CSL1" ‖ ephemeral public (32) ‖ nonce (24) ‖ XChaCha20-Poly1305(key, nonce, plaintext, aad)
|
||||
//! key = HKDF-SHA256(X25519(ephemeral, recipient), salt = ephemeral pub ‖ recipient pub,
|
||||
//! info = "custos seal v1" ‖ context)
|
||||
//! aad = "CSL1" ‖ ephemeral public ‖ context
|
||||
//!
|
||||
//! at rest = "CSR1" ‖ nonce (24) ‖ XChaCha20-Poly1305(HKDF(key, "", "custos rest v1" ‖ context), nonce,
|
||||
//! plaintext, "CSR1" ‖ context)
|
||||
//! ```
|
||||
//!
|
||||
//! `context` binds a box to its purpose (e.g. `approval:<factor id>:<request id>`): a box sealed for one
|
||||
//! request does not open as another.
|
||||
|
||||
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
||||
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
|
||||
use rand::Rng;
|
||||
use rand::rand_core::UnwrapErr;
|
||||
use rand::rngs::SysRng;
|
||||
use sha2::{Digest, Sha256};
|
||||
use x25519_dalek::{PublicKey, StaticSecret};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
const MAGIC: &[u8; 4] = b"CSL1";
|
||||
const REST: &[u8; 4] = b"CSR1";
|
||||
const NONCE: usize = 24;
|
||||
const TAG: usize = 16;
|
||||
/// The largest plaintext a box carries (a key pair's private key fits many times over).
|
||||
pub const MAX_PLAINTEXT: usize = 32 * 1024;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum SealError {
|
||||
#[error("not a sealed box, or it was changed")]
|
||||
Malformed,
|
||||
#[error("this box was not sealed for this key and purpose")]
|
||||
Rejected,
|
||||
#[error("not a valid public key")]
|
||||
BadKey,
|
||||
#[error("the secret is too large to seal")]
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
fn random<const N: usize>() -> Zeroizing<[u8; N]> {
|
||||
let mut b = Zeroizing::new([0u8; N]);
|
||||
UnwrapErr(SysRng).fill_bytes(b.as_mut());
|
||||
b
|
||||
}
|
||||
|
||||
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");
|
||||
k
|
||||
}
|
||||
|
||||
fn cipher(key: &[u8; 32]) -> XChaCha20Poly1305 {
|
||||
XChaCha20Poly1305::new_from_slice(key).expect("32-byte key")
|
||||
}
|
||||
|
||||
fn xnonce(n: &[u8]) -> XNonce {
|
||||
XNonce::try_from(n).expect("24-byte nonce")
|
||||
}
|
||||
|
||||
/// The one-time key pair of a device waiting for a secret. Its secret half never leaves memory and is
|
||||
/// wiped on drop.
|
||||
pub struct Recipient {
|
||||
secret: StaticSecret,
|
||||
public: [u8; 32],
|
||||
}
|
||||
|
||||
impl Recipient {
|
||||
pub fn generate() -> Recipient {
|
||||
let secret = StaticSecret::from(*random::<32>());
|
||||
let public = PublicKey::from(&secret).to_bytes();
|
||||
Recipient { secret, public }
|
||||
}
|
||||
|
||||
/// What the device sends: 32 bytes.
|
||||
pub fn public(&self) -> [u8; 32] {
|
||||
self.public
|
||||
}
|
||||
|
||||
/// The six digits both screens show, so the person approving sees it is this request.
|
||||
pub fn match_code(&self) -> String {
|
||||
match_code(&self.public)
|
||||
}
|
||||
|
||||
/// Opens a box sealed to this key for `context`.
|
||||
pub fn open(&self, sealed: &[u8], context: &[u8]) -> Result<Zeroizing<Vec<u8>>, SealError> {
|
||||
if sealed.len() < 4 + 32 + NONCE + TAG || &sealed[..4] != MAGIC {
|
||||
return Err(SealError::Malformed);
|
||||
}
|
||||
let eph: [u8; 32] = sealed[4..36].try_into().expect("32 bytes");
|
||||
let shared = self.secret.diffie_hellman(&PublicKey::from(eph));
|
||||
if !shared.was_contributory() {
|
||||
return Err(SealError::Rejected);
|
||||
}
|
||||
let key = derive(shared.as_bytes(), &[eph.as_slice(), &self.public].concat(), &[b"custos seal v1", context]);
|
||||
let aad = [MAGIC.as_slice(), &eph, context].concat();
|
||||
cipher(&key)
|
||||
.decrypt(&xnonce(&sealed[36..36 + NONCE]), Payload { msg: &sealed[36 + NONCE..], aad: &aad })
|
||||
.map(Zeroizing::new)
|
||||
.map_err(|_| SealError::Rejected)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Recipient {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Recipient {{ match_code: {} }}", self.match_code())
|
||||
}
|
||||
}
|
||||
|
||||
/// Seals `plaintext` to a recipient's public key for `context`. Only that recipient opens it.
|
||||
pub fn seal(recipient: &[u8], context: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, SealError> {
|
||||
let recipient: [u8; 32] = recipient.try_into().map_err(|_| SealError::BadKey)?;
|
||||
if plaintext.len() > MAX_PLAINTEXT {
|
||||
return Err(SealError::TooLarge);
|
||||
}
|
||||
let eph = StaticSecret::from(*random::<32>());
|
||||
let eph_pub = PublicKey::from(&eph).to_bytes();
|
||||
let shared = eph.diffie_hellman(&PublicKey::from(recipient));
|
||||
// A low-order "public key" would give a shared secret anyone knows.
|
||||
if !shared.was_contributory() {
|
||||
return Err(SealError::BadKey);
|
||||
}
|
||||
let key = derive(shared.as_bytes(), &[eph_pub.as_slice(), &recipient].concat(), &[b"custos seal v1", context]);
|
||||
let nonce = random::<NONCE>();
|
||||
let aad = [MAGIC.as_slice(), &eph_pub, context].concat();
|
||||
let ct = cipher(&key)
|
||||
.encrypt(&xnonce(nonce.as_ref()), Payload { msg: plaintext, aad: &aad })
|
||||
.expect("encryption cannot fail for in-memory buffers");
|
||||
Ok([MAGIC.as_slice(), &eph_pub, nonce.as_ref(), &ct].concat())
|
||||
}
|
||||
|
||||
/// Six digits from a public key: what the requesting screen and the approving screen both show.
|
||||
pub fn match_code(public: &[u8]) -> String {
|
||||
let h = Sha256::new().chain_update(b"custos match v1").chain_update(public).finalize();
|
||||
let n = u32::from_be_bytes([h[0], h[1], h[2], h[3]]) % 1_000_000;
|
||||
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]);
|
||||
let nonce = random::<NONCE>();
|
||||
let aad = [REST.as_slice(), context].concat();
|
||||
let ct = cipher(&k)
|
||||
.encrypt(&xnonce(nonce.as_ref()), Payload { msg: plaintext, aad: &aad })
|
||||
.expect("encryption cannot fail for in-memory buffers");
|
||||
[REST.as_slice(), nonce.as_ref(), &ct].concat()
|
||||
}
|
||||
|
||||
pub fn open_at_rest(key: &[u8; 32], context: &[u8], sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>, SealError> {
|
||||
if sealed.len() < 4 + NONCE + TAG || &sealed[..4] != REST {
|
||||
return Err(SealError::Malformed);
|
||||
}
|
||||
let k = derive(key, b"", &[b"custos rest v1", context]);
|
||||
let aad = [REST.as_slice(), context].concat();
|
||||
cipher(&k)
|
||||
.decrypt(&xnonce(&sealed[4..4 + NONCE]), Payload { msg: &sealed[4 + NONCE..], aad: &aad })
|
||||
.map(Zeroizing::new)
|
||||
.map_err(|_| SealError::Rejected)
|
||||
}
|
||||
|
||||
/// 32 random bytes from the OS (factor material, tokens).
|
||||
pub fn random_bytes() -> Zeroizing<[u8; 32]> {
|
||||
random()
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Mandatory tests for sealed boxes (docs/SEAL.md).
|
||||
|
||||
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() {
|
||||
let r = Recipient::generate();
|
||||
let other = Recipient::generate();
|
||||
let b = seal(&r.public(), b"approval:f1:r1", b"factor material").unwrap();
|
||||
assert_eq!(r.open(&b, b"approval:f1:r1").unwrap().as_slice(), b"factor material");
|
||||
assert_eq!(other.open(&b, b"approval:f1:r1"), Err(SealError::Rejected));
|
||||
// The same box for another request or factor does not open.
|
||||
assert_eq!(r.open(&b, b"approval:f1:r2"), Err(SealError::Rejected));
|
||||
// Two seals of the same secret differ (fresh ephemeral key and nonce).
|
||||
assert_ne!(b, seal(&r.public(), b"approval:f1:r1", b"factor material").unwrap());
|
||||
assert!(!b.windows(15).any(|w| w == b"factor material"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_changed_byte_is_refused() {
|
||||
let r = Recipient::generate();
|
||||
let b = seal(&r.public(), b"c", b"secret").unwrap();
|
||||
for i in 0..b.len() {
|
||||
let mut bad = b.clone();
|
||||
bad[i] ^= 1;
|
||||
assert!(r.open(&bad, b"c").is_err(), "byte {i}");
|
||||
}
|
||||
assert_eq!(r.open(&b[..b.len() - 1], b"c"), Err(SealError::Rejected));
|
||||
assert_eq!(r.open(&b[..20], b"c"), Err(SealError::Malformed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_public_keys_are_refused() {
|
||||
assert_eq!(seal(&[1u8; 31], b"c", b"s"), Err(SealError::BadKey));
|
||||
// The all-zero point (low order) would give a shared secret everyone knows.
|
||||
assert_eq!(seal(&[0u8; 32], b"c", b"s"), Err(SealError::BadKey));
|
||||
assert_eq!(seal(&Recipient::generate().public(), b"c", &vec![0u8; 40_000]), Err(SealError::TooLarge));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_match_code_is_six_digits_and_follows_the_key() {
|
||||
let r = Recipient::generate();
|
||||
assert_eq!(r.match_code(), match_code(&r.public()));
|
||||
assert_eq!(r.match_code().len(), 6);
|
||||
assert!(r.match_code().bytes().all(|b| b.is_ascii_digit()));
|
||||
// A known vector, so every implementation (the web app's wasm too) shows the same digits.
|
||||
assert_eq!(match_code(&[7u8; 32]), KNOWN_MATCH_CODE);
|
||||
let codes: std::collections::HashSet<String> = (0..50).map(|_| Recipient::generate().match_code()).collect();
|
||||
assert!(codes.len() > 45);
|
||||
assert!(!format!("{r:?}").contains(&format!("{:?}", r.public())));
|
||||
}
|
||||
|
||||
/// 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];
|
||||
let b = seal_at_rest(&key, b"totp:f1", b"share");
|
||||
assert_eq!(open_at_rest(&key, b"totp:f1", &b).unwrap().as_slice(), b"share");
|
||||
assert_eq!(open_at_rest(&[8u8; 32], b"totp:f1", &b), Err(SealError::Rejected));
|
||||
assert_eq!(open_at_rest(&key, b"totp:f2", &b), Err(SealError::Rejected));
|
||||
assert_eq!(open_at_rest(&key, b"totp:f1", b"CSR1"), Err(SealError::Malformed));
|
||||
}
|
||||
@@ -16,6 +16,10 @@ serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
hkdf.workspace = true
|
||||
sha2.workspace = true
|
||||
# The Domi identity (docs/IDENTITY.md): the mnemonic and the root key.
|
||||
bip39 = { version = "2", default-features = false, features = ["std", "zeroize"] }
|
||||
ed25519-dalek = { version = "2", default-features = false, features = ["std", "zeroize"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
data-encoding.workspace = true
|
||||
|
||||
@@ -55,7 +55,29 @@ pub fn seal(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], plaintext: &[u8], aad: &[u
|
||||
.expect("encryption cannot fail for in-memory buffers")
|
||||
}
|
||||
|
||||
/// HKDF-SHA256(ikm, salt, info) → 32-byte key: the factor, pair and single KEKs (docs/FACTORS.md).
|
||||
pub fn hkdf(ikm: &[u8], salt: &[u8], info: &[u8]) -> Zeroizing<[u8; KEY_LEN]> {
|
||||
let mut k = Zeroizing::new([0u8; KEY_LEN]);
|
||||
hkdf::Hkdf::<sha2::Sha256>::new(Some(salt), ikm).expand(info, k.as_mut()).expect("32 bytes is a valid HKDF length");
|
||||
k
|
||||
}
|
||||
|
||||
/// `None` when the tag does not verify: wrong key, or changed ciphertext, nonce or AAD.
|
||||
pub fn open(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], ciphertext: &[u8], aad: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
|
||||
cipher(key).decrypt(&nonce(n), Payload { msg: ciphertext, aad }).ok().map(Zeroizing::new)
|
||||
}
|
||||
|
||||
/// The Domi root secret from a 24-word mnemonic (docs/IDENTITY.md): HKDF-SHA256 over its BIP39 seed.
|
||||
pub fn domi_root_secret(mnemonic: &bip39::Mnemonic) -> Zeroizing<[u8; KEY_LEN]> {
|
||||
let seed = Zeroizing::new(mnemonic.to_seed_normalized(""));
|
||||
hkdf(seed.as_ref(), b"tessera root v1", b"ed25519")
|
||||
}
|
||||
|
||||
pub fn ed25519_public(secret: &[u8; KEY_LEN]) -> [u8; 32] {
|
||||
ed25519_dalek::SigningKey::from_bytes(secret).verifying_key().to_bytes()
|
||||
}
|
||||
|
||||
pub fn ed25519_sign(secret: &[u8; KEY_LEN], msg: &[u8]) -> [u8; 64] {
|
||||
use ed25519_dalek::Signer;
|
||||
ed25519_dalek::SigningKey::from_bytes(secret).sign(msg).to_bytes()
|
||||
}
|
||||
|
||||
@@ -1,19 +1,29 @@
|
||||
//! Reading and writing the header of a `.custos` file (docs/FORMAT.md, "Layout").
|
||||
//! Reading and writing the header of a `.custos` file (docs/FORMAT.md, "Layout"; version 2 in
|
||||
//! docs/FACTORS.md).
|
||||
|
||||
use crate::crypto::{KEY_LEN, NONCE_LEN, TAG_LEN};
|
||||
use crate::{Error, KdfParams};
|
||||
|
||||
pub const MAGIC: &[u8; 6] = b"CUSTOS";
|
||||
pub const VERSION: u16 = 1;
|
||||
/// Two factors (docs/FACTORS.md).
|
||||
pub const VERSION_2: u16 = 2;
|
||||
pub const MAX_SLOTS: usize = 8;
|
||||
pub const MAX_SLOTS_V2: usize = 64;
|
||||
pub const MAX_FACTORS: usize = 8;
|
||||
pub const SLOT_PASSWORD: u8 = 1;
|
||||
pub const SLOT_FACTOR: u8 = 2;
|
||||
pub const SLOT_PAIR: u8 = 3;
|
||||
pub const SLOT_SINGLE: u8 = 4;
|
||||
const KDF_ARGON2ID: u8 = 1;
|
||||
pub const SALT_LEN: usize = 32;
|
||||
pub const ID_LEN: usize = 16;
|
||||
/// kdf(1) m(4) t(4) p(4) salt(32) nonce(24): the part of a password slot that is its own AAD.
|
||||
const PW_AAD_LEN: usize = 1 + 12 + SALT_LEN + NONCE_LEN;
|
||||
const PW_PAYLOAD_LEN: usize = PW_AAD_LEN + KEY_LEN + TAG_LEN;
|
||||
const WRAPPED_LEN: usize = KEY_LEN + TAG_LEN;
|
||||
|
||||
/// One key slot as stored. Unknown kinds are kept and written back unchanged.
|
||||
/// One key slot as stored. Unknown kinds are kept and written back unchanged (version 1).
|
||||
#[derive(Clone)]
|
||||
pub struct RawSlot {
|
||||
pub kind: u8,
|
||||
@@ -73,7 +83,169 @@ impl PasswordSlot {
|
||||
}
|
||||
}
|
||||
|
||||
fn v2_aad(kind: u8, head: &[u8]) -> Vec<u8> {
|
||||
let mut a = Vec::with_capacity(9 + head.len());
|
||||
a.extend_from_slice(MAGIC);
|
||||
a.extend_from_slice(&VERSION_2.to_le_bytes());
|
||||
a.push(kind);
|
||||
a.extend_from_slice(head);
|
||||
a
|
||||
}
|
||||
|
||||
/// A factor slot (kind 2): the factor key `F`, wrapped by a KEK from the factor's material.
|
||||
pub struct FactorSlot {
|
||||
pub id: [u8; ID_LEN],
|
||||
pub kind: u8,
|
||||
/// Argon2id parameters; password factors only.
|
||||
pub kdf: Option<KdfParams>,
|
||||
pub salt: [u8; SALT_LEN],
|
||||
pub nonce: [u8; NONCE_LEN],
|
||||
pub wrapped: Vec<u8>,
|
||||
}
|
||||
|
||||
impl FactorSlot {
|
||||
fn head(&self) -> Vec<u8> {
|
||||
let mut p = Vec::with_capacity(ID_LEN + 1 + 13 + SALT_LEN + NONCE_LEN);
|
||||
p.extend_from_slice(&self.id);
|
||||
p.push(self.kind);
|
||||
if let Some(k) = self.kdf {
|
||||
p.push(KDF_ARGON2ID);
|
||||
p.extend_from_slice(&k.m_cost_kib.to_le_bytes());
|
||||
p.extend_from_slice(&k.t_cost.to_le_bytes());
|
||||
p.extend_from_slice(&k.p_cost.to_le_bytes());
|
||||
}
|
||||
p.extend_from_slice(&self.salt);
|
||||
p.extend_from_slice(&self.nonce);
|
||||
p
|
||||
}
|
||||
|
||||
pub fn aad(&self) -> Vec<u8> {
|
||||
v2_aad(SLOT_FACTOR, &self.head())
|
||||
}
|
||||
|
||||
pub fn raw(&self) -> RawSlot {
|
||||
let mut p = self.head();
|
||||
p.extend_from_slice(&self.wrapped);
|
||||
RawSlot { kind: SLOT_FACTOR, payload: p }
|
||||
}
|
||||
|
||||
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
|
||||
let kind = *payload.get(ID_LEN).ok_or(Error::Malformed)?;
|
||||
let id: [u8; ID_LEN] = payload[..ID_LEN].try_into().unwrap();
|
||||
let mut at = ID_LEN + 1;
|
||||
let kdf = match kind {
|
||||
1 => {
|
||||
if payload.len() != at + 13 + SALT_LEN + NONCE_LEN + WRAPPED_LEN {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
if payload[at] != KDF_ARGON2ID {
|
||||
return Err(Error::UnsupportedKdf);
|
||||
}
|
||||
let u32_at = |i: usize| u32::from_le_bytes(payload[i..i + 4].try_into().unwrap());
|
||||
let k = KdfParams { m_cost_kib: u32_at(at + 1), t_cost: u32_at(at + 5), p_cost: u32_at(at + 9) };
|
||||
k.check()?;
|
||||
at += 13;
|
||||
Some(k)
|
||||
}
|
||||
2..=5 => {
|
||||
if payload.len() != at + SALT_LEN + NONCE_LEN + WRAPPED_LEN {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
None
|
||||
}
|
||||
_ => return Err(Error::Malformed),
|
||||
};
|
||||
Ok(FactorSlot {
|
||||
id,
|
||||
kind,
|
||||
kdf,
|
||||
salt: payload[at..at + SALT_LEN].try_into().unwrap(),
|
||||
nonce: payload[at + SALT_LEN..at + SALT_LEN + NONCE_LEN].try_into().unwrap(),
|
||||
wrapped: payload[at + SALT_LEN + NONCE_LEN..].to_vec(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A pair slot (kind 3): the vault key, wrapped by a KEK from two factor keys. `a < b` bytewise.
|
||||
pub struct PairSlot {
|
||||
pub a: [u8; ID_LEN],
|
||||
pub b: [u8; ID_LEN],
|
||||
pub nonce: [u8; NONCE_LEN],
|
||||
pub wrapped: Vec<u8>,
|
||||
}
|
||||
|
||||
impl PairSlot {
|
||||
pub fn aad(&self) -> Vec<u8> {
|
||||
let mut h = Vec::with_capacity(2 * ID_LEN + NONCE_LEN);
|
||||
h.extend_from_slice(&self.a);
|
||||
h.extend_from_slice(&self.b);
|
||||
h.extend_from_slice(&self.nonce);
|
||||
v2_aad(SLOT_PAIR, &h)
|
||||
}
|
||||
|
||||
pub fn raw(&self) -> RawSlot {
|
||||
let mut p = Vec::with_capacity(2 * ID_LEN + NONCE_LEN + WRAPPED_LEN);
|
||||
p.extend_from_slice(&self.a);
|
||||
p.extend_from_slice(&self.b);
|
||||
p.extend_from_slice(&self.nonce);
|
||||
p.extend_from_slice(&self.wrapped);
|
||||
RawSlot { kind: SLOT_PAIR, payload: p }
|
||||
}
|
||||
|
||||
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
|
||||
if payload.len() != 2 * ID_LEN + NONCE_LEN + WRAPPED_LEN {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
let s = PairSlot {
|
||||
a: payload[..ID_LEN].try_into().unwrap(),
|
||||
b: payload[ID_LEN..2 * ID_LEN].try_into().unwrap(),
|
||||
nonce: payload[2 * ID_LEN..2 * ID_LEN + NONCE_LEN].try_into().unwrap(),
|
||||
wrapped: payload[2 * ID_LEN + NONCE_LEN..].to_vec(),
|
||||
};
|
||||
if s.a >= s.b {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// A single slot (kind 4, machine stores only): the vault key, wrapped by one factor key.
|
||||
pub struct SingleSlot {
|
||||
pub id: [u8; ID_LEN],
|
||||
pub nonce: [u8; NONCE_LEN],
|
||||
pub wrapped: Vec<u8>,
|
||||
}
|
||||
|
||||
impl SingleSlot {
|
||||
pub fn aad(&self) -> Vec<u8> {
|
||||
let mut h = Vec::with_capacity(ID_LEN + NONCE_LEN);
|
||||
h.extend_from_slice(&self.id);
|
||||
h.extend_from_slice(&self.nonce);
|
||||
v2_aad(SLOT_SINGLE, &h)
|
||||
}
|
||||
|
||||
pub fn raw(&self) -> RawSlot {
|
||||
let mut p = Vec::with_capacity(ID_LEN + NONCE_LEN + WRAPPED_LEN);
|
||||
p.extend_from_slice(&self.id);
|
||||
p.extend_from_slice(&self.nonce);
|
||||
p.extend_from_slice(&self.wrapped);
|
||||
RawSlot { kind: SLOT_SINGLE, payload: p }
|
||||
}
|
||||
|
||||
pub fn parse(payload: &[u8]) -> Result<Self, Error> {
|
||||
if payload.len() != ID_LEN + NONCE_LEN + WRAPPED_LEN {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
Ok(SingleSlot {
|
||||
id: payload[..ID_LEN].try_into().unwrap(),
|
||||
nonce: payload[ID_LEN..ID_LEN + NONCE_LEN].try_into().unwrap(),
|
||||
wrapped: payload[ID_LEN + NONCE_LEN..].to_vec(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Header {
|
||||
pub version: u16,
|
||||
pub slots: Vec<RawSlot>,
|
||||
pub body_nonce: [u8; NONCE_LEN],
|
||||
}
|
||||
@@ -82,7 +254,7 @@ impl Header {
|
||||
pub fn to_bytes(&self) -> Vec<u8> {
|
||||
let mut h = Vec::new();
|
||||
h.extend_from_slice(MAGIC);
|
||||
h.extend_from_slice(&VERSION.to_le_bytes());
|
||||
h.extend_from_slice(&self.version.to_le_bytes());
|
||||
h.push(self.slots.len() as u8);
|
||||
for s in &self.slots {
|
||||
h.push(s.kind);
|
||||
@@ -99,11 +271,13 @@ impl Header {
|
||||
return Err(Error::NotAVault);
|
||||
}
|
||||
let version = u16::from_le_bytes([bytes[6], bytes[7]]);
|
||||
if version != VERSION {
|
||||
return Err(Error::UnsupportedVersion(version));
|
||||
}
|
||||
let max = match version {
|
||||
VERSION => MAX_SLOTS,
|
||||
VERSION_2 => MAX_SLOTS_V2,
|
||||
v => return Err(Error::UnsupportedVersion(v)),
|
||||
};
|
||||
let count = bytes[8] as usize;
|
||||
if count == 0 || count > MAX_SLOTS {
|
||||
if count == 0 || count > max {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
let mut at = 9;
|
||||
@@ -120,6 +294,69 @@ impl Header {
|
||||
if bytes.len() < at + TAG_LEN {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
Ok((Header { slots, body_nonce }, at))
|
||||
let header = Header { version, slots, body_nonce };
|
||||
if version == VERSION_2 {
|
||||
header.check_v2()?;
|
||||
}
|
||||
Ok((header, at))
|
||||
}
|
||||
|
||||
/// Structural rules of a v2 header (docs/FACTORS.md, "Limits a reader enforces").
|
||||
fn check_v2(&self) -> Result<(), Error> {
|
||||
let mut ids = Vec::new();
|
||||
for s in self.slots.iter().filter(|s| s.kind == SLOT_FACTOR) {
|
||||
ids.push(FactorSlot::parse(&s.payload)?.id);
|
||||
}
|
||||
if ids.is_empty() || ids.len() > MAX_FACTORS {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
let mut seen = ids.clone();
|
||||
seen.sort();
|
||||
seen.dedup();
|
||||
if seen.len() != ids.len() {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
let mut singles = 0;
|
||||
for s in &self.slots {
|
||||
match s.kind {
|
||||
SLOT_FACTOR => {}
|
||||
SLOT_PAIR => {
|
||||
let p = PairSlot::parse(&s.payload)?;
|
||||
if !ids.contains(&p.a) || !ids.contains(&p.b) {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
}
|
||||
SLOT_SINGLE => {
|
||||
let p = SingleSlot::parse(&s.payload)?;
|
||||
if !ids.contains(&p.id) {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
singles += 1;
|
||||
}
|
||||
// A v1 password slot, or an unknown kind, has no place in a v2 header.
|
||||
_ => return Err(Error::Malformed),
|
||||
}
|
||||
}
|
||||
// A machine store is exactly one factor and its single slot.
|
||||
if singles > 0 && (singles != 1 || ids.len() != 1) {
|
||||
return Err(Error::Malformed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn factor_slots(&self) -> Vec<FactorSlot> {
|
||||
self.slots.iter().filter(|s| s.kind == SLOT_FACTOR).filter_map(|s| FactorSlot::parse(&s.payload).ok()).collect()
|
||||
}
|
||||
|
||||
pub fn pair_slots(&self) -> Vec<PairSlot> {
|
||||
self.slots.iter().filter(|s| s.kind == SLOT_PAIR).filter_map(|s| PairSlot::parse(&s.payload).ok()).collect()
|
||||
}
|
||||
|
||||
pub fn single_slot(&self) -> Option<SingleSlot> {
|
||||
self.slots.iter().find(|s| s.kind == SLOT_SINGLE).and_then(|s| SingleSlot::parse(&s.payload).ok())
|
||||
}
|
||||
|
||||
pub fn is_machine_store(&self) -> bool {
|
||||
self.slots.iter().any(|s| s.kind == SLOT_SINGLE)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
//! The Domi identity's root key (docs/IDENTITY.md). It lives in the vault body and never leaves it: nothing
|
||||
//! here or on [`Vault`] returns it, and the vault signs nothing with it but subkey certificates.
|
||||
//!
|
||||
//! Creating it is a typestate, so the mnemonic is always shown before the root exists:
|
||||
//!
|
||||
//! ```
|
||||
//! # use custos_vault::{identity::Enrollment, KdfParams, SecretString, Vault};
|
||||
//! # let mut vault = Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 })?;
|
||||
//! let mut words = Vec::new();
|
||||
//! let shown = Enrollment::begin().show(|w| words = w.iter().map(|s| s.to_string()).collect());
|
||||
//! let typed = shown.challenge().map(|i| words[i - 1].clone()); // the person types these back
|
||||
//! let confirmed = shown.confirm(&[&typed[0], &typed[1], &typed[2]]).map_err(|(_, e)| e)?;
|
||||
//! let root_public = confirmed.import(&mut vault)?;
|
||||
//! # Ok::<(), custos_vault::Error>(())
|
||||
//! ```
|
||||
//!
|
||||
//! Importing before the mnemonic was shown does not compile:
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! # use custos_vault::{identity::Enrollment, KdfParams, SecretString, Vault};
|
||||
//! # let mut vault = Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
|
||||
//! Enrollment::begin().import(&mut vault);
|
||||
//! ```
|
||||
//!
|
||||
//! Nor does confirming words that were never shown:
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! # use custos_vault::identity::Enrollment;
|
||||
//! Enrollment::begin().confirm(&["abandon", "abandon", "art"]);
|
||||
//! ```
|
||||
//!
|
||||
//! Nor importing straight after showing, without the person typing the words back:
|
||||
//!
|
||||
//! ```compile_fail
|
||||
//! # use custos_vault::{identity::Enrollment, KdfParams, SecretString, Vault};
|
||||
//! # let mut vault = Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
|
||||
//! Enrollment::begin().show(|_| {}).import(&mut vault);
|
||||
//! ```
|
||||
|
||||
use crate::crypto::{self, KEY_LEN};
|
||||
use crate::{Error, SecretString, Vault, hex, now_ms, unhex};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// The root signs `CERT_DOMAIN ‖ tbs`, and only a `tbs` that starts with `CERT_MAGIC ‖ its public key`.
|
||||
const CERT_DOMAIN: &[u8] = b"tessera cert v1\0";
|
||||
const CERT_MAGIC: &[u8] = b"TSC1";
|
||||
const WORDS: usize = 24;
|
||||
|
||||
/// Step 1: fresh entropy. Nothing is derived from it until the words have been shown.
|
||||
pub struct Enrollment {
|
||||
entropy: Zeroizing<[u8; 32]>,
|
||||
}
|
||||
|
||||
/// Step 2: the words were shown; the person must type three of them back.
|
||||
pub struct Shown {
|
||||
entropy: Zeroizing<[u8; 32]>,
|
||||
challenge: [usize; 3],
|
||||
}
|
||||
|
||||
/// Step 3: the words were confirmed. Holds the root secret; the entropy is gone.
|
||||
pub struct Confirmed {
|
||||
secret: Zeroizing<[u8; KEY_LEN]>,
|
||||
}
|
||||
|
||||
fn mnemonic(entropy: &[u8; 32]) -> bip39::Mnemonic {
|
||||
bip39::Mnemonic::from_entropy_in(bip39::Language::English, entropy)
|
||||
.expect("32 bytes is a valid BIP39 entropy length")
|
||||
}
|
||||
|
||||
fn normalize(w: &str) -> String {
|
||||
w.trim().to_lowercase()
|
||||
}
|
||||
|
||||
/// Three different word positions, 1-based, ascending.
|
||||
fn random_challenge() -> [usize; 3] {
|
||||
let mut picked = Vec::with_capacity(3);
|
||||
while picked.len() < 3 {
|
||||
let mut b = [0u8; 1];
|
||||
crypto::fill_random(&mut b);
|
||||
// 240 = 10 × 24: rejection sampling keeps every position equally likely.
|
||||
if b[0] < 240 {
|
||||
let i = (b[0] as usize % WORDS) + 1;
|
||||
if !picked.contains(&i) {
|
||||
picked.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
picked.sort();
|
||||
[picked[0], picked[1], picked[2]]
|
||||
}
|
||||
|
||||
impl Enrollment {
|
||||
/// 32 bytes from the OS CSPRNG.
|
||||
pub fn begin() -> Enrollment {
|
||||
let mut entropy = Zeroizing::new([0u8; 32]);
|
||||
crypto::fill_random(entropy.as_mut());
|
||||
Enrollment { entropy }
|
||||
}
|
||||
|
||||
/// Known entropy, for test vectors.
|
||||
pub fn with_entropy(entropy: [u8; 32]) -> Enrollment {
|
||||
Enrollment { entropy: Zeroizing::new(entropy) }
|
||||
}
|
||||
|
||||
/// Hands the 24 words to `display`, once. The only way to [`Shown`].
|
||||
pub fn show(self, display: impl FnOnce(&[&str])) -> Shown {
|
||||
let phrase = Zeroizing::new(mnemonic(&self.entropy).to_string());
|
||||
let words: Vec<&str> = phrase.split(' ').collect();
|
||||
display(&words);
|
||||
Shown { entropy: self.entropy, challenge: random_challenge() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Shown {
|
||||
/// The positions (1–24) of the three words to type back.
|
||||
pub fn challenge(&self) -> [usize; 3] {
|
||||
self.challenge
|
||||
}
|
||||
|
||||
/// Checks the three typed words (any case, surrounding spaces ignored). On a mismatch this `Shown` comes
|
||||
/// back with [`Error::WrongWords`], so the person can try again; the words are not shown again.
|
||||
pub fn confirm(self, words: &[&str; 3]) -> Result<Confirmed, (Shown, Error)> {
|
||||
let m = mnemonic(&self.entropy);
|
||||
let phrase = Zeroizing::new(m.to_string());
|
||||
let all: Vec<&str> = phrase.split(' ').collect();
|
||||
let ok = self.challenge.iter().zip(words).all(|(&i, typed)| *Zeroizing::new(normalize(typed)) == all[i - 1]);
|
||||
if !ok {
|
||||
return Err((self, Error::WrongWords));
|
||||
}
|
||||
Ok(Confirmed { secret: crypto::domi_root_secret(&m) })
|
||||
}
|
||||
}
|
||||
|
||||
impl Confirmed {
|
||||
/// Stores the root in `vault` and returns its public key. The caller saves the vault. A vault has one
|
||||
/// identity: a second import is [`Error::IdentityExists`].
|
||||
pub fn import(self, vault: &mut Vault) -> Result<[u8; 32], Error> {
|
||||
if vault.identity.is_some() {
|
||||
return Err(Error::IdentityExists);
|
||||
}
|
||||
let public = crypto::ed25519_public(&self.secret);
|
||||
vault.identity = Some(Root { secret: self.secret, public, created: now_ms(), issued: Vec::new() });
|
||||
Ok(public)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Enrollment {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("Enrollment([redacted])")
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Shown {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("Shown([redacted])")
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Confirmed {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("Confirmed([redacted])")
|
||||
}
|
||||
}
|
||||
|
||||
/// A cert the vault signed, for display (docs/IDENTITY.md). A record, not a trust list.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Issued {
|
||||
/// `app` or `device`.
|
||||
pub kind: String,
|
||||
pub app_id: String,
|
||||
pub purpose: String,
|
||||
/// The subkey's public key, base64url.
|
||||
pub subkey: String,
|
||||
/// The program or device it was issued to.
|
||||
pub label: String,
|
||||
/// Unix seconds.
|
||||
pub not_before: u64,
|
||||
pub not_after: u64,
|
||||
/// Unix milliseconds.
|
||||
pub issued: i64,
|
||||
}
|
||||
|
||||
/// The identity in an unlocked vault.
|
||||
pub(crate) struct Root {
|
||||
secret: Zeroizing<[u8; KEY_LEN]>,
|
||||
pub(crate) public: [u8; 32],
|
||||
pub(crate) created: i64,
|
||||
pub(crate) issued: Vec<Issued>,
|
||||
}
|
||||
|
||||
/// The `identity` body member.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) struct RootJson {
|
||||
root: SecretString,
|
||||
public: String,
|
||||
created: i64,
|
||||
#[serde(default)]
|
||||
issued: Vec<Issued>,
|
||||
}
|
||||
|
||||
impl Root {
|
||||
pub(crate) fn sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
|
||||
let names_me = tbs.len() > CERT_MAGIC.len() + 32
|
||||
&& &tbs[..CERT_MAGIC.len()] == CERT_MAGIC
|
||||
&& tbs[CERT_MAGIC.len()..CERT_MAGIC.len() + 32] == self.public;
|
||||
if !names_me {
|
||||
return Err(Error::NotACert);
|
||||
}
|
||||
let msg = Zeroizing::new([CERT_DOMAIN, tbs].concat());
|
||||
Ok(crypto::ed25519_sign(&self.secret, &msg))
|
||||
}
|
||||
|
||||
pub(crate) fn json(&self) -> RootJson {
|
||||
RootJson {
|
||||
root: SecretString::new(hex(self.secret.as_ref())),
|
||||
public: hex(&self.public),
|
||||
created: self.created,
|
||||
issued: self.issued.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `None` when malformed, or when the public key is not the secret's.
|
||||
pub(crate) fn from_json(j: &RootJson) -> Option<Root> {
|
||||
let secret = Zeroizing::new(unhex::<KEY_LEN>(j.root.expose())?);
|
||||
let public = unhex::<32>(&j.public)?;
|
||||
if crypto::ed25519_public(&secret) != public {
|
||||
return None;
|
||||
}
|
||||
Some(Root { secret, public, created: j.created, issued: j.issued.clone() })
|
||||
}
|
||||
}
|
||||
@@ -16,16 +16,19 @@ pub enum ItemType {
|
||||
Wifi,
|
||||
SecureNote,
|
||||
Card,
|
||||
/// A signing or SSH key pair (docs/FACTORS.md, "The key-pair item type").
|
||||
KeyPair,
|
||||
}
|
||||
|
||||
impl ItemType {
|
||||
pub const ALL: [ItemType; 6] = [
|
||||
pub const ALL: [ItemType; 7] = [
|
||||
ItemType::WebLogin,
|
||||
ItemType::ApiCredential,
|
||||
ItemType::LocalApp,
|
||||
ItemType::Wifi,
|
||||
ItemType::SecureNote,
|
||||
ItemType::Card,
|
||||
ItemType::KeyPair,
|
||||
];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
@@ -36,6 +39,7 @@ impl ItemType {
|
||||
ItemType::Wifi => "Wi-Fi",
|
||||
ItemType::SecureNote => "Secure note",
|
||||
ItemType::Card => "Card",
|
||||
ItemType::KeyPair => "Key pair",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +63,15 @@ impl ItemType {
|
||||
ItemType::Card => {
|
||||
&[("cardholder", false), ("number", true), ("expiry", false), ("cvv", true), ("pin", true)]
|
||||
}
|
||||
ItemType::KeyPair => &[
|
||||
("algorithm", false),
|
||||
("public-key", false),
|
||||
("public-pem", false),
|
||||
("private-key", true),
|
||||
("private-openssh", true),
|
||||
("fingerprint", false),
|
||||
("comment", false),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+584
-30
@@ -1,19 +1,25 @@
|
||||
//! The Custos vault: one `.custos` file, Argon2id + XChaCha20-Poly1305, documented in docs/FORMAT.md.
|
||||
//! The Custos vault: one `.custos` file, Argon2id + XChaCha20-Poly1305, documented in docs/FORMAT.md
|
||||
//! (version 1) and docs/FACTORS.md (version 2: any two factors).
|
||||
//!
|
||||
//! ```
|
||||
//! use custos_vault::{Item, ItemType, KdfParams, SecretString, Vault};
|
||||
//! use custos_vault::{FactorKind, Item, ItemType, KdfParams, SecretString, Unlock, Vault};
|
||||
//! let password = SecretString::from("Orbit7-Fable3-Quartz9-Lumen2");
|
||||
//! let device_key = [7u8; 32]; // in the app: a key file only this Windows account can read
|
||||
//! # let kdf = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
|
||||
//! let mut vault = Vault::create(&password, kdf)?;
|
||||
//! let mut vault = Vault::create_with(
|
||||
//! Unlock::Password(&password), "Master password",
|
||||
//! Unlock::Material(FactorKind::Device, &device_key), "This PC", kdf)?;
|
||||
//! vault.add(Item::new(ItemType::WebLogin, "GitHub", custos_vault::now_ms()));
|
||||
//! let bytes = vault.to_bytes()?;
|
||||
//! assert_eq!(Vault::open(&bytes, &password)?.items().len(), 1);
|
||||
//! let back = Vault::open_with(&bytes, Unlock::Password(&password), Unlock::Material(FactorKind::Device, &device_key))?;
|
||||
//! assert_eq!(back.items().len(), 1);
|
||||
//! # Ok::<(), custos_vault::Error>(())
|
||||
//! ```
|
||||
|
||||
mod crypto;
|
||||
mod device;
|
||||
mod format;
|
||||
pub mod identity;
|
||||
mod item;
|
||||
mod save;
|
||||
mod secret;
|
||||
@@ -23,7 +29,10 @@ pub use save::{CrashPoint, save_atomic, save_atomic_crashing};
|
||||
pub use secret::SecretString;
|
||||
|
||||
use crypto::KEY_LEN;
|
||||
use format::{Header, PasswordSlot, RawSlot, SALT_LEN, SLOT_PASSWORD};
|
||||
use format::{
|
||||
FactorSlot, Header, ID_LEN, MAX_FACTORS, PairSlot, PasswordSlot, RawSlot, SALT_LEN, SLOT_FACTOR, SLOT_PAIR,
|
||||
SLOT_PASSWORD, SingleSlot, VERSION, VERSION_2,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
@@ -45,6 +54,22 @@ pub enum Error {
|
||||
Corrupted,
|
||||
#[error("this device's unlock key no longer opens the vault; use the master password")]
|
||||
DeviceKeyRejected,
|
||||
#[error("this vault opens with two different factors")]
|
||||
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("this vault has no Domi identity yet")]
|
||||
NoIdentity,
|
||||
#[error("this vault already has a Domi identity")]
|
||||
IdentityExists,
|
||||
#[error("the Domi identity signs only certificates that name it")]
|
||||
NotACert,
|
||||
#[error("those words are not the ones in the recovery phrase")]
|
||||
WrongWords,
|
||||
#[error("{0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
@@ -80,12 +105,162 @@ impl Default for KdfParams {
|
||||
}
|
||||
}
|
||||
|
||||
/// What kind of secret a factor is (docs/FACTORS.md, "Factor KEKs").
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum FactorKind {
|
||||
/// The master password.
|
||||
Password,
|
||||
/// A key one device keeps (a DPAPI-protected key file, a key in the phone's storage).
|
||||
Device,
|
||||
/// A share the TOTP service releases after a valid code.
|
||||
Totp,
|
||||
/// A secret another paired device sends after you approve there.
|
||||
Approval,
|
||||
/// A WebAuthn PRF output (Face ID, Touch ID, Windows Hello passkey).
|
||||
Passkey,
|
||||
}
|
||||
|
||||
impl FactorKind {
|
||||
fn code(self) -> u8 {
|
||||
match self {
|
||||
FactorKind::Password => 1,
|
||||
FactorKind::Device => 2,
|
||||
FactorKind::Totp => 3,
|
||||
FactorKind::Approval => 4,
|
||||
FactorKind::Passkey => 5,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_code(c: u8) -> Option<Self> {
|
||||
Some(match c {
|
||||
1 => FactorKind::Password,
|
||||
2 => FactorKind::Device,
|
||||
3 => FactorKind::Totp,
|
||||
4 => FactorKind::Approval,
|
||||
5 => FactorKind::Passkey,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// One factor given to open a vault. `Debug` never prints the password or the material.
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Unlock<'a> {
|
||||
Password(&'a SecretString),
|
||||
/// Any other factor: its kind and 32..=64 bytes of material.
|
||||
Material(FactorKind, &'a [u8]),
|
||||
}
|
||||
|
||||
impl Unlock<'_> {
|
||||
fn kind(&self) -> FactorKind {
|
||||
match self {
|
||||
Unlock::Password(_) => FactorKind::Password,
|
||||
Unlock::Material(k, _) => *k,
|
||||
}
|
||||
}
|
||||
|
||||
/// Material for types 2..5 must be 32..=64 bytes, and a password is never passed as material.
|
||||
fn check(&self) -> Result<(), Error> {
|
||||
match self {
|
||||
Unlock::Password(_) => Ok(()),
|
||||
Unlock::Material(FactorKind::Password, _) => Err(Error::FactorRejected),
|
||||
Unlock::Material(_, m) if (32..=64).contains(&m.len()) => Ok(()),
|
||||
Unlock::Material(..) => Err(Error::FactorRejected),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Unlock<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Unlock::Password(_) => f.write_str("Password([redacted])"),
|
||||
Unlock::Material(k, _) => write!(f, "Material({k:?}, [redacted])"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A factor of an unlocked vault, as the app lists it. Never carries the factor key.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FactorInfo {
|
||||
/// 32 hex digits.
|
||||
pub id: String,
|
||||
pub kind: FactorKind,
|
||||
pub label: String,
|
||||
pub created: i64,
|
||||
}
|
||||
|
||||
/// A factor as the body keeps it: its key `F` is what lets an unlocked vault add pairs.
|
||||
#[derive(Clone)]
|
||||
struct FactorRec {
|
||||
id: [u8; ID_LEN],
|
||||
kind: FactorKind,
|
||||
label: String,
|
||||
created: i64,
|
||||
key: Zeroizing<[u8; KEY_LEN]>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct FactorJson {
|
||||
id: String,
|
||||
#[serde(rename = "type")]
|
||||
kind: FactorKind,
|
||||
label: String,
|
||||
created: i64,
|
||||
key: SecretString,
|
||||
}
|
||||
|
||||
fn hex(b: &[u8]) -> String {
|
||||
b.iter().map(|x| format!("{x:02x}")).collect()
|
||||
}
|
||||
|
||||
fn unhex<const N: usize>(s: &str) -> Option<[u8; N]> {
|
||||
if s.len() != 2 * N {
|
||||
return None;
|
||||
}
|
||||
let mut out = [0u8; N];
|
||||
for (i, o) in out.iter_mut().enumerate() {
|
||||
*o = u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()?;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
impl FactorRec {
|
||||
fn json(&self) -> FactorJson {
|
||||
FactorJson {
|
||||
id: hex(&self.id),
|
||||
kind: self.kind,
|
||||
label: self.label.clone(),
|
||||
created: self.created,
|
||||
key: SecretString::new(hex(self.key.as_ref())),
|
||||
}
|
||||
}
|
||||
|
||||
fn from_json(j: &FactorJson) -> Option<FactorRec> {
|
||||
Some(FactorRec {
|
||||
id: unhex(&j.id)?,
|
||||
kind: j.kind,
|
||||
label: j.label.clone(),
|
||||
created: j.created,
|
||||
key: Zeroizing::new(unhex(j.key.expose())?),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const BODY_FORMAT: u32 = 1;
|
||||
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";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Body {
|
||||
format: u32,
|
||||
items: Vec<Item>,
|
||||
#[serde(default)]
|
||||
factors: Vec<FactorJson>,
|
||||
#[serde(default)]
|
||||
identity: Option<identity::RootJson>,
|
||||
}
|
||||
|
||||
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
|
||||
@@ -93,18 +268,34 @@ struct Body {
|
||||
struct BodyRef<'a> {
|
||||
format: u32,
|
||||
items: &'a [Item],
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
factors: Vec<FactorJson>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
identity: Option<identity::RootJson>,
|
||||
}
|
||||
|
||||
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
|
||||
pub struct Vault {
|
||||
key: Zeroizing<[u8; KEY_LEN]>,
|
||||
version: u16,
|
||||
slots: Vec<RawSlot>,
|
||||
items: Vec<Item>,
|
||||
/// Version 2 only.
|
||||
factors: Vec<FactorRec>,
|
||||
/// Argon2 parameters for a password factor added later.
|
||||
kdf_new: KdfParams,
|
||||
/// The Domi identity's root key (docs/IDENTITY.md), never handed out.
|
||||
identity: Option<identity::Root>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Vault {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Vault").field("items", &self.items.len()).finish_non_exhaustive()
|
||||
f.debug_struct("Vault")
|
||||
.field("version", &self.version)
|
||||
.field("items", &self.items.len())
|
||||
.field("factors", &self.factors.len())
|
||||
.field("identity", &self.identity.is_some())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,21 +309,144 @@ fn password_slot(key: &[u8; KEY_LEN], password: &SecretString, kdf: KdfParams) -
|
||||
Ok(slot)
|
||||
}
|
||||
|
||||
/// The KEK a factor's material gives for one factor slot.
|
||||
fn factor_kek(u: &Unlock, salt: &[u8], kdf: Option<KdfParams>) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
|
||||
match (u, kdf) {
|
||||
(Unlock::Password(p), Some(k)) => crypto::derive_kek(p.expose().as_bytes(), salt, k),
|
||||
(Unlock::Material(_, m), None) => Ok(crypto::hkdf(m, salt, INFO_FACTOR)),
|
||||
_ => Err(Error::FactorRejected),
|
||||
}
|
||||
}
|
||||
|
||||
/// A new factor slot wrapping `key` (the factor key `F`) with `u`'s material.
|
||||
fn factor_slot(id: [u8; ID_LEN], key: &[u8; KEY_LEN], u: &Unlock, kdf: KdfParams) -> Result<FactorSlot, Error> {
|
||||
u.check()?;
|
||||
let kdf = matches!(u, Unlock::Password(_)).then_some(kdf);
|
||||
if let Some(k) = kdf {
|
||||
k.check()?;
|
||||
}
|
||||
let mut salt = [0u8; SALT_LEN];
|
||||
crypto::fill_random(&mut salt);
|
||||
let mut slot =
|
||||
FactorSlot { id, kind: u.kind().code(), kdf, salt, nonce: crypto::random_nonce(), wrapped: Vec::new() };
|
||||
let kek = factor_kek(u, &slot.salt, slot.kdf)?;
|
||||
slot.wrapped = crypto::seal(&kek, &slot.nonce, key, &slot.aad());
|
||||
Ok(slot)
|
||||
}
|
||||
|
||||
fn pair_kek(a: &FactorRec, b: &FactorRec) -> Zeroizing<[u8; KEY_LEN]> {
|
||||
let (x, y) = if a.id < b.id { (a, b) } else { (b, a) };
|
||||
let mut ikm = Zeroizing::new([0u8; 2 * KEY_LEN]);
|
||||
ikm[..KEY_LEN].copy_from_slice(x.key.as_ref());
|
||||
ikm[KEY_LEN..].copy_from_slice(y.key.as_ref());
|
||||
let mut salt = [0u8; 2 * ID_LEN];
|
||||
salt[..ID_LEN].copy_from_slice(&x.id);
|
||||
salt[ID_LEN..].copy_from_slice(&y.id);
|
||||
crypto::hkdf(ikm.as_ref(), &salt, INFO_PAIR)
|
||||
}
|
||||
|
||||
fn pair_slot(vault_key: &[u8; KEY_LEN], a: &FactorRec, b: &FactorRec) -> PairSlot {
|
||||
let (x, y) = if a.id < b.id { (a.id, b.id) } else { (b.id, a.id) };
|
||||
let mut slot = PairSlot { a: x, b: y, nonce: crypto::random_nonce(), wrapped: Vec::new() };
|
||||
slot.wrapped = crypto::seal(&pair_kek(a, b), &slot.nonce, vault_key, &slot.aad());
|
||||
slot
|
||||
}
|
||||
|
||||
fn single_kek(f: &FactorRec) -> Zeroizing<[u8; KEY_LEN]> {
|
||||
crypto::hkdf(f.key.as_ref(), &f.id, INFO_SINGLE)
|
||||
}
|
||||
|
||||
fn key32(k: Zeroizing<Vec<u8>>) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
|
||||
Ok(Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::Malformed)?))
|
||||
}
|
||||
|
||||
/// The first factor slot of `u`'s kind that `u` unwraps: its id and factor key.
|
||||
fn unwrap_factor(header: &Header, u: &Unlock) -> Result<FactorRec, Error> {
|
||||
u.check()?;
|
||||
for slot in header.factor_slots().into_iter().filter(|s| s.kind == u.kind().code()) {
|
||||
let kek = factor_kek(u, &slot.salt, slot.kdf)?;
|
||||
if let Some(k) = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()) {
|
||||
return Ok(FactorRec { id: slot.id, kind: u.kind(), label: String::new(), created: 0, key: key32(k)? });
|
||||
}
|
||||
}
|
||||
Err(if matches!(u, Unlock::Password(_)) { Error::WrongPassword } else { Error::FactorRejected })
|
||||
}
|
||||
|
||||
impl Vault {
|
||||
/// A new, empty vault with a fresh random vault key wrapped by `password`.
|
||||
/// A new, empty version-1 vault with a fresh random vault key wrapped by `password`.
|
||||
pub fn create(password: &SecretString, kdf: KdfParams) -> Result<Vault, Error> {
|
||||
let key = crypto::random_key();
|
||||
let slot = password_slot(&key, password, kdf)?;
|
||||
Ok(Vault { key, slots: vec![slot.raw()], items: Vec::new() })
|
||||
Ok(Vault {
|
||||
key,
|
||||
version: VERSION,
|
||||
slots: vec![slot.raw()],
|
||||
items: Vec::new(),
|
||||
factors: Vec::new(),
|
||||
kdf_new: kdf,
|
||||
identity: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A new, empty version-2 vault that opens with these two factors together (docs/FACTORS.md).
|
||||
pub fn create_with(a: Unlock, label_a: &str, b: Unlock, label_b: &str, kdf: KdfParams) -> Result<Vault, Error> {
|
||||
if a.kind() == FactorKind::Password && b.kind() == FactorKind::Password {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
let mut v = Vault {
|
||||
key: crypto::random_key(),
|
||||
version: VERSION_2,
|
||||
slots: Vec::new(),
|
||||
items: Vec::new(),
|
||||
factors: Vec::new(),
|
||||
kdf_new: kdf,
|
||||
identity: None,
|
||||
};
|
||||
v.add_factor(a, label_a)?;
|
||||
v.add_factor(b, label_b)?;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// A machine store: a separate vault that one device key opens alone, for a program that must
|
||||
/// open it unattended (the Claude Code store). Never for the user's own secrets.
|
||||
pub fn create_machine_store(material: &[u8], label: &str) -> Result<Vault, Error> {
|
||||
let u = Unlock::Material(FactorKind::Device, material);
|
||||
u.check()?;
|
||||
let key = crypto::random_key();
|
||||
let mut id = [0u8; ID_LEN];
|
||||
crypto::fill_random(&mut id);
|
||||
let rec = FactorRec {
|
||||
id,
|
||||
kind: FactorKind::Device,
|
||||
label: label.into(),
|
||||
created: now_ms(),
|
||||
key: crypto::random_key(),
|
||||
};
|
||||
let fslot = factor_slot(id, &rec.key, &u, KdfParams::DEFAULT)?;
|
||||
let mut single = SingleSlot { id, nonce: crypto::random_nonce(), wrapped: Vec::new() };
|
||||
single.wrapped = crypto::seal(&single_kek(&rec), &single.nonce, key.as_ref(), &single.aad());
|
||||
Ok(Vault {
|
||||
key,
|
||||
version: VERSION_2,
|
||||
slots: vec![fslot.raw(), single.raw()],
|
||||
items: Vec::new(),
|
||||
factors: vec![rec],
|
||||
kdf_new: KdfParams::DEFAULT,
|
||||
identity: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn open_file(path: &Path, password: &SecretString) -> Result<Vault, Error> {
|
||||
Vault::open(&std::fs::read(path)?, password)
|
||||
}
|
||||
|
||||
/// Unlocks a vault. Returns no data at all unless both the key slot and the body authenticate.
|
||||
/// Unlocks a version-1 vault with its password. A version-2 vault needs [`Vault::open_with`].
|
||||
/// Returns no data at all unless both the key slot and the body authenticate.
|
||||
pub fn open(bytes: &[u8], password: &SecretString) -> Result<Vault, Error> {
|
||||
let (header, body_at) = Header::parse(bytes)?;
|
||||
if header.version == VERSION_2 {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
let pw_slots: Vec<PasswordSlot> = header
|
||||
.slots
|
||||
.iter()
|
||||
@@ -145,34 +459,120 @@ impl Vault {
|
||||
for slot in &pw_slots {
|
||||
let kek = crypto::derive_kek(password.expose().as_bytes(), &slot.salt, slot.kdf)?;
|
||||
if let Some(k) = crypto::open(&kek, &slot.nonce, &slot.wrapped, &slot.aad()) {
|
||||
let key: Zeroizing<[u8; KEY_LEN]> =
|
||||
Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::Malformed)?);
|
||||
return Vault::open_body(bytes, header, body_at, key);
|
||||
let kdf = slot.kdf;
|
||||
let mut v = Vault::open_body(bytes, header, body_at, key32(k)?)?;
|
||||
v.kdf_new = kdf;
|
||||
return Ok(v);
|
||||
}
|
||||
}
|
||||
Err(Error::WrongPassword)
|
||||
}
|
||||
|
||||
/// Unlocks a version-2 vault with two different factors, in any order (docs/FACTORS.md, "Opening").
|
||||
pub fn open_with(bytes: &[u8], a: Unlock, b: Unlock) -> Result<Vault, Error> {
|
||||
let (header, body_at) = Header::parse(bytes)?;
|
||||
if header.version != VERSION_2 || header.is_machine_store() {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
// Refuse bad material before any Argon2 work.
|
||||
a.check()?;
|
||||
b.check()?;
|
||||
let fa = unwrap_factor(&header, &a)?;
|
||||
let fb = unwrap_factor(&header, &b)?;
|
||||
if fa.id == fb.id {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
let (x, y) = if fa.id < fb.id { (fa.id, fb.id) } else { (fb.id, fa.id) };
|
||||
// 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)?)
|
||||
}
|
||||
|
||||
/// Opens a machine store with its one device key. A user vault is never opened this way.
|
||||
pub fn open_machine_store(bytes: &[u8], material: &[u8]) -> Result<Vault, Error> {
|
||||
let (header, body_at) = Header::parse(bytes)?;
|
||||
if header.version != VERSION_2 || !header.is_machine_store() {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
let f = unwrap_factor(&header, &Unlock::Material(FactorKind::Device, material))?;
|
||||
let slot = header.single_slot().filter(|s| s.id == f.id).ok_or(Error::Corrupted)?;
|
||||
let k = crypto::open(&single_kek(&f), &slot.nonce, &slot.wrapped, &slot.aad()).ok_or(Error::Corrupted)?;
|
||||
Vault::open_body(bytes, header, body_at, key32(k)?)
|
||||
}
|
||||
|
||||
/// The format version of a vault file (1 or 2), from its header alone.
|
||||
pub fn version_of(bytes: &[u8]) -> Result<u16, Error> {
|
||||
Ok(Header::parse(bytes)?.0.version)
|
||||
}
|
||||
|
||||
/// The kinds of factor a vault opens with, from its header alone: what the unlock screen offers.
|
||||
pub fn factor_kinds(bytes: &[u8]) -> Result<Vec<FactorKind>, Error> {
|
||||
let (header, _) = Header::parse(bytes)?;
|
||||
if header.version == VERSION {
|
||||
return Ok(vec![FactorKind::Password]);
|
||||
}
|
||||
Ok(header.factor_slots().iter().filter_map(|s| FactorKind::from_code(s.kind)).collect())
|
||||
}
|
||||
|
||||
/// The factors a vault file has, from its header (no key needed): id (32 hex digits) and type. The app
|
||||
/// asks the TOTP service and paired devices for a factor by this id.
|
||||
pub fn factor_ids(bytes: &[u8]) -> Result<Vec<(String, FactorKind)>, Error> {
|
||||
let (header, _) = Header::parse(bytes)?;
|
||||
if header.version == VERSION {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Ok(header.factor_slots().iter().filter_map(|s| Some((hex(&s.id), FactorKind::from_code(s.kind)?))).collect())
|
||||
}
|
||||
|
||||
pub fn is_machine_store(bytes: &[u8]) -> Result<bool, Error> {
|
||||
Ok(Header::parse(bytes)?.0.is_machine_store())
|
||||
}
|
||||
|
||||
fn open_body(bytes: &[u8], header: Header, body_at: usize, key: Zeroizing<[u8; KEY_LEN]>) -> Result<Vault, Error> {
|
||||
let json =
|
||||
crypto::open(&key, &header.body_nonce, &bytes[body_at..], &bytes[..body_at]).ok_or(Error::Corrupted)?;
|
||||
let body: Body = serde_json::from_slice(&json).map_err(|_| Error::Corrupted)?;
|
||||
if body.format != BODY_FORMAT {
|
||||
let want = if header.version == VERSION_2 { BODY_FORMAT_2 } else { BODY_FORMAT };
|
||||
if body.format != want {
|
||||
return Err(Error::Corrupted);
|
||||
}
|
||||
Ok(Vault { key, slots: header.slots, items: body.items })
|
||||
let factors: Vec<FactorRec> =
|
||||
body.factors.iter().map(FactorRec::from_json).collect::<Option<_>>().ok_or(Error::Corrupted)?;
|
||||
// Every factor slot in the header has its key in the body, and the other way round.
|
||||
if header.version == VERSION_2 {
|
||||
let mut in_header: Vec<_> = header.factor_slots().iter().map(|s| s.id).collect();
|
||||
let mut in_body: Vec<_> = factors.iter().map(|f| f.id).collect();
|
||||
in_header.sort();
|
||||
in_body.sort();
|
||||
if in_header != in_body {
|
||||
return Err(Error::Corrupted);
|
||||
}
|
||||
}
|
||||
let kdf_new = header.factor_slots().iter().find_map(|s| s.kdf).unwrap_or(KdfParams::DEFAULT);
|
||||
let identity = match &body.identity {
|
||||
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 })
|
||||
}
|
||||
|
||||
/// Wraps the vault key for device unlock with key material only this device can produce (e.g. a
|
||||
/// Windows Hello signature). Keep the blob on the device; see docs/FORMAT.md, "Device key wrap".
|
||||
/// Windows Hello signature). Version 1 only: a version-2 vault never opens with one secret.
|
||||
pub fn wrap_for_device(&self, material: &[u8]) -> Result<Vec<u8>, Error> {
|
||||
if self.version == VERSION_2 {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
Ok(device::wrap(&self.key, material))
|
||||
}
|
||||
|
||||
/// Unlocks with a device blob instead of the password. Fails with `DeviceKeyRejected` when the
|
||||
/// material is wrong or the blob was changed, and with `Corrupted` when it belongs to another vault.
|
||||
/// Unlocks with a device blob instead of the password (version 1). Fails with `DeviceKeyRejected`
|
||||
/// when the material is wrong or the blob was changed, and with `Corrupted` when it belongs to another vault.
|
||||
pub fn open_with_device(bytes: &[u8], blob: &[u8], material: &[u8]) -> Result<Vault, Error> {
|
||||
let (header, body_at) = Header::parse(bytes)?;
|
||||
if header.version == VERSION_2 {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
let key = device::unwrap(blob, material)?;
|
||||
Vault::open_body(bytes, header, body_at, key)
|
||||
}
|
||||
@@ -180,9 +580,15 @@ impl Vault {
|
||||
/// The encrypted file contents, with a fresh body nonce.
|
||||
pub fn to_bytes(&self) -> Result<Vec<u8>, Error> {
|
||||
let body_nonce = crypto::random_nonce();
|
||||
let mut out = Header { slots: self.slots.clone(), body_nonce }.to_bytes();
|
||||
let mut out = Header { version: self.version, slots: self.slots.clone(), body_nonce }.to_bytes();
|
||||
let mut json = Zeroizing::new(Vec::with_capacity(4096 + 1024 * self.items.len()));
|
||||
let body = BodyRef { format: BODY_FORMAT, items: &self.items };
|
||||
let v2 = self.version == VERSION_2;
|
||||
let body = BodyRef {
|
||||
format: if v2 { BODY_FORMAT_2 } else { BODY_FORMAT },
|
||||
items: &self.items,
|
||||
factors: self.factors.iter().map(FactorRec::json).collect(),
|
||||
identity: self.identity.as_ref().map(identity::Root::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);
|
||||
out.extend_from_slice(&sealed);
|
||||
@@ -194,28 +600,147 @@ impl Vault {
|
||||
save_atomic(path, &self.to_bytes()?)
|
||||
}
|
||||
|
||||
/// Wraps the same vault key with a new password (new salt and nonce). The items are untouched;
|
||||
/// the old password stops working at the next save.
|
||||
/// Changes the master password. Version 1: a new password slot. Version 2: the password factor's
|
||||
/// key is rewrapped, so its pairs keep working (also after a forgotten password: open with two
|
||||
/// other factors, then set a new one). The old password stops working at the next save.
|
||||
pub fn change_password(&mut self, new_password: &SecretString, kdf: KdfParams) -> Result<(), Error> {
|
||||
let slot = password_slot(&self.key, new_password, kdf)?;
|
||||
self.slots.retain(|s| s.kind != SLOT_PASSWORD);
|
||||
self.slots.insert(0, slot.raw());
|
||||
if self.version == VERSION {
|
||||
let slot = password_slot(&self.key, new_password, kdf)?;
|
||||
self.slots.retain(|s| s.kind != SLOT_PASSWORD);
|
||||
self.slots.insert(0, slot.raw());
|
||||
self.kdf_new = kdf;
|
||||
return Ok(());
|
||||
}
|
||||
if self.is_store() {
|
||||
return Err(Error::FactorRejected);
|
||||
}
|
||||
self.kdf_new = kdf;
|
||||
let Some(rec) = self.factors.iter().find(|f| f.kind == FactorKind::Password).cloned() else {
|
||||
self.add_factor(Unlock::Password(new_password), "Master password")?;
|
||||
return Ok(());
|
||||
};
|
||||
let slot = factor_slot(rec.id, &rec.key, &Unlock::Password(new_password), kdf)?;
|
||||
let at = self.factor_slot_index(&rec.id).ok_or(Error::Corrupted)?;
|
||||
self.slots[at] = slot.raw();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_store(&self) -> bool {
|
||||
self.slots.iter().any(|s| s.kind == format::SLOT_SINGLE)
|
||||
}
|
||||
|
||||
fn factor_slot_index(&self, id: &[u8; ID_LEN]) -> Option<usize> {
|
||||
self.slots.iter().position(|s| s.kind == SLOT_FACTOR && s.payload.get(..ID_LEN) == Some(&id[..]))
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
if self.is_store() {
|
||||
return Err(Error::FactorRejected);
|
||||
}
|
||||
u.check()?;
|
||||
if self.factors.len() >= MAX_FACTORS
|
||||
|| (u.kind() == FactorKind::Password && self.factors.iter().any(|f| f.kind == FactorKind::Password))
|
||||
{
|
||||
return Err(Error::TooManyFactors);
|
||||
}
|
||||
let mut id = [0u8; ID_LEN];
|
||||
crypto::fill_random(&mut id);
|
||||
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.iter().filter(|f| !apart.contains(&f.id)) {
|
||||
self.slots.push(pair_slot(&self.key, &rec, other).raw());
|
||||
}
|
||||
self.factors.push(rec);
|
||||
Ok(hex(&id))
|
||||
}
|
||||
|
||||
/// Removes a factor (a lost phone, an old PC) and every pair it is part of. A vault keeps at least two.
|
||||
pub fn remove_factor(&mut self, id: &str) -> Result<(), Error> {
|
||||
let id: [u8; ID_LEN] = unhex(id).ok_or(Error::FactorRejected)?;
|
||||
if !self.factors.iter().any(|f| f.id == id) {
|
||||
return Err(Error::FactorRejected);
|
||||
}
|
||||
if self.factors.len() <= 2 {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
self.factors.retain(|f| f.id != id);
|
||||
self.slots.retain(|s| match s.kind {
|
||||
SLOT_FACTOR => s.payload.get(..ID_LEN) != Some(&id[..]),
|
||||
SLOT_PAIR => s.payload.get(..ID_LEN) != Some(&id[..]) && s.payload.get(ID_LEN..2 * ID_LEN) != Some(&id[..]),
|
||||
_ => true,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Turns an unlocked version-1 vault into version 2 with its password and a second factor.
|
||||
/// The vault key and the items stay; from the next save on, the password alone opens nothing.
|
||||
pub fn upgrade_to_two_factors(
|
||||
&mut self,
|
||||
password: &SecretString,
|
||||
kdf: KdfParams,
|
||||
second: Unlock,
|
||||
label: &str,
|
||||
) -> Result<(), Error> {
|
||||
if self.version != VERSION {
|
||||
return Err(Error::UnsupportedVersion(self.version));
|
||||
}
|
||||
if second.kind() == FactorKind::Password {
|
||||
return Err(Error::NeedTwoFactors);
|
||||
}
|
||||
second.check()?;
|
||||
self.version = VERSION_2;
|
||||
self.slots.clear();
|
||||
self.factors.clear();
|
||||
self.kdf_new = kdf;
|
||||
self.add_factor(Unlock::Password(password), "Master password")?;
|
||||
self.add_factor(second, label)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The factors of a version-2 vault, oldest first. Empty for version 1.
|
||||
pub fn factors(&self) -> Vec<FactorInfo> {
|
||||
self.factors
|
||||
.iter()
|
||||
.map(|f| FactorInfo { id: hex(&f.id), kind: f.kind, label: f.label.clone(), created: f.created })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 1 or 2.
|
||||
pub fn version(&self) -> u16 {
|
||||
self.version
|
||||
}
|
||||
|
||||
/// Whether two unlocked vaults share a vault key (tests: a password change keeps the key).
|
||||
#[doc(hidden)]
|
||||
pub fn same_key_as(&self, other: &Vault) -> bool {
|
||||
self.key[..] == other.key[..]
|
||||
}
|
||||
|
||||
/// The KDF parameters of the first password slot.
|
||||
/// The KDF parameters of the (first) password slot or password factor.
|
||||
pub fn kdf(&self) -> Option<KdfParams> {
|
||||
self.slots
|
||||
.iter()
|
||||
.filter(|s| s.kind == SLOT_PASSWORD)
|
||||
.find_map(|s| PasswordSlot::parse(&s.payload).ok())
|
||||
.map(|s| s.kdf)
|
||||
self.slots.iter().find_map(|s| match s.kind {
|
||||
SLOT_PASSWORD => PasswordSlot::parse(&s.payload).ok().map(|p| p.kdf),
|
||||
SLOT_FACTOR => FactorSlot::parse(&s.payload).ok().and_then(|f| f.kdf),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn items(&self) -> &[Item] {
|
||||
@@ -246,4 +771,33 @@ impl Vault {
|
||||
let i = self.items.iter().position(|it| it.id == id)?;
|
||||
Some(self.items.remove(i))
|
||||
}
|
||||
|
||||
// ---- the Domi identity (docs/IDENTITY.md); created with identity::Enrollment ----
|
||||
|
||||
/// The root public key, if this vault has a Domi identity.
|
||||
pub fn domi_root_public(&self) -> Option<[u8; 32]> {
|
||||
self.identity.as_ref().map(|r| r.public)
|
||||
}
|
||||
|
||||
/// When the identity was created (Unix milliseconds).
|
||||
pub fn domi_created(&self) -> Option<i64> {
|
||||
self.identity.as_ref().map(|r| r.created)
|
||||
}
|
||||
|
||||
/// Ed25519 with the root over `"tessera cert v1 | ||||