Compare commits

...

28 Commits

Author SHA1 Message Date
mnovak 92ab8a0d63 [vault] Identity: restore from the 24 words, revocation signing for revoked keys only, the backup secret (docs/IDENTITY.md; v0.10.0) 2026-11-04 09:21:11 +01:00
mnovak bf661a7338 [repo] Merge: feature/signing (signing keys for Artifex: custos-sign, the signing body member, the audit log; v0.9.0, PR #11) 2026-11-04 00:45:11 +01:00
mnovak 510d5eecd1 [repo] Undo cargo fmt churn in files this branch does not change; CLAUDE.md: the trap 2026-11-04 00:27:37 +01:00
mnovak 06410ab3be [vault] Signing: the signing body member (release and test key sets, scope, sign-only API, append-only audit log); custos-sign draws from SysRng; the wasm build links getrandom 0.2 to the browser CSPRNG 2026-11-04 00:26:11 +01:00
mnovak cd2963392d [vault] Signing: mandatory tests for scope, refusals and the audit log through a reopen 2026-11-04 00:26:11 +01:00
mnovak 59fdfa26ef [sign] custos-sign: minisign (prehashed), SHA256SUMS, Authenticode digests, the household CA; tools/signing/interop.ps1 2026-11-04 00:15:33 +01:00
mnovak 6c6ffd33c0 [sign] Tests: known answers from the real minisign 0.12 and openssl, the household CA, canonical manifests 2026-11-04 00:15:33 +01:00
mnovak 2a146f342d [vault] Signing: docs/SIGNING.md (keys, signature kinds, audit log) and the FORMAT.md member, before the code 2026-11-04 00:09:05 +01:00
mnovak 38c458d21b [repo] Merge: feature/kdbx (KeePass import and export: custos-kdbx, KDBX 3.1/4 read, KDBX 4 write; v0.8.0, PR #10) 2026-11-03 23:11:50 +01:00
mnovak 2c333390c5 [repo] Git: shell scripts keep LF line endings 2026-11-03 20:59:44 +01:00
mnovak c011463fe5 [kdbx] custos-kdbx: KDBX 3.1/4 reader, KDBX 4 writer, item mapping, KeePassXC test vectors and interop check; v0.8.0 2026-11-03 20:59:40 +01:00
mnovak 12fd17245b [vault] Items: optional folder and attachments (SecretBytes), for KeePass groups and files 2026-11-03 20:59:39 +01:00
mnovak 05ac32dfc3 [kdbx] Docs: KeePass import (KDBX 3.1, 4) and export (KDBX 4), the item mapping, limits, what does not survive 2026-11-03 20:59:39 +01:00
mnovak 73d9de2304 [repo] Merge: feature/domi-identity (the Domi identity's root key in the vault, domi_pair, PR #9) 2026-11-03 19:04:24 +01:00
mnovak 6c696ba3a6 [wasm] Domi pairing: seal a phone's device key and label to the waiting PC; v0.7.0 2026-11-03 18:54:09 +01:00
mnovak 1c4bf4b373 [vault] Identity: the Domi root key in the vault, mnemonic typestate, signs only certs 2026-11-03 18:52:10 +01:00
mnovak 680b66cff7 [vault] Identity: docs/IDENTITY.md and the mandatory tests, before the code 2026-11-03 18:52:01 +01:00
mnovak 6e4da02351 [repo] Merge: feature/web-factors (two factors in the browser, phone pairing, factors apart, PR #8) 2026-11-03 15:28:30 +01:00
mnovak e365f21d54 [wasm] Two factors in the browser: open_with (sealed answers, passkey PRF), phone pairing and approvals; factors added apart never pair; sender code; v0.6.0 2026-11-03 12:07:59 +01:00
mnovak df7c149b25 [repo] Merge: feature/seal-import (sealed boxes, key import, factor ids, PR #7) 2026-11-03 11:56:56 +01:00
mnovak 7a7a628fa5 [seal] Sealed boxes and key import: custos-seal (X25519 + XChaCha20-Poly1305, match code, at-rest sealing), custos_keys::import, Vault::factor_ids; v0.5.0 2026-11-02 18:05:00 +01:00
mnovak 7893dd199c [repo] Merge: feature/two-factors (format v2, machine store, key pairs and API keys, PR #6) 2026-11-02 16:24:43 +01:00
mnovak 3f3cd26590 [keys] Key pairs and API keys: custos-keys (Ed25519, ECDSA P-256, RSA), secret_key, api_key; threat model; v0.4.0 2026-11-02 15:49:07 +01:00
mnovak 12783c9b92 [docs] Keys: secret keys, API keys, key pairs; tests first 2026-11-02 15:46:44 +01:00
mnovak 02c6795f53 [vault] Format v2: factor, pair and single slots; open_with any two factors; upgrade from v1; key-pair item type 2026-11-02 15:45:55 +01:00
mnovak df6565941e [vault] Tests: any two factors, never one; factors added and removed alone; v1 upgrade; tamper; machine store 2026-11-02 15:45:54 +01:00
mnovak 4daffdff73 [docs] Factors: format version 2, any two of password, device, TOTP, approval, passkey; machine store 2026-11-02 15:39:47 +01:00
mnovak e3128b35aa [repo] Merge: feature/share-wasm (share links, browser build, PR #5) 2026-10-31 18:31:49 +01:00
68 changed files with 9614 additions and 122 deletions
+2
View File
@@ -1,2 +1,4 @@
# Keep the EFF list byte-for-byte as published (its sha256 is in SOURCES.md).
crates/custos-gen/wordlists/eff_large_wordlist.txt -text
*.sh text eol=lf
crates/custos-sign/tests/fixtures/** -text
+18 -4
View File
@@ -7,14 +7,22 @@ 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)
crates/custos-kdbx KeePass import (KDBX 3.1, 4) and export (KDBX 4); tools/kdbx/interop.sh checks it with keepassxc-cli
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
docs/KDBX.md KeePass files: reading, writing, limits, the item mapping and what does not survive
```
## Commands
@@ -33,11 +41,17 @@ 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; for KeePass files `aes`, `cbc`, `chacha20`, `salsa20`, `hmac`,
`sha2`). 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`
first, then a test, then the code.
- Branch → PR on Gitea (token in `$GITEA_TOKEN`, never echoed) → self-review in the PR body → merge `--no-ff`
→ push → `git rev-parse HEAD origin/main` → tag `vX.Y.Z` (the private app pins tags).
## Known traps
- `cargo fmt --all` reformats files that are not rustfmt-clean on `main` (custos-keys, custos-seal, custos-wasm and
some tests): run `rustfmt --edition 2024 <file>` on the files you changed, so a PR carries no unrelated churn.
Generated
+946 -44
View File
File diff suppressed because it is too large Load Diff
+7 -1
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*"]
[workspace.package]
version = "0.3.0"
version = "0.10.0"
edition = "2024"
license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
@@ -23,3 +23,9 @@ sha2 = "0.11"
hkdf = "0.13"
data-encoding = "2"
percent-encoding = "2"
# RSA-3072 key generation (custos-sign) takes minutes unoptimised; these keep `cargo test` usable.
[profile.dev.package.num-bigint-dig]
opt-level = 3
[profile.dev.package.rsa]
opt-level = 3
+1
View File
@@ -11,6 +11,7 @@ password and secret manager: everything that touches plaintext or keys.
| `custos-qr` | QR payloads: Wi-Fi join codes (escaped), plain secrets |
| `custos-share` | Private share links: encrypted in the sender's app, key in the link's `#fragment`, optional password ([`docs/SHARE.md`](docs/SHARE.md)) |
| `custos-wasm` | The same code compiled to WebAssembly for the web vault and the share page (no wasm-bindgen; `js/custos.mjs` is the whole JS side) |
| `custos-kdbx` | KeePass import (KDBX 3.1 and 4) and export (KDBX 4), checked against KeePassXC ([`docs/KDBX.md`](docs/KDBX.md)) |
Read [`docs/FORMAT.md`](docs/FORMAT.md) for the file format and [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md)
for what it does and does not protect. Report vulnerabilities as described in [`SECURITY.md`](SECURITY.md).
+1
View File
@@ -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"
+80
View File
@@ -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
}
}
+50
View File
@@ -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}");
}
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "custos-kdbx"
description = "KeePass KDBX 4 import and export for Custos: the file format and the item mapping"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-vault = { path = "../custos-vault" }
aes = "0.9"
cbc = { version = "0.2", features = ["alloc", "block-padding"] }
chacha20 = "0.10"
salsa20 = "0.11"
argon2.workspace = true
hmac.workspace = true
sha2.workspace = true
zeroize.workspace = true
rand.workspace = true
thiserror.workspace = true
data-encoding.workspace = true
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
roxmltree = { version = "0.21", default-features = false, features = ["std"] }
[dev-dependencies]
serde_json.workspace = true
+41
View File
@@ -0,0 +1,41 @@
//! A dev tool for the KeePassXC interop check (tools/kdbx/interop.sh). The password comes from
//! `KDBX_PASSWORD`, never from the command line.
//!
//! ```text
//! kdbx_tool new OUT [fast] an empty KDBX 4 database (fast: Argon2id 1 MiB, 2 passes)
//! kdbx_tool roundtrip IN OUT IN → Custos items → OUT, as the app's import and export do
//! kdbx_tool items IN the Custos items IN maps to, as JSON (test databases only: it prints secrets)
//! ```
use custos_kdbx::{Database, Kdf, Key, SecretString, WriteOptions, from_items, read, to_items, write};
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let password = SecretString::new(std::env::var("KDBX_PASSWORD").expect("set KDBX_PASSWORD"));
let key = Key { password: Some(&password), key_file: None };
let open = |path: &str| read(&std::fs::read(path).expect("read"), &key).unwrap_or_else(|e| panic!("{path}: {e}"));
match args.iter().map(String::as_str).collect::<Vec<_>>()[..] {
["new", out, ref rest @ ..] => {
let mut opts = WriteOptions::default();
if rest == ["fast"] {
opts.kdf = Kdf::Argon2id { m_kib: 1024, t: 2, p: 1 };
}
let db = Database { name: "Interop".into(), ..Default::default() };
std::fs::write(out, write(&db, &key, opts).expect("write")).expect("write file");
}
["roundtrip", input, out] => {
let db = open(input);
let items = to_items(&db);
let back = from_items(&items, &db.name);
std::fs::write(out, write(&back, &key, WriteOptions::default()).expect("write")).expect("write file");
eprintln!("{} items", items.len());
}
["items", input] => {
println!("{}", serde_json::to_string_pretty(&to_items(&open(input))).expect("json"));
}
_ => {
eprintln!("usage: kdbx_tool new OUT [fast] | roundtrip IN OUT | items IN");
std::process::exit(2);
}
}
}
+220
View File
@@ -0,0 +1,220 @@
//! The only module that calls the cryptographic crates: the composite key, key files, the KDFs, the
//! outer ciphers, the HMAC block keys and the inner stream (docs/KDBX.md, "Reading").
use crate::{Error, Key};
use aes::Aes256;
use aes::cipher::{BlockCipherEncrypt, BlockModeDecrypt, BlockModeEncrypt, KeyInit, KeyIvInit, StreamCipher};
use cbc::cipher::block_padding::Pkcs7;
use chacha20::ChaCha20;
use hmac::{Hmac, Mac};
use rand::Rng;
use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use sha2::{Digest, Sha256, Sha512};
use zeroize::Zeroizing;
pub(crate) type K32 = Zeroizing<[u8; 32]>;
pub(crate) type K64 = Zeroizing<[u8; 64]>;
pub(crate) fn fill_random(buf: &mut [u8]) {
UnwrapErr(SysRng).fill_bytes(buf);
}
pub(crate) fn sha256(parts: &[&[u8]]) -> K32 {
let mut h = Sha256::new();
for p in parts {
h.update(p);
}
Zeroizing::new(h.finalize().into())
}
pub(crate) fn sha512(parts: &[&[u8]]) -> K64 {
let mut h = Sha512::new();
for p in parts {
h.update(p);
}
Zeroizing::new(h.finalize().into())
}
/// SHA-256 over each key part's 32-byte form, concatenated (KeePass's composite key).
pub(crate) fn composite(key: &Key) -> Result<K32, Error> {
let mut parts: Vec<K32> = Vec::new();
if let Some(p) = key.password.filter(|p| !p.is_empty()) {
parts.push(sha256(&[p.expose().as_bytes()]));
}
if let Some(f) = key.key_file {
parts.push(key_file(f)?);
}
if parts.is_empty() {
return Err(Error::NoKey);
}
let refs: Vec<&[u8]> = parts.iter().map(|p| p.as_slice()).collect();
Ok(sha256(&refs))
}
/// A key file's 32-byte key: KeePass XML 2.0 or 1.0, 32 raw bytes, 64 hex digits, or SHA-256 of the file.
pub(crate) fn key_file(f: &[u8]) -> Result<K32, Error> {
let head = &f[..f.len().min(256)];
if head.windows(8).any(|w| w == b"<KeyFile") {
return xml_key_file(f);
}
if f.len() == 32 {
let mut k = Zeroizing::new([0u8; 32]);
k.copy_from_slice(f);
return Ok(k);
}
if f.len() == 64
&& f.iter().all(u8::is_ascii_hexdigit)
&& let Ok(b) = data_encoding::HEXLOWER_PERMISSIVE.decode(f)
{
let mut k = Zeroizing::new([0u8; 32]);
k.copy_from_slice(&b);
return Ok(k);
}
Ok(sha256(&[f]))
}
fn xml_key_file(f: &[u8]) -> Result<K32, Error> {
const BAD: Error = Error::Malformed("key file");
let text = std::str::from_utf8(f).map_err(|_| BAD)?;
let doc = roxmltree::Document::parse_with_options(
text,
roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: 1000, ..Default::default() },
)
.map_err(|_| BAD)?;
let find = |name: &str| doc.descendants().find(|n| n.has_tag_name(name));
let version = find("Version").and_then(|n| n.text()).unwrap_or("").trim().to_owned();
let data = find("Data").ok_or(BAD)?;
let body: Zeroizing<String> = Zeroizing::new(data.text().unwrap_or("").split_whitespace().collect());
let bytes = Zeroizing::new(if version.starts_with("2.") {
let b = data_encoding::HEXUPPER_PERMISSIVE.decode(body.as_bytes()).map_err(|_| BAD)?;
if let Some(hash) = data.attribute("Hash") {
let want = data_encoding::HEXUPPER_PERMISSIVE.decode(hash.trim().as_bytes()).map_err(|_| BAD)?;
if sha256(&[&b])[..4] != want[..] {
return Err(Error::Malformed("key file checksum"));
}
}
b
} else if version.starts_with("1.") {
data_encoding::BASE64.decode(body.as_bytes()).map_err(|_| BAD)?
} else {
return Err(Error::Malformed("key file version"));
});
let k: [u8; 32] = bytes.as_slice().try_into().map_err(|_| BAD)?;
Ok(Zeroizing::new(k))
}
/// Argon2d or Argon2id. The caller has checked the parameters against the limits.
pub(crate) fn argon2(composite: &[u8], id: bool, salt: &[u8], m_kib: u32, t: u32, p: u32) -> Result<K32, Error> {
use argon2::{Algorithm, Argon2, Params, Version};
let params = Params::new(m_kib, t, p, Some(32)).map_err(|_| Error::UnsupportedKdf)?;
let alg = if id { Algorithm::Argon2id } else { Algorithm::Argon2d };
let mut out = Zeroizing::new([0u8; 32]);
Argon2::new(alg, Version::V0x13, params)
.hash_password_into(composite, salt, out.as_mut())
.map_err(|_| Error::UnsupportedKdf)?;
Ok(out)
}
/// AES-KDF: `rounds` AES-256-ECB encryptions of both halves keyed with `seed`, then SHA-256.
pub(crate) fn aes_kdf(composite: &[u8], seed: &[u8; 32], rounds: u64) -> K32 {
let cipher = Aes256::new(seed.into());
let mut blocks = Zeroizing::new([[0u8; 16]; 2]);
blocks[0].copy_from_slice(&composite[..16]);
blocks[1].copy_from_slice(&composite[16..32]);
for _ in 0..rounds {
for b in blocks.iter_mut() {
cipher.encrypt_block(b.into());
}
}
sha256(&[&blocks[0], &blocks[1]])
}
pub(crate) struct Keys {
pub cipher: K32,
hmac_base: K64,
}
impl Keys {
pub(crate) fn new(master_seed: &[u8], transformed: &[u8]) -> Self {
Keys { cipher: sha256(&[master_seed, transformed]), hmac_base: sha512(&[master_seed, transformed, &[1]]) }
}
fn block_key(&self, index: u64) -> K64 {
sha512(&[&index.to_le_bytes(), self.hmac_base.as_slice()])
}
pub(crate) fn header_hmac(&self, header: &[u8]) -> [u8; 32] {
mac(self.block_key(u64::MAX).as_slice(), &[header])
}
pub(crate) fn block_hmac(&self, index: u64, data: &[u8]) -> [u8; 32] {
mac(self.block_key(index).as_slice(), &[&index.to_le_bytes(), &(data.len() as u32).to_le_bytes(), data])
}
}
fn mac(key: &[u8], parts: &[&[u8]]) -> [u8; 32] {
let mut m = <Hmac<Sha256>>::new_from_slice(key).expect("HMAC takes any key length");
for p in parts {
m.update(p);
}
m.finalize().into_bytes().into()
}
/// Constant-time comparison of two MACs.
pub(crate) fn same(a: &[u8; 32], b: &[u8]) -> bool {
b.len() == 32 && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
pub(crate) fn chacha20(key: &[u8; 32], nonce: &[u8; 12], data: &mut [u8]) {
ChaCha20::new(key.into(), nonce.into()).apply_keystream(data);
}
pub(crate) fn aes_cbc_decrypt(key: &[u8; 32], iv: &[u8; 16], data: &mut Vec<u8>) -> Result<(), Error> {
let n = cbc::Decryptor::<Aes256>::new(key.into(), iv.into())
.decrypt_padded::<Pkcs7>(data)
.map_err(|_| Error::Corrupted)?
.len();
data.truncate(n);
Ok(())
}
pub(crate) fn aes_cbc_encrypt(key: &[u8; 32], iv: &[u8; 16], data: &mut Vec<u8>) {
let len = data.len();
data.resize(len + 16 - len % 16, 0);
let n = cbc::Encryptor::<Aes256>::new(key.into(), iv.into())
.encrypt_padded::<Pkcs7>(data, len)
.expect("room for the padding")
.len();
data.truncate(n);
}
/// The inner stream that hides protected values.
pub(crate) enum InnerStream {
/// KDBX 4: ChaCha20 keyed from SHA-512 of the stream key.
ChaCha20(ChaCha20),
/// KDBX 3.1: Salsa20 keyed with SHA-256 of the stream key and KeePass's fixed nonce.
Salsa20(salsa20::Salsa20),
}
impl InnerStream {
pub(crate) fn chacha20(stream_key: &[u8]) -> Self {
let h = sha512(&[stream_key]);
let key = Zeroizing::new(<[u8; 32]>::try_from(&h[..32]).expect("32 bytes"));
let nonce: [u8; 12] = h[32..44].try_into().expect("12 bytes");
InnerStream::ChaCha20(ChaCha20::new((&*key).into(), (&nonce).into()))
}
pub(crate) fn salsa20(stream_key: &[u8]) -> Self {
const NONCE: [u8; 8] = [0xE8, 0x30, 0x09, 0x4B, 0x97, 0x20, 0x5D, 0x2A];
let key = sha256(&[stream_key]);
InnerStream::Salsa20(salsa20::Salsa20::new((&*key).into(), (&NONCE).into()))
}
pub(crate) fn apply(&mut self, data: &mut [u8]) {
match self {
InnerStream::ChaCha20(c) => c.apply_keystream(data),
InnerStream::Salsa20(c) => c.apply_keystream(data),
}
}
}
+568
View File
@@ -0,0 +1,568 @@
//! The outer KDBX 4 file: header, KDF parameters, HMAC blocks, payload cipher, gzip, inner header
//! (docs/KDBX.md, "Reading" and "Writing").
use crate::crypto::{self, InnerStream, K32, Keys};
use crate::{Database, Error, Key, xml};
use custos_vault::SecretBytes;
use std::io::{Read, Write};
use zeroize::Zeroizing;
const SIG1: [u8; 4] = [0x03, 0xD9, 0xA2, 0x9A];
const SIG2: [u8; 4] = [0x67, 0xFB, 0x4B, 0xB5];
const CIPHER_AES256: [u8; 16] = uuid(0x31c1f2e6_bf71_4350_be58_05216afc5aff);
const CIPHER_CHACHA20: [u8; 16] = uuid(0xd6038a2b_8b6f_4cb5_a524_339a31dbb59a);
const KDF_AES: [u8; 16] = uuid(0xc9d9f39a_628a_4460_bf74_0d08c18a4fea);
const KDF_ARGON2D: [u8; 16] = uuid(0xef636ddf_8c29_444b_91f7_a9a403e30a0c);
const KDF_ARGON2ID: [u8; 16] = uuid(0x9e298b19_56db_4773_b23d_fc3ec6f0a1e6);
const fn uuid(v: u128) -> [u8; 16] {
v.to_be_bytes()
}
const MAX_FILE: usize = 512 << 20;
const MAX_FIELD: usize = 64 << 10;
const MAX_PAYLOAD: u64 = 512 << 20;
const MAX_ARGON2_BYTES: u64 = 2 << 30;
const MAX_AES_ROUNDS: u64 = 1 << 30;
const BLOCK: usize = 1 << 20;
const STREAM_CHACHA20: u32 = 3;
/// The outer cipher an export uses.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cipher {
Aes256,
ChaCha20,
}
/// The key derivation an export uses. `m_kib` is Argon2's memory in KiB.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kdf {
Argon2d { m_kib: u32, t: u32, p: u32 },
Argon2id { m_kib: u32, t: u32, p: u32 },
Aes { rounds: u64 },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WriteOptions {
pub cipher: Cipher,
pub kdf: Kdf,
}
impl Default for WriteOptions {
/// ChaCha20 and Argon2id with the vault's own defaults (64 MiB, 20 passes, 1 lane).
fn default() -> Self {
WriteOptions { cipher: Cipher::ChaCha20, kdf: Kdf::Argon2id { m_kib: 65_536, t: 20, p: 1 } }
}
}
struct Cur<'a> {
b: &'a [u8],
pos: usize,
}
impl<'a> Cur<'a> {
fn take(&mut self, n: usize, e: Error) -> Result<&'a [u8], Error> {
let end = self.pos.checked_add(n).filter(|&end| end <= self.b.len()).ok_or(e)?;
let s = &self.b[self.pos..end];
self.pos = end;
Ok(s)
}
fn u8(&mut self, e: Error) -> Result<u8, Error> {
Ok(self.take(1, e)?[0])
}
fn u32(&mut self, e: Error) -> Result<u32, Error> {
Ok(u32::from_le_bytes(self.take(4, e)?.try_into().expect("4 bytes")))
}
}
/// Opens a KDBX 4 file.
pub fn read(bytes: &[u8], key: &Key) -> Result<Database, Error> {
if bytes.len() > MAX_FILE {
return Err(Error::TooLarge);
}
if bytes.len() < 12 || bytes[..4] != SIG1 || bytes[4..8] != SIG2 {
return Err(Error::NotKdbx);
}
let minor = u16::from_le_bytes([bytes[8], bytes[9]]);
let major = u16::from_le_bytes([bytes[10], bytes[11]]);
match major {
4 => {}
3 => return read3(bytes, key),
_ => return Err(Error::UnsupportedVersion(major, minor)),
}
// The outer header.
let mut c = Cur { b: bytes, pos: 12 };
let (mut cipher, mut compression, mut seed, mut iv, mut kdf) = (None, None, None, None, None);
loop {
let id = c.u8(Error::Corrupted)?;
let len = c.u32(Error::Corrupted)? as usize;
if len > MAX_FIELD {
return Err(Error::Malformed("header field too long"));
}
let data = c.take(len, Error::Corrupted)?;
match id {
0 => break,
2 => cipher = Some(data),
3 => compression = Some(u32::from_le_bytes(data.try_into().map_err(|_| Error::Malformed("compression"))?)),
4 => seed = Some(data),
7 => iv = Some(data),
11 => kdf = Some(data),
_ => {} // public custom data, and KDBX 3 fields that mean nothing here
}
}
let header = &bytes[..c.pos];
let hash = c.take(32, Error::Corrupted)?;
let hmac = c.take(32, Error::Corrupted)?;
if crypto::sha256(&[header])[..] != hash[..] {
return Err(Error::Corrupted);
}
let cipher = match cipher.ok_or(Error::Malformed("no cipher"))? {
c if c == CIPHER_AES256 => Cipher::Aes256,
c if c == CIPHER_CHACHA20 => Cipher::ChaCha20,
_ => return Err(Error::UnsupportedCipher),
};
let seed = seed.filter(|s| s.len() == 32).ok_or(Error::Malformed("master seed"))?;
let (kdf, salt) = parse_kdf(kdf.ok_or(Error::Malformed("no KDF parameters"))?)?;
// The key, checked against the header before anything is decrypted.
let transformed = transform(&crypto::composite(key)?, kdf, &salt)?;
let keys = Keys::new(seed, transformed.as_slice());
if !crypto::same(&keys.header_hmac(header), hmac) {
return Err(Error::WrongKey);
}
// HMAC blocks.
let mut payload = Vec::new();
for index in 0u64.. {
let mac = c.take(32, Error::Corrupted)?;
let len = c.u32(Error::Corrupted)? as usize;
let data = c.take(len, Error::Corrupted)?;
if !crypto::same(&keys.block_hmac(index, data), mac) {
return Err(Error::Corrupted);
}
if len == 0 {
break;
}
payload.extend_from_slice(data);
}
let mut plain = Zeroizing::new(payload);
let iv = iv.ok_or(Error::Malformed("no IV"))?;
match cipher {
Cipher::Aes256 => {
let iv: &[u8; 16] = iv.try_into().map_err(|_| Error::Malformed("IV"))?;
crypto::aes_cbc_decrypt(&keys.cipher, iv, &mut plain)?;
}
Cipher::ChaCha20 => {
let iv: &[u8; 12] = iv.try_into().map_err(|_| Error::Malformed("IV"))?;
crypto::chacha20(&keys.cipher, iv, &mut plain);
}
}
let inner = match compression {
Some(0) => plain,
Some(1) => gunzip(&plain)?,
_ => return Err(Error::Malformed("compression")),
};
// The inner header.
let mut c = Cur { b: &inner, pos: 0 };
let (mut stream_id, mut stream_key) = (None, None);
let mut pool = Vec::new();
loop {
let id = c.u8(Error::Malformed("inner header"))?;
let len = c.u32(Error::Malformed("inner header"))? as usize;
let data = c.take(len, Error::Malformed("inner header"))?;
match id {
0 => break,
1 => stream_id = Some(u32::from_le_bytes(data.try_into().map_err(|_| Error::Malformed("inner stream"))?)),
2 => stream_key = Some(data),
3 => {
let (_flags, content) = data.split_first().ok_or(Error::Malformed("attachment"))?;
pool.push(SecretBytes::from(content));
}
_ => {}
}
}
let stream_key = stream_key.filter(|k| !k.is_empty()).ok_or(Error::Malformed("inner stream"))?;
let mut stream = match stream_id {
Some(STREAM_CHACHA20) => InnerStream::chacha20(stream_key),
_ => return Err(Error::UnsupportedStream),
};
xml::parse(&inner[c.pos..], &mut stream, &pool)
}
/// KDBX 3.1: 16-bit header field lengths, AES-KDF from the header, no header HMAC (the first 32 bytes of the
/// payload must equal `StreamStartBytes` instead), SHA-256 hashed blocks, a Salsa20 inner stream, and the
/// attachments in `Meta/Binaries` (docs/KDBX.md, "KDBX 3.1").
fn read3(bytes: &[u8], key: &Key) -> Result<Database, Error> {
let mut c = Cur { b: bytes, pos: 12 };
let (mut cipher, mut compression, mut seed, mut iv) = (None, None, None, None);
let (mut tseed, mut rounds, mut stream_key, mut start, mut stream_id) = (None, None, None, None, None);
let u32_ = |d: &[u8]| d.try_into().map(u32::from_le_bytes).map_err(|_| Error::Malformed("header field"));
loop {
let id = c.u8(Error::Corrupted)?;
let len = u16::from_le_bytes(c.take(2, Error::Corrupted)?.try_into().expect("2 bytes")) as usize;
let data = c.take(len, Error::Corrupted)?;
match id {
0 => break,
2 => cipher = Some(data),
3 => compression = Some(u32_(data)?),
4 => seed = Some(data),
5 => tseed = Some(data),
6 => rounds = Some(u64::from_le_bytes(data.try_into().map_err(|_| Error::Malformed("rounds"))?)),
7 => iv = Some(data),
8 => stream_key = Some(data),
9 => start = Some(data),
10 => stream_id = Some(u32_(data)?),
_ => {}
}
}
let cipher = match cipher.ok_or(Error::Malformed("no cipher"))? {
c if c == CIPHER_AES256 => Cipher::Aes256,
c if c == CIPHER_CHACHA20 => Cipher::ChaCha20,
_ => return Err(Error::UnsupportedCipher),
};
let seed = seed.filter(|s| s.len() == 32).ok_or(Error::Malformed("master seed"))?;
let tseed: &[u8; 32] = tseed.and_then(|s| s.try_into().ok()).ok_or(Error::UnsupportedKdf)?;
let kdf = Kdf::Aes { rounds: rounds.ok_or(Error::UnsupportedKdf)? };
check_kdf(kdf)?;
let start: &[u8; 32] = start.and_then(|s| s.try_into().ok()).ok_or(Error::Malformed("stream start bytes"))?;
let stream_key = stream_key.filter(|k| !k.is_empty()).ok_or(Error::Malformed("inner stream"))?;
let mut stream = match stream_id {
Some(2) => InnerStream::salsa20(stream_key),
Some(STREAM_CHACHA20) => InnerStream::chacha20(stream_key),
_ => return Err(Error::UnsupportedStream),
};
let transformed = transform(&crypto::composite(key)?, kdf, tseed)?;
let keys = Keys::new(seed, transformed.as_slice());
let mut plain = Zeroizing::new(bytes[c.pos..].to_vec());
let iv = iv.ok_or(Error::Malformed("no IV"))?;
match cipher {
Cipher::Aes256 => {
let iv: &[u8; 16] = iv.try_into().map_err(|_| Error::Malformed("IV"))?;
// A wrong key gives garbage, usually with broken padding: that is a wrong key, not damage.
crypto::aes_cbc_decrypt(&keys.cipher, iv, &mut plain).map_err(|_| Error::WrongKey)?;
}
Cipher::ChaCha20 => {
let iv: &[u8; 12] = iv.try_into().map_err(|_| Error::Malformed("IV"))?;
crypto::chacha20(&keys.cipher, iv, &mut plain);
}
}
if plain.len() < 32 || !crypto::same(start, &plain[..32]) {
return Err(Error::WrongKey);
}
// Hashed blocks: index (u32), SHA-256 (32), length (u32), data; a zero length ends them.
let mut c = Cur { b: &plain, pos: 32 };
let mut payload = Zeroizing::new(Vec::new());
for index in 0u32.. {
if c.u32(Error::Corrupted)? != index {
return Err(Error::Corrupted);
}
let hash = c.take(32, Error::Corrupted)?;
let len = c.u32(Error::Corrupted)? as usize;
if len == 0 {
if hash.iter().any(|&b| b != 0) {
return Err(Error::Corrupted);
}
break;
}
let data = c.take(len, Error::Corrupted)?;
if crypto::sha256(&[data])[..] != hash[..] {
return Err(Error::Corrupted);
}
payload.extend_from_slice(data);
}
let xml_bytes = match compression {
Some(0) => payload,
Some(1) => gunzip(&payload)?,
_ => return Err(Error::Malformed("compression")),
};
xml::parse(&xml_bytes, &mut stream, &[])
}
/// Writes a KDBX 4.0 file (docs/KDBX.md, "Writing").
pub fn write(db: &Database, key: &Key, opts: WriteOptions) -> Result<Vec<u8>, Error> {
let composite = crypto::composite(key)?;
let mut seed = [0u8; 32];
let mut salt = [0u8; 32];
let mut stream_key = Zeroizing::new([0u8; 64]);
crypto::fill_random(&mut seed);
crypto::fill_random(&mut salt);
crypto::fill_random(stream_key.as_mut());
let mut iv = vec![0u8; if opts.cipher == Cipher::Aes256 { 16 } else { 12 }];
crypto::fill_random(&mut iv);
check_kdf(opts.kdf)?;
let transformed = transform(&composite, opts.kdf, &salt)?;
let keys = Keys::new(&seed, transformed.as_slice());
let mut out = Vec::new();
out.extend_from_slice(&SIG1);
out.extend_from_slice(&SIG2);
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&4u16.to_le_bytes());
let cipher_id = if opts.cipher == Cipher::Aes256 { CIPHER_AES256 } else { CIPHER_CHACHA20 };
field(&mut out, 2, &cipher_id);
field(&mut out, 3, &1u32.to_le_bytes());
field(&mut out, 4, &seed);
field(&mut out, 7, &iv);
field(&mut out, 11, &kdf_dict(opts.kdf, &salt));
field(&mut out, 0, b"\r\n\r\n");
let hash = crypto::sha256(&[&out]);
let hmac = keys.header_hmac(&out);
out.extend_from_slice(hash.as_slice());
out.extend_from_slice(&hmac);
let mut stream = InnerStream::chacha20(stream_key.as_slice());
let mut pool: Vec<&SecretBytes> = Vec::new();
let body = xml::write(db, &mut stream, &mut pool);
let mut inner = Zeroizing::new(Vec::with_capacity(body.len() + 128));
field(&mut inner, 1, &STREAM_CHACHA20.to_le_bytes());
field(&mut inner, 2, stream_key.as_slice());
for a in pool {
let mut b = Zeroizing::new(Vec::with_capacity(a.len() + 1));
b.push(0);
b.extend_from_slice(a.expose());
field(&mut inner, 3, &b);
}
field(&mut inner, 0, &[]);
inner.extend_from_slice(body.as_bytes());
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
gz.write_all(&inner).expect("writing to memory");
let mut payload = gz.finish().expect("writing to memory");
match opts.cipher {
Cipher::Aes256 => crypto::aes_cbc_encrypt(&keys.cipher, iv.as_slice().try_into().expect("16"), &mut payload),
Cipher::ChaCha20 => crypto::chacha20(&keys.cipher, iv.as_slice().try_into().expect("12"), &mut payload),
}
let mut index = 0u64;
for chunk in payload.chunks(BLOCK).chain(std::iter::once(&[][..])) {
out.extend_from_slice(&keys.block_hmac(index, chunk));
out.extend_from_slice(&(chunk.len() as u32).to_le_bytes());
out.extend_from_slice(chunk);
index += 1;
}
Ok(out)
}
fn field(out: &mut Vec<u8>, id: u8, data: &[u8]) {
out.push(id);
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
out.extend_from_slice(data);
}
pub(crate) fn gunzip(data: &[u8]) -> Result<Zeroizing<Vec<u8>>, Error> {
let mut out = Zeroizing::new(Vec::new());
flate2::read::GzDecoder::new(data).take(MAX_PAYLOAD + 1).read_to_end(&mut out).map_err(|_| Error::Corrupted)?;
if out.len() as u64 > MAX_PAYLOAD {
return Err(Error::TooLarge);
}
Ok(out)
}
fn transform(composite: &K32, kdf: Kdf, salt: &[u8]) -> Result<K32, Error> {
match kdf {
Kdf::Argon2d { m_kib, t, p } => crypto::argon2(composite.as_slice(), false, salt, m_kib, t, p),
Kdf::Argon2id { m_kib, t, p } => crypto::argon2(composite.as_slice(), true, salt, m_kib, t, p),
Kdf::Aes { rounds } => {
let seed: &[u8; 32] = salt.try_into().map_err(|_| Error::UnsupportedKdf)?;
Ok(crypto::aes_kdf(composite.as_slice(), seed, rounds))
}
}
}
fn check_kdf(kdf: Kdf) -> Result<(), Error> {
let ok = match kdf {
Kdf::Argon2d { m_kib, t, p } | Kdf::Argon2id { m_kib, t, p } => {
(1..=64).contains(&p)
&& (1..=1000).contains(&t)
&& u64::from(m_kib) * 1024 <= MAX_ARGON2_BYTES
&& m_kib >= 8 * p
}
Kdf::Aes { rounds } => (1..=MAX_AES_ROUNDS).contains(&rounds),
};
if ok { Ok(()) } else { Err(Error::UnsupportedKdf) }
}
// VariantDictionary value types.
const VD_U32: u8 = 0x04;
const VD_U64: u8 = 0x05;
const VD_BYTES: u8 = 0x42;
/// The KDF and its salt (Argon2 `S`) or seed (AES-KDF `S`), checked against the limits.
fn parse_kdf(d: &[u8]) -> Result<(Kdf, Vec<u8>), Error> {
const BAD: Error = Error::Malformed("KDF parameters");
let mut c = Cur { b: d, pos: 0 };
let version = u16::from_le_bytes(c.take(2, BAD)?.try_into().expect("2 bytes"));
if version & 0xFF00 != 0x0100 {
return Err(BAD);
}
let mut map: Vec<(&[u8], u8, &[u8])> = Vec::new();
loop {
let kind = c.u8(BAD)?;
if kind == 0 {
break;
}
let klen = c.u32(BAD)? as usize;
let k = c.take(klen, BAD)?;
let vlen = c.u32(BAD)? as usize;
let v = c.take(vlen, BAD)?;
map.push((k, kind, v));
}
let get = |name: &str, kind: u8| map.iter().find(|(k, t, _)| *k == name.as_bytes() && *t == kind).map(|e| e.2);
let u32_ = |name| get(name, VD_U32).and_then(|v| v.try_into().ok()).map(u32::from_le_bytes);
let u64_ = |name| get(name, VD_U64).and_then(|v| v.try_into().ok()).map(u64::from_le_bytes);
let id = get("$UUID", VD_BYTES).ok_or(BAD)?;
let salt = get("S", VD_BYTES).ok_or(Error::UnsupportedKdf)?.to_vec();
let kdf = if id == KDF_AES {
if salt.len() != 32 {
return Err(Error::UnsupportedKdf);
}
Kdf::Aes { rounds: u64_("R").ok_or(Error::UnsupportedKdf)? }
} else if id == KDF_ARGON2D || id == KDF_ARGON2ID {
let m = u64_("M").ok_or(Error::UnsupportedKdf)?;
let t = u64_("I").ok_or(Error::UnsupportedKdf)?;
let p = u32_("P").ok_or(Error::UnsupportedKdf)?;
let extra = |n| get(n, VD_BYTES).is_some_and(|v| !v.is_empty());
if u32_("V") != Some(0x13) || extra("K") || extra("A") || !(8..=64).contains(&salt.len()) {
return Err(Error::UnsupportedKdf);
}
if m % 1024 != 0 || m > MAX_ARGON2_BYTES || t > 1000 {
return Err(Error::UnsupportedKdf);
}
let (m_kib, t) = ((m / 1024) as u32, t as u32);
if id == KDF_ARGON2D { Kdf::Argon2d { m_kib, t, p } } else { Kdf::Argon2id { m_kib, t, p } }
} else {
return Err(Error::UnsupportedKdf);
};
check_kdf(kdf)?;
Ok((kdf, salt))
}
fn kdf_dict(kdf: Kdf, salt: &[u8; 32]) -> Vec<u8> {
let mut d = 0x0100u16.to_le_bytes().to_vec();
let mut item = |kind: u8, k: &str, v: &[u8]| {
d.push(kind);
d.extend_from_slice(&(k.len() as u32).to_le_bytes());
d.extend_from_slice(k.as_bytes());
d.extend_from_slice(&(v.len() as u32).to_le_bytes());
d.extend_from_slice(v);
};
match kdf {
Kdf::Argon2d { m_kib, t, p } | Kdf::Argon2id { m_kib, t, p } => {
let id = if matches!(kdf, Kdf::Argon2d { .. }) { KDF_ARGON2D } else { KDF_ARGON2ID };
item(VD_BYTES, "$UUID", &id);
item(VD_BYTES, "S", salt);
item(VD_U32, "P", &p.to_le_bytes());
item(VD_U64, "M", &(u64::from(m_kib) * 1024).to_le_bytes());
item(VD_U64, "I", &u64::from(t).to_le_bytes());
item(VD_U32, "V", &0x13u32.to_le_bytes());
}
Kdf::Aes { rounds } => {
item(VD_BYTES, "$UUID", &KDF_AES);
item(VD_U64, "R", &rounds.to_le_bytes());
item(VD_BYTES, "S", salt);
}
}
d.push(0);
d
}
/// Test hooks: build files with chosen KDF parameters, inner streams or payloads, to check the reader refuses them.
#[doc(hidden)]
pub mod testing {
use super::*;
/// A valid file around `inner` (inner header + XML, before gzip) with the given KDF dictionary bytes,
/// keyed with `transformed` directly (no KDF runs).
pub fn build(kdf_dict_bytes: &[u8], transformed: &[u8; 32], inner: &[u8], gzip: bool) -> Vec<u8> {
let payload = if gzip {
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
gz.write_all(inner).unwrap();
gz.finish().unwrap()
} else {
inner.to_vec()
};
assemble(kdf_dict_bytes, transformed, payload, gzip)
}
/// The same around a payload that is already gzipped.
pub fn build_compressed(kdf_dict_bytes: &[u8], transformed: &[u8; 32], gz: &[u8]) -> Vec<u8> {
assemble(kdf_dict_bytes, transformed, gz.to_vec(), true)
}
fn assemble(kdf_dict_bytes: &[u8], transformed: &[u8; 32], mut payload: Vec<u8>, gzip: bool) -> Vec<u8> {
let seed = [7u8; 32];
let iv = [9u8; 12];
let keys = Keys::new(&seed, transformed);
let mut out = Vec::new();
out.extend_from_slice(&SIG1);
out.extend_from_slice(&SIG2);
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&4u16.to_le_bytes());
field(&mut out, 2, &CIPHER_CHACHA20);
field(&mut out, 3, &u32::from(gzip).to_le_bytes());
field(&mut out, 4, &seed);
field(&mut out, 7, &iv);
field(&mut out, 11, kdf_dict_bytes);
field(&mut out, 0, b"\r\n\r\n");
let hash = crypto::sha256(&[&out]);
let hmac = keys.header_hmac(&out);
out.extend_from_slice(hash.as_slice());
out.extend_from_slice(&hmac);
crypto::chacha20(&keys.cipher, &iv, &mut payload);
for (index, chunk) in payload.chunks(BLOCK).chain(std::iter::once(&[][..])).enumerate() {
out.extend_from_slice(&keys.block_hmac(index as u64, chunk));
out.extend_from_slice(&(chunk.len() as u32).to_le_bytes());
out.extend_from_slice(chunk);
}
out
}
/// A KDF dictionary for AES-KDF with `rounds` (and a fixed seed), or raw entries.
pub fn aes_dict(rounds: u64) -> Vec<u8> {
kdf_dict(Kdf::Aes { rounds }, &[3u8; 32])
}
/// An Argon2 dictionary with the given raw values (memory in bytes), unchecked.
pub fn argon2_dict(id: bool, m_bytes: u64, t: u64, p: u32, version: u32) -> Vec<u8> {
let mut d = 0x0100u16.to_le_bytes().to_vec();
let mut item = |kind: u8, k: &str, v: &[u8]| {
d.push(kind);
d.extend_from_slice(&(k.len() as u32).to_le_bytes());
d.extend_from_slice(k.as_bytes());
d.extend_from_slice(&(v.len() as u32).to_le_bytes());
d.extend_from_slice(v);
};
item(VD_BYTES, "$UUID", if id { &KDF_ARGON2ID } else { &KDF_ARGON2D });
item(VD_BYTES, "S", &[5u8; 32]);
item(VD_U32, "P", &p.to_le_bytes());
item(VD_U64, "M", &m_bytes.to_le_bytes());
item(VD_U64, "I", &t.to_le_bytes());
item(VD_U32, "V", &version.to_le_bytes());
d.push(0);
d
}
/// The transformed key AES-KDF gives for a password and `aes_dict(rounds)`.
pub fn aes_transformed(password: &str, rounds: u64) -> [u8; 32] {
let composite = crypto::sha256(&[crypto::sha256(&[password.as_bytes()]).as_slice()]);
*crypto::aes_kdf(composite.as_slice(), &[3u8; 32], rounds)
}
/// An inner header: stream id, a 64-byte stream key of 1s, then `xml`.
pub fn inner(stream_id: u32, xml: &[u8]) -> Vec<u8> {
let mut v = Vec::new();
field(&mut v, 1, &stream_id.to_le_bytes());
field(&mut v, 2, &[1u8; 64]);
field(&mut v, 0, &[]);
v.extend_from_slice(xml);
v
}
}
+121
View File
@@ -0,0 +1,121 @@
//! KeePass KDBX import (3.1 and 4) and export (4) (docs/KDBX.md).
//!
//! Two layers: [`read`] / [`write`] turn bytes and a [`Key`] into a [`Database`] and back;
//! [`to_items`] / [`from_items`] map KeePass entries to Custos items and back.
mod crypto;
mod format;
mod map;
mod time;
mod xml;
pub use custos_vault::{SecretBytes, SecretString};
#[doc(hidden)]
pub use format::testing;
pub use format::{Cipher, Kdf, WriteOptions, read, write};
pub use map::{from_items, to_items};
pub use time::{format_iso, parse_iso};
/// A whole KDBX database, as far as Custos keeps it (docs/KDBX.md, "What does not survive").
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Database {
/// `Meta/DatabaseName`.
pub name: String,
pub root: Group,
/// The recycle bin group, when the file has one switched on. Its entries are not imported.
pub recycle_bin: Option<[u8; 16]>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Group {
pub uuid: [u8; 16],
pub name: String,
pub groups: Vec<Group>,
pub entries: Vec<Entry>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Entry {
pub uuid: [u8; 16],
/// In file order. Keys are unique within an entry.
pub strings: Vec<StringField>,
pub attachments: Vec<custos_vault::Attachment>,
pub tags: Vec<String>,
pub times: Times,
pub autotype: AutoType,
/// Older versions of this entry, oldest first (KeePass order). Their own history is empty.
pub history: Vec<Entry>,
}
impl Entry {
/// The value of the string called `key`.
pub fn get(&self, key: &str) -> Option<&SecretString> {
self.strings.iter().find(|s| s.key == key).map(|s| &s.value)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct StringField {
pub key: String,
pub value: SecretString,
/// Written XORed with the inner stream (KeePass's "protect in memory").
pub protected: bool,
}
/// Unix seconds (UTC).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Times {
pub created: i64,
pub modified: i64,
/// `ExpiryTime` when `Expires` is true.
pub expires: Option<i64>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AutoType {
pub default_sequence: String,
/// The `Window` of each association, in order.
pub windows: Vec<String>,
}
/// What opens a KDBX file: a password, a key file, or both.
#[derive(Clone, Copy, Default)]
pub struct Key<'a> {
/// An empty password counts as no password (as in KeePassXC).
pub password: Option<&'a SecretString>,
/// The key file's whole content.
pub key_file: Option<&'a [u8]>,
}
impl std::fmt::Debug for Key<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Key")
.field("password", &self.password.is_some())
.field("key_file", &self.key_file.is_some())
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Error {
#[error("this is not a KeePass database")]
NotKdbx,
#[error("unsupported KDBX version {0}.{1}")]
UnsupportedVersion(u16, u16),
#[error("a password or a key file is needed")]
NoKey,
#[error("wrong password or key file")]
WrongKey,
#[error("the file is damaged")]
Corrupted,
#[error("unsupported cipher: only AES-256 and ChaCha20 are supported")]
UnsupportedCipher,
#[error("unsupported key derivation settings")]
UnsupportedKdf,
#[error("unsupported inner stream: only ChaCha20 and Salsa20 are supported")]
UnsupportedStream,
#[error("the file is too large")]
TooLarge,
#[error("malformed KDBX file: {0}")]
Malformed(&'static str),
}
+410
View File
@@ -0,0 +1,410 @@
//! KeePass entries ↔ Custos items (docs/KDBX.md, "Mapping").
use crate::{AutoType, Database, Entry, Group, StringField, Times, crypto, time};
use custos_vault::{Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, SecretString};
const TYPE_KEY: &str = "custos-type";
const URL_EXTRA: &str = "KP2A_URL";
fn kind_name(k: ItemType) -> &'static str {
match k {
ItemType::WebLogin => "web-login",
ItemType::ApiCredential => "api-credential",
ItemType::LocalApp => "local-app",
ItemType::Wifi => "wifi",
ItemType::SecureNote => "secure-note",
ItemType::Card => "card",
ItemType::KeyPair => "key-pair",
}
}
/// The Custos field KeePass's `UserName` stands for.
fn user_field(k: ItemType) -> &'static str {
match k {
ItemType::Wifi => "ssid",
ItemType::Card => "cardholder",
_ => "username",
}
}
/// The Custos field KeePass's `Password` stands for.
fn pass_field(k: ItemType) -> &'static str {
match k {
ItemType::ApiCredential => "secret",
ItemType::Card => "number",
_ => "password",
}
}
fn in_template(k: ItemType, name: &str) -> Option<bool> {
k.template().iter().find(|(n, _)| *n == name).map(|&(_, s)| s)
}
/// A file from elsewhere has no `custos-type`: no user name, password or URL makes it a note.
fn guess(e: &Entry) -> ItemType {
let has = |k| e.get(k).is_some_and(|v| !v.is_empty());
if has("UserName") || has("Password") || has("URL") { ItemType::WebLogin } else { ItemType::SecureNote }
}
/// `KP2A_URL` or `KP2A_URL_<n>`: KeePassXC's extra URLs. Its number, `KP2A_URL` itself being 0.
fn extra_url(key: &str) -> Option<u32> {
let rest = key.strip_prefix(URL_EXTRA)?;
if rest.is_empty() {
return Some(0);
}
rest.strip_prefix('_').filter(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))?.parse().ok()
}
fn hex(b: &[u8; 16]) -> String {
b.iter().map(|x| format!("{x:02x}")).collect()
}
fn ms(secs: i64) -> i64 {
secs.saturating_mul(1000)
}
// ---- KeePass → Custos ----
/// Every entry outside the recycle bin, as a Custos item. The root group is not part of `folder`.
pub fn to_items(db: &Database) -> Vec<Item> {
let mut out = Vec::new();
collect(&db.root, &mut Vec::new(), db.recycle_bin, &mut out);
out
}
fn collect(g: &Group, path: &mut Vec<String>, bin: Option<[u8; 16]>, out: &mut Vec<Item>) {
for e in &g.entries {
out.push(entry_to_item(e, path));
}
for sub in &g.groups {
if Some(sub.uuid) == bin {
continue;
}
path.push(sub.name.clone());
collect(sub, path, bin, out);
path.pop();
}
}
/// One mapped value: the Custos field name, the value, and whether KeePass protected it.
struct Mapped {
name: String,
value: SecretString,
protected: bool,
/// From `UserName`, `Password` or `URL`: an empty one is only a template slot, never a field of its own.
standard: bool,
}
/// An entry's strings as Custos fields, in file order (extra URLs in their numeric order).
fn mapped(e: &Entry, kind: ItemType) -> Vec<Mapped> {
let mut out = Vec::new();
let mut extra_urls: Vec<(u32, &StringField)> = Vec::new();
let mut urls_at = None;
let mut primary_url = None;
let totp_seed = e.get("TOTP Seed").filter(|_| e.get("otp").is_none());
for s in &e.strings {
let m =
|name: &str, protected, standard| Mapped { name: name.into(), value: s.value.clone(), protected, standard };
match s.key.as_str() {
"Title" | "Notes" | TYPE_KEY | "TOTP Settings" => {}
"UserName" => out.push(m(user_field(kind), false, true)),
"Password" => out.push(m(pass_field(kind), true, true)),
"URL" => {
urls_at.get_or_insert(out.len());
primary_url = Some(m("url", false, true));
}
"otp" => out.push(m("totp", true, false)),
"TOTP Seed" if totp_seed.is_some() => out.push(Mapped {
name: "totp".into(),
value: totp_uri(e, s.value.expose()),
protected: true,
standard: false,
}),
k if let Some(n) = extra_url(k) => {
urls_at.get_or_insert(out.len());
extra_urls.push((n, s));
}
k => out.push(m(k, s.protected, false)),
}
}
extra_urls.sort_by_key(|(n, _)| *n);
let urls = extra_urls.into_iter().map(|(_, s)| Mapped {
name: "url".into(),
value: s.value.clone(),
protected: false,
standard: false,
});
// `URL` first, then the extra ones in their numeric order, wherever the first of them was in the file
// (KeePassXC sorts keys, so `KP2A_URL` comes before `URL` there).
let at = urls_at.unwrap_or(out.len());
out.splice(at..at, primary_url.into_iter().chain(urls));
out
}
/// KeePass 2's `TOTP Seed` (base32) with `TOTP Settings` ("period;digits"), as Custos keeps it: the bare
/// seed for 30 s / 6 digits, otherwise an otpauth:// URI.
fn totp_uri(e: &Entry, seed: &str) -> SecretString {
let settings = e.get("TOTP Settings").map(|s| s.expose().to_owned()).unwrap_or_default();
let mut parts = settings.split(';');
let period = parts.next().and_then(|p| p.trim().parse::<u32>().ok()).unwrap_or(30);
let digits = parts.next().and_then(|d| d.trim().parse::<u32>().ok()).unwrap_or(6);
let seed: String = seed.chars().filter(|c| !c.is_whitespace()).collect();
if period == 30 && digits == 6 {
return SecretString::new(seed);
}
let label: String = e
.get("Title")
.map(|t| t.expose())
.unwrap_or("")
.bytes()
.map(|b| if b.is_ascii_alphanumeric() { (b as char).to_string() } else { format!("%{b:02X}") })
.collect();
SecretString::new(format!("otpauth://totp/{label}?secret={seed}&period={period}&digits={digits}"))
}
/// Puts a value into the first unfilled template slot with that name, or appends it as a field.
fn put(item: &mut Item, filled: &mut Vec<bool>, name: &str, value: SecretString, secret: bool, standard: bool) {
let template = in_template(item.kind, name);
if let Some(i) = item.fields.iter().enumerate().position(|(i, f)| f.name == name && !filled[i]) {
item.fields[i].value = value;
item.fields[i].secret |= secret;
filled[i] = true;
} else if !(standard && value.is_empty()) {
item.fields.push(Field { name: name.into(), value, secret: secret || template == Some(true) });
filled.push(true);
}
}
fn entry_to_item(e: &Entry, folder: &[String]) -> Item {
let kind = e
.get(TYPE_KEY)
.and_then(|t| ItemType::ALL.into_iter().find(|k| kind_name(*k) == t.expose()))
.unwrap_or_else(|| guess(e));
let title = e.get("Title").map(|t| t.expose()).unwrap_or("");
let mut item = Item::new(kind, title, ms(e.times.created));
item.id = hex(&e.uuid);
item.modified = ms(e.times.modified);
item.notes = e.get("Notes").cloned().unwrap_or_default();
item.tags = e.tags.clone();
item.folder = folder.to_vec();
item.attachments = e.attachments.clone();
let mut filled = vec![false; item.fields.len()];
for m in mapped(e, kind) {
put(&mut item, &mut filled, &m.name, m.value, m.protected, m.standard);
}
if let Some(x) = e.times.expires {
put(&mut item, &mut filled, "expires", SecretString::new(time::format_iso(x)), false, false);
}
if !e.autotype.default_sequence.is_empty() {
put(&mut item, &mut filled, "autotype-sequence", e.autotype.default_sequence.as_str().into(), false, false);
}
for w in &e.autotype.windows {
put(&mut item, &mut filled, "autotype-match", w.as_str().into(), false, false);
}
item.history = history(e, kind);
item
}
/// For every snapshot, each secret field whose value differs in the next version (docs/KDBX.md).
fn history(e: &Entry, kind: ItemType) -> Vec<HistoryEntry> {
let secrets = |v: &Entry| -> Vec<(String, SecretString)> {
let mut seen: Vec<(String, SecretString)> = Vec::new();
for m in mapped(v, kind) {
let secret = m.protected || in_template(kind, &m.name) == Some(true);
if secret && !seen.iter().any(|(n, _)| *n == m.name) {
seen.push((m.name, m.value));
}
}
seen
};
let mut out = Vec::new();
let versions: Vec<&Entry> = e.history.iter().chain(std::iter::once(e)).collect();
for pair in versions.windows(2) {
let next = secrets(pair[1]);
for (name, old) in secrets(pair[0]) {
let now = next.iter().find(|(n, _)| *n == name).map(|(_, v)| v.expose()).unwrap_or("");
if !old.is_empty() && old.expose() != now {
out.push(HistoryEntry { field: name, value: old, changed: ms(pair[0].times.modified) });
}
}
}
let excess = out.len().saturating_sub(HISTORY_LIMIT);
out.drain(..excess);
out
}
// ---- Custos → KeePass ----
/// A database with one group per folder under a root group called `name`. Factors and the Domi identity
/// are not items, so they never get here.
pub fn from_items(items: &[Item], name: &str) -> Database {
let mut root = Group { uuid: random_uuid(), name: name.into(), ..Default::default() };
for item in items {
let mut g = &mut root;
for part in &item.folder {
let i = match g.groups.iter().position(|s| s.name == *part) {
Some(i) => i,
None => {
g.groups.push(Group { uuid: random_uuid(), name: part.clone(), ..Default::default() });
g.groups.len() - 1
}
};
g = &mut g.groups[i];
}
g.entries.push(item_to_entry(item));
}
Database { name: name.into(), root, recycle_bin: None }
}
fn random_uuid() -> [u8; 16] {
let mut u = [0u8; 16];
crypto::fill_random(&mut u);
u
}
/// The KeePass key a Custos field goes to, given which standard slots are already taken.
fn key_for(kind: ItemType, name: &str, used: &[String], urls: &mut u32) -> String {
let standard = match name {
n if n == user_field(kind) => Some("UserName"),
n if n == pass_field(kind) => Some("Password"),
"url" => Some("URL"),
"totp" => Some("otp"),
_ => None,
};
if let Some(k) = standard.filter(|k| !used.iter().any(|u| u == k)) {
return k.into();
}
if name == "url" {
let k = if *urls == 0 { URL_EXTRA.to_owned() } else { format!("{URL_EXTRA}_{urls}") };
*urls += 1;
return k;
}
// Never collide with a key KeePass gives a meaning to, or with one already written.
let reserved = |k: &str| {
["Title", "UserName", "Password", "URL", "Notes", "otp", TYPE_KEY, "TOTP Seed", "TOTP Settings"].contains(&k)
|| extra_url(k).is_some()
|| used.iter().any(|u| u == k)
};
let mut k = name.to_owned();
let mut n = 2;
while reserved(&k) {
k = format!("{name} ({n})");
n += 1;
}
k
}
fn item_to_entry(item: &Item) -> Entry {
let kind = item.kind;
let uuid = data_encoding::HEXLOWER_PERMISSIVE
.decode(item.id.as_bytes())
.ok()
.and_then(|b| <[u8; 16]>::try_from(b).ok())
.unwrap_or_else(random_uuid);
let mut e = Entry {
uuid,
tags: item.tags.clone(),
attachments: item.attachments.clone(),
times: Times {
created: item.created.div_euclid(1000),
modified: item.modified.div_euclid(1000),
expires: None,
},
..Default::default()
};
let first = |name: &str| item.field(name).map(|f| f.value.clone()).unwrap_or_default();
e.strings = vec![
StringField { key: "Title".into(), value: item.title.as_str().into(), protected: false },
StringField { key: "UserName".into(), value: first(user_field(kind)), protected: false },
StringField { key: "Password".into(), value: first(pass_field(kind)), protected: true },
StringField { key: "URL".into(), value: first("url"), protected: false },
StringField { key: "Notes".into(), value: item.notes.clone(), protected: false },
];
let mut used: Vec<String> = e.strings.iter().map(|s| s.key.clone()).collect();
let (mut seen_user, mut seen_pass, mut seen_url) = (false, false, false);
let (mut seen_seq, mut seen_exp) = (false, false);
let mut urls = 0;
for f in &item.fields {
let first_of = |seen: &mut bool| !std::mem::replace(seen, true);
if f.name == user_field(kind) && first_of(&mut seen_user)
|| f.name == pass_field(kind) && first_of(&mut seen_pass)
|| f.name == "url" && first_of(&mut seen_url)
{
continue; // already in a standard string
}
if f.name == "autotype-sequence" && first_of(&mut seen_seq) {
e.autotype.default_sequence = f.value.expose().to_owned();
continue;
}
if f.name == "autotype-match" {
if !f.value.is_empty() {
e.autotype.windows.push(f.value.expose().to_owned());
}
continue;
}
if f.name == "expires"
&& !seen_exp
&& let Some(x) = time::parse_iso(f.value.expose())
{
seen_exp = true;
e.times.expires = Some(x);
continue;
}
if f.value.is_empty() && in_template(kind, &f.name).is_some() {
continue;
}
let key = key_for(kind, &f.name, &used, &mut urls);
let protected = f.secret || key == "otp";
used.push(key.clone());
e.strings.push(StringField { key, value: f.value.clone(), protected });
}
if guess(&e) != kind {
e.strings.push(StringField { key: TYPE_KEY.into(), value: kind_name(kind).into(), protected: false });
}
e.history = snapshots(item, &e);
e
}
/// KeePass snapshots from Custos's per-field history: one per distinct change time, each with the values
/// as they were just before that change.
fn snapshots(item: &Item, current: &Entry) -> Vec<Entry> {
let mut hist: Vec<&HistoryEntry> = item.history.iter().collect();
hist.sort_by_key(|h| h.changed);
let mut times: Vec<i64> = hist.iter().map(|h| h.changed).collect();
times.dedup();
// A field's key in the current entry: the standard ones, otherwise its own name.
let key_of = |field: &str| -> String {
match field {
n if n == user_field(item.kind) => "UserName".into(),
n if n == pass_field(item.kind) => "Password".into(),
"totp" => "otp".into(),
n => n.to_owned(),
}
};
times
.iter()
.map(|&t| {
let mut s = Entry {
uuid: current.uuid,
strings: current.strings.clone(),
tags: current.tags.clone(),
times: Times { modified: t.div_euclid(1000), ..current.times },
autotype: AutoType::default(),
..Default::default()
};
let mut done: Vec<&str> = Vec::new();
for h in hist.iter().filter(|h| h.changed >= t) {
if done.contains(&h.field.as_str()) {
continue;
}
done.push(&h.field);
let key = key_of(&h.field);
match s.strings.iter_mut().find(|x| x.key == key) {
Some(x) => x.value = h.value.clone(),
None => s.strings.push(StringField { key, value: h.value.clone(), protected: true }),
}
}
s
})
.collect()
}
+111
View File
@@ -0,0 +1,111 @@
//! KDBX times: base64 of an i64 LE count of seconds since 0001-01-01 (KDBX 4), or ISO 8601 (KeePass XML).
/// Seconds from 0001-01-01T00:00:00Z to the Unix epoch.
const EPOCH_OFFSET: i64 = 62_135_596_800;
pub(crate) fn from_kdbx(text: &str) -> Option<i64> {
let t = text.trim();
if let Ok(b) = data_encoding::BASE64.decode(t.as_bytes())
&& let Ok(b) = <[u8; 8]>::try_from(b.as_slice())
{
return i64::from_le_bytes(b).checked_sub(EPOCH_OFFSET);
}
parse_iso(t)
}
pub(crate) fn to_kdbx(unix: i64) -> String {
data_encoding::BASE64.encode(&unix.saturating_add(EPOCH_OFFSET).to_le_bytes())
}
/// `YYYY-MM-DD` (midnight UTC) or `YYYY-MM-DDTHH:MM:SS` with an optional `Z` → Unix seconds.
pub fn parse_iso(s: &str) -> Option<i64> {
let s = s.trim();
let s = s.strip_suffix('Z').unwrap_or(s);
let (date, time) = match s.split_once('T') {
Some((d, t)) => (d, Some(t)),
None => (s, None),
};
let mut d = date.splitn(3, '-');
let y: i64 = num(d.next()?, 4)?;
let m: u32 = num(d.next()?, 2)? as u32;
let day: u32 = num(d.next()?, 2)? as u32;
if !(1..=12).contains(&m) || day == 0 || day > days_in_month(y, m) {
return None;
}
let mut secs = 0;
if let Some(t) = time {
let mut p = t.splitn(3, ':');
let (h, mi, se) = (num(p.next()?, 2)?, num(p.next()?, 2)?, num(p.next()?, 2)?);
if h > 23 || mi > 59 || se > 59 {
return None;
}
secs = h * 3600 + mi * 60 + se;
}
Some(days_from_civil(y, m, day) * 86_400 + secs)
}
/// Unix seconds → `YYYY-MM-DD` when it is midnight UTC, otherwise `YYYY-MM-DDTHH:MM:SSZ`.
pub fn format_iso(unix: i64) -> String {
let (days, secs) = (unix.div_euclid(86_400), unix.rem_euclid(86_400));
let (y, m, d) = civil_from_days(days);
if secs == 0 {
format!("{y:04}-{m:02}-{d:02}")
} else {
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", secs / 3600, secs / 60 % 60, secs % 60)
}
}
fn num(s: &str, len: usize) -> Option<i64> {
(s.len() == len && s.bytes().all(|b| b.is_ascii_digit())).then(|| s.parse().ok()).flatten()
}
fn days_in_month(y: i64, m: u32) -> u32 {
match m {
2 if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
// Howard Hinnant's civil-date algorithms.
fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400;
let mp = (i64::from(m) + 9) % 12;
let doy = (153 * mp + 2) / 5 + i64::from(d) - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
fn civil_from_days(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(yoe + era * 400 + i64::from(m <= 2), m, d)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn iso_round_trips_and_refuses_nonsense() {
assert_eq!(parse_iso("1970-01-01"), Some(0));
assert_eq!(parse_iso("2026-11-03T19:26:49Z"), Some(1_793_734_009));
assert_eq!(format_iso(1_793_734_009), "2026-11-03T19:26:49Z");
assert_eq!(format_iso(parse_iso("2024-02-29").unwrap()), "2024-02-29");
assert_eq!(format_iso(parse_iso("0001-01-01").unwrap()), "0001-01-01");
for bad in ["", "2023-02-29", "2026-13-01", "26-01-01", "2026-01-01T24:00:00Z", "next year", "2026-1-1"] {
assert_eq!(parse_iso(bad), None, "{bad}");
}
assert_eq!(from_kdbx(&to_kdbx(1_793_734_009)), Some(1_793_734_009));
assert_eq!(from_kdbx("2026-11-03T19:26:49Z"), Some(1_793_734_009));
}
}
+348
View File
@@ -0,0 +1,348 @@
//! The inner XML: parsed with roxmltree (no DTD, so no entity tricks), written by hand.
use crate::crypto::InnerStream;
use crate::{AutoType, Database, Entry, Error, Group, StringField, Times, time};
use custos_vault::{Attachment, SecretBytes, SecretString};
use roxmltree::{Node, NodeId};
use std::collections::HashMap;
use std::fmt::Write as _;
use zeroize::Zeroizing;
const MAX_DEPTH: usize = 256;
pub(crate) fn parse(xml: &[u8], stream: &mut InnerStream, pool: &[SecretBytes]) -> Result<Database, Error> {
let xml = xml.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(xml);
let body = std::str::from_utf8(xml).map_err(|_| Error::Malformed("XML is not UTF-8"))?;
let doc = roxmltree::Document::parse_with_options(
body,
roxmltree::ParsingOptions { allow_dtd: false, ..Default::default() },
)
.map_err(|e| match e {
roxmltree::Error::DtdDetected => Error::Malformed("XML with a DOCTYPE"),
_ => Error::Malformed("XML"),
})?;
// Protected values, unmasked in document order: every one consumes the stream, used or not.
let mut protected: HashMap<NodeId, Zeroizing<Vec<u8>>> = HashMap::new();
for n in doc.descendants().filter(|n| n.is_element()) {
if n.attribute("Protected").is_some_and(|v| v.eq_ignore_ascii_case("true")) {
let mut bytes = Zeroizing::new(
data_encoding::BASE64.decode(n_text(n).as_bytes()).map_err(|_| Error::Malformed("protected value"))?,
);
stream.apply(&mut bytes);
protected.insert(n.id(), bytes);
}
}
let root = doc.root_element();
if !root.has_tag_name("KeePassFile") {
return Err(Error::Malformed("not a KeePass XML document"));
}
let meta = child(root, "Meta");
let name = meta.and_then(|m| child(m, "DatabaseName")).map(text).unwrap_or_default();
let recycle_bin = meta
.filter(|m| child(*m, "RecycleBinEnabled").is_some_and(|n| text(n).eq_ignore_ascii_case("true")))
.and_then(|m| child(m, "RecycleBinUUID"))
.and_then(|n| uuid(n).ok())
.filter(|u| *u != [0; 16]);
let group = child(root, "Root").and_then(|r| child(r, "Group")).ok_or(Error::Malformed("no root group"))?;
// Attachments: KDBX 4 keeps them in the inner header (by index), KDBX 3.1 in Meta/Binaries (by ID).
let mut binaries: HashMap<String, SecretBytes> =
pool.iter().enumerate().map(|(i, b)| (i.to_string(), b.clone())).collect();
for b in meta.and_then(|m| child(m, "Binaries")).into_iter().flat_map(|bs| bs.children()) {
if !b.has_tag_name("Binary") {
continue;
}
let id = b.attribute("ID").ok_or(Error::Malformed("attachment"))?.to_owned();
let raw = match protected.get(&b.id()) {
Some(bytes) => bytes.clone(),
None => Zeroizing::new(
data_encoding::BASE64.decode(n_text(b).as_bytes()).map_err(|_| Error::Malformed("attachment"))?,
),
};
let data = if b.attribute("Compressed").is_some_and(|v| v.eq_ignore_ascii_case("true")) {
crate::format::gunzip(&raw)?
} else {
raw
};
binaries.insert(id, SecretBytes::new(data.to_vec()));
}
let ctx = Ctx { protected: &protected, binaries: &binaries };
Ok(Database { name, root: ctx.group(group, 0)?, recycle_bin })
}
struct Ctx<'a> {
protected: &'a HashMap<NodeId, Zeroizing<Vec<u8>>>,
binaries: &'a HashMap<String, SecretBytes>,
}
impl Ctx<'_> {
fn group(&self, n: Node, depth: usize) -> Result<Group, Error> {
if depth > MAX_DEPTH {
return Err(Error::Malformed("groups nested too deeply"));
}
let mut g = Group {
uuid: child(n, "UUID").map(uuid).transpose()?.unwrap_or_default(),
name: child(n, "Name").map(text).unwrap_or_default(),
..Default::default()
};
for c in n.children().filter(|c| c.is_element()) {
match c.tag_name().name() {
"Entry" => g.entries.push(self.entry(c, true)?),
"Group" => g.groups.push(self.group(c, depth + 1)?),
_ => {}
}
}
Ok(g)
}
fn entry(&self, n: Node, with_history: bool) -> Result<Entry, Error> {
let mut e = Entry { uuid: child(n, "UUID").map(uuid).transpose()?.unwrap_or_default(), ..Default::default() };
for c in n.children().filter(|c| c.is_element()) {
match c.tag_name().name() {
"Tags" => {
e.tags =
text(c).split([';', ',']).map(str::trim).filter(|t| !t.is_empty()).map(Into::into).collect()
}
"Times" => e.times = times(c),
"String" => {
let key = child(c, "Key").map(text).unwrap_or_default();
let v = child(c, "Value");
let (value, protected) = match v.and_then(|v| self.protected.get(&v.id())) {
Some(b) => {
let s = String::from_utf8(b.to_vec()).map_err(|_| Error::Malformed("protected value"))?;
(SecretString::new(s), true)
}
None => (SecretString::new(v.map(text).unwrap_or_default()), false),
};
if !e.strings.iter().any(|s| s.key == key) {
e.strings.push(StringField { key, value, protected });
}
}
"Binary" => {
let name = child(c, "Key").map(text).unwrap_or_default();
let r = child(c, "Value").and_then(|v| v.attribute("Ref")).ok_or(Error::Malformed("attachment"))?;
let data = self.binaries.get(r).ok_or(Error::Malformed("attachment"))?;
e.attachments.push(Attachment { name, data: data.clone() });
}
"AutoType" => {
e.autotype = AutoType {
default_sequence: child(c, "DefaultSequence").map(text).unwrap_or_default(),
windows: c
.children()
.filter(|a| a.has_tag_name("Association"))
.map(|a| child(a, "Window").map(text).unwrap_or_default())
.collect(),
}
}
"History" if with_history => {
for h in c.children().filter(|h| h.has_tag_name("Entry")) {
e.history.push(self.entry(h, false)?);
}
}
_ => {}
}
}
Ok(e)
}
}
fn child<'a, 'i>(n: Node<'a, 'i>, name: &str) -> Option<Node<'a, 'i>> {
n.children().find(|c| c.has_tag_name(name))
}
/// Base64 text without its whitespace.
fn n_text(n: Node) -> Zeroizing<String> {
Zeroizing::new(n.text().unwrap_or("").split_whitespace().collect())
}
fn text(n: Node) -> String {
n.text().unwrap_or("").to_owned()
}
fn uuid(n: Node) -> Result<[u8; 16], Error> {
let t = n.text().unwrap_or("").trim();
data_encoding::BASE64.decode(t.as_bytes()).ok().and_then(|b| b.try_into().ok()).ok_or(Error::Malformed("UUID"))
}
fn times(n: Node) -> Times {
let get = |name| child(n, name).and_then(|c| time::from_kdbx(c.text().unwrap_or("")));
let expires = child(n, "Expires").is_some_and(|c| text(c).trim().eq_ignore_ascii_case("true"));
Times {
created: get("CreationTime").unwrap_or(0),
modified: get("LastModificationTime").unwrap_or(0),
expires: if expires { get("ExpiryTime") } else { None },
}
}
/// The XML, protected values masked with `stream` in document order; attachments go to `pool` in the
/// order their `Ref`s are written.
pub(crate) fn write<'d>(
db: &'d Database,
stream: &mut InnerStream,
pool: &mut Vec<&'d SecretBytes>,
) -> Zeroizing<String> {
let mut w = W { out: Zeroizing::new(String::new()), stream, pool };
w.raw("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<KeePassFile>\n\t<Meta>\n");
w.el(2, "Generator", "Custos");
w.el(2, "DatabaseName", &db.name);
w.raw("\t\t<MemoryProtection>\n");
for (k, v) in [("ProtectTitle", "False"), ("ProtectUserName", "False"), ("ProtectPassword", "True")] {
w.el(3, k, v);
}
for (k, v) in [("ProtectURL", "False"), ("ProtectNotes", "False")] {
w.el(3, k, v);
}
w.raw("\t\t</MemoryProtection>\n");
w.el(2, "RecycleBinEnabled", "False");
w.el(2, "HistoryMaxItems", "20");
w.el(2, "HistoryMaxSize", "6291456");
w.raw("\t</Meta>\n\t<Root>\n");
w.group(&db.root, 2);
w.raw("\t\t<DeletedObjects/>\n\t</Root>\n</KeePassFile>\n");
w.out
}
struct W<'s, 'd> {
out: Zeroizing<String>,
stream: &'s mut InnerStream,
pool: &'s mut Vec<&'d SecretBytes>,
}
impl<'d> W<'_, 'd> {
fn raw(&mut self, s: &str) {
self.out.push_str(s);
}
fn indent(&mut self, n: usize) {
for _ in 0..n {
self.out.push('\t');
}
}
fn el(&mut self, depth: usize, name: &str, value: &str) {
self.indent(depth);
if value.is_empty() {
let _ = writeln!(self.out, "<{name}/>");
} else {
let _ = write!(self.out, "<{name}>");
escape(&mut self.out, value);
let _ = writeln!(self.out, "</{name}>");
}
}
fn times(&mut self, d: usize, t: &Times) {
self.indent(d);
self.raw("<Times>\n");
let m = time::to_kdbx(t.modified);
self.el(d + 1, "LastModificationTime", &m);
self.el(d + 1, "CreationTime", &time::to_kdbx(t.created));
self.el(d + 1, "LastAccessTime", &m);
self.el(d + 1, "ExpiryTime", &time::to_kdbx(t.expires.unwrap_or(t.modified)));
self.el(d + 1, "Expires", if t.expires.is_some() { "True" } else { "False" });
self.el(d + 1, "UsageCount", "0");
self.el(d + 1, "LocationChanged", &m);
self.indent(d);
self.raw("</Times>\n");
}
fn group(&mut self, g: &'d Group, d: usize) {
self.indent(d);
self.raw("<Group>\n");
self.el(d + 1, "UUID", &data_encoding::BASE64.encode(&g.uuid));
self.el(d + 1, "Name", &g.name);
self.el(d + 1, "IconID", "48");
self.el(d + 1, "IsExpanded", "True");
for e in &g.entries {
self.entry(e, d + 1, true);
}
for sub in &g.groups {
self.group(sub, d + 1);
}
self.indent(d);
self.raw("</Group>\n");
}
fn entry(&mut self, e: &'d Entry, d: usize, with_history: bool) {
self.indent(d);
self.raw("<Entry>\n");
self.el(d + 1, "UUID", &data_encoding::BASE64.encode(&e.uuid));
self.el(d + 1, "IconID", "0");
self.el(d + 1, "Tags", &e.tags.join(";"));
self.times(d + 1, &e.times);
for s in &e.strings {
self.indent(d + 1);
self.raw("<String>\n");
self.el(d + 2, "Key", &s.key);
self.indent(d + 2);
if s.protected {
let mut b = Zeroizing::new(s.value.expose().as_bytes().to_vec());
self.stream.apply(&mut b);
let _ = writeln!(self.out, "<Value Protected=\"True\">{}</Value>", data_encoding::BASE64.encode(&b));
} else if s.value.is_empty() {
self.raw("<Value/>\n");
} else {
self.raw("<Value>");
escape(&mut self.out, s.value.expose());
self.raw("</Value>\n");
}
self.indent(d + 1);
self.raw("</String>\n");
}
for a in &e.attachments {
let r = self.pool.len();
self.pool.push(&a.data);
self.indent(d + 1);
self.raw("<Binary>\n");
self.el(d + 2, "Key", &a.name);
self.indent(d + 2);
let _ = writeln!(self.out, "<Value Ref=\"{r}\"/>");
self.indent(d + 1);
self.raw("</Binary>\n");
}
self.indent(d + 1);
self.raw("<AutoType>\n");
self.el(d + 2, "Enabled", "True");
self.el(d + 2, "DataTransferObfuscation", "0");
self.el(d + 2, "DefaultSequence", &e.autotype.default_sequence);
for win in &e.autotype.windows {
self.indent(d + 2);
self.raw("<Association>\n");
self.el(d + 3, "Window", win);
self.el(d + 3, "KeystrokeSequence", "");
self.indent(d + 2);
self.raw("</Association>\n");
}
self.indent(d + 1);
self.raw("</AutoType>\n");
if with_history && !e.history.is_empty() {
self.indent(d + 1);
self.raw("<History>\n");
for h in &e.history {
self.entry(h, d + 2, false);
}
self.indent(d + 1);
self.raw("</History>\n");
}
self.indent(d);
self.raw("</Entry>\n");
}
}
/// XML text escaping. `\r` is written as a character reference so a parser's line-end normalization keeps
/// it; characters XML 1.0 cannot carry at all (other C0 controls) are dropped.
fn escape(out: &mut String, s: &str) {
for ch in s.chars() {
match ch {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\r' => out.push_str("&#13;"),
'\t' | '\n' => out.push(ch),
c if (c as u32) < 0x20 || c == '\u{FFFE}' || c == '\u{FFFF}' => {}
c => out.push(c),
}
}
}
@@ -0,0 +1,97 @@
// Files written by KeePassXC 2.7.12 (keepassxc-cli), from tools/kdbx/sample.xml, password "custos-test":
// V3 by `import` (KDBX 3.1, AES-KDF, AES-256, a recycle bin), V4 by `merge` of V3 into an empty KDBX 4
// file Custos wrote (KDBX 4.0, Argon2id 1 MiB, ChaCha20; KeePassXC keeps a file's format when it saves).
// These are test vectors: the first two steps of tools/kdbx/interop.sh make new ones
// (scratch script: base64 of each file, 100 characters per line).
const V3: &str = "
A9mimmf7S7UBAAMAAhAAMcHy5r9xQ1C+WAUhavxa/wMEAAEAAAAEIABxP6+yGbKtLFUqLZSBYUCDYrbP08dc4XTSSqHBRDGfewUg
AFDZzHIfvtxlCIOFQuMhnUD+NylHzyQm9bamu47pm/UrBggAgmVhAAAAAAAHEAA6MUS+RAp24tIyFbSnmrErCCAAA+p+nPcr2YHO
jXJHmIcuYjPzGWstYcLO7OiEoylZBl0JIACBvX6LL+NQDaZSTEd6UDMIjNQjLlh/0ZrbdX1W93wVzAoEAAIAAAAABAANCg0Kyl93
gyBLluY5EMk0XHCZdq9Ud2wtSiM9pdzcamLzP00nUlV0BnVsIHixNUf1ifpPmATO2Z01CHyoZE6jW1nwNyeuQT/YppuEeXh3K3AY
mDtjqB3bohJLgTyg1PslOOGhHr009FLUqVRSU042X92tmlUYmesXH+AWOPpBK1uoN/ZV2UButF+6kLFB5T2x/Ds1e97gxfPPS/hp
O/RQrjvugGAsoc6dZUpDv1Dw+NoyHXQNHW/mfLFDBP1iyve8Kp97NDvQpCyMZT2tbJvwPGyLVQgSMLXMPc3kBrDt0WqZ4Jmcx7z8
+Vr0/Ly1TzoWRvurUgcHSRtiUMvQmPl7X/LLbzg2S9XORw7oGAKvNPiyh7mriTpV9OVUapObkLVBnihZmYaj1xwHJtgcIv+dFpcY
hE4zA+/gqXf3RWDfwhY0p81tobTVaMAzd3Wu5H28NIWXs8z33i8LQ74CRH2Sq6s52JlRt62ofu2jcGlkFxNrv+j9+FE9kL0Sex5Y
8fZvx/bNrwT79Jea79V19zsQpT2tzSEM6cB3wDekj5Kba96kOc6bRH1J7HsNDSbDss0tF16MiTEBSIHW5lJwk1x/m8gmHBurHYUl
dXHZKN1MoJ+ROyfR0BrerI5ETlN48f7ZZTsO7L6twynU6MqiyDlXjGQUUFaVeUsObyklQ59+pD5CUx9ve0Uak8P2KS01gEXiBNtw
b+vBkSbiNcaSOrl4DXwXINPA3RpHURGjwu5M4HHWI9keIsrwfFmGRlH5oNroxihBFEOUSfL4ChdmG/rbtGxHekba5pyAWyVE0z4h
lYIKjldWKzQjtPCbWWmbGspopEaBL9G2GE9RpA4gRN3ZrDR6WcbBLQYNwOYoiPU38m1L1KjSV59WpzoL7/xfslTEvEH83LHkf6mt
LfbHC8Y2AVN27bt6C8zDTUYJFeUTiierSvf22s5m1s2NbfVqJC1XJFREJuusEY/RGPJa+OdSoN7E0sQFDOoDtZihZSSdp+IkdXkl
skgcIqyC8/ioos62g6xYWndMI9b+FgDuH1ADSSSugC3CfVMHhUio93o9Z41DsIQMSzliF2Ggp+0wIBwsakaxWoqjVh0ydRX39GQ0
eSC2z6Rt1TT1CouDQTsf5G57r4217pQvbzFhs7Yfc9ZetzCN5JBzw2hFYHEvoJR5YzAJD1txFt7AfeHdN/3F70RYpKbj8txOnS/F
aXuexKaHDBlVlEf2DakTjQNZpK+Su94TJ6me4mO5qJTeZ4KlEoRrAttY6DRQ0ThjHh5erLf44rrxzas8kqYE5XMe0iUiDVaIVwu1
9oOnqURbqMeDcoGqxrc/LkeSyEuZ+F4+xx9uJ15NV3eexj5E6OZoB5Wqy6gHdEXiPV0PmMJksJSI/IBtCR4/AzKoTUe6JRWJAd51
fDQ8r4CivKzwkMyyHMcaUu8LQ5jqt87EeGJ3mWnDRC0A8/TR25VOKmrLK1G+e+RTF/ySC0t6ndxQbt79HeNbio/E3goxVOAYfryO
vMhJS+aJsDwd9ERAFXFzFyrGb2iuyKvbT1GKDFWa/+voFiCtnMa/JF26Z6sr+Yytgr58bB9+7CJiCyqrywkCze8+NZ6v6LTj/xJ0
gflMpCavrnXTN2BzNUDoONsSk03RNDGxN7Y8S2m4BoRdRjJ0Sr2Ta8u5iePIg7TmIcnhP96pJ1qAZkZYdai87du/4wIHHBx/CLf1
xaOAVcg3M1E/EHxxlJ9K3G0QBO05RXQL73riIAj3NFAIV8OIMTxq+fwkTG1VLGwfPS7Ezkt6vE5pkSaktlC+XVsuWroZpUXbvGXv
bGcLGCWr4pciROyCAm9NDvuZNrgkLLewmAGRYlgX7iZUNPwfmypEw7ians6jV4BEKYu71FZngB7FqM5t8NaTx9Ljed8Qt+IGCKa9
ZioRmIOrelaRo+NB8/Bas/vdg7AsrVsIZrSEF5JdFhJZ2Cx/AoTwZ7yhOg3Vl3kwG6VfwQrVZA9PpO4StthFQY5KeJGIRkn9KRyY
mYnL2fnPiof0ZCPwe0gQKQrGjjkYqOPZtM3YNkUtMoP9O1fz8BbBoDxa0E49qGgNxgzIEV1fw7w0pHnT4RaeX8hu+SaRWRW5dqxa
GLEjicraTg1fC5WDyh/RH3T6F9KQ2oiUKjZnUHSBJRZf++rquooN51mKS8LWC8Tti5NhWz69psjygpxeNEMrorQpV9KFtE5JNMtt
mjoF6j1uiXL2muNSlEzNyXBvKTWRYiMesHIKpORaOce3zO2PZOqnykN8ro9/zonA50z9kodJ7Skq/HiwM+MSyVKogLSgM1uHBdRl
ce0S3zBq1go514OLX5LGLDdLmu3OgRNxCC/KC4YT806pLDjpRW+Q7xItfta2TOsvjqB02tE+IrBFw2BmPtWCRq3zpyUl+PHS+bd6
5tDiCZQSN1dr9BAsnPY6nsXNJTy9AnSZ3J7rZlk52rrCTiZ/uSlTeEQDONndkof4z9Qd7+edKN7ZFk+f/GTtpyH/kzxdQ0cLnH/7
lPf7cJIjlVJ+Irt43uR0wc0w8ONftEyByVMqO4maMUbuTFbJdTUuPoZxs1HepWRrzzcy8ggx5XUe5556vuO1kWTgXmt38ms8DPx2
EezM4gWIDruwEca+7OiLDhGdhWqFAx22YinL5EvarEO9xvu44pjgbuyM87rdipjXrqOhCsvPUkWTG1NG+vEs7XYCft/iPFBDgnNJ
L544kOGEDtdLZB7rSt++gUh0Vmph6CXxCq15P+3IuTFYxWoueN4dI01bXhc3/HprHwCrJDYBzD+T0lRh9pn8n6FhFC2xc/CcNbbC
Hl4THNc9Rs3qmWBpz5aHW+isE4B7Aeaq85VFpZ75IPXjlaO0FAzB4RxIh14YmnF44IrS8cHpRf0IvDnTk6RJe+iDVRCbw7AHbWu8
6hYI6tHBtnCtVYX1kkK+93zBG23dqaNyz6pxqI+ULNLsoROxcC6RGVJLMJad7YCxdsVzzo9sCTrlykZKi7pU5hZo3/epKMfRmGLY
CX84PBeCeMXZzLpFdsp/+jPcdHhaG9A4XkWSlR9CmvFNf9jTckuApYF/FDYGdAnMSC5QNJhE4aKexL8LnbF2qZ9xb/JE+0M63W8u
uRsucRNuOGjP8cn43MsvQ/5SSZuyv1H4hXKekKMEj92zlKofKZe3Sw28kZv4XekSUdTWoUycehykkHOfJ6GCIGQx8Vp59FDD7Ux3
TjYD6Z0M+jsjciIDVUpGWPxM7TbWgUxYqPPliu70TG7yD6ZcJ/ZR6vcYIq1kE1+HhySLdmdKCRPDoRFxslWEGygRgP0f1j84koa3
oB2/WqEboTG3FjStCForRlWqip1fqoO8CN9m5JcqWuR4tU0z0yCnRb22OWfAGroGtOZdZq65bkl7QwvcO1UAMmVocprocUWcuL+S
95lOV30LGMck7hawZIMsPIGxEwaAHOY1x7GXNyJNXyokllWzIOQB9f8ijgZ2K0aXlY0BMNeahOg0GtLJ1wD9TiIJjR0EfeX6K4SE
B7N9w5IVBxFj2ov51V+QJ2JNgBcz9LY4tzlRf2WtUGjsrTu5tKADCawDylACdyuAIf01TxjwI6KFUqbcoHxmdbcg1pzogiRFwS9A
RAaW5cFVdAQZfGrb7OWAVlVv39I/7ERpKl8v+kaZtcWJo4ti8h93Tk87oUBzTmw/EuvmEPqmGb3U74aeNiusERjDETPvptNA4AQ+
wacNeHlR8Xoo7OtEbO+bgPYq0iGdnQ==
";
const V4: &str = "
A9mimmf7S7UAAAQAAhAAAADWA4ori29MtaUkM5ox27WaAwQAAAABAAAABCAAAADzupOsQNxJtVlkoq/jSw09K0bVSZhptX92AZ1p
i1Pc0QcMAAAAJwtbrtLHFXIogTGFC4sAAAAAAUIFAAAAJFVVSUQQAAAAnimLGVbbR3OyPfw+xvCh5gUBAAAASQgAAAACAAAAAAAA
AAUBAAAATQgAAAAAABAAAAAAAAQBAAAAUAQAAAABAAAAQgEAAABTIAAAAOH9a1nQE9Z0DF7AXihl/5svsTxxIIsQrLyRqgPGli+D
BAEAAABWBAAAABMAAAAAAAQAAAANCg0KIlabXPdaLY1rYYaqe9H8l1/Gt/dAEcsHxmVR2oBITjLi4+QPmaXni/MJuSznD3Mk/O7W
YO67iKNBV7s3/9/ikiisk3nXhJ4Lqt9eZkb7R9Hy/DMSz+bPBHi9B9V6oD54oAsAAJsOIWmXzG35TT0OQ2M2K6GBwLAN9ZbyhohI
yk5GrqyFh/Q5M4/i0wjSBS1LmurEvAF9VxcCuFdZyTZrJxoGj2R5Y1fts01H37aFGCOiJP54EoTYs3aJzrzBk+WeSJZ7fvx7+2tA
7NfV8l4UtMaaw/nIoLQoMMGY4hyS58sMXtu1btPNfvKHvJUUSspQoEyOQ6yNuOB/mCGSOJhN4lTuWWXavJwFEIX8tBEI1CzHwken
kK8uiZleYqo+IqpZN0yVvZwUhfb+k+VASWAw7O/I/WOA4ONOdID058GIDWYEHuLoSIVRW+BXDm8n5WS5DQ7faaBjhQt6oZDSQRAv
EVSfN0R7MZe4xr4pXHV+B0oS6fTOsYCjxNYlznqnckivTz5lInl9uun4h1UQUwT59o0L/CiNrAI4todbXb9laCJl+xJTljMoPzYD
afNdVC5LLmETU7ThsMvgPsmcthzzqS9SdUfrzDZBD/u83Wwbpp2tHx4m6jGFabN8WgA7S2QqddfPJRo4DjpgaqHyuMFTarNM546f
+qhTN1X2kWLUUeRtZ7Pnh6Nv9uy12wMktM/S2WXRm17+MATqOSJcDx+REChuuXEl20gY4cxgReiPyr09ruRaN3WKdex+e2gP3DQa
mxIX7NsKwBRLwX6b/tDc22vAs64X43fJEuNJF/5WFWr96SgO0LDph5JZKHnuT+rU/g5ji0c095PJH2a/wFx8QiFEr5BA6kYVSPIU
8isa5v8TdQpk4V+yl7GRf72sW2wLeSwiS+oad8ttNNxOzA6uiXaWQTKsESN7Q6qxgKxsToqqdiAm3hCr4jKd1k7VUIllspabwXqW
OVXu1dUyT9gcsMK/DNru5M5Xel7ZtKF5O1TBoE7V5o2qjy7hnqhjcNM9DnoeshEbG8Ll97JFnmyfClYx2yy3uCdgwpryfqimllXA
cqCvsX47vDQYPK/HXmd9249qP+k2nLEen1QiHhY9qlIt0LwyiYEe+17C/rVN9UQdVWQYGpKnK4tw2R1h1+f+3LSjr9CjzK9JBI65
GwENYY/V0iwWwTvLzKbnjSB6ZcUCC34jxLQTWIMjACm0ltKCNfOC6iF338IMglQtZ+RDKEfxxY3zjB22Pqk8ZAyK+xKEGb0DCjlq
xtwbLlelOpSaoO7xR9GyuBdLyKzjsNEe/Oo92bl9uF6ugrtbhV1Nwjb9awhZ056H83/HizMbf1J88m2pROz31gD2rDrBkHiXQ/iW
RLgpzriEgpPUrDNtQB8XOlO0yJnJR3oIyG/SQbGnx2sGghbXWYvIioLnr54YBBXFT9zGBOQKnf185xsiLpqiEr62RalPynMncCFc
zH+/zdl8JbYHR/mcVRKJ95hA6Y0gk2RWqo4tLt7yz80y8Ctu0/4gh/LYjjkUId5P8McNVEBhcFQbzavkLlUNsovZOjjl67UxzM7l
F/fbBjULIdb6caRa/EDgGef/0bfUuU5ZEM9AMxPgxXrCRReH/e+YNVR743bdUw6bMjOjg4sq4B4H2ERuwiEKL1Rl+Vm/AlEwR/8u
jO3C7uSbDz/um+giIsJQxoHwHKlYa3C3/Gx9AP1gzUgRDkxDPYtMRUT34YMieBMcDsi598PFXnZWFBt3wl7ppNbCrZq3/jRqs90j
zR5hBgAB/Tsqa3OaZoz/uGkwGVKQmonziHVKgBrAKHZOJvtlfWDkmIAg0khQ95OmB9WGYOZu3YraxCW4G+CNV0WSYzgxK7c3Xvsr
3tv5Ne2eORtioat6GnnrliMCeK1UaXKI4aiYcT7ZUn11/OqSDBXn8vyFjNIL3ozGhiOQDvVv8DM2sd1JHEv7Zj2XJIdebJuUCy/S
shs5/GHyHYg6t0r3LeprOND1YMp9Ty332Zy5wCrttFI9nKown5WrQSa6GL+Etfwhk9tfISKI5PxPv6FPEzBs6LERj1SxED65CmPu
9N0VdK78dAsNe26AIwTZKYqUDhYwWbEeXNIx1WalO3zk9C4VsXQ3YpWwwbFtam4w3CdoWaqQrSPPddRkzo62KKxxiHYfPcA/gE56
mFuIjjS9kBr40UboApMTgBTqQD3fDveHJ0WiTNMsLHTKWXIL6ZZt1UksPuraCqurolSP7VrGpN9ioyoDdimY6WzMbEYmFY8gEM1F
YFzybW4RE3IPfUILQFvByPoEwRnaq5ah7ynrL/ZVk1y+kt+s563cxaUzOXf9sKOB1Ycweo/EHrg21gkkN8Nu73T1rGEVQv9q0sDW
6DnZ66gSuUUHNH9aAQkHW6069jFUjl9/3lsc0+BodGPOL7s+B6/sdRVRX4w3ujBcheKoEb2mAxvpuA604M0HSqNO30hqUIWawzES
CLtzpJysjcw3u0ySRT3wfcZcVcvhcEsNdBwJQ3Iz8fFMukWeZMnmfVwvBb1JrSb2vURX8P31uZQDnbaAjAnZfMUE1kngQqk038uA
VrRbhGoPhWXCOKpt8E1dWQwchP3L5YdhMfAI7ND5e3Nn90iMqI8BVvDYdVHbS0BdrI5GFGy/anKbKdMcBDfaFFr6N0QexQ05zWg5
huld3SVmStBKTQJJIyEstVFY44MtEXtA7iNwi82vLa2uKIA6DD89Fe44ktXLgReThc+iH4o2+7jiap8pFFzYh19rG9mFE9U22T2B
O2SmGea8K2ad+1+g/EA12W1jEnGuAxIZlMPV05Kd+1xBMB2YMu+Pdffpbp1MJQbfRAs3el3NEeq0/UUIGW9LOupqAZY7vElk47Kg
FI93N49DzC4Mhv0M36X38PKaCq5mi47Mxd1yKwc1y3GQBIN91gLVx0txw6yjiHcWbqFEPvQY2UEnr0dT5Xm2I8TnJ2tpKz42eTEs
S9kcqvNCNV1KhQ9jrlMi9+64qbD6vUpNCq7DjIiaZP8MYpgoZnWsJloTIaTVGPbqUsruGHe/8K8gx//34RmA2K3FkofH4iC/ztSJ
u+x5NXjEyVyEyHT8HvKj5JZXN7tFoqEyL43pevk7OaYmLOEh1RKRegDkcJrglQBqSohUTu/dd9SgM6AlVxMvS7H5Hw5+Oq5s6s8K
+vda4a8mWeJfRH0em5Sk0IXkxUR9I+OBuYnREoDT/dliDavRJ+IF0plHeOre7bFQFu8Rsv02PnHeYhJmVME38kxYXOuxMmZ4muuj
7UaKV6sxHsPdWU5IMe9qGi5qSWp0Q21KLZ89DBWT56vwkySR0QjZTTbb/wmUYT57S9MCrmhF/ncbJM7A14xrjl0y/0K65N7Y8UgD
7Fol550Yl+rhTYWM/egpIJr9wmz6FHuHw86DZv/RHJyKPgfIPlZvy+Z3eaSwGz8jeTa+NaSY9+v0TpVTHDBTyeZ17t8L0cW0RU0v
Olwh939wYrYVE6SzQFv85nllEmRN0J/O3lzm/LaCydqzEpezAg1Xxd3VxXEMZAgc3B14O4rzDTigTHdi1/6yk3lQnxYVOCaFgEbC
n3SWMHJMnT31P/sWIOs/Cn57A2IZ4i1JsqoGORyo8NXSOcRrOusTTewH9MJiRkEelYlRrEV1xWl1ZGt1jcjbkkOdunvio3JM/xpe
C/aBgU7zc28doM9AdKq51ZEYx3JU3VqKE/+quCgeEmz5vE7OSya7jSE+v0jTD7JOKTs/hwJWslKCr93R/mspG38Pv5Lq/ksNRLwz
m9fIgtGblTCK/O/oz6iSSNvhJL54Uu+8C9X2k+rUcHDGi7SkqRdrpmdudgfGHQuOwLOA7lQlh1yKuDy5pEeVmyrgUFqehpa37vDS
CswLKbmv3UA3Op95mptfwdj6b+Jqy4/V9bSW9KbBgAmYhFoQM29QLbL+c3bCjPmPxxe9ff/on/KPR5tHRBeeIlywWbZh+CMWoYkt
NqnfihsZJgT0EECsY7tPNPK5BphIPstuKTjxPPDXG5XhVpF7NLC2/yhvMmOu1X0Hzp4jKf3C8zvlZOPK5UBIbfB7EQOzMZdqtHzq
BHdA9FSFNSUm2fVRCA1YDtUAOqF6AF/j0btxILsn/C5jANRGZPcVWzoowmd6//xYMHCqJqW8Df2yAAAAAA==
";
+353
View File
@@ -0,0 +1,353 @@
//! The KDBX 4 file format (docs/KDBX.md, "Tests"): round trips, keys, tampering, hostile input.
use custos_kdbx::{
AutoType, Cipher, Database, Entry, Error, Group, Kdf, Key, SecretBytes, SecretString, StringField, Times,
WriteOptions, read, testing, write,
};
use custos_vault::Attachment;
use sha2::{Digest, Sha256};
/// Cheap parameters so the tamper tests can run the KDF once per byte.
const FAST: WriteOptions = WriteOptions { cipher: Cipher::ChaCha20, kdf: Kdf::Argon2id { m_kib: 64, t: 1, p: 1 } };
fn pw(s: &str) -> SecretString {
SecretString::from(s)
}
fn s(key: &str, value: &str, protected: bool) -> StringField {
StringField { key: key.into(), value: value.into(), protected }
}
pub fn sample() -> Database {
let snapshot = Entry {
uuid: [2; 16],
strings: vec![s("Title", "GitHub", false), s("Password", "Old-Secret-Value", true)],
times: Times { created: 1_700_000_000, modified: 1_700_000_100, expires: None },
..Default::default()
};
let login = Entry {
uuid: [2; 16],
strings: vec![
s("Title", "GitHub & <Gist>", false),
s("UserName", "alice", false),
s("Password", "Hunter2-Secret-Value", true),
s("URL", "https://github.com", false),
s("Notes", "line one\r\nline \"two\"\n\ttabbed — Česky", false),
s("Recovery code", "Protected-Recovery-Code", true),
s("Empty protected", "", true),
s("Plain", "", false),
],
attachments: vec![Attachment {
name: "id_ed25519".into(),
data: SecretBytes::from(&b"\x00\x01Attached-Key"[..]),
}],
tags: vec!["dev".into(), "work".into()],
times: Times { created: 1_700_000_000, modified: 1_700_000_200, expires: Some(1_800_000_000) },
autotype: AutoType {
default_sequence: "{USERNAME}{TAB}{PASSWORD}{ENTER}".into(),
windows: vec!["*GitHub*".into()],
},
history: vec![snapshot],
};
let note = Entry {
uuid: [3; 16],
strings: vec![s("Title", "Note", false), s("Notes", "just text", false)],
times: Times { created: 0, modified: 0, expires: None },
..Default::default()
};
Database {
name: "Test database".into(),
root: Group {
uuid: [1; 16],
name: "Root".into(),
entries: vec![note],
groups: vec![Group {
uuid: [4; 16],
name: "Internet".into(),
entries: vec![login],
groups: vec![Group { uuid: [5; 16], name: "Empty".into(), ..Default::default() }],
}],
},
recycle_bin: None,
}
}
fn key(p: &SecretString) -> Key<'_> {
Key { password: Some(p), key_file: None }
}
#[test]
fn write_then_read_is_identical_for_every_cipher_and_kdf() {
let db = sample();
let p = pw("correct horse");
for cipher in [Cipher::ChaCha20, Cipher::Aes256] {
for kdf in
[Kdf::Argon2id { m_kib: 64, t: 1, p: 1 }, Kdf::Argon2d { m_kib: 128, t: 2, p: 2 }, Kdf::Aes { rounds: 100 }]
{
let bytes = write(&db, &key(&p), WriteOptions { cipher, kdf }).unwrap();
assert_eq!(read(&bytes, &key(&p)).unwrap(), db, "{cipher:?} {kdf:?}");
}
}
// Every write is fresh: seed, IV, salt and inner stream key.
assert_ne!(write(&db, &key(&p), FAST).unwrap(), write(&db, &key(&p), FAST).unwrap());
}
#[test]
fn the_wrong_password_or_no_key_fails_clearly() {
let p = pw("right");
let bytes = write(&sample(), &key(&p), FAST).unwrap();
assert_eq!(read(&bytes, &key(&pw("wrong"))), Err(Error::WrongKey));
assert_eq!(read(&bytes, &Key::default()), Err(Error::NoKey));
// An empty password is no password.
assert_eq!(read(&bytes, &key(&pw(""))), Err(Error::NoKey));
let e = read(&bytes, &key(&pw("Typed-Attempt-9"))).unwrap_err().to_string();
assert!(!e.contains("Typed-Attempt-9") && !e.contains("right"), "{e}");
}
fn xml_v2(key: &[u8; 32]) -> Vec<u8> {
let hex: String = key.iter().map(|b| format!("{b:02X}")).collect();
let hash: String = Sha256::digest(key)[..4].iter().map(|b| format!("{b:02X}")).collect();
let (a, b) = hex.split_at(32);
format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<KeyFile>\n\t<Meta>\n\t\t<Version>2.0</Version>\n\t</Meta>\n\t<Key>\n\t\t<Data Hash=\"{hash}\">\n\t\t\t{a}\n\t\t\t{b}\n\t\t</Data>\n\t</Key>\n</KeyFile>\n"
)
.into_bytes()
}
#[test]
fn every_key_file_kind_works_alone_and_with_a_password() {
let raw: [u8; 32] = core::array::from_fn(|i| (i * 7 + 3) as u8);
let hex: Vec<u8> = raw.iter().map(|b| format!("{b:02x}")).collect::<String>().into_bytes();
let v1 = format!(
"<?xml version=\"1.0\" encoding=\"utf-8\"?><KeyFile><Meta><Version>1.00</Version></Meta><Key><Data>{}</Data></Key></KeyFile>",
data_encoding::BASE64.encode(&raw)
)
.into_bytes();
// These four are the same 32-byte key written four ways: each opens what another wrote.
let same = [raw.to_vec(), hex, xml_v2(&raw), v1];
let p = pw("pw");
for with_pw in [false, true] {
fn k<'a>(p: Option<&'a SecretString>, f: &'a [u8]) -> Key<'a> {
Key { password: p, key_file: Some(f) }
}
let p = with_pw.then_some(&p);
let bytes = write(&sample(), &k(p, &same[0]), FAST).unwrap();
for f in &same {
assert_eq!(read(&bytes, &k(p, f)).unwrap(), sample());
}
assert_eq!(read(&bytes, &k(p, b"another file")), Err(Error::WrongKey));
if let Some(p) = p {
assert_eq!(read(&bytes, &key(p)), Err(Error::WrongKey), "the key file is needed too");
}
}
// Any other file is hashed.
let photo = b"\x89PNG not really a key file, just some bytes".to_vec();
let bytes = write(&sample(), &Key { password: None, key_file: Some(&photo) }, FAST).unwrap();
assert!(read(&bytes, &Key { password: None, key_file: Some(&photo) }).is_ok());
// A version 2.0 key file with a wrong checksum is refused, not guessed.
let mut bad = xml_v2(&raw);
let at = bad.windows(6).position(|w| w == b"Hash=\"").unwrap() + 6;
bad[at] = if bad[at] == b'0' { b'1' } else { b'0' };
assert_eq!(
write(&sample(), &Key { password: None, key_file: Some(&bad) }, FAST),
Err(Error::Malformed("key file checksum"))
);
}
/// Where the parts of a file written with FAST start: header end, then the 64 bytes of hash + HMAC.
fn header_len(bytes: &[u8]) -> usize {
let mut pos = 12;
loop {
let id = bytes[pos];
let len = u32::from_le_bytes(bytes[pos + 1..pos + 5].try_into().unwrap()) as usize;
pos += 5 + len;
if id == 0 {
return pos;
}
}
}
#[test]
fn changing_any_byte_fails_and_never_panics() {
let p = pw("pw");
let small = Database { name: "x".into(), ..Default::default() };
let bytes = write(&small, &key(&p), FAST).unwrap();
let h = header_len(&bytes);
for i in 0..bytes.len() {
let mut b = bytes.clone();
b[i] ^= 0x01;
let r = read(&b, &key(&p));
assert!(r.is_err(), "byte {i} of {} changed and the file still opened", bytes.len());
let e = r.unwrap_err();
if (12..h).contains(&i) || (h..h + 32).contains(&i) {
// Header or its hash: caught by the hash (or the field structure) before any key work.
assert!(matches!(e, Error::Corrupted | Error::Malformed(_) | Error::NotKdbx), "byte {i}: {e:?}");
} else if (h + 32..h + 64).contains(&i) {
assert_eq!(e, Error::WrongKey, "byte {i} (header HMAC)");
} else if i >= h + 64 {
assert_eq!(e, Error::Corrupted, "byte {i} (blocks)");
}
}
}
#[test]
fn truncation_at_any_point_fails() {
let p = pw("pw");
let bytes = write(&Database::default(), &key(&p), FAST).unwrap();
for len in 0..bytes.len() {
assert!(read(&bytes[..len], &key(&p)).is_err(), "truncated to {len}");
}
}
#[test]
fn not_kdbx_kdbx3_and_future_versions() {
let p = pw("pw");
assert_eq!(read(b"", &key(&p)), Err(Error::NotKdbx));
assert_eq!(read(b"PK\x03\x04 a zip file", &key(&p)), Err(Error::NotKdbx));
let mut kdb1 = vec![0x03, 0xD9, 0xA2, 0x9A, 0x65, 0xFB, 0x4B, 0xB5];
kdb1.extend([0; 120]);
assert_eq!(read(&kdb1, &key(&p)), Err(Error::NotKdbx));
let good = write(&Database::default(), &key(&p), FAST).unwrap();
let with_version = |minor: u16, major: u16| {
let mut b = good.clone();
b[8..10].copy_from_slice(&minor.to_le_bytes());
b[10..12].copy_from_slice(&major.to_le_bytes());
b
};
assert_eq!(read(&with_version(1, 2), &key(&p)), Err(Error::UnsupportedVersion(2, 1)));
assert_eq!(read(&with_version(0, 5), &key(&p)), Err(Error::UnsupportedVersion(5, 0)));
// KDBX 4.1 reads like 4.0 (only the header hash notices the changed version bytes).
let v41 = with_version(1, 4);
assert_eq!(read(&v41, &key(&p)), Err(Error::Corrupted));
}
/// Replaces the cipher id in a file and fixes the header hash, so only the cipher is wrong.
fn with_cipher(bytes: &[u8], id: [u8; 16]) -> Vec<u8> {
let mut b = bytes.to_vec();
assert_eq!(b[12], 2, "the cipher is the first field");
b[17..33].copy_from_slice(&id);
let h = header_len(&b);
let hash = Sha256::digest(&b[..h]);
b[h..h + 32].copy_from_slice(&hash);
b
}
#[test]
fn twofish_and_unknown_ciphers_are_refused() {
let p = pw("pw");
let bytes = write(&Database::default(), &key(&p), FAST).unwrap();
let twofish = 0xad68f29f_576f_4bb9_a36a_d47af965346cu128.to_be_bytes();
assert_eq!(read(&with_cipher(&bytes, twofish), &key(&p)), Err(Error::UnsupportedCipher));
assert_eq!(read(&with_cipher(&bytes, [0; 16]), &key(&p)), Err(Error::UnsupportedCipher));
}
#[test]
fn kdf_parameters_out_of_limits_are_refused_before_any_work() {
let p = pw("pw");
let inner = testing::inner(3, b"<KeePassFile/>");
let t = [0u8; 32];
let start = std::time::Instant::now();
for dict in [
testing::argon2_dict(true, 4 << 30, 1, 1, 0x13), // 4 GiB
testing::argon2_dict(true, (64 << 10) + 1, 1, 1, 0x13), // not whole KiB
testing::argon2_dict(true, 64 << 10, 1001, 1, 0x13),
testing::argon2_dict(true, 64 << 10, 0, 1, 0x13),
testing::argon2_dict(false, 64 << 10, 1, 0, 0x13),
testing::argon2_dict(false, 64 << 10, 1, 65, 0x13),
testing::argon2_dict(false, 64 << 10, 1, 1, 0x10), // Argon2 version 1.0
testing::aes_dict(1 << 31),
testing::aes_dict(0),
] {
assert_eq!(read(&testing::build(&dict, &t, &inner, true), &key(&p)), Err(Error::UnsupportedKdf));
}
assert!(start.elapsed().as_secs() < 5, "the limits are checked before Argon2 or AES-KDF runs");
}
/// A file that opens with password "pw" (AES-KDF, 1 round) around this inner XML.
fn file_around(xml: &[u8], stream: u32) -> Vec<u8> {
testing::build(&testing::aes_dict(1), &testing::aes_transformed("pw", 1), &testing::inner(stream, xml), true)
}
#[test]
fn the_test_builder_itself_makes_files_that_open() {
let xml =
b"<KeePassFile><Root><Group><UUID>AAAAAAAAAAAAAAAAAAAAAA==</UUID><Name>R</Name></Group></Root></KeePassFile>";
let db = read(&file_around(xml, 3), &key(&pw("pw"))).unwrap();
assert_eq!(db.root.name, "R");
}
#[test]
fn doctype_and_entity_tricks_are_refused() {
let laughs = br#"<?xml version="1.0"?>
<!DOCTYPE lolz [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">]>
<KeePassFile><Meta><DatabaseName>&lol2;</DatabaseName></Meta></KeePassFile>"#;
assert_eq!(read(&file_around(laughs, 3), &key(&pw("pw"))), Err(Error::Malformed("XML with a DOCTYPE")));
let xxe =
br#"<?xml version="1.0"?><!DOCTYPE x [<!ENTITY e SYSTEM "file:///etc/passwd">]><KeePassFile>&e;</KeePassFile>"#;
assert_eq!(read(&file_around(xxe, 3), &key(&pw("pw"))), Err(Error::Malformed("XML with a DOCTYPE")));
}
#[test]
fn deep_nesting_and_broken_xml_are_refused() {
let mut deep = b"<KeePassFile><Root>".to_vec();
for _ in 0..300 {
deep.extend_from_slice(b"<Group><UUID>AAAAAAAAAAAAAAAAAAAAAA==</UUID>");
}
for _ in 0..300 {
deep.extend_from_slice(b"</Group>");
}
deep.extend_from_slice(b"</Root></KeePassFile>");
assert_eq!(read(&file_around(&deep, 3), &key(&pw("pw"))), Err(Error::Malformed("groups nested too deeply")));
for bad in [&b"<KeePassFile><Root>"[..], b"not xml", b"\xff\xfe", b"<Other/>"] {
assert!(matches!(read(&file_around(bad, 3), &key(&pw("pw"))), Err(Error::Malformed(_))));
}
// A protected value that is not base64, and an attachment reference to nothing.
let bad_value = b"<KeePassFile><Root><Group><Entry><String><Key>Password</Key><Value Protected=\"True\">!!</Value></String></Entry></Group></Root></KeePassFile>";
assert_eq!(read(&file_around(bad_value, 3), &key(&pw("pw"))), Err(Error::Malformed("protected value")));
let bad_ref = b"<KeePassFile><Root><Group><Entry><Binary><Key>a</Key><Value Ref=\"7\"/></Binary></Entry></Group></Root></KeePassFile>";
assert_eq!(read(&file_around(bad_ref, 3), &key(&pw("pw"))), Err(Error::Malformed("attachment")));
}
#[test]
fn salsa20_inner_stream_is_refused() {
let xml = b"<KeePassFile/>";
assert_eq!(read(&file_around(xml, 2), &key(&pw("pw"))), Err(Error::UnsupportedStream));
assert_eq!(read(&file_around(xml, 0), &key(&pw("pw"))), Err(Error::UnsupportedStream));
}
#[test]
fn a_gzip_bomb_stops_at_the_limit() {
// 600 MiB of zeros, compressed: a few hundred KiB on disk.
use flate2::{Compression, write::GzEncoder};
use std::io::Write;
let mut gz = GzEncoder::new(Vec::new(), Compression::fast());
let zeros = vec![0u8; 1 << 20];
gz.write_all(&testing::inner(3, b"")).unwrap();
for _ in 0..600 {
gz.write_all(&zeros).unwrap();
}
let bomb = gz.finish().unwrap();
assert!(bomb.len() < 4 << 20);
let file = testing::build_compressed(&testing::aes_dict(1), &testing::aes_transformed("pw", 1), &bomb);
assert_eq!(read(&file, &key(&pw("pw"))), Err(Error::TooLarge));
}
#[test]
fn no_secret_in_debug_output() {
let db = sample();
let p = pw("Master-Password-Here");
let file = [7u8; 32];
let k = Key { password: Some(&p), key_file: Some(&file) };
for out in [format!("{db:?}"), format!("{db:#?}"), format!("{k:?}"), format!("{:?}", Error::WrongKey)] {
for leaked in [
"Hunter2-Secret-Value",
"Protected-Recovery-Code",
"Old-Secret-Value",
"Attached-Key",
"Master-Password-Here",
] {
assert!(!out.contains(leaked), "{leaked} in {out}");
}
}
assert!(format!("{db:?}").contains("Internet"), "non-secret parts stay readable");
}
+87
View File
@@ -0,0 +1,87 @@
//! Files KeePassXC wrote open with what tools/kdbx/sample.xml put in them (docs/KDBX.md, "Tests").
use custos_kdbx::{Error, Key, SecretString, read, to_items};
use custos_vault::{Item, ItemType};
include!("data/keepassxc_files.rs");
fn bytes(b64: &str) -> Vec<u8> {
let clean: String = b64.split_whitespace().collect();
data_encoding::BASE64.decode(clean.as_bytes()).unwrap()
}
fn open(b64: &str) -> custos_kdbx::Database {
let p = SecretString::from("custos-test");
read(&bytes(b64), &Key { password: Some(&p), key_file: None }).unwrap()
}
fn field<'a>(item: &'a Item, name: &str) -> Vec<&'a str> {
item.fields.iter().filter(|f| f.name == name).map(|f| f.value.expose()).collect()
}
fn check(items: &[Item]) {
let by = |title: &str| items.iter().find(|i| i.title == title).unwrap_or_else(|| panic!("no {title}"));
let gh = by("GitHub");
assert_eq!(gh.id, "11".repeat(16));
assert_eq!(gh.kind, ItemType::WebLogin);
assert_eq!(gh.folder, ["Internet"]);
assert_eq!(field(gh, "username"), ["alice"]);
assert_eq!(field(gh, "password"), ["Hunter3-Current & <ok>"]);
assert_eq!(field(gh, "url"), ["https://github.com", "https://gist.github.com", "https://api.github.com"]);
assert!(field(gh, "totp")[0].starts_with("otpauth://totp/GitHub:alice?secret=JBSWY3DPEHPK3PXP"));
assert_eq!(field(gh, "Recovery codes"), ["Recovery-Secret-123"]);
assert!(gh.field("Recovery codes").unwrap().secret, "protected in KeePass, secret in Custos");
assert_eq!(field(gh, "Account id"), ["42"]);
assert!(!gh.field("Account id").unwrap().secret);
assert_eq!(field(gh, "expires"), ["2030-01-01"]);
assert_eq!(field(gh, "autotype-sequence"), ["{USERNAME}{TAB}{PASSWORD}{ENTER}"]);
assert_eq!(field(gh, "autotype-match"), ["*GitHub*", "Firefox - GitHub"]);
assert_eq!(gh.notes.expose(), "Line one\nLine two & <three>");
assert_eq!(gh.tags, ["dev", "work"]);
assert_eq!(gh.created, 1_682_935_200_000); // 2023-05-01T10:00:00Z
assert_eq!(gh.modified, 1_769_938_200_000); // 2026-02-01T09:30:00Z
let history: Vec<(&str, i64)> = gh.history.iter().map(|h| (h.value.expose(), h.changed)).collect();
assert_eq!(history, [("Hunter1-Oldest", 1_704_096_000_000), ("Hunter2-Old", 1_735_718_400_000)]);
assert!(gh.history.iter().all(|h| h.field == "password"));
assert_eq!(gh.attachments.len(), 1);
assert_eq!(gh.attachments[0].name, "codes.txt");
assert_eq!(gh.attachments[0].data.expose(), b"Backup codes:\n1111-2222\n3333-4444\n");
let mail = by("Mail");
assert_eq!(mail.folder, ["Internet", "Mail"]);
assert_eq!(field(mail, "totp"), ["otpauth://totp/Mail?secret=JBSWY3DPEHPK3PXP&period=60&digits=8"]);
let note = by("Alarm code");
assert_eq!(note.kind, ItemType::SecureNote, "no user name, password or URL");
assert!(note.folder.is_empty());
assert_eq!(note.notes.expose(), "Front door: 4711");
}
#[test]
fn keepassxc_kdbx_3_1_with_a_recycle_bin() {
let db = open(V3);
assert_eq!(db.name, "Custos interop");
assert!(db.recycle_bin.is_some());
let items = to_items(&db);
check(&items);
assert_eq!(items.len(), 3, "the recycle bin's entry is not imported");
assert!(items.iter().all(|i| i.title != "Old account"));
}
#[test]
fn keepassxc_kdbx_4() {
let db = open(V4);
let items = to_items(&db);
check(&items);
// This file's recycle bin is switched off, so the merged "Recycle Bin" is an ordinary group.
assert!(items.iter().any(|i| i.title == "Old account" && i.folder == ["Recycle Bin"]));
}
#[test]
fn keepassxc_files_refuse_the_wrong_password() {
let wrong = SecretString::from("custos-test ");
for f in [V3, V4] {
assert_eq!(read(&bytes(f), &Key { password: Some(&wrong), key_file: None }), Err(Error::WrongKey));
}
}
+262
View File
@@ -0,0 +1,262 @@
//! Custos items ↔ KeePass entries (docs/KDBX.md, "Mapping").
use custos_kdbx::{
AutoType, Cipher, Database, Entry, Group, Kdf, Key, SecretBytes, SecretString, StringField, Times, WriteOptions,
from_items, read, to_items, write,
};
use custos_vault::{Attachment, Field, Item, ItemType};
const FAST: WriteOptions = WriteOptions { cipher: Cipher::ChaCha20, kdf: Kdf::Argon2id { m_kib: 64, t: 1, p: 1 } };
const T: i64 = 1_790_000_000_000; // whole seconds: KeePass keeps seconds
fn through_a_file(items: &[Item]) -> Vec<Item> {
let p = SecretString::from("pw");
let key = Key { password: Some(&p), key_file: None };
let bytes = write(&from_items(items, "Custos"), &key, FAST).unwrap();
to_items(&read(&bytes, &key).unwrap())
}
fn every_type() -> Vec<Item> {
let mut login = Item::new(ItemType::WebLogin, "GitHub", T);
login.set("username", "alice", T);
login.set("password", "First-Pass-1", T);
login.set("password", "Second-Pass-2", T + 1000);
login.set("password", "Current-Pass-3", T + 2000);
login.set("url", "https://github.com", T);
login.set("totp", "JBSWY3DPEHPK3PXP", T);
login.set("autotype-match", "*GitHub*", T);
login.set("autotype-sequence", "{USERNAME}{TAB}{PASSWORD}{ENTER}", T);
login.add_field(Field::text("url", "https://gist.github.com"));
login.add_field(Field::text("url", "https://api.github.com"));
login.add_field(Field::secret("Recovery code", "Recovery-1234"));
login.add_field(Field::text("Account", ""));
login.add_field(Field::text("expires", "2031-06-30T12:00:00Z"));
login.add_field(Field::text("autotype-match", "Firefox - GitHub"));
login.tags = vec!["dev".into(), "work".into()];
login.notes = "line one\r\nline <two> & \"three\"".into();
login.folder = vec!["Internet".into(), "Code".into()];
login.modified = T + 2000;
let mut api = Item::new(ItemType::ApiCredential, "Stripe", T);
for (k, v) in
[("service", "Stripe"), ("key-id", "pk_live_1"), ("secret", "sk-Old"), ("endpoint", "https://api.stripe.com")]
{
api.set(k, v, T);
}
api.set("secret", "sk-New", T + 5000);
api.set("expires", "2027-01-31", T);
let mut app = Item::new(ItemType::LocalApp, "Backup tool", T);
for (k, v) in [("target", "restic"), ("username", "backup"), ("password", "Restic-Pass")] {
app.set(k, v, T);
}
let mut wifi = Item::new(ItemType::Wifi, "Home", T);
for (k, v) in [("ssid", "Domi"), ("password", "Wifi-Pass"), ("security", "WPA"), ("hidden", "false")] {
wifi.set(k, v, T);
}
let mut note = Item::new(ItemType::SecureNote, "Keys", T);
note.notes = "the spare key is with the neighbours".into();
note.attachments =
vec![Attachment { name: "id_ed25519".into(), data: SecretBytes::from(&b"\x00\xffkey bytes"[..]) }];
note.folder = vec!["Home".into()];
let mut card = Item::new(ItemType::Card, "Visa", T);
for (k, v) in [
("cardholder", "A N Other"),
("number", "4111111111111111"),
("expiry", "12/29"),
("cvv", "123"),
("pin", "0000"),
] {
card.set(k, v, T);
}
// Two secret fields changed at the same moment: one KeePass snapshot.
card.set("number", "4000000000000002", T + 9000);
card.set("cvv", "456", T + 9000);
let mut pair = Item::new(ItemType::KeyPair, "Signing key", T);
for (k, v) in [
("algorithm", "ed25519"),
("public-key", "ssh-ed25519 AAAA… me"),
("private-key", "-----BEGIN PRIVATE KEY-----\nMC4…\n-----END PRIVATE KEY-----\n"),
] {
pair.set(k, v, T);
}
let empty: Vec<Item> = ItemType::ALL.into_iter().map(|k| Item::new(k, &format!("empty {k:?}"), T)).collect();
[vec![login, api, app, wifi, note, card, pair], empty].concat()
}
#[test]
fn every_item_type_survives_export_and_import() {
let items = every_type();
let back = through_a_file(&items);
assert_eq!(back.len(), items.len());
// Items come back folder by folder (root first), so match them by id.
for a in &items {
let b = back.iter().find(|b| b.id == a.id).unwrap_or_else(|| panic!("{} is missing", a.title));
assert_eq!(a, b, "{}", a.title);
for (fa, fb) in a.fields.iter().zip(&b.fields) {
assert_eq!(fa.value, fb.value, "{} / {}", a.title, fa.name);
}
assert_eq!(a.notes, b.notes, "{}", a.title);
}
}
#[test]
fn the_export_looks_like_keepass_to_keepassxc() {
let db = from_items(&every_type(), "Custos");
let internet = db.root.groups.iter().find(|g| g.name == "Internet").unwrap();
let gh = &internet.groups[0].entries[0];
assert_eq!(internet.groups[0].name, "Code");
let get = |e: &Entry, k: &str| e.get(k).map(|v| v.expose().to_owned());
assert_eq!(get(gh, "UserName").as_deref(), Some("alice"));
assert_eq!(get(gh, "URL").as_deref(), Some("https://github.com"));
assert_eq!(get(gh, "KP2A_URL").as_deref(), Some("https://gist.github.com"));
assert_eq!(get(gh, "KP2A_URL_1").as_deref(), Some("https://api.github.com"));
assert_eq!(get(gh, "otp").as_deref(), Some("JBSWY3DPEHPK3PXP"));
assert!(gh.strings.iter().find(|s| s.key == "Password").unwrap().protected);
assert!(gh.strings.iter().find(|s| s.key == "Recovery code").unwrap().protected);
assert!(gh.get("custos-type").is_none(), "a login looks like a login without help");
assert_eq!(gh.times.expires, custos_kdbx::parse_iso("2031-06-30T12:00:00Z"));
assert_eq!(gh.autotype.windows, ["*GitHub*", "Firefox - GitHub"]);
// Two password changes: two snapshots, oldest first, each with the password it had then.
let old: Vec<String> = gh.history.iter().map(|h| h.get("Password").unwrap().expose().to_owned()).collect();
assert_eq!(old, ["First-Pass-1", "Second-Pass-2"]);
let entry = |title: &str| {
fn find<'a>(g: &'a Group, t: &str) -> Option<&'a Entry> {
g.entries
.iter()
.find(|e| e.get("Title").unwrap().expose() == t)
.or_else(|| g.groups.iter().find_map(|s| find(s, t)))
}
find(&db.root, title).unwrap()
};
let api = entry("Stripe");
assert_eq!(api.get("custos-type").unwrap().expose(), "api-credential");
assert_eq!(api.get("Password").unwrap().expose(), "sk-New");
assert_eq!(api.times.expires, custos_kdbx::parse_iso("2027-01-31"));
let card = entry("Visa");
assert_eq!(card.get("UserName").unwrap().expose(), "A N Other");
assert_eq!(card.get("Password").unwrap().expose(), "4000000000000002");
assert!(card.strings.iter().find(|s| s.key == "cvv").unwrap().protected);
assert_eq!(card.history.len(), 1, "both changes in one snapshot");
assert_eq!(card.history[0].get("cvv").unwrap().expose(), "123");
assert_eq!(card.history[0].get("Password").unwrap().expose(), "4111111111111111");
assert_eq!(entry("Home").get("UserName").unwrap().expose(), "Domi", "Wi-Fi: SSID as the user name");
assert!(entry("Keys").get("custos-type").is_none(), "a note looks like a note");
// Empty template fields stay out; Custos's own type and template names come back as custom strings.
assert!(entry("empty ApiCredential").get("key-id").is_none());
}
fn s(key: &str, value: &str, protected: bool) -> StringField {
StringField { key: key.into(), value: value.into(), protected }
}
#[test]
fn a_keepass_database_maps_as_the_table_says() {
let entry = |n: u8, strings: Vec<StringField>| Entry {
uuid: [n; 16],
strings,
times: Times { created: 1_700_000_000, modified: 1_700_000_500, expires: None },
..Default::default()
};
let mut login = entry(
1,
vec![
s("Notes", "n", false),
s("KP2A_URL_2", "https://three.example", false),
s("KP2A_URL", "https://two.example", false),
s("Password", "Now-1", true),
s("PIN", "9999", true),
s("Title", "Bank", false),
s("TOTP Seed", "JBSW Y3DP EHPK 3PXP", true),
s("URL", "https://one.example", false),
s("UserName", "me", false),
],
);
login.tags = vec!["money".into(), "important".into()];
login.autotype = AutoType { default_sequence: "{PASSWORD}{ENTER}".into(), windows: vec![] };
// Snapshots: the PIN changed first, then the password; the last one changed nothing secret.
login.history = vec![
entry(1, vec![s("Title", "Bank", false), s("Password", "Old-1", true), s("PIN", "1111", true)]),
entry(1, vec![s("Title", "Bank", false), s("Password", "Old-1", true), s("PIN", "9999", true)]),
entry(1, vec![s("Title", "Bank renamed", false), s("Password", "Now-1", true), s("PIN", "9999", true)]),
];
for (i, h) in login.history.iter_mut().enumerate() {
h.times.modified = 1_700_000_100 + i as i64 * 100;
}
let only_custom = entry(2, vec![s("Title", "Licence", false), s("Licence key", "ABCD-EFGH", true)]);
let binned = entry(3, vec![s("Title", "Deleted", false), s("Password", "x", true)]);
let db = Database {
name: "KeePass".into(),
root: Group {
uuid: [9; 16],
name: "Root".into(),
entries: vec![only_custom],
groups: vec![
Group { uuid: [8; 16], name: "Banking".into(), entries: vec![login], groups: vec![] },
Group { uuid: [7; 16], name: "Recycle Bin".into(), entries: vec![binned], groups: vec![] },
],
},
recycle_bin: Some([7; 16]),
};
let items = to_items(&db);
assert_eq!(items.len(), 2, "nothing from the recycle bin");
let licence = &items[0];
assert_eq!(licence.kind, ItemType::SecureNote);
assert_eq!(licence.fields, [Field::secret("Licence key", "ABCD-EFGH")]);
let bank = &items[1];
assert_eq!(bank.kind, ItemType::WebLogin);
assert_eq!(bank.id, "01".repeat(16));
assert_eq!(bank.folder, ["Banking"]);
assert_eq!(bank.tags, ["money", "important"]);
let f = |name: &str| bank.fields.iter().filter(|f| f.name == name).map(|f| f.value.expose()).collect::<Vec<_>>();
assert_eq!(f("url"), ["https://one.example", "https://two.example", "https://three.example"]);
assert_eq!(f("totp"), ["JBSWY3DPEHPK3PXP"], "default settings: the bare seed, spaces removed");
assert_eq!(f("PIN"), ["9999"]);
assert_eq!(f("autotype-sequence"), ["{PASSWORD}{ENTER}"]);
let h: Vec<(&str, &str, i64)> =
bank.history.iter().map(|h| (h.field.as_str(), h.value.expose(), h.changed)).collect();
assert_eq!(h, [("PIN", "1111", 1_700_000_100_000), ("password", "Old-1", 1_700_000_200_000)]);
assert_eq!(bank.created, 1_700_000_000_000);
assert_eq!(bank.modified, 1_700_000_500_000);
}
#[test]
fn field_names_keepass_reserves_are_renamed_not_lost() {
let mut item = Item::new(ItemType::WebLogin, "Odd", T);
item.add_field(Field::text("Title", "a field called Title"));
item.add_field(Field::secret("custos-type", "not a type"));
item.add_field(Field::text("KP2A_URL", "not a URL"));
let db = from_items(&[item], "x");
let e = &db.root.entries[0];
assert_eq!(e.get("Title").unwrap().expose(), "Odd");
assert_eq!(e.get("Title (2)").unwrap().expose(), "a field called Title");
assert_eq!(e.get("custos-type (2)").unwrap().expose(), "not a type");
assert_eq!(e.get("KP2A_URL (2)").unwrap().expose(), "not a URL");
let keys: Vec<&str> = e.strings.iter().map(|s| s.key.as_str()).collect();
let mut unique = keys.clone();
unique.sort();
unique.dedup();
assert_eq!(keys.len(), unique.len(), "keys are unique: {keys:?}");
}
#[test]
fn ids_survive_and_bad_ids_get_a_fresh_uuid() {
let mut a = Item::new(ItemType::SecureNote, "a", T);
a.id = "00112233445566778899aabbccddeeff".into();
let mut b = Item::new(ItemType::SecureNote, "b", T);
b.id = "not hex".into();
let db = from_items(&[a, b], "x");
assert_eq!(
db.root.entries[0].uuid,
[0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]
);
assert_ne!(db.root.entries[1].uuid, [0; 16]);
}
+17
View File
@@ -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"] }
+223
View File
@@ -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())
}
+7
View File
@@ -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-----
+111
View File
@@ -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}");
}
}
+16
View File
@@ -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
+180
View File
@@ -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()
}
+74
View File
@@ -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));
}
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "custos-sign"
description = "Custos Domi: release signatures without the key leaving the vault (minisign, SHA256SUMS, Authenticode digests) and the household CA"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
thiserror.workspace = true
zeroize.workspace = true
data-encoding.workspace = true
# The RustCrypto generation custos-keys already uses (digest 0.10, signature 2).
ed25519-dalek = "2"
rsa = { version = "0.9", default-features = false, features = ["sha2", "u64_digit"] }
sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] }
blake2 = "0.10"
x509-cert = { version = "0.2.5", features = ["builder"] }
# rsa 0.9 generates keys through rand_core 0.6; the bytes come from `rand`'s SysRng (lib.rs, `OsRng06`).
rand_core = "0.6"
rand.workspace = true
[dev-dependencies]
minisign-verify = "0.3"
x509-cert = { version = "0.2.5", features = ["builder"] }
rsa = { version = "0.9", features = ["sha2"] }
sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] }
+53
View File
@@ -0,0 +1,53 @@
//! For tools/signing/interop.ps1 only: makes **throwaway test keys** in a temp folder and signs with them, so the
//! real minisign, signtool and osslsigncode can check what this crate produces. The vault never does this: there,
//! keys are made inside the vault and only signatures come out.
//!
//! interop ca <dir> root.cer, root.pem, leaf.cer, leaf.key.der (test only)
//! interop authenticode <leaf.key.der> <file.dig> writes <file.dig>.signed
//! interop minisign <dir> <file> <dir>/minisign.pub, <file>.minisig
//! interop manifest <dir> <SHA256SUMS> <SHA256SUMS>.minisig, with the key in <dir>
use std::fs;
use std::path::Path;
use custos_sign::*;
use data_encoding::BASE64;
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let arg = |i: usize| args.get(i).map(String::as_str).expect("missing argument");
match arg(0) {
"ca" => {
let dir = Path::new(arg(1));
fs::create_dir_all(dir).unwrap();
let root = new_root("Domi Interop Test Root", 1).unwrap();
let leaf = new_code_signing("Domi Interop Test Signing", 1, &root.secret, &root.cert_der).unwrap();
fs::write(dir.join("root.cer"), &root.cert_der).unwrap();
fs::write(dir.join("root.pem"), cert_pem(&root.cert_der)).unwrap();
fs::write(dir.join("leaf.cer"), &leaf.cert_der).unwrap();
fs::write(dir.join("leaf.key.der"), leaf.secret.expose()).unwrap();
}
"authenticode" => {
let key = RsaSecret::from_pkcs8_der(fs::read(arg(1)).unwrap()).unwrap();
let dig = fs::read_to_string(arg(2)).unwrap();
let digest = BASE64.decode(dig.trim().as_bytes()).unwrap();
let sig = authenticode(&key, &digest).unwrap();
fs::write(format!("{}.signed", arg(2)), BASE64.encode(&sig)).unwrap();
}
"minisign" | "manifest" => {
let dir = Path::new(arg(1));
let file = Path::new(arg(2));
let key = new_ed25519();
fs::write(dir.join("minisign.pub"), minisign_public(&key.public, &key.key_id)).unwrap();
let data = fs::read(file).unwrap();
let name = file.file_name().unwrap().to_str().unwrap();
let sig = if arg(0) == "manifest" {
manifest(&key.secret, &key.key_id, std::str::from_utf8(&data).unwrap(), 1_793_750_000).unwrap()
} else {
minisign(&key.secret, &key.key_id, &blake2b512(&data), name, 1_793_750_000).unwrap()
};
fs::write(format!("{}.minisig", file.display()), sig).unwrap();
}
other => panic!("unknown command {other}"),
}
}
+362
View File
@@ -0,0 +1,362 @@
//! Custos Domi · signing: the signature formats docs/SIGNING.md describes, over digests, so the file never has to
//! reach the vault and the key never has to leave it.
//!
//! - minisign (prehashed `ED`, what minisign and Tauri's updater verify) over a BLAKE2b-512 digest;
//! - a canonical `SHA256SUMS` manifest, checked here and signed as minisign;
//! - Authenticode: RSA PKCS#1 v1.5 over the 32-byte digest `signtool sign /dg` writes;
//! - the household CA: a self-signed RSA-3072 root and a code-signing leaf it issues (X.509 v3).
//!
//! Secret keys are [`Ed25519Secret`] and [`RsaSecret`]: zeroized on drop, printed as `[redacted]`.
use std::fmt;
use std::str::FromStr;
use std::time::Duration;
use blake2::{Blake2b512, Digest};
use data_encoding::BASE64;
use ed25519_dalek::{Signer as _, SigningKey};
use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use rsa::RsaPrivateKey;
use rsa::pkcs1v15;
use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey, EncodePublicKey};
use rsa::signature::hazmat::PrehashSigner;
use sha2_010::Sha256;
use x509_cert::Certificate;
use x509_cert::builder::{Builder, CertificateBuilder, Profile};
use x509_cert::der::{Decode, Encode};
use x509_cert::ext::pkix::ExtendedKeyUsage;
use x509_cert::name::Name;
use x509_cert::serial_number::SerialNumber;
use x509_cert::spki::SubjectPublicKeyInfoOwned;
use x509_cert::time::Validity;
use zeroize::Zeroizing;
/// Authenticode's code-signing purpose (RFC 5280 id-kp-codeSigning).
const CODE_SIGNING: x509_cert::der::oid::ObjectIdentifier =
x509_cert::der::oid::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.3");
const RSA_BITS: usize = 3072;
const DAY: u64 = 24 * 60 * 60;
/// The largest manifest Custos signs (docs/SIGNING.md).
pub const MAX_MANIFEST: usize = 32 * 1024;
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum Error {
#[error("the digest must be {0} bytes")]
DigestLength(usize),
#[error("the file name cannot be used in a signature: {0}")]
FileName(&'static str),
#[error("the manifest is not in canonical SHA256SUMS form: line {line}: {why}")]
Manifest { line: usize, why: &'static str },
#[error("the key cannot be read")]
BadKey,
#[error("the certificate cannot be built or read")]
Certificate,
}
/// An Ed25519 seed. Wiped on drop; never printed.
pub struct Ed25519Secret(Zeroizing<[u8; 32]>);
impl Ed25519Secret {
pub fn from_bytes(seed: [u8; 32]) -> Self {
Ed25519Secret(Zeroizing::new(seed))
}
/// The seed, for storing in the vault body. Only the vault calls this.
pub fn expose(&self) -> &[u8; 32] {
&self.0
}
pub fn public(&self) -> [u8; 32] {
SigningKey::from_bytes(&self.0).verifying_key().to_bytes()
}
}
impl fmt::Debug for Ed25519Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
/// An RSA private key as PKCS#8 DER. Wiped on drop; never printed.
pub struct RsaSecret(Zeroizing<Vec<u8>>);
impl RsaSecret {
pub fn from_pkcs8_der(der: Vec<u8>) -> Result<Self, Error> {
let der = Zeroizing::new(der);
RsaPrivateKey::from_pkcs8_der(&der).map_err(|_| Error::BadKey)?;
Ok(RsaSecret(der))
}
/// The PKCS#8 DER, for storing in the vault body. Only the vault calls this.
pub fn expose(&self) -> &[u8] {
&self.0
}
fn key(&self) -> Result<RsaPrivateKey, Error> {
RsaPrivateKey::from_pkcs8_der(&self.0).map_err(|_| Error::BadKey)
}
}
impl fmt::Debug for RsaSecret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
/// Fills `buf` from the OS CSPRNG through `rand`'s `SysRng`, as the rest of the workspace does (the browser build
/// routes it to `crypto.getRandomValues`).
fn fill(buf: &mut [u8]) {
rand::Rng::fill_bytes(&mut UnwrapErr(SysRng), buf);
}
/// rand_core 0.6's interface, which `rsa` 0.9 generates keys with, over [`fill`].
struct OsRng06;
impl rand_core::RngCore for OsRng06 {
fn next_u32(&mut self) -> u32 {
let mut b = [0u8; 4];
fill(&mut b);
u32::from_le_bytes(b)
}
fn next_u64(&mut self) -> u64 {
let mut b = [0u8; 8];
fill(&mut b);
u64::from_le_bytes(b)
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
fill(dest);
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
fill(dest);
Ok(())
}
}
impl rand_core::CryptoRng for OsRng06 {}
// ---- minisign ----
/// A new Ed25519 key with a random minisign key id.
pub struct NewEd25519 {
pub secret: Ed25519Secret,
pub public: [u8; 32],
pub key_id: [u8; 8],
}
pub fn new_ed25519() -> NewEd25519 {
let mut seed = Zeroizing::new([0u8; 32]);
fill(&mut *seed);
let mut key_id = [0u8; 8];
fill(&mut key_id);
let secret = Ed25519Secret(seed);
let public = secret.public();
NewEd25519 { secret, public, key_id }
}
/// minisign prints a key id as one little-endian u64 in upper-case hex.
pub fn key_id_hex(key_id: &[u8; 8]) -> String {
format!("{:016X}", u64::from_le_bytes(*key_id))
}
/// The BLAKE2b-512 of `data`: what a prehashed minisign signature signs.
pub fn blake2b512(data: &[u8]) -> [u8; 64] {
Blake2b512::digest(data).into()
}
/// `minisign.pub`: the public key file minisign `-V -p` and Tauri (base64 of it) read.
pub fn minisign_public(public: &[u8; 32], key_id: &[u8; 8]) -> String {
let mut raw = Vec::with_capacity(42);
raw.extend_from_slice(b"Ed");
raw.extend_from_slice(key_id);
raw.extend_from_slice(public);
format!("untrusted comment: minisign public key {}\n{}\n", key_id_hex(key_id), BASE64.encode(&raw))
}
/// A prehashed minisign signature file over a file whose BLAKE2b-512 is `digest`.
/// The trusted comment is `timestamp:<unix seconds>\tfile:<file>\thashed`, as minisign writes it.
pub fn minisign(
secret: &Ed25519Secret,
key_id: &[u8; 8],
digest: &[u8],
file: &str,
timestamp: u64,
) -> Result<String, Error> {
let digest: &[u8; 64] = digest.try_into().map_err(|_| Error::DigestLength(64))?;
check_file_name(file)?;
let key = SigningKey::from_bytes(&secret.0);
let signature = key.sign(digest).to_bytes();
let trusted = format!("timestamp:{timestamp}\tfile:{file}\thashed");
let mut global_msg = Vec::with_capacity(64 + trusted.len());
global_msg.extend_from_slice(&signature);
global_msg.extend_from_slice(trusted.as_bytes());
let global = key.sign(&global_msg).to_bytes();
let mut line = Vec::with_capacity(74);
line.extend_from_slice(b"ED");
line.extend_from_slice(key_id);
line.extend_from_slice(&signature);
Ok(format!(
"untrusted comment: signature from Custos key {}\n{}\ntrusted comment: {trusted}\n{}\n",
key_id_hex(key_id),
BASE64.encode(&line),
BASE64.encode(&global)
))
}
fn check_file_name(file: &str) -> Result<(), Error> {
if file.is_empty() {
return Err(Error::FileName("empty"));
}
if file.len() > 255 {
return Err(Error::FileName("longer than 255 bytes"));
}
if file.chars().any(char::is_control) {
return Err(Error::FileName("control characters"));
}
if file.contains(['/', '\\']) {
return Err(Error::FileName("a path, not a file name"));
}
Ok(())
}
// ---- the SHA256SUMS manifest ----
/// Checks that `text` is a canonical `SHA256SUMS` (docs/SIGNING.md): `<64 lower hex> <name>\n` lines, names
/// without `/`, `\`, control characters or a leading `-`, unique, sorted by bytes, at least one line.
pub fn manifest_check(text: &str) -> Result<(), Error> {
let err = |line: usize, why: &'static str| Err(Error::Manifest { line, why });
if text.len() > MAX_MANIFEST {
return err(0, "larger than 32 KiB");
}
if text.is_empty() {
return err(0, "empty");
}
if !text.ends_with('\n') {
return err(text.lines().count(), "the last line has no newline");
}
let mut prev: Option<&str> = None;
for (i, line) in text.split_terminator('\n').enumerate() {
let n = i + 1;
if line.ends_with('\r') {
return err(n, "CRLF line ending");
}
let Some((hash, name)) = line.split_once(" ") else {
return err(n, "not `<sha256> <name>`");
};
if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
return err(n, "the hash is not 64 lower-case hex digits");
}
if name.is_empty()
|| name.starts_with(['-', ' ', '*'])
|| name.contains(['/', '\\'])
|| name.chars().any(char::is_control)
{
return err(n, "not a plain file name");
}
if prev.is_some_and(|p| p.as_bytes() >= name.as_bytes()) {
return err(n, "names are not sorted and unique");
}
prev = Some(name);
}
Ok(())
}
/// Signs a canonical manifest as minisign (file name `SHA256SUMS`).
pub fn manifest(secret: &Ed25519Secret, key_id: &[u8; 8], text: &str, timestamp: u64) -> Result<String, Error> {
manifest_check(text)?;
minisign(secret, key_id, &blake2b512(text.as_bytes()), "SHA256SUMS", timestamp)
}
// ---- Authenticode ----
/// RSA PKCS#1 v1.5 with the SHA-256 DigestInfo over the 32 bytes of signtool's `.dig` (384 bytes for RSA-3072):
/// what goes, base64-encoded, into `.dig.signed`.
pub fn authenticode(secret: &RsaSecret, digest: &[u8]) -> Result<Vec<u8>, Error> {
if digest.len() != 32 {
return Err(Error::DigestLength(32));
}
let key = pkcs1v15::SigningKey::<Sha256>::new(secret.key()?);
let sig: pkcs1v15::Signature = key.sign_prehash(digest).map_err(|_| Error::BadKey)?;
Ok(Box::<[u8]>::from(sig).into_vec())
}
// ---- the household CA ----
/// A new RSA-3072 key and its certificate.
pub struct NewCert {
pub secret: RsaSecret,
pub cert_der: Vec<u8>,
}
fn new_rsa() -> Result<(RsaPrivateKey, RsaSecret), Error> {
let key = RsaPrivateKey::new(&mut OsRng06, RSA_BITS).map_err(|_| Error::BadKey)?;
let der = key.to_pkcs8_der().map_err(|_| Error::BadKey)?.as_bytes().to_vec();
Ok((key, RsaSecret(Zeroizing::new(der))))
}
fn serial() -> Result<SerialNumber, Error> {
let mut bytes = [0u8; 16];
fill(&mut bytes);
bytes[0] &= 0x7f; // positive
bytes[0] |= 0x01; // and without a leading zero byte
SerialNumber::new(&bytes).map_err(|_| Error::Certificate)
}
fn name(cn: &str) -> Result<Name, Error> {
if cn.is_empty() || cn.len() > 64 || cn.contains([',', '+', '=', '"', '\\', '<', '>', ';', '#']) {
return Err(Error::Certificate);
}
Name::from_str(&format!("CN={cn},O=Domi")).map_err(|_| Error::Certificate)
}
fn spki(key: &RsaPrivateKey) -> Result<SubjectPublicKeyInfoOwned, Error> {
let der = key.to_public_key().to_public_key_der().map_err(|_| Error::Certificate)?;
SubjectPublicKeyInfoOwned::from_der(der.as_bytes()).map_err(|_| Error::Certificate)
}
/// A self-signed root CA, valid for `years` years from now.
pub fn new_root(cn: &str, years: u64) -> Result<NewCert, Error> {
let (key, secret) = new_rsa()?;
let spki = spki(&key)?;
let signer = pkcs1v15::SigningKey::<Sha256>::new(key);
let validity = Validity::from_now(Duration::from_secs(years * 365 * DAY)).map_err(|_| Error::Certificate)?;
let builder = CertificateBuilder::new(Profile::Root, serial()?, validity, name(cn)?, spki, &signer)
.map_err(|_| Error::Certificate)?;
let cert = builder.build::<pkcs1v15::Signature>().map_err(|_| Error::Certificate)?;
Ok(NewCert { secret, cert_der: cert.to_der().map_err(|_| Error::Certificate)? })
}
/// A code-signing leaf issued by `issuer`, valid for `years` years from now.
pub fn new_code_signing(cn: &str, years: u64, issuer: &RsaSecret, issuer_cert: &[u8]) -> Result<NewCert, Error> {
let issuer_cert = Certificate::from_der(issuer_cert).map_err(|_| Error::Certificate)?;
let (key, secret) = new_rsa()?;
let signer = pkcs1v15::SigningKey::<Sha256>::new(issuer.key()?);
let validity = Validity::from_now(Duration::from_secs(years * 365 * DAY)).map_err(|_| Error::Certificate)?;
let profile = Profile::Leaf {
issuer: issuer_cert.tbs_certificate.subject.clone(),
enable_key_agreement: false,
enable_key_encipherment: false,
};
let mut builder = CertificateBuilder::new(profile, serial()?, validity, name(cn)?, spki(&key)?, &signer)
.map_err(|_| Error::Certificate)?;
builder.add_extension(&ExtendedKeyUsage(vec![CODE_SIGNING])).map_err(|_| Error::Certificate)?;
let cert = builder.build::<pkcs1v15::Signature>().map_err(|_| Error::Certificate)?;
Ok(NewCert { secret, cert_der: cert.to_der().map_err(|_| Error::Certificate)? })
}
/// A certificate as PEM, for tools that want text.
pub fn cert_pem(der: &[u8]) -> String {
let b64 = BASE64.encode(der);
let mut out = String::from("-----BEGIN CERTIFICATE-----\n");
for chunk in b64.as_bytes().chunks(64) {
out.push_str(std::str::from_utf8(chunk).expect("base64 is ASCII"));
out.push('\n');
}
out.push_str("-----END CERTIFICATE-----\n");
out
}
/// The SHA-256 (hex) of `bytes`, for the audit log.
pub fn sha256_hex(bytes: &[u8]) -> String {
Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
}
+6
View File
@@ -0,0 +1,6 @@
Throwaway **test keys** for the known-answer tests in `../kat.rs`. They sign nothing real and are not secret.
- `minisign.key`, `minisign.pub`: made by minisign 0.12 (`minisign -G -W`, unencrypted);
`payload.bin.minisig`: `minisign -S -m payload.bin -t "timestamp:1700000000<TAB>file:payload.bin<TAB>hashed"`.
- `rsa3072.pk8.der`: `openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072`, then `openssl pkcs8 -topk8 -nocrypt`;
`digest.openssl.sig`: `openssl pkeyutl -sign -in digest.bin -pkeyopt digest:sha256` (PKCS#1 v1.5).
+1
View File
@@ -0,0 +1 @@
a 32-byte authenticode digest!!!
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
untrusted comment: minisign encrypted secret key
RWQAAEIyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxBvPgUoXv/LZDCnnxOD2qjtAzgKzt2QB+BBy+4kjkKJHj7TUGad2U26fufPhzOCFF9AZps7DyYNRcA1poNz0wBTitny8hZc7AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
+2
View File
@@ -0,0 +1,2 @@
untrusted comment: minisign public key F2BF174A81CF1BC4
RWTEG8+BShe/8m6fufPhzOCFF9AZps7DyYNRcA1poNz0wBTitny8hZc7
+1
View File
@@ -0,0 +1 @@
Domi release test payload: not a real file.
+4
View File
@@ -0,0 +1,4 @@
untrusted comment: signature from minisign secret key
RUTEG8+BShe/8k8Vdth34r/l/IFsZ8pkM0jYtPdZhh0DM64A4TS0EKmGNrkj5Pu2Xwc2tIyuRxlM7v4EBYvg56e31UQelhhc2QY=
trusted comment: timestamp:1700000000 file:payload.bin hashed
dt96Kkj7fBuSn8yp9AA3Ggx3FFf5G6Ta6MnGjyP//1FsvNhJtwd2Mh3dgDLwJqXPggz+P3mJgFrfFvg53CohAg==
Binary file not shown.
+177
View File
@@ -0,0 +1,177 @@
//! Mandatory test 1 (docs/SIGNING.md): known answers for every signature kind, from tools that are not this crate.
//! The fixtures are throwaway test keys: `minisign.key` was made by minisign 0.12 (`-G -W`, unencrypted) and
//! `payload.bin.minisig` signed by it; `rsa3072.pk8.der` and `digest.openssl.sig` by `openssl pkeyutl`.
//! tools/signing/interop.ps1 checks the other direction with the real minisign, signtool and osslsigncode.
use std::fs;
use std::path::PathBuf;
use custos_sign::*;
use data_encoding::BASE64;
use x509_cert::Certificate;
use x509_cert::der::{Decode, Encode};
fn fixture(name: &str) -> Vec<u8> {
fs::read(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(name)).unwrap()
}
fn text(name: &str) -> String {
String::from_utf8(fixture(name)).unwrap()
}
/// The seed and key id of minisign's unencrypted secret key file.
fn minisign_key() -> (Ed25519Secret, [u8; 8]) {
let file = text("minisign.key");
let raw = BASE64.decode(file.lines().nth(1).unwrap().as_bytes()).unwrap();
assert_eq!(&raw[0..2], b"Ed");
assert_eq!(&raw[2..4], &[0, 0], "the fixture key must be unencrypted");
// sig_alg 2, kdf_alg 2, cksum_alg 2, salt 32, opslimit 8, memlimit 8, then key id 8 and seed ‖ public 64.
let key_id: [u8; 8] = raw[54..62].try_into().unwrap();
let seed: [u8; 32] = raw[62..94].try_into().unwrap();
(Ed25519Secret::from_bytes(seed), key_id)
}
#[test]
fn minisign_signature_equals_the_real_minisigns() {
let (secret, key_id) = minisign_key();
let ours = minisign(&secret, &key_id, &blake2b512(&fixture("payload.bin")), "payload.bin", 1_700_000_000).unwrap();
let theirs = text("payload.bin.minisig");
// The untrusted comment is free text; the signature, the trusted comment and the global signature are not.
let tail = |s: &str| s.lines().skip(1).map(String::from).collect::<Vec<_>>();
assert_eq!(tail(&ours), tail(&theirs));
assert!(ours.ends_with('\n'));
}
#[test]
fn the_public_key_file_equals_the_real_minisigns() {
let (secret, key_id) = minisign_key();
let ours = minisign_public(&secret.public(), &key_id);
assert_eq!(ours, text("minisign.pub"));
}
#[test]
fn minisign_verify_accepts_our_signatures_and_rejects_a_changed_file() {
// minisign-verify is what Tauri's updater checks signatures with.
let (secret, key_id) = minisign_key();
let public = minisign_verify::PublicKey::decode(&text("minisign.pub")).unwrap();
let data = b"the installer bytes";
let sig = minisign(&secret, &key_id, &blake2b512(data), "Arca_0.2.0_x64-setup.exe", 1_793_750_000).unwrap();
let sig = minisign_verify::Signature::decode(&sig).unwrap();
public.verify(data, &sig, false).unwrap();
assert!(public.verify(b"another file", &sig, false).is_err());
assert_eq!(sig.trusted_comment(), "timestamp:1793750000\tfile:Arca_0.2.0_x64-setup.exe\thashed");
}
#[test]
fn a_manifest_is_signed_over_its_own_text() {
let (secret, key_id) = minisign_key();
let sums =
format!("{} Arca_0.2.0_x64-setup.exe\n{} Arca_0.2.0_x64-setup.exe.sig\n", "a".repeat(64), "0".repeat(64));
let sig = manifest(&secret, &key_id, &sums, 1_793_750_000).unwrap();
let public = minisign_verify::PublicKey::decode(&text("minisign.pub")).unwrap();
public.verify(sums.as_bytes(), &minisign_verify::Signature::decode(&sig).unwrap(), false).unwrap();
assert!(sig.contains("\tfile:SHA256SUMS\t"));
}
#[test]
fn only_a_canonical_manifest_is_signed() {
let h = "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3";
assert!(manifest_check(&format!("{h} a.exe\n{h} b.exe\n")).is_ok());
let bad = [
("", "empty"),
(&*format!("{h} b.exe\n{h} a.exe\n"), "sorted"),
(&*format!("{h} a.exe\n{h} a.exe\n"), "sorted and unique"),
(&*format!("{} a.exe\n", h.to_uppercase()), "lower-case"),
(&*format!("{h} a.exe\r\n"), "CRLF"),
(&*format!("{h} a.exe"), "no newline"),
(&*format!("{h} a.exe\n"), "not `<sha256> <name>`"),
(&*format!("{h} *a.exe\n"), "not `<sha256> <name>`"),
(&*format!("{h} dir/a.exe\n"), "plain file name"),
(&*format!("{h} -rf\n"), "plain file name"),
(&*format!("{} a.exe\n", &h[..63]), "64 lower-case"),
];
for (t, why) in bad {
let e = manifest_check(t).unwrap_err().to_string();
assert!(e.contains(why), "{t:?}: {e}");
}
let big = format!("{h} {}\n", "x".repeat(MAX_MANIFEST));
assert!(manifest_check(&big).unwrap_err().to_string().contains("32 KiB"));
}
#[test]
fn authenticode_signature_equals_openssls() {
let key = RsaSecret::from_pkcs8_der(fixture("rsa3072.pk8.der")).unwrap();
let ours = authenticode(&key, &fixture("digest.bin")).unwrap();
assert_eq!(ours.len(), 384);
assert_eq!(ours, fixture("digest.openssl.sig"));
assert_eq!(authenticode(&key, &[0u8; 31]).unwrap_err(), Error::DigestLength(32));
assert_eq!(authenticode(&key, &[0u8; 64]).unwrap_err(), Error::DigestLength(32));
}
#[test]
fn digests_and_file_names_are_checked() {
let (secret, key_id) = minisign_key();
assert_eq!(minisign(&secret, &key_id, &[0u8; 32], "a", 1).unwrap_err(), Error::DigestLength(64));
for bad in ["", "dir/a.exe", "a\\b", "a\nb", "tab\there"] {
assert!(matches!(minisign(&secret, &key_id, &[0u8; 64], bad, 1), Err(Error::FileName(_))), "{bad:?}");
}
}
#[test]
fn the_household_ca_issues_a_code_signing_leaf() {
use rsa::pkcs1v15::{Signature, VerifyingKey};
use rsa::pkcs8::DecodePublicKey;
use rsa::signature::Verifier;
use x509_cert::ext::pkix::{BasicConstraints, ExtendedKeyUsage};
let root = new_root("Domi Household Root CA", 10).unwrap();
let rkey = RsaSecret::from_pkcs8_der(root.secret.expose().to_vec()).unwrap();
let leaf = new_code_signing("Domi Code Signing", 2, &rkey, &root.cert_der).unwrap();
let rc = Certificate::from_der(&root.cert_der).unwrap();
let lc = Certificate::from_der(&leaf.cert_der).unwrap();
assert_eq!(rc.tbs_certificate.subject.to_string(), "CN=Domi Household Root CA,O=Domi");
assert_eq!(rc.tbs_certificate.issuer, rc.tbs_certificate.subject);
assert_eq!(lc.tbs_certificate.issuer, rc.tbs_certificate.subject);
let years = |c: &Certificate| {
let v = &c.tbs_certificate.validity;
(v.not_after.to_unix_duration().as_secs() - v.not_before.to_unix_duration().as_secs()) / (365 * 86_400)
};
assert_eq!((years(&rc), years(&lc)), (10, 2));
let (_, bc) = rc.tbs_certificate.get::<BasicConstraints>().unwrap().unwrap();
assert!(bc.ca);
let (_, bc) = lc.tbs_certificate.get::<BasicConstraints>().unwrap().unwrap();
assert!(!bc.ca);
let (_, eku) = lc.tbs_certificate.get::<ExtendedKeyUsage>().unwrap().unwrap();
assert_eq!(eku.0.iter().map(|o| o.to_string()).collect::<Vec<_>>(), vec!["1.3.6.1.5.5.7.3.3"]);
// The leaf is signed by the root's key, and the leaf's key is the one in its certificate.
let rpub = VerifyingKey::<sha2_010::Sha256>::from_public_key_der(
&rc.tbs_certificate.subject_public_key_info.to_der().unwrap(),
)
.unwrap();
let sig = Signature::try_from(lc.signature.raw_bytes()).unwrap();
rpub.verify(&lc.tbs_certificate.to_der().unwrap(), &sig).unwrap();
let digest = [7u8; 32];
let lsig = authenticode(&leaf.secret, &digest).unwrap();
let lpub = VerifyingKey::<sha2_010::Sha256>::from_public_key_der(
&lc.tbs_certificate.subject_public_key_info.to_der().unwrap(),
)
.unwrap();
use rsa::signature::hazmat::PrehashVerifier;
lpub.verify_prehash(&digest, &Signature::try_from(lsig.as_slice()).unwrap()).unwrap();
assert!(cert_pem(&root.cert_der).starts_with("-----BEGIN CERTIFICATE-----\n"));
}
#[test]
fn secrets_never_print() {
let (secret, _) = minisign_key();
let rsa = RsaSecret::from_pkcs8_der(fixture("rsa3072.pk8.der")).unwrap();
assert_eq!(format!("{secret:?}"), "[redacted]");
assert_eq!(format!("{rsa:?}"), "[redacted]");
let made = new_ed25519();
assert_eq!(format!("{:?}", made.secret), "[redacted]");
assert_eq!(made.public, made.secret.public());
}
+10
View File
@@ -16,6 +16,16 @@ serde_json.workspace = true
thiserror.workspace = true
hkdf.workspace = true
sha2.workspace = true
data-encoding.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"] }
# Signing keys for releases (docs/SIGNING.md).
custos-sign = { path = "../custos-sign" }
[dev-dependencies]
tempfile = "3"
minisign-verify = "0.3"
rsa = { version = "0.9", features = ["sha2"] }
sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] }
x509-cert = "0.2.5"
+22
View File
@@ -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()
}
+245 -8
View File
@@ -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)
}
}
+306
View File
@@ -0,0 +1,306 @@
//! 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 and
//! revocations of keys the person revoked. It derives each app's backup secret from it.
//!
//! 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";
/// And `REVOKE_DOMAIN ‖ tbs`, only for a `tbs` that starts with `REVOKE_MAGIC ‖ its public key ‖ a key the
/// person revoked ‖ that key's revoked_at` (Fundamentum docs/TESSERA.md §12).
const REVOKE_DOMAIN: &[u8] = b"tessera revoke v1\0";
const REVOKE_MAGIC: &[u8] = b"TRV1";
/// magic 4, root 32, subkey 32, revoked_at 8, part 2, parts 2, count 4.
const REVOKE_HEADER: usize = 84;
const BACKUP_SALT: &[u8] = b"tessera backup v1";
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() }
}
/// Restores an identity from its whole phrase, typed back (docs/IDENTITY.md, "Restoring it"): all 24
/// words prove more than three. Any case, any spacing. Anything that is not 24 English BIP39 words with a
/// valid checksum is [`Error::NotAMnemonic`], which names no word.
pub fn restore(phrase: &str) -> Result<Confirmed, Error> {
// Room for lowercasing without a reallocation that would leave a copy behind.
let mut joined = Zeroizing::new(String::with_capacity(phrase.len() * 3 + 1));
for (i, w) in phrase.split_whitespace().enumerate() {
if i > 0 {
joined.push(' ');
}
joined.extend(w.chars().flat_map(char::to_lowercase));
}
if joined.split(' ').count() != WORDS {
return Err(Error::NotAMnemonic);
}
let m =
bip39::Mnemonic::parse_in_normalized(bip39::Language::English, &joined).map_err(|_| Error::NotAMnemonic)?;
Ok(Confirmed { secret: crypto::domi_root_secret(&m) })
}
}
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, Default, 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,
/// Unix seconds: when the person revoked the key (core 0.10.0).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revoked_at: Option<u64>,
/// The signed `TRV1` statements, base64url, once an app sent the events to keep.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub revocation: Vec<String>,
}
/// 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 sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
let names_me = tbs.len() >= REVOKE_HEADER && &tbs[..4] == REVOKE_MAGIC && tbs[4..36] == self.public;
if !names_me {
return Err(Error::NotARevocation);
}
let subkey = data_encoding::BASE64URL_NOPAD.encode(&tbs[36..68]);
let at = u64::from_be_bytes(tbs[68..76].try_into().expect("8 bytes"));
if !self.issued.iter().any(|i| i.subkey == subkey && i.revoked_at == Some(at)) {
return Err(Error::NotARevocation);
}
let msg = Zeroizing::new([REVOKE_DOMAIN, tbs].concat());
Ok(crypto::ed25519_sign(&self.secret, &msg))
}
/// Marks every cert of `subkey` revoked; keeps the earliest time if one was marked before.
pub(crate) fn mark_revoked(&mut self, subkey: &str, at: u64) -> Result<u64, Error> {
let mut certs = self.issued.iter().filter(|i| i.subkey == subkey).peekable();
if certs.peek().is_none() {
return Err(Error::UnknownKey);
}
let at = certs.filter_map(|i| i.revoked_at).min().unwrap_or(at);
self.issued.iter_mut().filter(|i| i.subkey == subkey).for_each(|i| i.revoked_at = Some(at));
Ok(at)
}
pub(crate) fn record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error> {
let mut certs = self.issued.iter_mut().filter(|i| i.subkey == subkey).peekable();
if certs.peek().is_none() {
return Err(Error::UnknownKey);
}
certs.for_each(|i| i.revocation = statements.clone());
Ok(())
}
/// `HKDF-SHA256(salt "tessera backup v1", ikm = root secret, info = app id)` (docs/IDENTITY.md).
pub(crate) fn backup_secret(&self, app_id: &str) -> Zeroizing<[u8; KEY_LEN]> {
crypto::hkdf(self.secret.as_ref(), BACKUP_SALT, app_id.as_bytes())
}
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() })
}
}
+35 -2
View File
@@ -1,6 +1,6 @@
//! Typed items and their templates (docs/FORMAT.md, "Item types and their fields").
use crate::secret::SecretString;
use crate::secret::{SecretBytes, SecretString};
use serde::{Deserialize, Serialize};
use std::fmt;
@@ -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),
],
}
}
}
@@ -103,6 +116,19 @@ impl fmt::Debug for HistoryEntry {
}
}
/// A file kept with an item (imported from KeePass, docs/KDBX.md). The content counts as secret.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attachment {
pub name: String,
pub data: SecretBytes,
}
impl fmt::Debug for Attachment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Attachment").field("name", &self.name).field("len", &self.data.len()).finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Item {
pub id: String,
@@ -119,6 +145,11 @@ pub struct Item {
pub modified: i64,
#[serde(default)]
pub history: Vec<HistoryEntry>,
/// Folder names, outermost first (a KeePass group path). Empty: no folder.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub folder: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub attachments: Vec<Attachment>,
}
impl Item {
@@ -138,6 +169,8 @@ impl Item {
created: now,
modified: now,
history: Vec::new(),
folder: Vec::new(),
attachments: Vec::new(),
}
}
+643 -32
View File
@@ -1,29 +1,39 @@
//! 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;
pub mod signing;
pub use item::{Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
pub use save::{CrashPoint, save_atomic, save_atomic_crashing};
pub use secret::SecretString;
pub use secret::{SecretBytes, 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 +55,32 @@ 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("these are not the 24 words of a recovery phrase: check each word and their order")]
NotAMnemonic,
#[error("the Domi identity signs a revocation only for a key revoked in Custos, at the time it was revoked")]
NotARevocation,
#[error("the Domi identity did not certify this key")]
UnknownKey,
#[error("this vault already has {0} signing keys")]
SigningExists(&'static str),
#[error("signing keys: {0}")]
Signing(String),
#[error("{0}")]
Io(#[from] std::io::Error),
}
@@ -80,12 +116,164 @@ 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>,
#[serde(default)]
signing: Option<signing::StoreJson>,
}
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
@@ -93,18 +281,38 @@ 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>,
#[serde(skip_serializing_if = "Option::is_none")]
signing: Option<signing::StoreJson>,
}
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
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>,
/// Signing keys and their audit log (docs/SIGNING.md); no key is ever handed out.
signing: signing::Store,
}
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 +326,147 @@ 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,
signing: signing::Store::default(),
})
}
/// 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,
signing: signing::Store::default(),
};
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,
signing: signing::Store::default(),
})
}
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 +479,133 @@ 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,
};
let signing = match body.signing {
Some(j) => signing::Store::from_json(j).ok_or(Error::Corrupted)?,
None => signing::Store::default(),
};
Ok(Vault {
key,
version: header.version,
slots: header.slots,
items: body.items,
factors,
kdf_new,
identity,
signing,
})
}
/// Wraps the vault key for device unlock with key material only this device can produce (e.g. a
/// 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 +613,16 @@ 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),
signing: self.signing.json(),
};
serde_json::to_writer(&mut *json, &body).map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?;
let sealed = crypto::seal(&self.key, &body_nonce, &json, &out);
out.extend_from_slice(&sealed);
@@ -194,28 +634,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 +805,56 @@ 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" ‖ tbs`. Refuses a `tbs` that does not start with
/// `TSC1` and this root's public key ([`Error::NotACert`]): the root signs certificates and nothing else.
pub fn domi_sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
self.identity.as_ref().ok_or(Error::NoIdentity)?.sign_cert(tbs)
}
/// The certs this vault has signed, oldest first.
pub fn domi_issued(&self) -> &[identity::Issued] {
self.identity.as_ref().map(|r| r.issued.as_slice()).unwrap_or(&[])
}
/// Records a cert this vault signed. The caller saves the vault.
pub fn domi_record(&mut self, issued: identity::Issued) -> Result<(), Error> {
self.identity.as_mut().ok_or(Error::NoIdentity)?.issued.push(issued);
Ok(())
}
/// The person revoked the key `subkey` (base64url): marks every cert of it. Returns the revocation time in
/// effect, the earlier one if it was marked before. The caller saves the vault.
pub fn domi_mark_revoked(&mut self, subkey: &str, revoked_at: u64) -> Result<u64, Error> {
self.identity.as_mut().ok_or(Error::NoIdentity)?.mark_revoked(subkey, revoked_at)
}
/// Ed25519 with the root over `"tessera revoke v1\0" ‖ tbs`, for a `tbs` that starts with `TRV1`, this
/// root's public key, a key marked revoked and its `revoked_at` ([`Error::NotARevocation`] otherwise).
pub fn domi_sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
self.identity.as_ref().ok_or(Error::NoIdentity)?.sign_revocation(tbs)
}
/// Keeps the signed statements (base64url `TRV1`) with every cert of `subkey`. The caller saves the vault.
pub fn domi_record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error> {
self.identity.as_mut().ok_or(Error::NoIdentity)?.record_revocation(subkey, statements)
}
/// The backup secret of the app `app_id` (docs/IDENTITY.md): derived from the root, handed to that app
/// only. The caller checks `app_id` (a-z, 0-9, `-`) and the app's right to it.
pub fn domi_backup_secret(&self, app_id: &str) -> Result<Zeroizing<[u8; 32]>, Error> {
Ok(self.identity.as_ref().ok_or(Error::NoIdentity)?.backup_secret(app_id))
}
}
+52
View File
@@ -57,3 +57,55 @@ impl<'de> Deserialize<'de> for SecretString {
String::deserialize(d).map(Self::new)
}
}
/// Bytes that are wiped from memory when dropped and never printed (an attachment's content).
/// `Debug` gives `[redacted]`; serialized as base64.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct SecretBytes(Zeroizing<Vec<u8>>);
impl SecretBytes {
pub fn new(b: Vec<u8>) -> Self {
Self(Zeroizing::new(b))
}
/// The content. Keep the borrow short.
pub fn expose(&self) -> &[u8] {
&self.0
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl From<&[u8]> for SecretBytes {
fn from(b: &[u8]) -> Self {
Self::new(b.to_vec())
}
}
impl fmt::Debug for SecretBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
impl Serialize for SecretBytes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&Zeroizing::new(data_encoding::BASE64.encode(&self.0)))
}
}
impl<'de> Deserialize<'de> for SecretBytes {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = Zeroizing::new(String::deserialize(d)?);
data_encoding::BASE64
.decode(s.as_bytes())
.map(Self::new)
.map_err(|_| serde::de::Error::custom("attachment data is not base64"))
}
}
+718
View File
@@ -0,0 +1,718 @@
//! Signing keys for releases and the audit log of every request (docs/SIGNING.md): the vault body member
//! `signing`. A key's secret is used inside this module and never handed out: the public API returns
//! public keys, certificates, signatures and audit entries only.
use std::fmt;
use custos_sign::{Ed25519Secret, RsaSecret};
use serde::{Deserialize, Serialize};
use crate::{Error, SecretBytes, Vault};
/// What a request may be refused with. Every refusal names why, and none carries key material.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Refusal {
#[error("there is no signing key `{0}`")]
NoKey(String),
#[error("{0}")]
OutOfScope(String),
#[error("{0}")]
Invalid(String),
#[error("`{0}` is a release key: it signs only after Mark approves")]
NeedsApproval(String),
}
impl Refusal {
/// The audit outcome this refusal is recorded as.
pub fn outcome(&self) -> Outcome {
match self {
Refusal::OutOfScope(_) => Outcome::OutOfScope,
Refusal::NeedsApproval(_) => Outcome::Refused,
Refusal::NoKey(_) | Refusal::Invalid(_) => Outcome::Invalid,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
Release,
Test,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum KeyKind {
Ed25519,
RootCa,
CodeSigning,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SignKind {
Minisign,
Manifest,
Authenticode,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Via {
Local,
Remote,
}
/// What the build says it is signing. Shown on the card and kept in the audit log; Custos cannot check it
/// against the file (docs/SIGNING.md, the wrong-file risk).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Context {
pub repo: String,
pub commit: String,
pub pipeline: String,
pub step: String,
/// `manual`, `push` or `tag`. A test key never signs for `tag`.
pub trigger: String,
pub file: String,
pub size: u64,
pub sha256: String,
}
/// A signing request, from the Domi pipe or the factor service's mailbox.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Request {
pub key: String,
pub kind: SignKind,
/// BLAKE2b-512 of the file (minisign) or signtool's 32-byte digest (authenticode). Empty for a manifest.
pub digest: Vec<u8>,
/// The `SHA256SUMS` text, for a manifest.
pub manifest: Option<String>,
pub context: Context,
pub via: Via,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Approval {
/// Mark approved this request on the card.
Mark,
/// Nobody was asked: allowed for test keys only.
Auto,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Outcome {
Approved,
Auto,
Refused,
Expired,
OutOfScope,
Invalid,
}
/// One audit entry. Append-only: nothing edits or removes one.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuditEntry {
pub at: i64,
pub key: String,
pub kind: SignKind,
pub outcome: Outcome,
pub via: Via,
#[serde(flatten)]
pub context: Context,
/// SHA-256 (hex) of what was returned, for signed outcomes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signature: Option<String>,
/// Why, for refusals the vault decided.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
/// A signature handed back to the build.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signed {
/// The `.minisig` text (minisign, manifest) or the raw RSA signature (authenticode).
pub bytes: Vec<u8>,
pub sha256: String,
}
/// A key as the app may see it: public parts only.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct KeyView {
pub id: String,
pub kind: KeyKind,
pub role: Role,
pub name: String,
pub created: i64,
pub pipelines: Vec<String>,
pub repos: Vec<String>,
/// Test keys are approved automatically (within scope, never for a `tag` trigger).
pub auto_approve: bool,
/// minisign's key id (hex, as minisign prints it), for Ed25519 keys.
pub key_id: Option<String>,
/// The `minisign.pub` text, for Ed25519 keys.
pub minisign_public: Option<String>,
/// The certificate (DER), for root and code-signing keys.
pub cert: Option<Vec<u8>>,
pub issuer: Option<String>,
}
enum Secret {
Ed25519(Ed25519Secret),
Rsa(RsaSecret),
}
struct Key {
id: String,
kind: KeyKind,
role: Role,
name: String,
secret: Secret,
public: Option<[u8; 32]>,
key_id: Option<[u8; 8]>,
cert: Option<Vec<u8>>,
issuer: Option<String>,
created: i64,
pipelines: Vec<String>,
repos: Vec<String>,
}
impl fmt::Debug for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Key").field("id", &self.id).field("kind", &self.kind).field("secret", &"[redacted]").finish()
}
}
/// The keys and the log, in the vault.
#[derive(Debug, Default)]
pub(crate) struct Store {
keys: Vec<Key>,
audit: Vec<AuditEntry>,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct KeyJson {
id: String,
kind: KeyKind,
role: Role,
name: String,
secret: SecretBytes,
#[serde(default, skip_serializing_if = "Option::is_none")]
public: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
key_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
cert: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
issuer: Option<String>,
created: i64,
#[serde(default)]
pipelines: Vec<String>,
#[serde(default)]
repos: Vec<String>,
}
#[derive(Serialize, Deserialize)]
pub(crate) struct StoreJson {
#[serde(default)]
keys: Vec<KeyJson>,
#[serde(default)]
audit: Vec<AuditEntry>,
}
fn b64(bytes: &[u8]) -> String {
data_encoding::BASE64.encode(bytes)
}
fn unb64(s: &str) -> Option<Vec<u8>> {
data_encoding::BASE64.decode(s.as_bytes()).ok()
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn unhex8(s: &str) -> Option<[u8; 8]> {
if s.len() != 16 {
return None;
}
let mut out = [0u8; 8];
for (i, o) in out.iter_mut().enumerate() {
*o = u8::from_str_radix(&s[2 * i..2 * i + 2], 16).ok()?;
}
Some(out)
}
impl Store {
pub(crate) fn is_empty(&self) -> bool {
self.keys.is_empty() && self.audit.is_empty()
}
pub(crate) fn from_json(j: StoreJson) -> Option<Store> {
let mut keys = Vec::new();
for k in j.keys {
let secret = match k.kind {
KeyKind::Ed25519 => {
let seed: [u8; 32] = k.secret.expose().try_into().ok()?;
Secret::Ed25519(Ed25519Secret::from_bytes(seed))
}
KeyKind::RootCa | KeyKind::CodeSigning => {
Secret::Rsa(RsaSecret::from_pkcs8_der(k.secret.expose().to_vec()).ok()?)
}
};
let public = match &k.public {
Some(p) => Some(unb64(p)?.try_into().ok()?),
None => None,
};
// The stored public key must be the secret's, as for the identity root.
if let (Secret::Ed25519(s), Some(p)) = (&secret, public) {
if s.public() != p {
return None;
}
}
let key_id = match &k.key_id {
Some(h) => Some(unhex8(h)?),
None => None,
};
let cert = match &k.cert {
Some(c) => Some(unb64(c)?),
None => None,
};
keys.push(Key {
id: k.id,
kind: k.kind,
role: k.role,
name: k.name,
secret,
public,
key_id,
cert,
issuer: k.issuer,
created: k.created,
pipelines: k.pipelines,
repos: k.repos,
});
}
Some(Store { keys, audit: j.audit })
}
pub(crate) fn json(&self) -> Option<StoreJson> {
if self.is_empty() {
return None;
}
let keys = self
.keys
.iter()
.map(|k| KeyJson {
id: k.id.clone(),
kind: k.kind,
role: k.role,
name: k.name.clone(),
secret: SecretBytes::new(match &k.secret {
Secret::Ed25519(s) => s.expose().to_vec(),
Secret::Rsa(s) => s.expose().to_vec(),
}),
public: k.public.map(|p| b64(&p)),
key_id: k.key_id.map(|i| hex(&i)),
cert: k.cert.as_ref().map(|c| b64(c)),
issuer: k.issuer.clone(),
created: k.created,
pipelines: k.pipelines.clone(),
repos: k.repos.clone(),
})
.collect();
Some(StoreJson { keys, audit: self.audit.clone() })
}
fn get(&self, id: &str) -> Option<&Key> {
self.keys.iter().find(|k| k.id == id)
}
}
fn in_scope(list: &[String], what: &str) -> bool {
list.iter().any(|x| x == "*" || x == what)
}
fn clean_list(list: &[String]) -> Result<Vec<String>, Error> {
let mut out: Vec<String> = Vec::new();
for x in list.iter().map(|s| s.trim()).filter(|s| !s.is_empty()) {
if x.len() > 100 || x.chars().any(char::is_control) {
return Err(Error::Signing("a pipeline or repo name is not usable".into()));
}
if !out.iter().any(|o| o == x) {
out.push(x.to_string());
}
}
Ok(out)
}
impl Vault {
/// Creates the release set (`domi-release`, `domi-root`, `domi-code-signing`) or the test set (`domi-test`,
/// `domi-test-root`, `domi-test-code-signing`). The caller saves. Slow: two RSA-3072 keys.
pub fn signing_create(
&mut self,
role: Role,
pipelines: &[String],
repos: &[String],
now: i64,
) -> Result<Vec<String>, Error> {
if self.signing.keys.iter().any(|k| k.role == role) {
return Err(Error::SigningExists(match role {
Role::Release => "release",
Role::Test => "test",
}));
}
let pipelines = clean_list(pipelines)?;
let repos = clean_list(repos)?;
let (ed_id, root_id, leaf_id, ed_name, root_name, leaf_name) = match role {
Role::Release => (
"domi-release",
"domi-root",
"domi-code-signing",
"Domi release",
"Domi Household Root CA",
"Domi Code Signing",
),
Role::Test => (
"domi-test",
"domi-test-root",
"domi-test-code-signing",
"Domi test",
"Domi Test Root (never trusted)",
"Domi Test Code Signing",
),
};
let ed = custos_sign::new_ed25519();
let root = custos_sign::new_root(root_name, 10).map_err(|e| Error::Signing(e.to_string()))?;
let leaf = custos_sign::new_code_signing(leaf_name, 2, &root.secret, &root.cert_der)
.map_err(|e| Error::Signing(e.to_string()))?;
let key = |id: &str, kind, name: &str, secret, cert, issuer: Option<&str>, scoped: bool| Key {
id: id.into(),
kind,
role,
name: name.into(),
secret,
public: None,
key_id: None,
cert,
issuer: issuer.map(String::from),
created: now,
pipelines: if scoped { pipelines.clone() } else { Vec::new() },
repos: if scoped { repos.clone() } else { Vec::new() },
};
let mut ed_key = key(ed_id, KeyKind::Ed25519, ed_name, Secret::Ed25519(ed.secret), None, None, true);
ed_key.public = Some(ed.public);
ed_key.key_id = Some(ed.key_id);
let root_key =
key(root_id, KeyKind::RootCa, root_name, Secret::Rsa(root.secret), Some(root.cert_der), None, false);
let leaf_key = key(
leaf_id,
KeyKind::CodeSigning,
leaf_name,
Secret::Rsa(leaf.secret),
Some(leaf.cert_der),
Some(root_id),
true,
);
self.signing.keys.extend([ed_key, root_key, leaf_key]);
Ok(vec![ed_id.into(), root_id.into(), leaf_id.into()])
}
/// Every signing key, public parts only.
pub fn signing_keys(&self) -> Vec<KeyView> {
self.signing
.keys
.iter()
.map(|k| KeyView {
id: k.id.clone(),
kind: k.kind,
role: k.role,
name: k.name.clone(),
created: k.created,
pipelines: k.pipelines.clone(),
repos: k.repos.clone(),
auto_approve: k.role == Role::Test && k.kind != KeyKind::RootCa,
key_id: k.key_id.map(|i| custos_sign::key_id_hex(&i)),
minisign_public: match (k.public, k.key_id) {
(Some(p), Some(i)) => Some(custos_sign::minisign_public(&p, &i)),
_ => None,
},
cert: k.cert.clone(),
issuer: k.issuer.clone(),
})
.collect()
}
/// Changes who may ask for a key. The caller saves.
pub fn signing_set_scope(&mut self, id: &str, pipelines: &[String], repos: &[String]) -> Result<(), Error> {
let (pipelines, repos) = (clean_list(pipelines)?, clean_list(repos)?);
let k = self
.signing
.keys
.iter_mut()
.find(|k| k.id == id)
.ok_or_else(|| Error::Signing(format!("no key `{id}`")))?;
if k.kind == KeyKind::RootCa {
return Err(Error::Signing("a root CA signs no requests, so it has no scope".into()));
}
k.pipelines = pipelines;
k.repos = repos;
Ok(())
}
/// A key's certificate (DER): public, for installing the root or giving signtool the leaf.
pub fn signing_export_cert(&self, id: &str) -> Result<Vec<u8>, Error> {
let k = self.signing.get(id).ok_or_else(|| Error::Signing(format!("no key `{id}`")))?;
k.cert.clone().ok_or_else(|| Error::Signing(format!("`{id}` has no certificate")))
}
/// Whether `req` could be signed: the key exists and can do the kind, the input is well formed, the pipeline
/// and repo are in the key's scope, and a test key is not asked for a `tag` build. Shown before any card.
pub fn signing_check(&self, req: &Request) -> Result<KeyView, Refusal> {
let k = self.signing.get(&req.key).ok_or_else(|| Refusal::NoKey(req.key.clone()))?;
let fits = matches!(
(k.kind, req.kind),
(KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest)
| (KeyKind::CodeSigning, SignKind::Authenticode)
);
if k.kind == KeyKind::RootCa {
return Err(Refusal::Invalid(format!("`{}` is a root CA: it signs only the certificate it issued", k.id)));
}
if !fits {
return Err(Refusal::Invalid(format!("`{}` cannot make {:?} signatures", k.id, req.kind)));
}
match req.kind {
SignKind::Minisign if req.digest.len() != 64 => {
return Err(Refusal::Invalid("a minisign digest is BLAKE2b-512: 64 bytes".into()));
}
SignKind::Authenticode if req.digest.len() != 32 => {
return Err(Refusal::Invalid("an Authenticode digest is SHA-256: 32 bytes".into()));
}
SignKind::Manifest => {
let text = req.manifest.as_deref().ok_or_else(|| Refusal::Invalid("no manifest text".into()))?;
custos_sign::manifest_check(text).map_err(|e| Refusal::Invalid(e.to_string()))?;
}
_ => {}
}
let file = &req.context.file;
if req.kind != SignKind::Manifest
&& (file.is_empty() || file.len() > 255 || file.contains(['/', '\\']) || file.chars().any(char::is_control))
{
return Err(Refusal::Invalid("the file name is missing or not a plain name".into()));
}
if !in_scope(&k.pipelines, &req.context.pipeline) {
return Err(Refusal::OutOfScope(format!("pipeline `{}` may not use `{}`", req.context.pipeline, k.id)));
}
if !in_scope(&k.repos, &req.context.repo) {
return Err(Refusal::OutOfScope(format!("repo `{}` may not use `{}`", req.context.repo, k.id)));
}
if k.role == Role::Test && req.context.trigger == "tag" {
return Err(Refusal::OutOfScope(format!("`{}` is a test key: it never signs a tag (release) build", k.id)));
}
Ok(self.signing_keys().into_iter().find(|v| v.id == k.id).expect("the key exists"))
}
/// Checks `req` again and signs it, recording the outcome. `Approval::Auto` works for test keys only.
/// A refusal is recorded too. The caller saves.
pub fn signing_sign(&mut self, req: &Request, approval: Approval, now: i64) -> Result<Signed, Refusal> {
let view = match self.signing_check(req) {
Ok(v) => v,
Err(r) => {
self.signing_record(req, r.outcome(), Some(r.to_string()), None, now);
return Err(r);
}
};
if approval == Approval::Auto && !view.auto_approve {
let r = Refusal::NeedsApproval(req.key.clone());
self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now);
return Err(r);
}
let k = self.signing.get(&req.key).expect("checked");
let seconds = (now.max(0) / 1000) as u64;
let bytes = match (&k.secret, req.kind) {
(Secret::Ed25519(s), SignKind::Minisign) => custos_sign::minisign(
s,
&k.key_id.expect("ed25519 keys have an id"),
&req.digest,
&req.context.file,
seconds,
)
.map(String::into_bytes),
(Secret::Ed25519(s), SignKind::Manifest) => custos_sign::manifest(
s,
&k.key_id.expect("ed25519 keys have an id"),
req.manifest.as_deref().unwrap_or_default(),
seconds,
)
.map(String::into_bytes),
(Secret::Rsa(s), SignKind::Authenticode) => custos_sign::authenticode(s, &req.digest),
_ => unreachable!("signing_check matched the key to the kind"),
};
let bytes = match bytes {
Ok(b) => b,
Err(e) => {
let r = Refusal::Invalid(e.to_string());
self.signing_record(req, Outcome::Invalid, Some(r.to_string()), None, now);
return Err(r);
}
};
let sha256 = custos_sign::sha256_hex(&bytes);
let outcome = if approval == Approval::Auto { Outcome::Auto } else { Outcome::Approved };
self.signing_record(req, outcome, None, Some(sha256.clone()), now);
Ok(Signed { bytes, sha256 })
}
/// Records a request that was not signed: Mark refused it, or nobody answered in time. The caller saves.
pub fn signing_refuse(&mut self, req: &Request, outcome: Outcome, reason: Option<String>, now: i64) {
let outcome = match outcome {
Outcome::Approved | Outcome::Auto => Outcome::Refused,
o => o,
};
self.signing_record(req, outcome, reason, None, now);
}
fn signing_record(
&mut self,
req: &Request,
outcome: Outcome,
reason: Option<String>,
signature: Option<String>,
now: i64,
) {
let mut context = req.context.clone();
if req.kind == SignKind::Manifest {
context.file = "SHA256SUMS".into();
}
self.signing.audit.push(AuditEntry {
at: now,
key: req.key.clone(),
kind: req.kind,
outcome,
via: req.via,
context,
signature,
reason,
});
}
/// Every request any key was named in, oldest first.
pub fn signing_audit(&self) -> &[AuditEntry] {
&self.signing.audit
}
}
#[cfg(test)]
mod tests {
//! Mandatory test 2 for the core: no API path returns a private key. It lives here because only this module can
//! see the secrets to look for.
use super::*;
use crate::{KdfParams, SecretString};
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
fn req(key: &str, kind: SignKind, digest: usize) -> Request {
Request {
key: key.into(),
kind,
digest: vec![5; digest],
manifest: None,
context: Context {
repo: "Arca".into(),
pipeline: "release".into(),
trigger: "tag".into(),
file: "a.exe".into(),
..Default::default()
},
via: Via::Local,
}
}
#[test]
fn no_api_path_returns_a_private_key() {
let mut v =
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
v.signing_create(Role::Release, &s(&["*"]), &s(&["*"]), 1).unwrap();
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), 1).unwrap();
let secrets: Vec<Vec<u8>> = v
.signing
.keys
.iter()
.map(|k| match &k.secret {
Secret::Ed25519(s) => s.expose().to_vec(),
Secret::Rsa(s) => s.expose().to_vec(),
})
.collect();
assert_eq!(secrets.len(), 6);
// Every public way out: views (serialised and printed), certificates, minisign public keys, checks,
// signatures of every kind, refusals, the audit log, errors, and the Debug of the vault's own store.
let mut out = String::new();
let views = v.signing_keys();
out += &serde_json::to_string(&views).unwrap();
out += &format!("{views:?}{:?}", v.signing);
for k in &views {
if let Ok(c) = v.signing_export_cert(&k.id) {
out += &data_encoding::HEXLOWER.encode(&c);
}
}
let mut reqs =
vec![req("domi-release", SignKind::Minisign, 64), req("domi-code-signing", SignKind::Authenticode, 32)];
reqs.push(req("domi-root", SignKind::Authenticode, 32));
reqs.push(req("domi-test", SignKind::Minisign, 64));
for r in &reqs {
out += &format!("{:?}", v.signing_check(r));
for approval in [Approval::Mark, Approval::Auto] {
match v.signing_sign(r, approval, 2) {
Ok(signed) => out += &format!("{signed:?}{}", data_encoding::HEXLOWER.encode(&signed.bytes)),
Err(e) => out += &format!("{e:?}{e}"),
}
}
}
out += &serde_json::to_string(v.signing_audit()).unwrap();
out += &format!("{:?}", v.signing_audit());
out += &format!("{:?}", v.signing_create(Role::Release, &[], &[], 3));
for secret in &secrets {
for enc in [
data_encoding::HEXLOWER.encode(secret),
data_encoding::HEXUPPER.encode(secret),
data_encoding::BASE64.encode(secret),
data_encoding::BASE64URL_NOPAD.encode(secret),
] {
assert!(!out.contains(&enc), "a secret appears in an output");
}
}
// Partial copies too: every 16-byte window of the numbers that are actually private. (A PKCS#8 RSA key
// also holds the public modulus and DER headers, which the certificate rightly shows.)
for private in private_parts(&secrets) {
for w in private.windows(16).step_by(8) {
assert!(!out.contains(&data_encoding::HEXLOWER.encode(w)), "part of a secret appears in an output");
assert!(!out.contains(&data_encoding::BASE64.encode(w)[..20]), "part of a secret appears in an output");
}
}
}
/// Ed25519 seeds as they are; for RSA the private exponent and the primes.
fn private_parts(secrets: &[Vec<u8>]) -> Vec<Vec<u8>> {
use rsa::pkcs8::DecodePrivateKey;
use rsa::traits::PrivateKeyParts;
let mut out = Vec::new();
for s in secrets {
if s.len() == 32 {
out.push(s.clone());
} else {
let k = rsa::RsaPrivateKey::from_pkcs8_der(s).unwrap();
out.push(k.d().to_bytes_be());
out.extend(k.primes().iter().map(|p| p.to_bytes_be()));
}
}
assert!(out.len() >= 2 + 4 * 3, "seeds, exponents and primes");
out
}
}
+241
View File
@@ -0,0 +1,241 @@
//! Mandatory tests for format version 2 (docs/FACTORS.md): any two factors open the vault, one never
//! does, factors come and go without the others, v1 upgrades, tampering fails, machine stores.
use custos_vault::{Error, FactorKind, Item, ItemType, KdfParams, SecretString, Unlock, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
fn pw(s: &str) -> SecretString {
SecretString::from(s)
}
const DEVICE: [u8; 32] = [7; 32];
const TOTP: [u8; 32] = [9; 32];
const PHONE: [u8; 32] = [11; 32];
fn two_factor_vault() -> Vault {
let mut v = Vault::create_with(
Unlock::Password(&pw("Orbit7-Fable3")),
"Master password",
Unlock::Material(FactorKind::Device, &DEVICE),
"MARK-PC",
FAST,
)
.unwrap();
v.add(Item::new(ItemType::WebLogin, "GitHub", 1_000));
v
}
fn open(bytes: &[u8], a: Unlock, b: Unlock) -> Result<Vault, Error> {
Vault::open_with(bytes, a, b)
}
#[test]
fn any_two_factors_open_and_one_never_does() {
let mut v = two_factor_vault();
v.add_factor(Unlock::Material(FactorKind::Totp, &TOTP), "TOTP backup").unwrap();
let bytes = v.to_bytes().unwrap();
let p = pw("Orbit7-Fable3");
let pairs = [
(Unlock::Password(&p), Unlock::Material(FactorKind::Device, &DEVICE)),
(Unlock::Password(&p), Unlock::Material(FactorKind::Totp, &TOTP)),
(Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Totp, &TOTP)),
// Order does not matter.
(Unlock::Material(FactorKind::Totp, &TOTP), Unlock::Password(&p)),
];
for (a, b) in pairs {
assert_eq!(open(&bytes, a, b).unwrap().items().len(), 1);
}
// One factor, alone or twice, is never enough.
assert!(matches!(open(&bytes, Unlock::Password(&p), Unlock::Password(&p)), Err(Error::NeedTwoFactors)));
assert!(matches!(
open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Device, &DEVICE)),
Err(Error::NeedTwoFactors)
));
// The v1 entry point refuses a v2 vault rather than guessing.
assert!(matches!(Vault::open(&bytes, &p), Err(Error::NeedTwoFactors)));
}
#[test]
fn wrong_factors_are_named() {
let bytes = two_factor_vault().to_bytes().unwrap();
let dev = Unlock::Material(FactorKind::Device, &DEVICE);
assert!(matches!(open(&bytes, Unlock::Password(&pw("wrong")), dev), Err(Error::WrongPassword)));
let bad = [8u8; 32];
assert!(matches!(
open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &bad)),
Err(Error::FactorRejected)
));
// A factor of a type the vault does not have.
assert!(matches!(
open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Passkey, &PHONE)),
Err(Error::FactorRejected)
));
// Material outside 32..=64 bytes is refused before any work.
assert!(matches!(
open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &[1; 31])),
Err(Error::FactorRejected)
));
}
#[test]
fn a_factor_is_added_and_removed_without_the_others() {
let p = pw("Orbit7-Fable3");
let bytes = two_factor_vault().to_bytes().unwrap();
let mut v = open(&bytes, Unlock::Password(&p), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
// Only the new factor's material is needed: its pairs come from the factor keys in the body.
let phone = v.add_factor(Unlock::Material(FactorKind::Approval, &PHONE), "Phone").unwrap();
let bytes = v.to_bytes().unwrap();
let mut v = open(&bytes, Unlock::Material(FactorKind::Approval, &PHONE), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
let kinds: Vec<_> = v.factors().iter().map(|f| f.kind).collect();
assert_eq!(kinds, [FactorKind::Password, FactorKind::Device, FactorKind::Approval]);
// A lost device: drop its factor; the other two still open, the device no longer helps.
let device = v.factors()[1].id.clone();
v.remove_factor(&device).unwrap();
let bytes = v.to_bytes().unwrap();
assert!(open(&bytes, Unlock::Password(&p), Unlock::Material(FactorKind::Approval, &PHONE)).is_ok());
assert!(matches!(
open(&bytes, Unlock::Password(&p), Unlock::Material(FactorKind::Device, &DEVICE)),
Err(Error::FactorRejected)
));
// Never below two factors.
let mut v = open(&bytes, Unlock::Password(&p), Unlock::Material(FactorKind::Approval, &PHONE)).unwrap();
assert!(matches!(v.remove_factor(&phone), Err(Error::NeedTwoFactors)));
}
#[test]
fn a_forgotten_password_is_replaced_with_two_other_factors() {
let mut v = two_factor_vault();
v.add_factor(Unlock::Material(FactorKind::Totp, &TOTP), "TOTP backup").unwrap();
let bytes = v.to_bytes().unwrap();
let mut v = open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Totp, &TOTP)).unwrap();
v.change_password(&pw("New9-Password4"), FAST).unwrap();
let bytes2 = v.to_bytes().unwrap();
let dev = || Unlock::Material(FactorKind::Device, &DEVICE);
assert!(open(&bytes2, Unlock::Password(&pw("New9-Password4")), dev()).is_ok());
assert!(matches!(open(&bytes2, Unlock::Password(&pw("Orbit7-Fable3")), dev()), Err(Error::WrongPassword)));
// The vault key and the pair slots stayed: same key before and after.
let before = open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), dev()).unwrap();
let after = open(&bytes2, Unlock::Password(&pw("New9-Password4")), dev()).unwrap();
assert!(before.same_key_as(&after));
}
#[test]
fn a_v1_vault_upgrades_and_its_password_alone_stops_working() {
let p = pw("Orbit7-Fable3");
let mut v1 = Vault::create(&p, FAST).unwrap();
v1.add(Item::new(ItemType::SecureNote, "note", 1));
let old = v1.to_bytes().unwrap();
assert_eq!(Vault::version_of(&old).unwrap(), 1);
let mut v = Vault::open(&old, &p).unwrap();
v.upgrade_to_two_factors(&p, FAST, Unlock::Material(FactorKind::Device, &DEVICE), "MARK-PC").unwrap();
let new = v.to_bytes().unwrap();
assert_eq!(Vault::version_of(&new).unwrap(), 2);
assert_eq!(Vault::factor_kinds(&new).unwrap(), [FactorKind::Password, FactorKind::Device]);
// The header names each factor by the id the unlocked vault lists; a v1 file has none.
let ids = Vault::factor_ids(&new).unwrap();
let listed: Vec<(String, FactorKind)> = v.factors().into_iter().map(|f| (f.id, f.kind)).collect();
assert_eq!(ids, listed);
assert!(Vault::factor_ids(&old).unwrap().is_empty());
assert!(matches!(Vault::open(&new, &p), Err(Error::NeedTwoFactors)));
let back = open(&new, Unlock::Password(&p), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
assert_eq!(back.items().len(), 1);
assert!(back.same_key_as(&v1));
}
#[test]
fn flipping_any_header_byte_fails() {
let bytes = two_factor_vault().to_bytes().unwrap();
let header_len = bytes.len() - 16 - 30; // well inside the header + body; every byte is checked below
for i in 0..header_len {
let mut t = bytes.clone();
t[i] ^= 0x01;
let r = open(&t, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &DEVICE));
assert!(r.is_err(), "byte {i} flipped and the vault still opened");
}
}
#[test]
fn a_machine_store_opens_with_its_device_key_alone() {
const STORE: [u8; 32] = [42; 32];
let mut s = Vault::create_machine_store(&STORE, "Claude Code store").unwrap();
s.add(Item::new(ItemType::ApiCredential, "deploy key", 1));
let bytes = s.to_bytes().unwrap();
assert!(Vault::is_machine_store(&bytes).unwrap());
assert_eq!(Vault::open_machine_store(&bytes, &STORE).unwrap().items().len(), 1);
assert!(matches!(Vault::open_machine_store(&bytes, &[43; 32]), Err(Error::FactorRejected)));
// A user vault is never opened as a machine store, nor a store as a user vault.
let user = two_factor_vault().to_bytes().unwrap();
assert!(!Vault::is_machine_store(&user).unwrap());
assert!(matches!(Vault::open_machine_store(&user, &DEVICE), Err(Error::NeedTwoFactors)));
assert!(Vault::open_with(&bytes, Unlock::Material(FactorKind::Device, &STORE), Unlock::Material(FactorKind::Device, &STORE)).is_err());
}
#[test]
fn limits_are_enforced() {
let mut v = two_factor_vault();
for i in 0..6u8 {
v.add_factor(Unlock::Material(FactorKind::Device, &[100 + i; 32]), "extra").unwrap();
}
assert_eq!(v.factors().len(), 8);
assert!(matches!(v.add_factor(Unlock::Material(FactorKind::Device, &[1; 32]), "ninth"), Err(Error::TooManyFactors)));
// Every pair still opens with 8 factors (8 factor slots + 28 pair slots).
let bytes = v.to_bytes().unwrap();
assert!(open(&bytes, Unlock::Material(FactorKind::Device, &[100; 32]), Unlock::Material(FactorKind::Device, &[105; 32])).is_ok());
}
#[test]
fn no_factor_material_in_debug_output() {
let secret = [0xAB; 32];
let u = Unlock::Material(FactorKind::Device, &secret);
let p = pw("Orbit7-Fable3");
let printed = format!("{u:?} {:?}", Unlock::Password(&p));
assert!(!printed.contains("171") && !printed.to_lowercase().contains("ab, ab") && !printed.contains("Orbit7"), "{printed}");
let v = two_factor_vault();
let printed = format!("{v:?} {:?}", v.factors());
for f in v.factors() {
assert!(!printed.contains(&f.id[..8]) || !printed.contains("key"), "{printed}");
}
assert!(!printed.contains("0707070707"));
}
#[test]
fn the_key_pair_item_type_round_trips() {
let mut v = two_factor_vault();
let mut k = Item::new(ItemType::KeyPair, "deploy@home", 5);
k.set("algorithm", "ed25519", 5);
k.set("private-key", "-----BEGIN PRIVATE KEY-----\n…", 5);
v.add(k);
let bytes = v.to_bytes().unwrap();
let back = open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap();
let item = back.items().iter().find(|i| i.kind == ItemType::KeyPair).unwrap();
assert!(item.fields.iter().any(|f| f.name == "private-key" && f.secret));
}
#[test]
fn factors_on_one_device_never_open_together() {
let mut v = two_factor_vault();
let passkey = v.add_factor(Unlock::Material(FactorKind::Passkey, &PHONE), "Phone passkey").unwrap();
let approval = [12u8; 32];
v.add_factor_apart(Unlock::Material(FactorKind::Approval, &approval), "Phone", &[&passkey]).unwrap();
let bytes = v.to_bytes().unwrap();
let phone = Unlock::Material(FactorKind::Passkey, &PHONE);
let phone_approval = Unlock::Material(FactorKind::Approval, &approval);
assert!(matches!(open(&bytes, phone, phone_approval), Err(Error::SameDevice)));
assert!(matches!(open(&bytes, phone_approval, phone), Err(Error::SameDevice)));
// Each still pairs with everything else.
let p = pw("Orbit7-Fable3");
assert!(open(&bytes, Unlock::Password(&p), phone).is_ok());
assert!(open(&bytes, Unlock::Password(&p), phone_approval).is_ok());
assert!(open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), phone_approval).is_ok());
// A factor added later pairs with both.
let mut v = open(&bytes, Unlock::Password(&p), phone).unwrap();
v.add_factor(Unlock::Material(FactorKind::Totp, &TOTP), "TOTP backup").unwrap();
let bytes = v.to_bytes().unwrap();
assert!(open(&bytes, Unlock::Material(FactorKind::Totp, &TOTP), phone_approval).is_ok());
// Only existing factors can be named.
assert!(matches!(
v.add_factor_apart(Unlock::Material(FactorKind::Device, &[13; 32]), "x", &["00112233445566778899aabbccddeeff"]),
Err(Error::FactorRejected)
));
}
+395
View File
@@ -0,0 +1,395 @@
//! Mandatory tests for the Domi identity (docs/IDENTITY.md): the mnemonic order, the vector shared with
//! Fundamentum, signing only certs, persistence, and no way to get the root key out.
use custos_vault::identity::{Enrollment, Issued};
use custos_vault::{Error, FactorKind, KdfParams, SecretString, Unlock, Vault};
use ed25519_dalek::{Signature, VerifyingKey};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
/// The root public key of `abandon` × 23 + `art` (Fundamentum `crates/tessera/tests/mandatory.rs`).
const ROOT_PUB_ZERO: &str = "vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs";
const CERT_DOMAIN: &[u8] = b"tessera cert v1\0";
fn vault() -> Vault {
Vault::create(&SecretString::from("pw"), FAST).unwrap()
}
fn b64url(s: &str) -> Vec<u8> {
data_encoding::BASE64URL_NOPAD.decode(s.as_bytes()).unwrap()
}
/// Runs the whole enrolment with known entropy, typing the right words. Returns the words shown.
fn enrol(v: &mut Vault, entropy: [u8; 32]) -> Vec<String> {
let mut words = Vec::new();
let shown = Enrollment::with_entropy(entropy).show(|w| words = w.iter().map(|s| s.to_string()).collect());
let pick = shown.challenge().map(|i| words[i - 1].clone());
let confirmed = shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap();
confirmed.import(v).unwrap();
words
}
#[test]
fn the_zero_vector_matches_fundamentum() {
let mut v = vault();
let words = enrol(&mut v, [0; 32]);
assert_eq!(words.len(), 24);
assert!(words[..23].iter().all(|w| w == "abandon") && words[23] == "art");
assert_eq!(v.domi_root_public().unwrap().to_vec(), b64url(ROOT_PUB_ZERO));
}
#[test]
fn the_same_mnemonic_gives_the_same_root() {
let (mut a, mut b) = (vault(), vault());
enrol(&mut a, [42; 32]);
enrol(&mut b, [42; 32]);
assert_eq!(a.domi_root_public(), b.domi_root_public());
let mut c = vault();
enrol(&mut c, [43; 32]);
assert_ne!(a.domi_root_public(), c.domi_root_public());
}
#[test]
fn the_mnemonic_is_shown_before_anything_is_imported() {
// The order trap at run time; at compile time see the compile_fail doctests in src/identity.rs.
let v = vault();
let mut log = Vec::new();
let shown = Enrollment::begin().show(|w| {
assert_eq!(w.len(), 24);
log.push("shown");
});
assert_eq!(log, ["shown"]);
assert!(v.domi_root_public().is_none(), "nothing in the vault before confirm + import");
// Wrong words: refused, and the same Shown comes back to try again.
let (shown, e) = shown.confirm(&["zoo", "zoo", "zoo"]).expect_err("wrong words are refused");
assert!(matches!(e, Error::WrongWords));
let c = shown.challenge();
assert!(c.iter().all(|&i| (1..=24).contains(&i)) && c[0] != c[1] && c[1] != c[2] && c[0] != c[2]);
assert!(v.domi_root_public().is_none());
}
#[test]
fn the_challenge_accepts_any_spacing_and_case() {
let mut v = vault();
let mut words = Vec::new();
let shown = Enrollment::with_entropy([5; 32]).show(|w| words = w.iter().map(|s| s.to_string()).collect());
let pick = shown.challenge().map(|i| format!(" {} ", words[i - 1].to_uppercase()));
shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap().import(&mut v).unwrap();
assert!(v.domi_root_public().is_some());
}
#[test]
fn an_identity_is_created_once() {
let mut v = vault();
enrol(&mut v, [1; 32]);
let first = v.domi_root_public();
let mut words = Vec::new();
let shown = Enrollment::with_entropy([2; 32]).show(|w| words = w.iter().map(|s| s.to_string()).collect());
let pick = shown.challenge().map(|i| words[i - 1].clone());
let c = shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap();
assert!(matches!(c.import(&mut v), Err(Error::IdentityExists)));
assert_eq!(v.domi_root_public(), first);
}
/// A cert's to-be-signed bytes as tessera makes them: TSC1 ‖ root ‖ subkey ‖ ids ‖ validity.
fn tbs(root: &[u8; 32]) -> Vec<u8> {
let mut t = b"TSC1".to_vec();
t.extend_from_slice(root);
t.extend_from_slice(&[9; 32]);
t.extend_from_slice(b"\x06fiscus\x04sync");
t.extend_from_slice(&1u64.to_be_bytes());
t.extend_from_slice(&2u64.to_be_bytes());
t
}
#[test]
fn the_root_signs_certs_and_nothing_else() {
let mut v = vault();
assert!(matches!(v.domi_sign_cert(&tbs(&[0; 32])), Err(Error::NoIdentity)));
enrol(&mut v, [0; 32]);
let root = v.domi_root_public().unwrap();
let t = tbs(&root);
let sig = v.domi_sign_cert(&t).unwrap();
let vk = VerifyingKey::from_bytes(&root).unwrap();
vk.verify_strict(&[CERT_DOMAIN, &t].concat(), &Signature::from_bytes(&sig)).unwrap();
// Not a cert, a cert for another root, the bare prefix: refused.
assert!(matches!(v.domi_sign_cert(b"pay 100 CZK to mallory"), Err(Error::NotACert)));
assert!(matches!(v.domi_sign_cert(&tbs(&[1; 32])), Err(Error::NotACert)));
assert!(matches!(v.domi_sign_cert(&t[..36]), Err(Error::NotACert)));
}
#[test]
fn the_identity_survives_saving_in_both_versions() {
let issued = Issued {
kind: "app".into(),
app_id: "fiscus".into(),
purpose: "sync".into(),
subkey: "CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk".into(),
label: "fiscus.exe".into(),
not_before: 1,
not_after: 2,
issued: 3,
revoked_at: Some(4),
revocation: vec!["VFJWMQ".into()],
};
// Version 1.
let mut v = vault();
enrol(&mut v, [0; 32]);
v.domi_record(issued.clone()).unwrap();
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert_eq!(back.domi_root_public(), v.domi_root_public());
assert_eq!(back.domi_issued(), std::slice::from_ref(&issued));
assert!(back.domi_created().is_some());
let t = tbs(&back.domi_root_public().unwrap());
assert_eq!(back.domi_sign_cert(&t).unwrap(), v.domi_sign_cert(&t).unwrap(), "the same key came back");
// Version 2.
let pw = SecretString::from("pw");
let mut v2 =
Vault::create_with(Unlock::Password(&pw), "pw", Unlock::Material(FactorKind::Device, &[7; 32]), "pc", FAST)
.unwrap();
enrol(&mut v2, [3; 32]);
let bytes = v2.to_bytes().unwrap();
let back = Vault::open_with(&bytes, Unlock::Password(&pw), Unlock::Material(FactorKind::Device, &[7; 32])).unwrap();
assert_eq!(back.domi_root_public(), v2.domi_root_public());
// A vault without an identity still opens and has none.
let plain = Vault::open(&vault().to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert!(plain.domi_root_public().is_none() && plain.domi_issued().is_empty());
}
#[test]
fn a_record_needs_an_identity() {
let mut v = vault();
let i = Issued {
kind: "app".into(),
app_id: "x".into(),
purpose: "y".into(),
subkey: String::new(),
label: String::new(),
not_before: 0,
not_after: 1,
issued: 0,
..Issued::default()
};
assert!(matches!(v.domi_record(i), Err(Error::NoIdentity)));
assert!(matches!(v.domi_mark_revoked("x", 1), Err(Error::NoIdentity)));
assert!(matches!(v.domi_backup_secret("fiscus"), Err(Error::NoIdentity)));
}
// ---- v1.1: restoring, revoking, the backup secret (docs/IDENTITY.md) ----
const ZERO_PHRASE: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
abandon art";
const REVOKE_DOMAIN: &[u8] = b"tessera revoke v1\0";
const SUBKEY_9: &str = "CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk"; // [9; 32]
#[test]
fn the_24_words_restore_the_same_root() {
let mut v = vault();
Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut v).unwrap();
assert_eq!(v.domi_root_public().unwrap().to_vec(), b64url(ROOT_PUB_ZERO));
// Any case, any spacing, as long as the words are right.
let mut w = vault();
let messy = format!(" {}\n", ZERO_PHRASE.to_uppercase().replace(' ', " \t"));
Enrollment::restore(&messy).unwrap().import(&mut w).unwrap();
assert_eq!(w.domi_root_public(), v.domi_root_public());
// And from words that were shown: the same root as enrolling.
let mut e = vault();
let words = enrol(&mut e, [42; 32]);
let mut r = vault();
Enrollment::restore(&words.join(" ")).unwrap().import(&mut r).unwrap();
assert_eq!(r.domi_root_public(), e.domi_root_public());
}
#[test]
fn a_wrong_phrase_restores_nothing_and_names_no_word() {
let bad_checksum = ZERO_PHRASE.replace("art", "abandon");
let short = "abandon ".repeat(11) + "about";
let typo = ZERO_PHRASE.replacen("abandon", "abandn", 1);
for phrase in [bad_checksum.as_str(), short.as_str(), typo.as_str(), "", "art"] {
let e = Enrollment::restore(phrase).map(|_| ()).unwrap_err();
assert!(matches!(e, Error::NotAMnemonic), "{phrase}");
let shown = format!("{e} {e:?}");
assert!(!shown.contains("abandon") && !shown.contains("art "), "{shown}");
}
// Into a vault that has one already: refused, the old one stays.
let mut v = vault();
enrol(&mut v, [5; 32]);
let before = v.domi_root_public();
assert!(matches!(Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut v), Err(Error::IdentityExists)));
assert_eq!(v.domi_root_public(), before);
}
/// A revocation's to-be-signed bytes as tessera makes them: TRV1 ‖ root ‖ subkey ‖ revoked_at ‖ part ‖
/// parts ‖ count ‖ hashes.
fn trv1(root: &[u8; 32], subkey: &[u8; 32], revoked_at: u64) -> Vec<u8> {
let mut t = b"TRV1".to_vec();
t.extend_from_slice(root);
t.extend_from_slice(subkey);
t.extend_from_slice(&revoked_at.to_be_bytes());
t.extend_from_slice(&0u16.to_be_bytes());
t.extend_from_slice(&1u16.to_be_bytes());
t.extend_from_slice(&1u32.to_be_bytes());
t.extend_from_slice(&[7; 32]);
t
}
fn issued_to(subkey: &str, app_id: &str) -> Issued {
Issued {
kind: "app".into(),
app_id: app_id.into(),
purpose: "sync".into(),
subkey: subkey.into(),
label: "fiscus.exe".into(),
not_before: 1,
not_after: 2,
issued: 3,
..Issued::default()
}
}
#[test]
fn the_root_signs_a_revocation_only_for_a_key_the_person_revoked() {
let mut v = vault();
enrol(&mut v, [0; 32]);
let root = v.domi_root_public().unwrap();
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
// Issued, but not revoked yet: refused.
let t = trv1(&root, &[9; 32], 1000);
assert!(matches!(v.domi_sign_revocation(&t), Err(Error::NotARevocation)));
// An unknown key cannot be marked.
assert!(matches!(v.domi_mark_revoked("CgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo", 1000), Err(Error::UnknownKey)));
// A renewal issued a second cert for the same key: marking covers both, and the first time stays.
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
assert_eq!(v.domi_mark_revoked(SUBKEY_9, 1000).unwrap(), 1000);
assert_eq!(v.domi_mark_revoked(SUBKEY_9, 2000).unwrap(), 1000, "the first revocation time stays");
assert!(v.domi_issued().iter().all(|i| i.revoked_at == Some(1000)));
let sig = v.domi_sign_revocation(&t).unwrap();
let vk = VerifyingKey::from_bytes(&root).unwrap();
vk.verify_strict(&[REVOKE_DOMAIN, &t].concat(), &Signature::from_bytes(&sig)).unwrap();
assert!(
vk.verify_strict(&[CERT_DOMAIN, &t].concat(), &Signature::from_bytes(&sig)).is_err(),
"not a cert signature"
);
// Another time, another key, another root, a cert, garbage, the bare prefix: refused.
for bad in [
trv1(&root, &[9; 32], 999),
trv1(&root, &[10; 32], 1000),
trv1(&[1; 32], &[9; 32], 1000),
tbs(&root),
b"pay 100 CZK to mallory".to_vec(),
t[..76].to_vec(),
] {
assert!(matches!(v.domi_sign_revocation(&bad), Err(Error::NotARevocation)), "{bad:?}");
}
// And the cert signer never signs a revocation.
assert!(matches!(v.domi_sign_cert(&t), Err(Error::NotACert)));
// The statements are kept with every cert of the key, and survive a save.
v.domi_record_revocation(SUBKEY_9, vec!["first".into(), "second".into()]).unwrap();
assert!(matches!(
v.domi_record_revocation("CgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo", vec![]),
Err(Error::UnknownKey)
));
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
assert!(back.domi_issued().iter().all(|i| i.revoked_at == Some(1000) && i.revocation == ["first", "second"]));
assert_eq!(back.domi_sign_revocation(&t).unwrap(), sig);
}
#[test]
fn a_cert_without_a_revocation_is_saved_as_before() {
let mut v = vault();
enrol(&mut v, [0; 32]);
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
let json = serde_json::to_string(&v.domi_issued()[0]).unwrap();
assert!(!json.contains("revoked_at") && !json.contains("revocation"), "{json}");
// And a record from core 0.7.0, without the two members, reads.
let old: Issued = serde_json::from_str(
r#"{"kind":"app","app_id":"fiscus","purpose":"sync","subkey":"x","label":"l","not_before":1,"not_after":2,"issued":3}"#,
)
.unwrap();
assert_eq!((old.revoked_at, old.revocation.len()), (None, 0));
}
#[test]
fn the_backup_secret_matches_fundamentum() {
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
let mut v = vault();
enrol(&mut v, [0; 32]);
let secret = v.domi_backup_secret("fiscus").unwrap();
let expand = |info: &[u8]| {
let mut out = [0u8; 32];
hkdf::Hkdf::<sha2::Sha256>::from_prk(secret.as_ref()).unwrap().expand(info, &mut out).unwrap();
out
};
// Fundamentum docs/TESSERA.md §12.
assert_eq!(expand(b"mailbox").to_vec(), b64url("IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU"));
let key = expand(b"seal");
let tag = chacha20poly1305::XChaCha20Poly1305::new_from_slice(&key)
.unwrap()
.encrypt(&chacha20poly1305::XNonce::try_from(&[0u8; 24][..]).unwrap(), Payload { msg: b"", aad: b"" })
.unwrap();
assert_eq!(tag, b64url("ci_JRbtsx5prR83KT9Y7LA"));
// One per app, the same from the restored words.
assert_ne!(*v.domi_backup_secret("calenda").unwrap(), *secret);
let mut r = vault();
Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut r).unwrap();
assert_eq!(*r.domi_backup_secret("fiscus").unwrap(), *secret);
}
#[test]
fn nothing_prints_the_root() {
let mut v = vault();
let mut words = Vec::new();
let e = Enrollment::with_entropy([0; 32]);
assert_eq!(format!("{e:?}"), "Enrollment([redacted])");
let shown = e.show(|w| words = w.iter().map(|s| s.to_string()).collect());
assert_eq!(format!("{shown:?}"), "Shown([redacted])");
let pick = shown.challenge().map(|i| words[i - 1].clone());
let c = shown.confirm(&[&pick[0], &pick[1], &pick[2]]).map_err(|(_, e)| e).unwrap();
assert_eq!(format!("{c:?}"), "Confirmed([redacted])");
c.import(&mut v).unwrap();
let dbg = format!("{v:?}");
assert!(!dbg.contains("abandon") && !dbg.to_lowercase().contains("root"), "{dbg}");
}
/// No key export: the public surface of the identity module is locked. A new public function fails this
/// test until it has been checked to return no secret.
#[test]
fn the_identity_surface_is_locked() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut got = Vec::new();
for file in ["identity.rs", "lib.rs"] {
let text = std::fs::read_to_string(dir.join(file)).unwrap();
for line in text.lines() {
let l = line.trim();
if l.starts_with("pub fn ") && (file == "identity.rs" || l.starts_with("pub fn domi_")) {
got.push(format!("{file}: {}", l.trim_end_matches(" {")));
}
}
}
got.sort();
let mut want = vec![
"identity.rs: pub fn begin() -> Enrollment",
"identity.rs: pub fn challenge(&self) -> [usize; 3]",
"identity.rs: pub fn confirm(self, words: &[&str; 3]) -> Result<Confirmed, (Shown, Error)>",
"identity.rs: pub fn import(self, vault: &mut Vault) -> Result<[u8; 32], Error>",
"identity.rs: pub fn restore(phrase: &str) -> Result<Confirmed, Error>",
"identity.rs: pub fn show(self, display: impl FnOnce(&[&str])) -> Shown",
"identity.rs: pub fn with_entropy(entropy: [u8; 32]) -> Enrollment",
// The app's own backup secret, derived: by design (docs/IDENTITY.md), never the root.
"lib.rs: pub fn domi_backup_secret(&self, app_id: &str) -> Result<Zeroizing<[u8; 32]>, Error>",
"lib.rs: pub fn domi_created(&self) -> Option<i64>",
"lib.rs: pub fn domi_issued(&self) -> &[identity::Issued]",
"lib.rs: pub fn domi_mark_revoked(&mut self, subkey: &str, revoked_at: u64) -> Result<u64, Error>",
"lib.rs: pub fn domi_record(&mut self, issued: identity::Issued) -> Result<(), Error>",
"lib.rs: pub fn domi_record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error>",
"lib.rs: pub fn domi_root_public(&self) -> Option<[u8; 32]>",
"lib.rs: pub fn domi_sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error>",
"lib.rs: pub fn domi_sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error>",
];
want.sort();
assert_eq!(got, want, "review the identity surface: it must never return the root secret");
}
+47 -2
View File
@@ -2,7 +2,8 @@
//! password change, no secret in Debug/Display.
use custos_vault::{
CrashPoint, Error, Field, Item, ItemType, KdfParams, SecretString, Vault, save_atomic, save_atomic_crashing,
Attachment, CrashPoint, Error, Field, Item, ItemType, KdfParams, SecretBytes, SecretString, Vault, save_atomic,
save_atomic_crashing,
};
use std::path::Path;
@@ -104,8 +105,11 @@ fn tampered_kdf_params_are_refused_before_argon2_runs() {
fn not_a_vault_and_future_versions_are_refused() {
assert!(matches!(Vault::open(b"hello world, not a vault at all", &pw("x")), Err(Error::NotAVault)));
let mut bytes = sample_vault("pw").to_bytes().unwrap();
// Version 2 exists now (docs/FACTORS.md); a v1 file relabelled as 2 is malformed, 3 is unknown.
bytes[6] = 2;
assert!(matches!(Vault::open(&bytes, &pw("pw")), Err(Error::UnsupportedVersion(2))));
assert!(matches!(Vault::open(&bytes, &pw("pw")), Err(Error::Malformed)));
bytes[6] = 3;
assert!(matches!(Vault::open(&bytes, &pw("pw")), Err(Error::UnsupportedVersion(3))));
}
fn opens_with(path: &Path, password: &str, title: &str) -> bool {
@@ -226,3 +230,44 @@ fn device_wrap_opens_the_same_vault_and_nothing_else() {
assert!(Vault::open_with_device(&bytes, &other, material).is_err());
assert!(!format!("{:?}", Error::DeviceKeyRejected).contains("signature"));
}
#[test]
fn folders_and_attachments_survive_a_save_and_old_bodies_still_open() {
// core 0.8.0 (docs/FORMAT.md): `folder` and `attachments` are optional item members.
let mut item = Item::new(ItemType::SecureNote, "Keys", 1);
item.folder = vec!["Internet".into(), "Mail".into()];
item.attachments =
vec![Attachment { name: "id_ed25519".into(), data: SecretBytes::from(&b"\x00\xffAttached-Secret"[..]) }];
let mut v = Vault::create(&pw("pw"), FAST).unwrap();
v.add(item.clone());
v.add(Item::new(ItemType::WebLogin, "Plain", 1));
let back = Vault::open(&v.to_bytes().unwrap(), &pw("pw")).unwrap();
assert_eq!(back.items(), v.items());
assert_eq!(back.items()[0].folder, ["Internet", "Mail"]);
assert_eq!(back.items()[0].attachments[0].data.expose(), b"\x00\xffAttached-Secret");
assert!(back.items()[1].folder.is_empty() && back.items()[1].attachments.is_empty());
// An item written by an older core has neither member.
let old: Item = serde_json::from_str(
r#"{"id":"00112233445566778899aabbccddeeff","type":"web-login","title":"Old","created":1,"modified":1}"#,
)
.unwrap();
assert!(old.folder.is_empty() && old.attachments.is_empty());
// Without them, the JSON has no trace of them either (an older core reads it unchanged).
let json = serde_json::to_string(&old).unwrap();
assert!(!json.contains("folder") && !json.contains("attachments"), "{json}");
// Attachment data that is not base64 is refused, not guessed.
let bad = r#"{"id":"0","type":"secure-note","title":"x","created":1,"modified":1,"attachments":[{"name":"a","data":"!!"}]}"#;
assert!(serde_json::from_str::<Item>(bad).is_err());
}
#[test]
fn attachment_bytes_never_print() {
let a = Attachment { name: "secret.txt".into(), data: SecretBytes::from(&b"Attached-Secret-Bytes"[..]) };
let mut item = Item::new(ItemType::SecureNote, "With file", 1);
item.attachments.push(a.clone());
for out in [format!("{a:?}"), format!("{item:?}"), format!("{item:#?}"), format!("{:?}", a.data)] {
assert!(!out.contains("Attached-Secret-Bytes") && !out.contains("QXR0YWNoZWQt"), "{out}");
}
assert!(format!("{a:?}").contains("secret.txt"));
}
+207
View File
@@ -0,0 +1,207 @@
//! Mandatory tests for signing keys (docs/SIGNING.md): scope (4) and the audit log through a reopen (6). That no API
//! path returns a private key (2) is a unit test in src/signing.rs, which can see the stored secrets; the app tests
//! it again over its pipe ops and mailbox messages.
use custos_vault::signing::{Approval, AuditEntry, Context, KeyKind, Outcome, Refusal, Request, Role, SignKind, Via};
use custos_vault::{Error, KdfParams, SecretString, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
fn vault_with_keys() -> Vault {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca", "Fabrica"]), NOW).unwrap();
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap();
v
}
fn ctx(pipeline: &str, repo: &str, trigger: &str) -> Context {
Context {
repo: repo.into(),
commit: "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1".into(),
pipeline: pipeline.into(),
step: "sign".into(),
trigger: trigger.into(),
file: "Arca_0.2.0_x64-setup.exe".into(),
size: 25_145_977,
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
}
}
fn minisign_req(key: &str, c: Context) -> Request {
Request {
key: key.into(),
kind: SignKind::Minisign,
digest: vec![7; 64],
manifest: None,
context: c,
via: Via::Local,
}
}
fn authenticode_req(key: &str, c: Context) -> Request {
Request {
key: key.into(),
kind: SignKind::Authenticode,
digest: vec![9; 32],
manifest: None,
context: c,
via: Via::Remote,
}
}
#[test]
fn the_release_and_test_sets_are_made_once_each() {
let mut v = vault_with_keys();
let keys = v.signing_keys();
let ids: Vec<&str> = keys.iter().map(|k| k.id.as_str()).collect();
assert_eq!(
ids,
["domi-release", "domi-root", "domi-code-signing", "domi-test", "domi-test-root", "domi-test-code-signing"]
);
assert_eq!(keys[1].kind, KeyKind::RootCa);
assert_eq!(keys[2].issuer.as_deref(), Some("domi-root"));
assert_eq!(keys[5].issuer.as_deref(), Some("domi-test-root"));
assert!(!keys[0].auto_approve && !keys[2].auto_approve);
assert!(keys[3].auto_approve && keys[5].auto_approve && !keys[4].auto_approve);
assert!(keys[0].minisign_public.as_deref().unwrap().starts_with("untrusted comment: minisign public key "));
assert!(matches!(v.signing_create(Role::Release, &[], &[], NOW), Err(Error::SigningExists("release"))));
// The root's certificate is exported; a key without one is not.
assert_eq!(v.signing_export_cert("domi-root").unwrap(), keys[1].cert.clone().unwrap());
assert!(v.signing_export_cert("domi-release").is_err());
}
#[test]
fn every_kind_signs_and_verifies() {
use rsa::pkcs1v15::{Signature, VerifyingKey};
use rsa::pkcs8::DecodePublicKey;
use rsa::signature::hazmat::PrehashVerifier;
use x509_cert::der::{Decode, Encode};
let mut v = vault_with_keys();
let data = b"the installer";
let mut req = minisign_req("domi-release", ctx("release", "Arca", "tag"));
req.digest = custos_sign::blake2b512(data).to_vec();
let sig = v.signing_sign(&req, Approval::Mark, NOW).unwrap();
let public = minisign_verify::PublicKey::decode(v.signing_keys()[0].minisign_public.as_deref().unwrap()).unwrap();
let text = String::from_utf8(sig.bytes.clone()).unwrap();
public.verify(data, &minisign_verify::Signature::decode(&text).unwrap(), false).unwrap();
assert_eq!(sig.sha256, custos_sign::sha256_hex(&sig.bytes));
let sums = format!("{} Arca_0.2.0_x64-setup.exe\n", "c".repeat(64));
let man = Request { kind: SignKind::Manifest, digest: vec![], manifest: Some(sums.clone()), ..req.clone() };
let msig = v.signing_sign(&man, Approval::Mark, NOW).unwrap();
public
.verify(
sums.as_bytes(),
&minisign_verify::Signature::decode(std::str::from_utf8(&msig.bytes).unwrap()).unwrap(),
false,
)
.unwrap();
let auth = authenticode_req("domi-code-signing", ctx("release", "Arca", "tag"));
let asig = v.signing_sign(&auth, Approval::Mark, NOW).unwrap();
let cert = x509_cert::Certificate::from_der(&v.signing_export_cert("domi-code-signing").unwrap()).unwrap();
let key = VerifyingKey::<sha2_010::Sha256>::from_public_key_der(
&cert.tbs_certificate.subject_public_key_info.to_der().unwrap(),
)
.unwrap();
key.verify_prehash(&auth.digest, &Signature::try_from(asig.bytes.as_slice()).unwrap()).unwrap();
}
#[test]
fn a_pipeline_or_repo_off_the_list_is_refused_even_when_approved() {
let mut v = vault_with_keys();
for c in [ctx("nightly", "Arca", "tag"), ctx("release", "Custos", "tag")] {
let req = minisign_req("domi-release", c);
assert!(matches!(v.signing_check(&req), Err(Refusal::OutOfScope(_))));
assert!(matches!(v.signing_sign(&req, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))));
}
let leaf = authenticode_req("domi-code-signing", ctx("release", "Custos", "tag"));
assert!(
matches!(v.signing_sign(&leaf, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))),
"the leaf has the same scope"
);
// Widening the scope takes an explicit change.
v.signing_set_scope("domi-release", &s(&["release", "nightly"]), &s(&["Arca"])).unwrap();
assert!(v.signing_sign(&minisign_req("domi-release", ctx("nightly", "Arca", "tag")), Approval::Mark, NOW).is_ok());
assert!(v.signing_set_scope("domi-root", &s(&["*"]), &s(&["*"])).is_err());
}
#[test]
fn release_keys_never_sign_without_mark_and_test_keys_never_sign_a_tag() {
let mut v = vault_with_keys();
let r = v.signing_sign(&minisign_req("domi-release", ctx("release", "Arca", "tag")), Approval::Auto, NOW);
assert!(matches!(r, Err(Refusal::NeedsApproval(_))));
let t = v.signing_sign(&minisign_req("domi-test", ctx("ci", "Arca", "manual")), Approval::Auto, NOW);
assert!(t.is_ok());
let tag = v.signing_sign(&minisign_req("domi-test", ctx("ci", "Arca", "tag")), Approval::Auto, NOW);
assert!(matches!(tag, Err(Refusal::OutOfScope(m)) if m.contains("never signs a tag")));
let leaf =
v.signing_sign(&authenticode_req("domi-test-code-signing", ctx("ci", "Arca", "push")), Approval::Auto, NOW);
assert!(leaf.is_ok());
}
#[test]
fn malformed_requests_and_the_root_are_refused() {
let mut v = vault_with_keys();
let mut short = minisign_req("domi-release", ctx("release", "Arca", "tag"));
short.digest = vec![0; 32];
let wrong_key = authenticode_req("domi-release", ctx("release", "Arca", "tag"));
let root = authenticode_req("domi-root", ctx("release", "Arca", "tag"));
let mut path = minisign_req("domi-release", ctx("release", "Arca", "tag"));
path.context.file = "..\\evil.exe".into();
let man =
Request { kind: SignKind::Manifest, manifest: Some("not sums\n".into()), digest: vec![], ..short.clone() };
let none = minisign_req("nope", ctx("release", "Arca", "tag"));
for r in [&short, &wrong_key, &root, &path, &man] {
assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{r:?}");
}
assert!(matches!(v.signing_sign(&none, Approval::Mark, NOW), Err(Refusal::NoKey(_))));
}
#[test]
fn the_audit_log_records_every_outcome_and_survives_a_reopen() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("v.custos");
let mut v = vault_with_keys();
let rel = minisign_req("domi-release", ctx("release", "Arca", "tag"));
let signed = v.signing_sign(&rel, Approval::Mark, NOW).unwrap();
v.signing_sign(&minisign_req("domi-test", ctx("ci", "Arca", "manual")), Approval::Auto, NOW + 1).unwrap();
v.signing_refuse(&rel, Outcome::Refused, None, NOW + 2);
v.signing_refuse(&rel, Outcome::Expired, Some("no answer in 5 minutes".into()), NOW + 3);
let _ = v.signing_sign(&minisign_req("domi-release", ctx("nightly", "Arca", "tag")), Approval::Mark, NOW + 4);
let _ = v.signing_sign(&minisign_req("nope", ctx("release", "Arca", "tag")), Approval::Mark, NOW + 5);
// A refusal can never be recorded as a signature.
v.signing_refuse(&rel, Outcome::Approved, None, NOW + 6);
v.save(&path).unwrap();
let reopened = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
let audit: &[AuditEntry] = reopened.signing_audit();
let outcomes: Vec<Outcome> = audit.iter().map(|e| e.outcome).collect();
assert_eq!(
outcomes,
[
Outcome::Approved,
Outcome::Auto,
Outcome::Refused,
Outcome::Expired,
Outcome::OutOfScope,
Outcome::Invalid,
Outcome::Refused
]
);
assert_eq!(audit[0].signature.as_deref(), Some(signed.sha256.as_str()));
assert!(audit[2..].iter().all(|e| e.signature.is_none()));
assert_eq!(audit[0].context, ctx("release", "Arca", "tag"));
assert_eq!(audit[0].via, Via::Local);
assert_eq!(audit[3].reason.as_deref(), Some("no answer in 5 minutes"));
assert_eq!(reopened.signing_audit(), v.signing_audit());
// The keys came back too, and still sign.
let mut reopened = reopened;
assert!(reopened.signing_sign(&rel, Approval::Mark, NOW + 7).is_ok());
}
+3
View File
@@ -14,6 +14,7 @@ custos-vault = { path = "../custos-vault" }
custos-share = { path = "../custos-share" }
custos-totp = { path = "../custos-totp" }
custos-qr = { path = "../custos-qr" }
custos-seal = { path = "../custos-seal" }
serde.workspace = true
serde_json.workspace = true
data-encoding.workspace = true
@@ -22,3 +23,5 @@ qrcode = { version = "0.14", default-features = false, features = ["svg"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
getrandom = "0.4"
# rand_core 0.6 (custos-sign, through custos-vault) uses getrandom 0.2: the same browser CSPRNG (lib.rs, `fill_v02`).
getrandom02 = { package = "getrandom", version = "0.2", features = ["custom"] }
+208 -1
View File
@@ -16,9 +16,15 @@
//! Requests are `{"op": …, …}`; responses `{"ok": true, …}` or `{"ok": false, "error": "<message>"}`.
//! See [`handle`] for the operations. One vault at a time is held here while unlocked; `lock` drops it
//! (and with it the key, wiped).
//!
//! Two factors (docs/FACTORS.md, docs/SEAL.md): the page asks for a one-time key (`recipient`), sends its
//! public half to the factor service, and passes the sealed answer back in `open_with`. The key's secret
//! half never leaves this module. A paired phone keeps its approval material wrapped with its passkey's
//! PRF output (`phone_enrol`, `phone_approve`); unwrapped, it exists only inside one call.
use custos_seal::Recipient;
use custos_share::{Payload, ShareError};
use custos_vault::{Item, ItemType, SecretString, Vault};
use custos_vault::{FactorKind, Item, ItemType, SecretString, Unlock, Vault};
use data_encoding::BASE64;
use qrcode::render::svg;
use qrcode::{EcLevel, QrCode};
@@ -29,6 +35,24 @@ use zeroize::Zeroizing;
thread_local! {
static VAULT: RefCell<Option<Vault>> = const { RefCell::new(None) };
/// One-time keys waiting for a sealed answer, by their public key (base64). Each is used once.
static RECIPIENTS: RefCell<Vec<(String, Recipient)>> = const { RefCell::new(Vec::new()) };
}
/// At most this many one-time keys wait at once; the oldest goes first.
const MAX_RECIPIENTS: usize = 8;
/// The at-rest context of a phone's approval material, wrapped with its passkey's PRF output.
const PHONE_APPROVAL: &[u8] = b"custos phone approval v1";
/// One factor given to `open_with`.
#[derive(Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", rename_all_fields = "camelCase")]
enum FactorIn {
Password { password: SecretString },
/// A factor service's or a device's answer, sealed to a key from `recipient` (`pub`) for `context`.
Sealed { factor: FactorKind, r#pub: String, sealed: String, context: String },
/// Material the page holds itself: a passkey's PRF output (base64).
Material { factor: FactorKind, material: SecretString },
}
#[derive(Deserialize)]
@@ -67,6 +91,47 @@ enum Request {
fragment: String,
password: Option<SecretString>,
},
/// The format version and the factors (id, type) of a vault, from its header alone.
Factors {
vault: String,
},
/// A new one-time key: `{pub, match}`.
Recipient,
/// The match code of a public key (base64), for example a requesting device's.
MatchCode {
r#pub: String,
},
/// Opens a version-2 vault with two different factors.
OpenWith {
vault: String,
factors: Vec<FactorIn>,
},
/// Pairs this phone with a PC that waits with the one-time key `pub`: makes the phone's approval
/// material and seals it with the passkey's PRF output (`prf`, base64) to the PC for `context`.
/// Returns the box, its sender code, and the material wrapped with the PRF output (`wrapped`).
PhoneEnrol {
r#pub: String,
context: String,
label: String,
prf: SecretString,
},
/// Approves a request: unwraps this phone's approval material with the PRF output and seals it to
/// the requester's key for `context` (`approval:<factor>:<request id>`).
PhoneApprove {
wrapped: String,
prf: SecretString,
r#pub: String,
context: String,
},
/// Pairs this phone as a Domi device (Custos docs/07_domi_identity.md): seals its device label and its
/// Ed25519 device public key (`device`, base64url, made non-extractable by the page) to the PC that
/// waits with `pub`, for `domi-pair:<id>`. Returns the box and its sender code. Nothing secret goes in.
DomiPair {
r#pub: String,
id: String,
label: String,
device: String,
},
}
fn err(msg: impl ToString) -> Value {
@@ -80,6 +145,7 @@ pub fn primary_secret(kind: ItemType) -> &'static str {
ItemType::ApiCredential => "secret",
ItemType::Card => "number",
ItemType::SecureNote => "notes",
ItemType::KeyPair => "private-key",
}
}
@@ -90,6 +156,7 @@ fn primary_user(kind: ItemType) -> Option<&'static str> {
ItemType::Wifi => Some("ssid"),
ItemType::Card => Some("cardholder"),
ItemType::SecureNote => None,
ItemType::KeyPair => Some("public-key"),
}
}
@@ -176,6 +243,48 @@ fn payload_json(p: &Payload) -> Value {
})
}
fn b64(s: &str) -> Option<Zeroizing<Vec<u8>>> {
BASE64.decode(s.as_bytes()).ok().map(Zeroizing::new)
}
fn key32(s: &SecretString) -> Option<Zeroizing<[u8; 32]>> {
let v = b64(s.expose())?;
let a: [u8; 32] = v.as_slice().try_into().ok()?;
Some(Zeroizing::new(a))
}
fn take_recipient(public: &str) -> Option<Recipient> {
RECIPIENTS.with_borrow_mut(|r| r.iter().position(|(p, _)| p == public).map(|i| r.remove(i).1))
}
/// The material for one factor; a password stays a password.
enum Given {
Password(SecretString),
Material(FactorKind, Zeroizing<Vec<u8>>),
}
fn given(f: FactorIn) -> Result<Given, String> {
match f {
FactorIn::Password { password } => Ok(Given::Password(password)),
FactorIn::Material { factor, material } => {
Ok(Given::Material(factor, b64(material.expose()).ok_or("A malformed factor.")?))
}
FactorIn::Sealed { factor, r#pub, sealed, context } => {
let me = take_recipient(&r#pub).ok_or("That request expired. Ask again.")?;
let sealed = b64(&sealed).ok_or("A malformed answer.")?;
let m = me.open(&sealed, context.as_bytes()).map_err(|e| e.to_string())?;
Ok(Given::Material(factor, m))
}
}
}
fn unlock(g: &Given) -> Unlock<'_> {
match g {
Given::Password(p) => Unlock::Password(p),
Given::Material(k, m) => Unlock::Material(*k, m),
}
}
fn share_error(e: ShareError) -> Value {
json!({ "ok": false, "error": e.to_string(), "code": format!("{e:?}") })
}
@@ -252,6 +361,96 @@ pub fn handle(request: &[u8]) -> Value {
Err(e) => share_error(e),
}
}
Request::Factors { vault } => {
let Some(bytes) = b64(&vault) else { return err("The vault file is damaged.") };
match (Vault::version_of(&bytes), Vault::factor_ids(&bytes)) {
(Ok(version), Ok(ids)) => json!({
"ok": true,
"version": version,
"factors": ids.iter().map(|(id, kind)| json!({ "id": id, "kind": kind })).collect::<Vec<_>>(),
}),
(Err(e), _) | (_, Err(e)) => err(e),
}
}
Request::Recipient => {
let me = Recipient::generate();
let public = BASE64.encode(&me.public());
let code = me.match_code();
RECIPIENTS.with_borrow_mut(|r| {
if r.len() >= MAX_RECIPIENTS {
r.remove(0);
}
r.push((public.clone(), me));
});
json!({ "ok": true, "pub": public, "match": code })
}
Request::MatchCode { r#pub } => match b64(&r#pub) {
Some(p) if p.len() == 32 => json!({ "ok": true, "match": custos_seal::match_code(&p) }),
_ => err("Not a valid public key."),
},
Request::OpenWith { vault, factors } => {
let Some(bytes) = b64(&vault) else { return err("The vault file is damaged.") };
let mut factors = factors.into_iter();
let (Some(a), Some(b), None) = (factors.next(), factors.next(), factors.next()) else {
return err("Choose two different factors.");
};
let (a, b) = match (given(a), given(b)) {
(Ok(a), Ok(b)) => (a, b),
(Err(e), _) | (_, Err(e)) => return err(e),
};
match Vault::open_with(&bytes, unlock(&a), unlock(&b)) {
Ok(v) => {
let out = items(&v);
VAULT.set(Some(v));
out
}
Err(e) => err(e),
}
}
Request::PhoneEnrol { r#pub, context, label, prf } => {
let (Some(public), Some(prf_key)) = (b64(&r#pub), key32(&prf)) else { return err("A malformed request.") };
let material = custos_seal::random_bytes();
let plain = Zeroizing::new(
json!({ "label": label, "passkey": prf.expose(), "approval": BASE64.encode(material.as_ref()) })
.to_string(),
);
match custos_seal::seal(&public, context.as_bytes(), plain.as_bytes()) {
Ok(sealed) => json!({
"ok": true,
"code": custos_seal::sender_code(&sealed).unwrap_or_default(),
"sealed": BASE64.encode(&sealed),
"wrapped": BASE64.encode(&custos_seal::seal_at_rest(&prf_key, PHONE_APPROVAL, material.as_ref())),
}),
Err(e) => err(e),
}
}
Request::DomiPair { r#pub, id, label, device } => {
let device_ok = data_encoding::BASE64URL_NOPAD.decode(device.as_bytes()).is_ok_and(|d| d.len() == 32);
let id_ok = !id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
let (Some(public), true, true) = (b64(&r#pub), device_ok, id_ok) else { return err("A malformed request.") };
let label: String = label.trim().chars().filter(|c| !c.is_control()).take(40).collect();
let plain = json!({ "label": label, "device": device }).to_string();
match custos_seal::seal(&public, format!("domi-pair:{id}").as_bytes(), plain.as_bytes()) {
Ok(sealed) => json!({
"ok": true,
"code": custos_seal::sender_code(&sealed).unwrap_or_default(),
"sealed": BASE64.encode(&sealed),
}),
Err(e) => err(e),
}
}
Request::PhoneApprove { wrapped, prf, r#pub, context } => {
let (Some(wrapped), Some(prf_key), Some(public)) = (b64(&wrapped), key32(&prf), b64(&r#pub)) else {
return err("A malformed request.");
};
let Ok(material) = custos_seal::open_at_rest(&prf_key, PHONE_APPROVAL, &wrapped) else {
return err("This passkey does not belong to this phone's pairing.");
};
match custos_seal::seal(&public, context.as_bytes(), &material) {
Ok(sealed) => json!({ "ok": true, "sealed": BASE64.encode(&sealed) }),
Err(e) => err(e),
}
}
}
}
@@ -274,6 +473,14 @@ mod abi {
Ok(())
}
/// The same for getrandom 0.2, which rand_core 0.6 (custos-sign's RSA and X.509 crates) is built on. The
/// browser never makes signing keys, but the crates must link.
fn fill_v02(dest: &mut [u8]) -> Result<(), getrandom02::Error> {
unsafe { random_fill(dest.as_mut_ptr(), dest.len()) };
Ok(())
}
getrandom02::register_custom_getrandom!(fill_v02);
#[unsafe(no_mangle)]
pub extern "C" fn alloc(len: usize) -> *mut u8 {
if len == 0 {
+158
View File
@@ -0,0 +1,158 @@
//! Two factors in the browser: opening a version-2 vault with a sealed answer or a passkey's PRF output,
//! and a phone's pairing and approvals (docs/FACTORS.md, docs/SEAL.md).
use custos_seal::Recipient;
use custos_vault::{FactorKind, Item, ItemType, KdfParams, SecretString, Unlock, Vault};
use data_encoding::BASE64;
use serde_json::{Value, json};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const PASSWORD: &str = "Test4-Vault7-Only2";
const SECRET: &str = "s3cret-Ž!";
fn call(v: Value) -> Value {
custos_wasm::handle(v.to_string().as_bytes())
}
/// A version-2 vault: the master password and a TOTP factor with `totp` as its material.
fn vault(totp: &[u8]) -> Vault {
let pw = SecretString::from(PASSWORD);
let mut v = Vault::create_with(Unlock::Password(&pw), "Master password", Unlock::Material(FactorKind::Totp, totp), "TOTP", FAST)
.unwrap();
let mut login = Item::new(ItemType::WebLogin, "GitHub", 0);
login.set("password", SECRET, 0);
v.add(login);
v
}
fn b64(v: &Vault) -> String {
BASE64.encode(&v.to_bytes().unwrap())
}
#[test]
fn factors_from_the_header() {
let v = vault(&[3; 32]);
let r = call(json!({ "op": "factors", "vault": b64(&v) }));
assert_eq!(r["version"], 2, "{r}");
let kinds: Vec<&str> = r["factors"].as_array().unwrap().iter().map(|f| f["kind"].as_str().unwrap()).collect();
assert_eq!(kinds, ["password", "totp"]);
let totp = v.factors().into_iter().find(|f| f.kind == FactorKind::Totp).unwrap();
assert_eq!(r["factors"][1]["id"], totp.id.as_str());
}
#[test]
fn open_with_password_and_a_sealed_totp_release() {
let material = [3u8; 32];
let v = vault(&material);
let file = b64(&v);
let totp = v.factors().into_iter().find(|f| f.kind == FactorKind::Totp).unwrap().id;
let context = format!("totp:{totp}");
let me = call(json!({ "op": "recipient" }));
let public = BASE64.decode(me["pub"].as_str().unwrap().as_bytes()).unwrap();
assert_eq!(me["match"], custos_seal::match_code(&public));
// What the factor service sends back after a valid code.
let sealed = BASE64.encode(&custos_seal::seal(&public, context.as_bytes(), &material).unwrap());
let sealed_in = |ctx: &str| json!({ "kind": "sealed", "factor": "totp", "pub": me["pub"], "sealed": sealed, "context": ctx });
let password = json!({ "kind": "password", "password": PASSWORD });
// Only the right context opens it.
let wrong = call(json!({ "op": "open_with", "vault": file, "factors": [password, sealed_in("totp:other")] }));
assert_eq!(wrong["ok"], false);
// The key is used once, even when the answer was refused.
let again = call(json!({ "op": "open_with", "vault": file, "factors": [password, sealed_in(&context)] }));
assert_eq!(again["error"], "That request expired. Ask again.");
let me = call(json!({ "op": "recipient" }));
let public = BASE64.decode(me["pub"].as_str().unwrap().as_bytes()).unwrap();
let sealed = BASE64.encode(&custos_seal::seal(&public, context.as_bytes(), &material).unwrap());
let ok = call(json!({ "op": "open_with", "vault": file, "factors": [
{ "kind": "sealed", "factor": "totp", "pub": me["pub"], "sealed": sealed, "context": context },
password,
]}));
assert_eq!(ok["ok"], true, "{ok}");
assert_eq!(ok["items"].as_array().unwrap().len(), 1);
assert!(!ok.to_string().contains(SECRET));
call(json!({ "op": "lock" }));
// One factor, or the same one twice, never opens it.
for factors in [json!([password]), json!([password, password])] {
let r = call(json!({ "op": "open_with", "vault": file, "factors": factors }));
assert_eq!(r["ok"], false, "{r}");
}
}
#[test]
fn a_phone_pairs_then_opens_and_approves() {
let mut v = vault(&[3; 32]);
let prf = [9u8; 32];
let prf64 = BASE64.encode(&prf);
// The PC waits with a one-time key; the phone seals its pairing to it.
let pc = Recipient::generate();
let context = "pair:abc";
let r = call(json!({ "op": "phone_enrol", "pub": BASE64.encode(&pc.public()), "context": context, "label": "Phone", "prf": prf64 }));
assert_eq!(r["ok"], true, "{r}");
let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap();
assert_eq!(r["code"], custos_seal::sender_code(&sealed).unwrap(), "the PC checks the code the phone shows");
assert!(pc.open(&sealed, b"pair:other").is_err());
let plain: Value = serde_json::from_slice(&pc.open(&sealed, context.as_bytes()).unwrap()).unwrap();
assert_eq!((plain["label"].as_str(), plain["passkey"].as_str()), (Some("Phone"), Some(prf64.as_str())));
let approval = BASE64.decode(plain["approval"].as_str().unwrap().as_bytes()).unwrap();
assert_eq!(approval.len(), 32);
let wrapped = r["wrapped"].as_str().unwrap();
assert!(!r.to_string().contains(plain["approval"].as_str().unwrap()), "the material leaves only sealed or wrapped");
// The PC adds both factors.
let passkey_id = v.add_factor(Unlock::Material(FactorKind::Passkey, &prf), "Phone passkey").unwrap();
let approval_id = v.add_factor_apart(Unlock::Material(FactorKind::Approval, &approval), "Phone", &[&passkey_id]).unwrap();
let file = b64(&v);
// The phone opens it with its passkey and the master password.
let r = call(json!({ "op": "open_with", "vault": file, "factors": [
{ "kind": "material", "factor": "passkey", "material": prf64 },
{ "kind": "password", "password": PASSWORD },
]}));
assert_eq!(r["ok"], true, "{r}");
call(json!({ "op": "lock" }));
// Its two factors never open it together.
let me = call(json!({ "op": "recipient" }));
let public = BASE64.decode(me["pub"].as_str().unwrap().as_bytes()).unwrap();
let sealed = BASE64.encode(&custos_seal::seal(&public, b"approval:x:y", &approval).unwrap());
let r = call(json!({ "op": "open_with", "vault": file, "factors": [
{ "kind": "material", "factor": "passkey", "material": prf64 },
{ "kind": "sealed", "factor": "approval", "pub": me["pub"], "sealed": sealed, "context": "approval:x:y" },
]}));
assert_eq!(r["error"], "these two factors are kept on the same device; use one of them with another factor");
// The PC asks the phone; the phone approves with its passkey.
let requester = Recipient::generate();
let req_pub = BASE64.encode(&requester.public());
assert_eq!(call(json!({ "op": "match_code", "pub": req_pub }))["match"], requester.match_code());
let ctx = format!("approval:{approval_id}:r1");
let wrong_key = call(json!({ "op": "phone_approve", "wrapped": wrapped, "prf": BASE64.encode(&[8u8; 32]), "pub": req_pub, "context": ctx }));
assert_eq!(wrong_key["ok"], false);
let r = call(json!({ "op": "phone_approve", "wrapped": wrapped, "prf": prf64, "pub": req_pub, "context": ctx }));
let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap();
let m = requester.open(&sealed, ctx.as_bytes()).unwrap();
let pw = SecretString::from(PASSWORD);
assert!(Vault::open_with(&v.to_bytes().unwrap(), Unlock::Password(&pw), Unlock::Material(FactorKind::Approval, &m)).is_ok());
}
#[test]
fn a_phone_pairs_as_a_domi_device() {
// The PC waits with a one-time key; the phone seals its device public key and label to it.
let pc = Recipient::generate();
let device = data_encoding::BASE64URL_NOPAD.encode(&[5u8; 32]);
let r = call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc_-1", "label": " Pixel\n", "device": device }));
assert_eq!(r["ok"], true, "{r}");
let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap();
assert_eq!(r["code"], custos_seal::sender_code(&sealed).unwrap());
assert!(pc.open(&sealed, b"domi-pair:other").is_err(), "the box is for this pairing only");
let plain: Value = serde_json::from_slice(&pc.open(&sealed, b"domi-pair:abc_-1").unwrap()).unwrap();
assert_eq!(plain, json!({ "label": "Pixel", "device": device }));
// Malformed: a device key of the wrong length, an id that would change the context.
let short = data_encoding::BASE64URL_NOPAD.encode(&[5u8; 31]);
assert_eq!(call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc", "label": "x", "device": short }))["ok"], false);
assert_eq!(call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "a:b", "label": "x", "device": device }))["ok"], false);
}
+147
View File
@@ -0,0 +1,147 @@
# Two factors: vault format version 2
A version-2 vault never opens with one secret. It opens with **any two of its factors**: the master
password, a key kept by one device, a share released by a TOTP check, a secret held by another device that
it releases after you approve, a passkey's PRF output. Each pair of factors wraps the vault key.
Version 1 (`docs/FORMAT.md`) stays readable. A v1 vault becomes v2 when a second factor is added; from then
on, Custos writes it as v2 only.
A **machine store** (the Claude Code store) is the one exception: a separate file whose vault key is
wrapped by one device key alone, so a program can open it unattended. It never holds the user's secrets.
## Keys
```
factor material ──KDF──► factor KEK ──unwraps──► factor key F (32 random bytes, one per factor)
F_a ‖ F_b ──HKDF-SHA256(salt = id_a ‖ id_b, info "custos pair v2")──► pair KEK ──unwraps──► vault key
```
- Every factor has a random 16-byte **id** and a random 32-byte **factor key** `F`. The factor's material
(the password, a device key, a released share…) only unwraps `F`.
- A **pair slot** for every pair of factors wraps the vault key with a key derived from both factor keys.
Two factors of the same vault always have a pair slot; one factor never unwraps the vault key by itself.
- The factor keys are also stored **inside the encrypted body**. An unlocked vault can therefore add a
factor (only the new factor's material is needed) or drop one, without the other factors present.
Changing the password rewraps the password factor's `F`; the pair slots stay as they are.
Factor KEKs:
| Type | Code | Material | KEK |
|:--|:--|:--|:--|
| password | 1 | the master password | Argon2id(password, salt, m, t, p), limits as in v1 |
| device | 2 | 32..=64 bytes the device keeps (a key file protected by Windows DPAPI, a key in the phone's storage) | HKDF-SHA256(material, salt, "custos factor v2") |
| totp | 3 | 32 bytes the TOTP service releases after a valid code | same |
| approval | 4 | 32 bytes another paired device sends after you approve there | same |
| passkey | 5 | a WebAuthn PRF output (32 bytes) | same |
The type only tells the app which material to ask for; the cryptography is the same for 2..5.
## Layout
The v1 layout with `version = 2`, up to 64 slots and these slot kinds (`docs/FORMAT.md`, "Layout"):
```
kind 2, factor slot
16 factor id
1 type 1..=5 (table above)
13 kdf type 1 only: kdf(1) = 1 (Argon2id), m_cost, t_cost, p_cost (u32 each)
32 salt
24 wrap nonce
48 wrapped F 32-byte factor key + 16-byte tag
AAD = magic ‖ version ‖ kind ‖ everything in the payload before the wrapped F
kind 3, pair slot
16 id a the smaller of the two ids (bytewise)
16 id b
24 wrap nonce
48 wrapped vault key
AAD = magic ‖ version ‖ kind ‖ id a ‖ id b ‖ nonce
kind 4, single slot (machine stores only)
16 factor id
24 wrap nonce
48 wrapped vault key KEK = HKDF-SHA256(F, salt = id, info "custos single v2")
AAD = magic ‖ version ‖ kind ‖ id ‖ nonce
```
Kind 1 (the v1 password slot) does not occur in a v2 file; a reader treats one as malformed. The body AAD
is the whole header, as in v1.
### Limits a reader enforces
- 1 ..= 64 slots; at most 8 factor slots; a factor type outside 1..=5 is malformed.
- A pair slot whose two ids are equal, or not in order, or name a factor that has no factor slot, is malformed.
- Argon2 limits as in v1, checked before any work.
- Material for types 2..5: 32 ..= 64 bytes, else `FactorRejected` before any work.
### Opening
The app passes two factors (a password, or a type and its material). For each one, the reader tries the
factor slots of that type; the first that unwraps gives `(id, F)`. With two distinct ids it opens their pair
slot, then the body.
| Situation | Error |
|:--|:--|
| Fewer than two different factors given, or two of the same factor | `NeedTwoFactors` |
| A given factor unwraps no factor slot of its type | `FactorRejected` (a wrong password says so: `WrongPassword`) |
| Both unwrap, but their pair slot is missing or fails | `Corrupted` |
| A machine store: its one device factor unwraps, then the single slot | — |
## Which factors a file has
`Vault::factor_ids(bytes)` reads the header alone and returns each factor's id and type. No key is needed,
because ids and types are not secret. The app uses them to ask the TOTP service or a paired device for a
factor. Those services pass material through a mailbox they cannot read; see `docs/SEAL.md`.
## In the browser and on a phone
`custos-wasm` opens a version-2 vault with any two factors (`open_with`). A factor that comes from the
factor service or from another device arrives as a box sealed to a one-time key the module made
(`recipient`); the key's secret half never leaves WebAssembly memory and is used once.
**Pairing a phone** gives the vault two factors at once, both added by the PC (which writes the file):
1. The PC waits with a one-time key and shows its match code; the phone shows the same code.
2. On the phone, a passkey is created and evaluated with the WebAuthn PRF extension
(salt `SHA-256("custos passkey v1")`). Its 32-byte output is the **passkey** factor's material.
3. `phone_enrol` makes 32 random bytes, the phone's **approval** material, and seals both to the PC
(context `pair:<pairing id>`). The phone keeps the approval material only wrapped with the PRF output
(at-rest sealing, context `custos phone approval v1`), so stolen browser storage is not a factor.
4. The phone shows the box's sender code (`docs/SEAL.md`); the PC adds the factors only after you confirm it
shows the same code. It adds the approval factor **apart** from the passkey (`add_factor_apart`).
**Factors on one device never pair.** `add_factor_apart` writes no pair slot between the new factor and the
ones named, so those two open nothing together (`Error::SameDevice`) while each still pairs with every other
factor. A phone's passkey and its approval key, or a PC's device key and its approval key, are added apart.
`phone_approve` unwraps the approval material with a fresh PRF output (Face ID, Touch ID) and seals it to a
requesting device, for `approval:<factor id>:<request id>`. The material exists unwrapped only inside that call.
## Body
`"format": 2`, and a `factors` list next to `items`:
```json
"factors": [
{ "id": "9f2c…(32 hex)", "type": "password", "label": "Master password", "created": 1793600000000, "key": "…(64 hex)" },
{ "id": "41aa…", "type": "device", "label": "MARK-PC", "created": 1793600000000, "key": "…" }
]
```
`key` is the factor key `F`. It is inside the body's encryption like every secret in the vault.
### The key-pair item type
`key-pair` (new in body format 2): `algorithm` (`ed25519`, `ecdsa-p256`, `rsa-3072`, `rsa-4096`),
`public-key` (OpenSSH line), `public-pem` (SPKI PEM), `private-key`* (PKCS#8 PEM), `private-openssh`* (OpenSSH
private key), `fingerprint` (SHA256:… as `ssh-keygen -l` prints it), `comment`.
## What it protects
- The vault file plus one factor opens nothing: a stolen password, a copied key file, a compromised TOTP
service or one lost phone each give one factor key, never the vault key.
- A device factor is only as private as the device: Windows DPAPI binds the key file to the Windows account
on that machine, so a copy of the file does not work elsewhere, but malware running as that account can
use it. That is one factor, which is why it is never enough alone.
- Losing a factor is not losing the vault: any other two open it, and the lost one can then be removed.
+14 -27
View File
@@ -1,5 +1,7 @@
# The `.custos` vault file, format version 1
Version 2 (two factors, the machine store) is in `docs/FACTORS.md`; it reuses this layout.
One file holds one vault. Everything after the header is one XChaCha20-Poly1305 ciphertext.
The header is not secret, but it is authenticated: changing any byte of it makes the body fail to open.
All integers are little-endian. The code is `crates/custos-vault/src/format.rs`.
@@ -117,6 +119,16 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed:
- `fields` is an ordered list; a name may repeat (several `url`s). Unknown names are kept as custom fields.
- `history` keeps the previous value of a secret field each time it changes (newest last, at most 20 per item).
- Readers ignore JSON members they do not know, so later versions can add them.
- `identity` (optional, core 0.7.0): the Domi identity's root key and the certs it issued (docs/IDENTITY.md);
since core 0.10.0 a cert may carry `revoked_at` and `revocation`.
An older Custos drops it when it saves, so every Custos that saves the vault must be 0.7.0 or later.
- `folder` (optional item member, core 0.8.0): a list of folder names, outermost first (a KeePass group path,
docs/KDBX.md). Absent or empty = no folder.
- `attachments` (optional item member, core 0.8.0): `[{"name": "id_rsa", "data": "<base64>"}]`, files kept with
the item (imported from KeePass). The data counts as secret: it is never logged or printed.
An older Custos drops `folder` and `attachments` when it saves.
- `signing` (optional, core 0.9.0): signing keys for releases and the audit log of every signing request
(docs/SIGNING.md). An older Custos drops it when it saves, so every Custos that saves the vault must be 0.9.0 or later.
### Item types and their fields (v1)
@@ -133,34 +145,9 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed:
`notes` is secret for every type (it is shown only on reveal).
## Planned KDBX 4 mapping (export comes in v1.2)
## KDBX 4 (KeePass)
KeePassXC-compatible: standard strings where KeePass has them, custom strings otherwise. Secret fields
become *protected* strings.
| Custos | KDBX 4 entry |
|:--|:--|
| `title` | `Title` |
| `username` (web-login, local-app) | `UserName` |
| `password`* (web-login, local-app, wifi) | `Password` (protected) |
| first `url` | `URL` |
| 2nd, 3rd … `url` | `KP2A_URL_1`, `KP2A_URL_2`, … (KeePassXC reads these) |
| `notes` | `Notes` |
| `totp` | `otp` (protected), as an `otpauth://` URI (KeePassXC's format) |
| `autotype-sequence` | `AutoType/DefaultSequence` |
| `autotype-match` | `AutoType/Association/Window` |
| `type` | custom string `custos-type` |
| `api-credential`: `service`, `key-id`, `endpoint`, `expires` | custom strings `service`, `key-id`, `endpoint`; `expires` → entry `Times/Expires` + `ExpiryTime` |
| `api-credential`: `secret`* | `Password` (protected) |
| `local-app`: `target` | custom string `target` |
| `wifi`: `ssid`, `security`, `hidden` | `UserName` = ssid, custom strings `security`, `hidden` |
| `card`: `number`* | `Password` (protected) |
| `card`: `cardholder`, `expiry` | `UserName` = cardholder, custom string `expiry` |
| `card`: `cvv`*, `pin`* | protected custom strings `cvv`, `pin` |
| other custom fields | custom strings of the same name, protected when secret |
| `tags` | `Tags` (`;`-separated) |
| `created`, `modified` | `Times/CreationTime`, `Times/LastModificationTime` |
| `history` entries | `History` entries (one per change, with that old password) |
Import and export, with the full field mapping and what does not survive: docs/KDBX.md.
## Device key wrap (not part of the file)
+99
View File
@@ -0,0 +1,99 @@
# The Domi identity (`custos-vault`, `identity`)
Every Domi app gets its own subkey, certified by **one root Ed25519 key per person**. The root key lives in
the vault and never leaves it: no function of this crate returns it, and the vault signs nothing with it but
subkey certificates and revocations of keys the person revoked. The certificate format, the match code and verification are in Fundamentum
(`crates/tessera`, `docs/TESSERA.md`); this page is the vault side.
## Creating it: the order is mandatory
```
entropy 32 bytes from the OS CSPRNG
mnemonic BIP39 English, 24 words, shown ONCE
confirm the person types 3 words the vault picks at random
root Ed25519 secret = HKDF-SHA256(salt = "tessera root v1", ikm = BIP39 seed(mnemonic, ""), info = "ed25519")
import the secret goes into the vault; entropy, seed and mnemonic are wiped
```
A key that was created non-extractable first could never be backed up. So the code cannot do it in the other
order: `identity::Enrollment` is a typestate.
| Type | Holds | Only way forward |
|:--|:--|:--|
| `Enrollment` | the entropy | `show(display)`: hands the 24 words to `display`, once |
| `Shown` | the entropy, 3 word positions | `confirm(words)`: the 3 words, or it hands itself back to try again |
| `Confirmed` | the derived root secret; the entropy is wiped | `import(&mut vault)`: stores the root, returns its public key |
`import` exists only on `Confirmed`, `Confirmed` only comes from `confirm`, and `confirm` only from `show`.
Swapping the order does not compile (`compile_fail` doctests in `src/identity.rs`). None of the three types
is `Clone` or `Serialize`; each prints `[redacted]`.
Test vector: entropy `00` × 32 → `abandon` × 23 + `art` → root public key
`vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs` (base64url). Fundamentum pins the same value.
### Restoring it from the 24 words (core 0.10.0)
`Enrollment::restore(phrase)` takes the whole phrase, typed back, and gives a `Confirmed`: the person typed
all 24 words, which proves more than three. The words are checked against the BIP39 English list and its
checksum (any case, any spacing between them); anything else is `Error::NotAMnemonic`, which names no word.
The same words give the same root, so every app and every group trusts it again.
## In the vault file
A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it open as before:
```json
"identity": {
"root": "<64 hex: the Ed25519 secret>",
"public": "<64 hex>",
"created": 1793000000000,
"issued": [
{ "kind": "app", "app_id": "fiscus", "purpose": "sync", "subkey": "<base64url>", "label": "fiscus.exe",
"not_before": 1793000000, "not_after": 1824536000, "issued": 1793000000000,
"revoked_at": 1795000000, "revocation": ["<base64url TRV1>"] }
]
}
```
- `issued` records each cert the vault signed, for *Domi identity → apps and devices*. It is a record, not
a trust list.
- `revoked_at` (Unix seconds, core 0.10.0) is set when the person revokes the key; `revocation` holds the
signed statements once they exist. Both are left out until then. A renewed key has several certs: all of
them are marked.
- **A Custos older than core 0.10.0 drops `revoked_at` and `revocation` when it saves the vault**, so a
revocation in progress would have to be started again.
- **An older Custos drops the member when it saves the vault** (it ignores members it does not know). Every
Custos that saves this vault must run core 0.7.0 or later. The mnemonic recovers the root either way.
## Using it
| Function | What |
|:--|:--|
| `Vault::domi_root_public()` | the root public key, if there is an identity |
| `Vault::domi_sign_cert(tbs)` | Ed25519 over `"tessera cert v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TSC1` followed by this root's public key |
| `Vault::domi_issued()`, `domi_record(issued)` | the record of issued certs |
| `Vault::domi_mark_revoked(subkey, at)` | the person revoked this key: marks every cert of it, returns the time in effect (the first one, if it was marked before) |
| `Vault::domi_sign_revocation(tbs)` | Ed25519 over `"tessera revoke v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TRV1`, this root's public key, a key marked revoked and that key's `revoked_at` |
| `Vault::domi_record_revocation(subkey, statements)` | keeps the signed statements with the key's certs |
| `Vault::domi_backup_secret(app_id)` | the app's backup secret (below) |
The prefix checks mean the vault is not a general signing oracle: whatever the app hands it, the result
can only ever verify as a certificate naming this root, or as a revocation of a key the person revoked, at
the time they did. The two domains differ, so neither can pass for the other. Statement format: Fundamentum
docs/TESSERA.md §12.
### The backup secret (core 0.10.0)
```
backup secret = HKDF-SHA256(salt = "tessera backup v1", ikm = the root secret, info = app id)
```
Custos hands an app its own (Domi pipe `backup_key`, behind the app's namespace grant); the app seals its
backup with it and names its backup mailbox from it (Fundamentum docs/TESSERA.md §12). It comes back from
the 24 words alone. The caller passes a valid app id (a-z, 0-9, `-`). Test vector, shared with Fundamentum:
the zero-entropy root, app `fiscus` → `HKDF-Expand(secret, "mailbox")` =
`IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU`, and XChaCha20-Poly1305 with
`HKDF-Expand(secret, "seal")`, a zero nonce and empty input = `ci_JRbtsx5prR83KT9Y7LA` (the tag).
## What it does not protect
The root secret is in the vault body, so everything in docs/THREAT_MODEL.md about an unlocked vault applies:
malware running as you while the vault is open can read it from memory. It never reaches the webview, the
Domi pipe, logs or the web vault.
+128
View File
@@ -0,0 +1,128 @@
# KeePass import and export (`custos-kdbx`)
Custos reads KeePass's KDBX 3.1 and KDBX 4 files (4.0 and 4.1) and writes KDBX 4.0, so a vault can move in from
KeePassXC or KeePass 2 and back out to them. KeePassXC 2.7 still writes 3.1 for a database with AES-KDF (its
command line does by default); its app writes 4.0 with Argon2d. The crate has two layers:
1. **The file format** (`read`, `write`): bytes and a key in, a KDBX database model out, and back. It knows
groups, entries, strings, attachments, times, auto-type and history. It does not know Custos items.
2. **The mapping** (`to_items`, `from_items`): KDBX entries to Custos items and back (the table below).
No custom crypto: AES-256 (`aes`, `cbc`), ChaCha20 (`chacha20`), SHA-256/512 (`sha2`), HMAC-SHA-256 (`hmac`),
Argon2d/id (`argon2`), all RustCrypto. Compression is gzip (`flate2`), XML is `quick-xml` events.
## Reading
| Step | What |
|:--|:--|
| Signature | `03 D9 A2 9A`, `67 FB 4B B5`, then minor/major version (u16 LE each). Major 4 here; major 3 is read as below ("KDBX 3.1"); anything else is `UnsupportedVersion` |
| Outer header | TLV fields: id (u8), length (u32 LE), data, until id 0. Cipher, compression, master seed (32 bytes), IV, KDF parameters (a VariantDictionary) |
| Header checks | SHA-256 of the header (mismatch: `Corrupted`), then HMAC-SHA-256 of the header with the block key for index 2⁶⁴−1 (mismatch: `WrongKey`) |
| Key | composite = SHA-256(SHA-256(password) ‖ key-file key); with only one of the two, only that one goes in |
| KDF | Argon2d or Argon2id (`S`, `P`, `M` bytes, `I`, `V` = 0x13; a non-empty secret `K` or data `A` is refused), or AES-KDF (`R` rounds of AES-256-ECB keyed with `S` over both halves, then SHA-256) |
| Keys | cipher key = SHA-256(master seed ‖ transformed); HMAC base = SHA-512(master seed ‖ transformed ‖ 0x01); block *i* key = SHA-512(u64 LE *i* ‖ HMAC base) |
| Blocks | HMAC (32) ‖ length (u32 LE) ‖ data, each checked: HMAC-SHA-256(block key, u64 LE index ‖ u32 LE length ‖ data). A zero-length block ends the stream. A failed block: `Corrupted` |
| Payload | AES-256-CBC (PKCS#7) or ChaCha20 (96-bit IV) decryption, then gunzip if the compression flag is 1 |
| Inner header | TLV: inner stream id (3 = ChaCha20; Salsa20 = 2 is refused), inner stream key (64 bytes), binaries (flag byte ‖ data, in pool order), end |
| XML | protected values are XORed with the inner stream, key = SHA-512(stream key)[0..32], nonce = [32..44], in document order |
### KDBX 3.1
The same key, cipher and XML, with these differences: header field lengths are u16; the KDF is always AES-KDF
from the header (`TransformSeed`, `TransformRounds`); there is no header HMAC: after decryption the first 32
bytes must equal the header's `StreamStartBytes` (otherwise `WrongKey`); the payload is SHA-256 hashed blocks
(index u32, hash, length u32, data; a changed block is `Corrupted`); the inner stream is Salsa20 (key =
SHA-256 of `ProtectedStreamKey`, KeePass's fixed nonce `E8 30 09 4B 97 20 5D 2A`), and its id and key are in the
outer header; attachments are in `Meta/Binaries` (base64, gzipped when `Compressed="True"`), referenced by ID.
**Key files** (`Key::key_file`): KeePass XML 2.0 (`<Data Hash="…">` hex, the hash is checked), XML 1.0 (base64),
exactly 32 bytes (used as is), exactly 64 hex digits (decoded), anything else: SHA-256 of the file.
### Limits (checked before any expensive work)
| What | Limit | Error |
|:--|:--|:--|
| File size | 512 MiB | `TooLarge` |
| A header field | 64 KiB (a binary in the inner header: 256 MiB) | `Malformed` |
| Argon2 | `M` ≤ 2 GiB, `I` 1 ..= 1000, `P` 1 ..= 64, `V` = 0x13 | `UnsupportedKdf` |
| AES-KDF | `R` 1 ..= 2³⁰ | `UnsupportedKdf` |
| Decompressed payload | 512 MiB | `TooLarge` |
| XML | no `<!DOCTYPE>` (entities are never expanded), element depth ≤ 256 | `Malformed` |
| Unknown cipher (Twofish) | | `UnsupportedCipher` |
| Inner stream other than ChaCha20 (and Salsa20 in 3.1) | | `UnsupportedStream` |
No error carries any part of the password, the key or a value. A panic on any input is a bug.
## Writing
KDBX 4.0: ChaCha20, gzip, Argon2id (`M` = 64 MiB, `I` = 20, `P` = 1 by default: the vault's own defaults),
ChaCha20 inner stream with a fresh 64-byte key, a fresh master seed, IV and salt from the OS CSPRNG. Every
`Password` and every string Custos keeps secret is written protected. Blocks are 1 MiB. AES-256 and AES-KDF
can be chosen (`WriteOptions`) so the reader is tested against both.
The export is protected **by its own password only** (and optionally a key file). It is meant for moving to
KeePassXC or for an offline backup; the app says so before it writes one.
## Mapping: KeePass entry ↔ Custos item
Entry UUID ↔ item `id` (16 bytes ↔ 32 hex digits), so importing the same file again finds the items it
already imported.
| KDBX entry | Custos item |
|:--|:--|
| group path below the root group | `folder` (list of group names; the root itself is not included) |
| `Title` | `title` |
| `UserName` | `username` (web-login, local-app, and any type without its own), `ssid` (wifi), `cardholder` (card) |
| `Password` (protected) | `password` (web-login, local-app, wifi, and others), `secret` (api-credential), `number` (card) |
| `URL`, then `KP2A_URL`, `KP2A_URL_1`, … (exactly those names) | `url`, repeated in that order |
| `Notes` | `notes` |
| `otp` (KeePassXC) | `totp` |
| `TOTP Seed` + `TOTP Settings` (KeePass 2 / older KeePassXC) | `totp`, as an `otpauth://` URI when the settings are not 30 s / 6 digits |
| `custos-type` | the item type (written by Custos; other files are guessed: no user name, password or URL → secure-note, otherwise web-login) |
| any other string | a field with the same name; secret when protected. A Custos field whose name KeePass reserves (`Title`, `custos-type`, `KP2A_URL`, …) or that is already taken is written as `name (2)`, `name (3)`, … |
| `Tags` (`;` or `,` separated) | `tags` |
| `Times/CreationTime`, `LastModificationTime` | `created`, `modified` (seconds; milliseconds are dropped on export) |
| `Times/Expires` + `ExpiryTime` | field `expires`: `YYYY-MM-DD` at midnight UTC, else `YYYY-MM-DDTHH:MM:SSZ` |
| `Binary` (attachments) | `attachments` (name and bytes) |
| `AutoType/DefaultSequence` | `autotype-sequence` |
| each `AutoType/Association/Window` | `autotype-match`, repeated |
| `History` | `history`: for each snapshot, each secret field (the password, every protected string) whose value differs in the next version: `{field, value, changed: the snapshot's modification time}`, newest 20 kept. On export, one snapshot per distinct change time, with the values just before that change |
On export, an empty field from the item's template is left out; every other field is written, even when
empty. `custos-type` is written only when the type differs from what the guess above would give, so a plain
KeePass entry comes back without it. The root group is named after the export (default "Custos"); folders
become groups under it. Imported items come back folder by folder: extra fields after the template's ones.
### What does not survive
Said plainly, so nobody expects it:
- **Icons, colours, custom icons, `OverrideURL`**, an entry's or group's `CustomData`, group notes and settings.
- **History of non-secret fields**: KeePass snapshots hold every field; Custos keeps old values of secret
fields only, at most 20 per item (KeePassXC keeps 10 snapshots by default).
- **Auto-type**: a per-window keystroke sequence and the "auto-type disabled" switch.
- **The recycle bin**: entries in it are not imported. Deleted-object records are not kept.
- **Database settings** (`Meta`): name, description, history limits, KDF and cipher. The export uses its own.
- Sub-second times.
Custos items that have nothing in KeePass go out as custom strings (`custos-type`, the template fields such as
`key-id` or `cvv`) and come back the same. Version 2 vault factors and the Domi identity are never exported.
## Tests (`crates/custos-kdbx/tests/`)
- `format.rs`: write → read is identical for every cipher and KDF; wrong password, no key, each key-file kind
(four spellings of one key open each other's files); a changed byte anywhere (header and hash: `Corrupted`,
header HMAC: `WrongKey`, blocks: `Corrupted`); truncation at every length; out-of-limit KDF parameters refused
in well under a second; DOCTYPE (billion laughs, XXE), deep nesting, broken XML, a gzip bomb, a Salsa20 inner
stream in KDBX 4, Twofish and unknown versions refused; no secret in any `Debug` output.
- `keepassxc.rs`: two files KeePassXC 2.7.12 wrote from `tools/kdbx/sample.xml` (base64 test vectors in
`tests/data/`, password `custos-test`): KDBX 3.1 from `import`, KDBX 4.0 from `merge` into a Custos file. Both
open with the expected folders, fields, protected strings, extra URLs, both TOTP forms, expiry, auto-type,
history and attachment; the 3.1 file's recycle bin is skipped; a wrong password is `WrongKey`.
- `mapping.rs`: every item type through `from_items` → write → read → `to_items` is unchanged, field by field;
what the export looks like to KeePassXC; a KeePass-style database maps as the table says; reserved names are
renamed, ids survive.
- `tools/kdbx/interop.sh` (WSL + Nix with `keepassxc-cli`, not part of `cargo test`): KeePassXC makes a 3.1 and a
4.0 file from `sample.xml`; Custos reads each, maps it to items and back, and writes KDBX 4; KeePassXC opens
that, `compare.py` checks both XML exports entry by entry (leaving out only what "What does not survive"
lists), `attachment-export` compares the attachment bytes, and `show --totp` gives the 8-digit code.
+61
View File
@@ -0,0 +1,61 @@
# Keys, API keys and key pairs
What `custos-gen` and `custos-keys` generate besides passwords. All randomness comes from the OS CSPRNG.
## Secret keys (`custos_gen::secret_key`)
16 ..= 128 random bytes (default 32 = 256 bits), written as lowercase hex, base64url without padding, or
standard base64 with padding. For symmetric keys, HMAC and JWT secrets, encryption passphrases for tools.
## API keys (`custos_gen::api_key`)
```
<prefix>_<32 base62 characters><6 base62 characters of checksum> e.g. domi_7Kq…Zx41aP0c
```
- `prefix`: empty, or a lowercase letter then up to 15 lowercase letters or digits. It says what the key is
for at a glance, and lets leak scanners find it. No prefix: the key starts with the 32 characters.
- 32 base62 characters: 190.5 bits, each character uniform (rejection sampling, no modulo bias).
- The checksum is CRC-32 (IEEE) of everything before it, in base62, padded to 6 characters. It catches typos
and lets a scanner tell a real key from random text. It is not a security feature.
## Key pairs (`custos_keys::generate`)
| Algorithm | Name in the item | Notes |
|:--|:--|:--|
| Ed25519 | `ed25519` | the default: SSH, signing, minisign-style tools |
| ECDSA P-256 | `ecdsa-p256` | where Ed25519 is not accepted (some cloud KMS, older hardware) |
| RSA 3072 / 4096 | `rsa-3072`, `rsa-4096` | for systems that accept nothing else; generation takes seconds |
Each gives:
- `public-key`: the OpenSSH public line (`ssh-ed25519 AAAA… comment`), for `authorized_keys`;
- `public-pem`: the SubjectPublicKeyInfo PEM;
- `private-key`*: the PKCS#8 PEM (unencrypted; the vault is its encryption);
- `private-openssh`*: the OpenSSH private key (unencrypted, same reason), for `ssh -i`;
- `fingerprint`: `SHA256:…`, exactly as `ssh-keygen -l` prints it.
The crates are RustCrypto's: `ssh-key`, `ed25519-dalek` (its Ed25519 backend), `p256`, `rsa`.
## Importing (`custos_keys::import`)
An existing private key becomes the same kind of item. Accepted formats:
| Input | Header | Algorithms |
|:--|:--|:--|
| OpenSSH private key | `BEGIN OPENSSH PRIVATE KEY` | Ed25519, ECDSA P-256, RSA |
| PKCS#8 | `BEGIN PRIVATE KEY` | Ed25519, ECDSA P-256, RSA |
| PKCS#1 | `BEGIN RSA PRIVATE KEY` | RSA |
| SEC1 | `BEGIN EC PRIVATE KEY` | ECDSA P-256 |
- **The public line, the PEMs and the fingerprint are derived from the private key**, never copied from the
input. A pasted public key therefore cannot disagree with its private key.
- **RSA:** 2048 to 4096 bits. An imported 2048-bit key is named `rsa-2048`; Custos never generates one.
- **A passphrase-protected key is refused** (`Encrypted`): OpenSSH with a cipher, `ENCRYPTED PRIVATE KEY`,
or PKCS#1 with `Proc-Type: 4,ENCRYPTED`. Remove the passphrase first (`ssh-keygen -p`); the vault is the
key's encryption.
- **Comment:** an OpenSSH key keeps its own comment; the other formats take the item's name.
- **Line ends:** CRLF and surrounding whitespace are accepted, as in a paste or a Windows file.
- **Errors never repeat the input.**
- **ssh-key 0.6.7 conversion bug:** its `TryFrom<&RsaKeypair> for rsa::RsaPrivateKey` uses `p` twice. Custos
rebuilds the key from `n, e, d, p, q` and validates it instead.
+62
View File
@@ -0,0 +1,62 @@
# Sealed boxes (`custos-seal`)
The two-factor services (`docs/FACTORS.md`, types 3 and 4) pass factor material through a mailbox on the
home server. The mailbox must never be able to read it. So the device that wants a secret makes a
**one-time X25519 key pair**, sends only the public half, and whoever releases the secret seals it to that
key. The same box carries a secret from the user's PC to a Claude Code cloud session.
## The box, version 1
```
sealed = "CSL1" ‖ E (32) ‖ nonce (24) ‖ XChaCha20-Poly1305(K, nonce, plaintext, aad)
E the sender's ephemeral X25519 public key (a fresh one per box)
R the recipient's one-time public key
K HKDF-SHA256(ikm = X25519(e, R), salt = E ‖ R, info = "custos seal v1" ‖ context)
aad "CSL1" ‖ E ‖ context
```
- **`context`** names the purpose, for example `approval:<factor id>:<request id>` or `cloud:<request id>`.
A box opens only with the context it was sealed for, so a box for one request does not work as another.
- **A low-order public key is refused** on both sides: the shared secret must be contributory.
- **Plaintext limit:** 32 KiB.
- **The recipient's secret half** lives only in memory, as `x25519_dalek::StaticSecret` with `zeroize`,
and is wiped on drop. Nothing writes it to disk.
## The match code
Six digits that the requesting screen and the approving screen both show:
```
match = u32_be(SHA-256("custos match v1" ‖ R)[0..4]) mod 1 000 000, zero-padded to 6 digits
```
If they differ, someone else's request is waiting: deny it. The code is not a secret. It only ties the
approval to the key the box is sealed for.
Test vector: R = `07` × 32 → `684361`.
### The sender code
The match code of a box's ephemeral key E (`sender_code`). When the receiver must know who sealed a box,
as when a PC adds a phone's factors, the sealing screen shows this code and the receiving screen asks the
person to confirm it. E is fresh for every box, so each box has its own code.
## At rest
The factor service keeps each TOTP share sealed with its own key, which comes from a systemd credential
that is not in its state directory:
```
at rest = "CSR1" ‖ nonce (24) ‖ XChaCha20-Poly1305(HKDF-SHA256(key, salt = "", info = "custos rest v1" ‖ context),
nonce, plaintext, "CSR1" ‖ context)
```
What this protects: a leaked copy of `/var/lib/custos-factors` without the credential gives nothing.
What it does not protect: anyone who controls the running server. That is one factor, which is why a
factor is never enough alone.
## Crates
`x25519-dalek` 2 (dalek-cryptography, the X25519 sibling of the `ed25519-dalek` used for key pairs),
`chacha20poly1305`, `hkdf`, `sha2`, and `rand`'s `SysRng`.
+146
View File
@@ -0,0 +1,146 @@
# Signing keys (core 0.9.0)
Custos signs releases for Fabrica Domi · Artifex without a private key ever leaving the vault. A build asks for a
signature over a **digest**; Custos checks who may ask, Mark approves with a match code, and the vault signs and
records it. This page is the contract for the keys, the signature kinds and the audit log.
## Where the keys live
In the vault body, next to `identity` (FORMAT.md), as the optional member `signing`:
```json
"signing": {
"keys": [
{ "id": "domi-release", "kind": "ed25519", "role": "release", "name": "Domi release",
"secret": "<base64>", "public": "<base64>", "keyId": "<16 hex>", "created": 1793750000000,
"pipelines": ["release"], "repos": ["Arca", "Fabrica"] },
{ "id": "domi-root", "kind": "root-ca", "role": "release", "name": "Domi Household Root CA",
"secret": "<base64>", "cert": "<base64 DER>", "created": 1793750000000, "pipelines": [], "repos": [] },
{ "id": "domi-code-signing", "kind": "code-signing", "role": "release", "name": "Domi Code Signing",
"secret": "<base64>", "cert": "<base64 DER>", "issuer": "domi-root", "created": 1793750000000,
"pipelines": ["release"], "repos": ["Arca"] }
],
"audit": [
{ "at": 1793750100000, "key": "domi-release", "kind": "minisign", "outcome": "approved", "via": "local",
"repo": "Arca", "commit": "6925d0cb08b9…", "pipeline": "release", "step": "sign", "trigger": "tag",
"file": "Arca_0.1.0_x64-setup.exe", "size": 25145977, "sha256": "c4995c6e…", "signature": "<sha256 hex>" }
]
}
```
Why a body member and not new item types: item types are a closed list, so an older Custos (or the web vault on an
older core) would refuse a whole vault that has an item of a new type; and an item's fields can be revealed,
copied, shared, exported to KeePass and edited, which are all paths a signing key must never take. A body member is
ignored by older readers (FORMAT.md, "Readers ignore JSON members they do not know") and is reachable only through
the functions below. As with `identity`, an older Custos drops `signing` when it saves: every Custos that saves the
vault must be 0.9.0 or later. There is no mnemonic for these keys: back the vault up.
### Keys
| `kind` | Key | Signs | Created |
| :-- | :-- | :-- | :-- |
| `ed25519` | Ed25519; `secret` is the 32-byte seed, `public` the 32-byte key, `keyId` minisign's 8-byte key id | `minisign`, `manifest` | random |
| `root-ca` | RSA-3072; `secret` is PKCS#8 DER; `cert` a self-signed X.509 v3 CA certificate, valid 10 years | only the leaf it issues, at creation; never a request | random |
| `code-signing` | RSA-3072; `secret` PKCS#8 DER; `cert` an X.509 v3 leaf issued by `issuer`, valid 2 years, EKU code signing | `authenticode` | random |
`role` is `release` or `test`. *Create release keys* makes `domi-release`, `domi-root` and `domi-code-signing`.
*Create test keys* makes `domi-test` (Ed25519) and `domi-test-code-signing`, a leaf issued by its own
`domi-test-root`: a test certificate never chains to the household root, so an automatically approved signature is
never trusted by Mark's PCs.
`pipelines` and `repos` list who may ask (pipeline names, repository folder names; `*` means any). A request from
a pipeline or repo not on its key's lists is refused **even when approved**. Release keys always need approval.
Test keys are approved automatically, but only for requests whose `trigger` is not `tag` (a manual run, a push).
Certificates:
- root: subject and issuer `CN=<name>, O=Domi`, `basicConstraints` CA (critical), `keyUsage` keyCertSign + cRLSign
(critical), subject key identifier;
- leaf: subject `CN=<name>, O=Domi`, `basicConstraints` not a CA, `keyUsage` digitalSignature + nonRepudiation,
`extKeyUsage` codeSigning, subject and authority key identifiers; both signed with sha256WithRSAEncryption.
The root's certificate (public part only) is exported as DER (`.cer`) to install as Trusted Root and Trusted
Publisher.
## Signature kinds
A request names a key, a kind and what to sign. Custos never receives the file.
| `kind` | The request carries | Custos returns |
| :-- | :-- | :-- |
| `minisign` | `digest`: BLAKE2b-512 of the file (64 bytes) | a `.minisig` file (prehashed, `ED`) |
| `manifest` | `manifest`: the `SHA256SUMS` text itself (≤ 32 KiB, canonical, see below) | a `.minisig` file over it |
| `authenticode` | `digest`: the 32-byte SHA-256 in signtool's `.dig` | the RSA PKCS#1 v1.5 signature (384 bytes) for `.dig.signed` |
### minisign
minisign's format (`jedisct1.github.io/minisign`), the **prehashed** variant, the one current minisign writes by
default and Tauri's updater (minisign-verify) checks:
```
untrusted comment: signature from Custos key <KEYID>
base64("ED" ‖ key_id ‖ ed25519(BLAKE2b-512(file)))
trusted comment: timestamp:<unix seconds> file:<file name> hashed
base64(ed25519(signature ‖ trusted comment text))
```
`key_id` is the key's 8 bytes as stored; `<KEYID>` is them as one little-endian u64 in upper-case hex, as minisign
prints it. The trusted comment text is what follows `trusted comment: `, without the newline. Every line ends in `\n`.
The public key file is `untrusted comment: minisign public key <KEYID>` and `base64("Ed" ‖ key_id ‖ public)`.
Tauri's updater wants the same two files one level further wrapped: its `pubkey` and each `.sig` are the base64 of
the whole minisign text. That wrapping is the build's job.
### manifest
`SHA256SUMS` in one canonical form, so the same set of files always gives the same bytes: one line per file,
`<64 lower-case hex> <name>\n` (two spaces), names without `/`, `\`, control characters or leading `-`, unique,
sorted by their UTF-8 bytes, no empty file. Custos checks the form, hashes the text itself and signs it as `minisign`
(file name `SHA256SUMS`). A text in any other form is refused, not normalised.
### authenticode
The file is signed by Windows' own tools in three steps, so the key stays in Custos:
1. `signtool sign /dg <dir> /fd sha256 /f <leaf.cer> <file>` writes `<file>.dig` (the base64 of the 32-byte SHA-256
of the signature's authenticated attributes, no newline) and `<file>.p7u` (the unsigned PKCS#7).
2. Custos signs those 32 bytes: RSA PKCS#1 v1.5 with the SHA-256 DigestInfo. The build writes the base64 of the
384 bytes, no newline, to `<file>.dig.signed`.
3. `signtool sign /di <dir> <file>` puts the signature in; `signtool timestamp /tr <url> /td sha256 <file>` adds a
timestamp.
Checked on 2026-11-04 with signtool 10.0.26100 and a throwaway RSA-3072 key: the result verifies with
`osslsigncode verify -CAfile <root>`; `signtool verify /pa` on a machine that does not trust the root fails only
with "terminated in a root certificate which is not trusted", and a wrong signature gives "No signature found".
`signtool verify /pa` on a machine that trusts the root is the last check, done where the root is installed.
## The audit log
`audit` is append-only: there is no function that edits or removes an entry. Every request a key is named in gets
one entry, whatever happened:
| `outcome` | |
| :-- | :-- |
| `approved` | Mark approved; signed |
| `auto` | a test key; signed without asking |
| `refused` | Mark refused |
| `expired` | nobody answered within 5 minutes |
| `out-of-scope` | the pipeline or repo is not on the key's lists (whether or not it was approved) |
| `invalid` | the request was malformed (wrong digest length, a manifest not in canonical form, a kind the key cannot do) |
`signature` is the SHA-256 (hex) of what was returned, for the signed outcomes. `via` is `local` (the Domi pipe) or
`remote` (the factor service's mailbox). The entry is part of the vault, so it survives a reopen and travels with it.
## The API (custos-vault)
```
Vault::signing_create(role, pipelines, repos, now) -> ids // release or test set
Vault::signing_keys() -> [SigningKeyView] // public parts only
Vault::signing_set_scope(id, pipelines, repos)
Vault::signing_export_cert(id) -> DER // a certificate, never a key
Vault::signing_minisign_public(id) -> minisign.pub text
Vault::signing_check(&request) -> Ok | Refusal // before asking Mark
Vault::signing_sign(&request, Approval::{Mark, Auto}, now) -> Signed // checks again, signs, records
Vault::signing_refuse(&request, outcome, now) // records refused / expired
Vault::signing_audit() -> [AuditEntry]
```
No function returns a `secret`. The views and the audit entries print and serialise without one; there is a test.
+18 -1
View File
@@ -14,12 +14,15 @@ just as plainly, what it does not.
| Attacker | Has | Gets | Why |
|:--|:--|:--|:--|
| Thief or sync server | The `.custos` file (any number of old versions) | Item count and sizes roughly (the ciphertext length), the KDF parameters. Nothing else. | XChaCha20-Poly1305 over the whole body; titles, URLs and usernames are inside it too. |
| Thief with one factor (v2) | The file plus the master password, or a copied key file, or a lost phone | Nothing | A version-2 vault opens only with two different factors (docs/FACTORS.md); one factor unwraps one factor key, never the vault key. |
| Offline guesser | The file and a GPU farm | One Argon2id evaluation (64 MiB, 20 passes by default, ≈ 0.75 s on a desktop CPU) per guess | A 4-word memorable password with digits (~65 bits) is out of reach; a weak master password is not. **The master password is the whole defence here.** |
| Tamperer | Write access to the file | Can destroy it, or roll it back to an older version they saw. Cannot change, reorder, add or remove items unnoticed. | The header is the body's AAD; each slot's parameters are its wrap's AAD. |
| Share server operator | Every share blob, its id, size, expiry, view count, the uploader's login and the recipients' IP addresses | Nothing of the secret | The key is in the link's `#fragment`, which browsers never send; the server stores ciphertext only (docs/SHARE.md). |
| Someone who gets a share link | The link (chat history, a forwarded mail) | The secret, if the share still has views left; with a password share, also one Argon2id evaluation (19 MiB) per password guess | That is what a link is. Use 1 view (the default): once it is opened, it is gone, and the sender learns about interception when the recipient finds it used. |
| Link-preview bot | The link, fetched by a chat app | Nothing; the view is not used | The page asks for a click on *Reveal* before it fetches the share. |
| Someone who crashes the machine mid-save | — | Nothing | Atomic save: temp file, fsync, rename; the previous version is kept as `.bak`. |
| Someone with a KeePass export | A `.kdbx` file Custos exported (docs/KDBX.md) | Everything in it, with its one password (or key file): one Argon2id evaluation per guess | An export leaves the two-factor protection behind on purpose, to move to KeePassXC or as an offline backup. The app says so before it writes one. Factors and the Domi identity are never in it. |
| A hostile `.kdbx` file | An import the user starts | A refusal | Size, header, KDF and decompression limits are checked before any work; the XML parser takes no DTD; a panic on any input is a bug (docs/KDBX.md, "Limits"). |
## What is NOT protected
@@ -34,7 +37,11 @@ just as plainly, what it does not.
desktop app), and by any clipboard manager that ignores the "exclude from history" marker.
- **Auto-type** sends keystrokes to whatever window has focus. The app re-checks the target window before
typing, but a window that steals focus at the wrong moment can receive them.
- **Device unlock (Windows Hello).** The blob on disk is only as strong as the device key behind it: anyone
- **A device factor (v2) on its own device.** The key file is bound to one Windows account by DPAPI; malware
running as that account can use it. That is one factor, and a v2 vault never opens with one.
- **The machine store** (the Claude Code store) opens with its device key alone, by design: anything running as
the user can open it. It must hold only what that program generated, never the user's own secrets.
- **Device unlock (Windows Hello, version 1 only).** The blob on disk is only as strong as the device key behind it: anyone
who can make Windows Hello sign as you on that machine (your PIN, your face, or malware running while
you approve a prompt) can unlock the vault there. It does not help an attacker who has only the vault file.
- **Rollback.** Someone with write access to the synced file can replace it with an older version.
@@ -53,6 +60,16 @@ just as plainly, what it does not.
revealed or copied value passes through JavaScript strings, which cannot be wiped. Lock (or close the tab)
when done.
- **The factor service holds one factor.** It releases the TOTP factor after a valid code, so whoever
controls the home server has that factor. It is one factor, never enough alone. Approval material and
cloud secrets pass through it only as sealed boxes (`docs/SEAL.md`), which it cannot open.
- **A paired phone's browser storage** holds its approval material wrapped with the passkey's PRF output,
which the authenticator gives only after Face ID or Touch ID. The passkey and the approval key are added
apart (docs/FACTORS.md), so the phone alone is one device and opens nothing: it still needs the master
password, the TOTP code or a PC.
- **An approval is only as careful as the person approving.** Compare the six-digit match code on both
screens; a request you did not start is someone else's.
## Design rules that follow from this
- No custom cryptography: Argon2id (`argon2`), XChaCha20-Poly1305 (`chacha20poly1305`), the OS CSPRNG
Binary file not shown.
+139
View File
@@ -0,0 +1,139 @@
"""Compares two KeePassXC XML exports entry by entry (docs/KDBX.md, "Tests").
python3 compare.py before.xml after.xml
Leaves out exactly what docs/KDBX.md says does not survive: icons, colours, custom data, group settings,
history beyond the secret fields, per-window auto-type sequences, the recycle bin, sub-second times.
A KeePass 2 `TOTP Seed` + `TOTP Settings` pair counts as equal to the `otp` URI Custos writes for it.
Exit status 1 and a list of differences when anything else changed. Prints no values, only keys.
"""
import base64
import gzip
import sys
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from urllib.parse import parse_qs, urlparse
EPOCH_OFFSET = 62_135_596_800
def when(text):
text = (text or "").strip()
try:
raw = base64.b64decode(text, validate=True)
if len(raw) == 8:
return int.from_bytes(raw, "little", signed=True) - EPOCH_OFFSET
except ValueError:
pass
return int(datetime.strptime(text.rstrip("Z"), "%Y-%m-%dT%H:%M:%S").replace(tzinfo=timezone.utc).timestamp())
def binaries(root):
out = {}
for b in root.findall("./Meta/Binaries/Binary"):
data = base64.b64decode(b.text or "")
if b.get("Compressed", "").lower() == "true":
data = gzip.decompress(data)
out[b.get("ID")] = data
return out
def totp(strings):
"""(secret, period, digits) from `otp` or from `TOTP Seed` + `TOTP Settings`."""
if "otp" in strings:
v = strings["otp"]
if v.startswith("otpauth://"):
q = parse_qs(urlparse(v).query)
return (q["secret"][0].upper(), int(q.get("period", ["30"])[0]), int(q.get("digits", ["6"])[0]))
return (v.replace(" ", "").upper(), 30, 6)
if "TOTP Seed" in strings:
parts = (strings.get("TOTP Settings") or "30;6").split(";")
return (strings["TOTP Seed"].replace(" ", "").upper(), int(parts[0]), int(parts[1]))
return None
def entry(e, bins, with_history=True):
strings = {}
for s in e.findall("String"):
strings[s.findtext("Key")] = s.findtext("Value") or ""
t = totp(strings)
for k in ("otp", "TOTP Seed", "TOTP Settings", "custos-type"):
strings.pop(k, None)
times = e.find("Times")
expires = times.findtext("Expires", "False").lower() == "true"
out = {
"strings": strings,
"totp": t,
"attachments": {b.findtext("Key"): bins.get(b.find("Value").get("Ref")) for b in e.findall("Binary")},
"tags": sorted(x.strip() for x in (e.findtext("Tags") or "").replace(",", ";").split(";") if x.strip()),
"created": when(times.findtext("CreationTime")),
"modified": when(times.findtext("LastModificationTime")),
"expires": when(times.findtext("ExpiryTime")) if expires else None,
"autotype": (
e.findtext("AutoType/DefaultSequence") or "",
[a.findtext("Window") or "" for a in e.findall("AutoType/Association")],
),
}
if with_history:
versions = [entry(h, bins, False) for h in e.findall("History/Entry")] + [out]
changes = []
for old, new in zip(versions, versions[1:]):
# Custos keeps the old values of secret fields: the password is the one every file has.
if old["strings"].get("Password", "") not in ("", new["strings"].get("Password", "")):
changes.append((old["modified"], old["strings"]["Password"]))
out["history"] = changes
return out
def entries(path):
root = ET.parse(path).getroot()
bins = binaries(root)
meta = root.find("Meta")
bin_uuid = meta.findtext("RecycleBinUUID") if meta.findtext("RecycleBinEnabled", "").lower() == "true" else None
out = {}
def walk(g, folder):
for e in g.findall("Entry"):
out[e.findtext("UUID")] = (folder, entry(e, bins))
for sub in g.findall("Group"):
if sub.findtext("UUID") != bin_uuid:
walk(sub, folder + [sub.findtext("Name")])
walk(root.find("Root/Group"), [])
return out
def main(before, after):
a, b = entries(before), entries(after)
problems = []
for uuid in sorted(set(a) | set(b)):
if uuid not in b:
problems.append(f"{uuid}: missing after the round trip")
continue
if uuid not in a:
problems.append(f"{uuid}: new after the round trip")
continue
(fa, ea), (fb, eb) = a[uuid], b[uuid]
if fa != fb:
problems.append(f"{uuid}: folder {fa} became {fb}")
for k in ea:
if k == "strings":
for key in sorted(set(ea[k]) | set(eb[k])):
if ea[k].get(key) != eb[k].get(key):
problems.append(f"{uuid}: string {key!r} differs")
elif k == "attachments" and None in [*ea[k].values(), *eb[k].values()]:
# KeePassXC's XML export of a KDBX 4 database leaves the attachment data out: compare names
# here; interop.sh compares the content with `attachment-export`.
if sorted(ea[k]) != sorted(eb[k]):
problems.append(f"{uuid}: attachment names differ")
elif ea[k] != eb[k]:
problems.append(f"{uuid}: {k} differs")
print(f"{len(a)} entries before, {len(b)} after, {len(problems)} differences")
for p in problems:
print(" " + p)
return 1 if problems else 0
if __name__ == "__main__":
sys.exit(main(*sys.argv[1:3]))
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
# KeePassXC interop check (docs/KDBX.md, "Tests"). Needs keepassxc-cli (2.7), cargo and python3; on the dev
# machine run it in WSL inside `nix shell nixpkgs#keepassxc nixpkgs#cargo nixpkgs#rustc nixpkgs#stdenv.cc
# nixpkgs#python3`. Works in a fresh temporary folder; the test password is not a secret.
#
# 1. KeePassXC imports sample.xml (every feature in the mapping table) → KDBX 3.1 with a recycle bin.
# 2. Custos writes an empty KDBX 4 file; KeePassXC merges (1) into it and saves it → KDBX 4 written by KeePassXC.
# 3. Custos reads (1) and (2), maps them to items and back, and writes KDBX 4 again.
# 4. KeePassXC opens what Custos wrote; compare.py checks the XML exports and attachment-export the bytes.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
repo=$(cd "$here/../.." && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
export KDBX_PASSWORD=custos-test
K=${KEEPASSXC_CLI:-keepassxc-cli}
pw() { printf '%s\n' "$KDBX_PASSWORD"; }
cargo build -q --release --manifest-path "$repo/Cargo.toml" -p custos-kdbx --example kdbx_tool \
--target-dir "${CARGO_TARGET_DIR:-$work/target}"
tool="${CARGO_TARGET_DIR:-$work/target}/release/examples/kdbx_tool"
cd "$work"
{ pw; pw; } | $K import -q -p "$here/sample.xml" v3.kdbx
"$tool" new v4.kdbx fast
{ pw; pw; } | $K merge -q v4.kdbx v3.kdbx
for v in v3 v4; do
printf 'KDBX version of %s: ' "$v"; od -A n -t u2 -j 8 -N 4 "$v.kdbx" | awk '{print $2 "." $1}'
pw | $K export -q -f xml "$v.kdbx" > "$v.xml"
"$tool" roundtrip "$v.kdbx" "$v-custos.kdbx"
pw | $K export -q -f xml "$v-custos.kdbx" > "$v-custos.xml"
python3 "$here/compare.py" "$v.xml" "$v-custos.xml"
for db in "$v.kdbx" "$v-custos.kdbx"; do
pw | $K attachment-export -q --stdout "$db" Internet/GitHub codes.txt | sha256sum
done | uniq | wc -l | grep -qx 1 || { echo "$v: the attachment changed"; exit 1; }
pw | $K show -q --totp "$v-custos.kdbx" Internet/Mail/Mail | grep -qE '^[0-9]{8}$' \
|| { echo "$v: no 8-digit TOTP after the round trip"; exit 1; }
done
echo "interop: ok"
+386
View File
@@ -0,0 +1,386 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<KeePassFile>
<Meta>
<Generator>KeePassXC</Generator>
<DatabaseName>Custos interop</DatabaseName>
<MemoryProtection>
<ProtectTitle>False</ProtectTitle>
<ProtectUserName>False</ProtectUserName>
<ProtectPassword>True</ProtectPassword>
<ProtectURL>False</ProtectURL>
<ProtectNotes>False</ProtectNotes>
</MemoryProtection>
<RecycleBinEnabled>True</RecycleBinEnabled>
<RecycleBinUUID>mZmZmZmZmZmZmZmZmZmZmQ==</RecycleBinUUID>
<HistoryMaxItems>10</HistoryMaxItems>
<HistoryMaxSize>6291456</HistoryMaxSize>
<Binaries>
<Binary ID="0" Compressed="False">QmFja3VwIGNvZGVzOgoxMTExLTIyMjIKMzMzMy00NDQ0Cg==</Binary>
</Binaries>
</Meta>
<Root>
<Group>
<UUID>AQEBAQEBAQEBAQEBAQEBAQ==</UUID>
<Name>Passwords</Name>
<Notes/>
<IconID>48</IconID>
<Times>
<LastModificationTime>2023-05-01T10:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2023-05-01T10:00:00Z</LastAccessTime>
<ExpiryTime>2023-05-01T10:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2023-05-01T10:00:00Z</LocationChanged>
</Times>
<IsExpanded>True</IsExpanded>
<DefaultAutoTypeSequence/>
<EnableAutoType>null</EnableAutoType>
<EnableSearching>null</EnableSearching>
<LastTopVisibleEntry>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleEntry>
<Entry>
<UUID>MzMzMzMzMzMzMzMzMzMzMw==</UUID>
<IconID>0</IconID>
<Tags>
</Tags>
<Times>
<LastModificationTime>2026-04-01T12:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2026-04-01T12:00:00Z</LastAccessTime>
<ExpiryTime>2026-04-01T12:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2026-04-01T12:00:00Z</LocationChanged>
</Times>
<String>
<Key>Title</Key>
<Value>Alarm code</Value>
</String>
<String>
<Key>UserName</Key>
<Value/>
</String>
<String>
<Key>Password</Key>
<Value ProtectInMemory="True"/>
</String>
<String>
<Key>URL</Key>
<Value/>
</String>
<String>
<Key>Notes</Key>
<Value>Front door: 4711</Value>
</String>
<AutoType>
<Enabled>True</Enabled>
<DataTransferObfuscation>0</DataTransferObfuscation>
<DefaultSequence/>
</AutoType>
</Entry>
<Group>
<UUID>AgICAgICAgICAgICAgICAg==</UUID>
<Name>Internet</Name>
<Notes/>
<IconID>48</IconID>
<Times>
<LastModificationTime>2023-05-01T10:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2023-05-01T10:00:00Z</LastAccessTime>
<ExpiryTime>2023-05-01T10:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2023-05-01T10:00:00Z</LocationChanged>
</Times>
<IsExpanded>True</IsExpanded>
<DefaultAutoTypeSequence/>
<EnableAutoType>null</EnableAutoType>
<EnableSearching>null</EnableSearching>
<LastTopVisibleEntry>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleEntry>
<Entry>
<UUID>EREREREREREREREREREREQ==</UUID>
<IconID>0</IconID>
<Tags>dev;work</Tags>
<Times>
<LastModificationTime>2026-02-01T09:30:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2026-02-01T09:30:00Z</LastAccessTime>
<ExpiryTime>2030-01-01T00:00:00Z</ExpiryTime>
<Expires>True</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2026-02-01T09:30:00Z</LocationChanged>
</Times>
<String>
<Key>Title</Key>
<Value>GitHub</Value>
</String>
<String>
<Key>UserName</Key>
<Value>alice</Value>
</String>
<String>
<Key>URL</Key>
<Value>https://github.com</Value>
</String>
<String>
<Key>KP2A_URL</Key>
<Value>https://gist.github.com</Value>
</String>
<String>
<Key>KP2A_URL_1</Key>
<Value>https://api.github.com</Value>
</String>
<String>
<Key>Password</Key>
<Value ProtectInMemory="True">Hunter3-Current &amp; &lt;ok&gt;</Value>
</String>
<String>
<Key>Notes</Key>
<Value>Line one
Line two &amp; &lt;three&gt;</Value>
</String>
<String>
<Key>otp</Key>
<Value ProtectInMemory="True">otpauth://totp/GitHub:alice?secret=JBSWY3DPEHPK3PXP&amp;period=30&amp;digits=6&amp;issuer=GitHub</Value>
</String>
<String>
<Key>Recovery codes</Key>
<Value ProtectInMemory="True">Recovery-Secret-123</Value>
</String>
<String>
<Key>Account id</Key>
<Value>42</Value>
</String>
<Binary>
<Key>codes.txt</Key>
<Value Ref="0"/>
</Binary>
<AutoType>
<Enabled>True</Enabled>
<DataTransferObfuscation>0</DataTransferObfuscation>
<DefaultSequence>{USERNAME}{TAB}{PASSWORD}{ENTER}</DefaultSequence>
<Association>
<Window>*GitHub*</Window>
<KeystrokeSequence/>
</Association>
<Association>
<Window>Firefox - GitHub</Window>
<KeystrokeSequence/>
</Association>
</AutoType>
<History>
<Entry>
<UUID>EREREREREREREREREREREQ==</UUID>
<IconID>0</IconID>
<Tags>
</Tags>
<Times>
<LastModificationTime>2024-01-01T08:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2024-01-01T08:00:00Z</LastAccessTime>
<ExpiryTime>2024-01-01T08:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2024-01-01T08:00:00Z</LocationChanged>
</Times>
<String>
<Key>Title</Key>
<Value>GitHub</Value>
</String>
<String>
<Key>UserName</Key>
<Value>alice</Value>
</String>
<String>
<Key>URL</Key>
<Value>https://github.com</Value>
</String>
<String>
<Key>KP2A_URL</Key>
<Value>https://gist.github.com</Value>
</String>
<String>
<Key>KP2A_URL_1</Key>
<Value>https://api.github.com</Value>
</String>
<String>
<Key>Password</Key>
<Value ProtectInMemory="True">Hunter1-Oldest</Value>
</String>
<AutoType>
<Enabled>True</Enabled>
<DataTransferObfuscation>0</DataTransferObfuscation>
<DefaultSequence/>
</AutoType>
</Entry>
<Entry>
<UUID>EREREREREREREREREREREQ==</UUID>
<IconID>0</IconID>
<Tags>
</Tags>
<Times>
<LastModificationTime>2025-01-01T08:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2025-01-01T08:00:00Z</LastAccessTime>
<ExpiryTime>2025-01-01T08:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2025-01-01T08:00:00Z</LocationChanged>
</Times>
<String>
<Key>Title</Key>
<Value>GitHub</Value>
</String>
<String>
<Key>UserName</Key>
<Value>alice</Value>
</String>
<String>
<Key>URL</Key>
<Value>https://github.com</Value>
</String>
<String>
<Key>KP2A_URL</Key>
<Value>https://gist.github.com</Value>
</String>
<String>
<Key>KP2A_URL_1</Key>
<Value>https://api.github.com</Value>
</String>
<String>
<Key>Password</Key>
<Value ProtectInMemory="True">Hunter2-Old</Value>
</String>
<AutoType>
<Enabled>True</Enabled>
<DataTransferObfuscation>0</DataTransferObfuscation>
<DefaultSequence/>
</AutoType>
</Entry>
</History>
</Entry>
<Group>
<UUID>AwMDAwMDAwMDAwMDAwMDAw==</UUID>
<Name>Mail</Name>
<Notes/>
<IconID>48</IconID>
<Times>
<LastModificationTime>2023-05-01T10:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2023-05-01T10:00:00Z</LastAccessTime>
<ExpiryTime>2023-05-01T10:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2023-05-01T10:00:00Z</LocationChanged>
</Times>
<IsExpanded>True</IsExpanded>
<DefaultAutoTypeSequence/>
<EnableAutoType>null</EnableAutoType>
<EnableSearching>null</EnableSearching>
<LastTopVisibleEntry>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleEntry>
<Entry>
<UUID>IiIiIiIiIiIiIiIiIiIiIg==</UUID>
<IconID>0</IconID>
<Tags>
</Tags>
<Times>
<LastModificationTime>2026-03-01T12:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2026-03-01T12:00:00Z</LastAccessTime>
<ExpiryTime>2026-03-01T12:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2026-03-01T12:00:00Z</LocationChanged>
</Times>
<String>
<Key>Title</Key>
<Value>Mail</Value>
</String>
<String>
<Key>UserName</Key>
<Value>bob@example.com</Value>
</String>
<String>
<Key>Password</Key>
<Value ProtectInMemory="True">Mail-Pass-77</Value>
</String>
<String>
<Key>URL</Key>
<Value>https://mail.example.com</Value>
</String>
<String>
<Key>Notes</Key>
<Value/>
</String>
<String>
<Key>TOTP Seed</Key>
<Value ProtectInMemory="True">JBSWY3DPEHPK3PXP</Value>
</String>
<String>
<Key>TOTP Settings</Key>
<Value>60;8</Value>
</String>
<AutoType>
<Enabled>True</Enabled>
<DataTransferObfuscation>0</DataTransferObfuscation>
<DefaultSequence/>
</AutoType>
</Entry>
</Group>
</Group>
<Group>
<UUID>mZmZmZmZmZmZmZmZmZmZmQ==</UUID>
<Name>Recycle Bin</Name>
<Notes/>
<IconID>48</IconID>
<Times>
<LastModificationTime>2023-05-01T10:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2023-05-01T10:00:00Z</LastAccessTime>
<ExpiryTime>2023-05-01T10:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2023-05-01T10:00:00Z</LocationChanged>
</Times>
<IsExpanded>True</IsExpanded>
<DefaultAutoTypeSequence/>
<EnableAutoType>null</EnableAutoType>
<EnableSearching>null</EnableSearching>
<LastTopVisibleEntry>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleEntry>
<Entry>
<UUID>RERERERERERERERERERERA==</UUID>
<IconID>0</IconID>
<Tags>
</Tags>
<Times>
<LastModificationTime>2026-04-02T12:00:00Z</LastModificationTime>
<CreationTime>2023-05-01T10:00:00Z</CreationTime>
<LastAccessTime>2026-04-02T12:00:00Z</LastAccessTime>
<ExpiryTime>2026-04-02T12:00:00Z</ExpiryTime>
<Expires>False</Expires>
<UsageCount>0</UsageCount>
<LocationChanged>2026-04-02T12:00:00Z</LocationChanged>
</Times>
<String>
<Key>Title</Key>
<Value>Old account</Value>
</String>
<String>
<Key>UserName</Key>
<Value>gone</Value>
</String>
<String>
<Key>Password</Key>
<Value ProtectInMemory="True">Deleted-Pass</Value>
</String>
<AutoType>
<Enabled>True</Enabled>
<DataTransferObfuscation>0</DataTransferObfuscation>
<DefaultSequence/>
</AutoType>
</Entry>
</Group>
</Group>
<DeletedObjects/>
</Root>
</KeePassFile>
+65
View File
@@ -0,0 +1,65 @@
# Checks custos-sign against the real tools (docs/SIGNING.md, mandatory test 1):
# minisign -V on a minisign signature and on a signed SHA256SUMS;
# signtool /dg -> custos-sign -> signtool /di on an exe, then osslsigncode verify against the test root,
# and signtool verify /pa (which passes only where the test root is trusted; it is not installed by this script).
# Needs: Windows SDK signtool; WSL Debian with Nix (minisign, osslsigncode come from nixpkgs).
# Usage: powershell -File tools/signing/interop.ps1 [-Exe <unsigned exe to sign a copy of>]
param([string]$Exe = "")
# Exit codes decide; PowerShell 5.1 would turn a tool's expected stderr into a terminating error under 'Stop'.
$ErrorActionPreference = 'Continue'
$root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$work = Join-Path ([System.IO.Path]::GetTempPath()) ("custos-sign-interop-" + [guid]::NewGuid())
New-Item -ItemType Directory $work | Out-Null
$signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" | Sort-Object FullName | Select-Object -Last 1
if (-not $signtool) { throw "signtool not found (Windows SDK)" }
$failed = 0
function Check($name, $ok) { if ($ok) { "PASS $name" } else { "FAIL $name"; $script:failed++ } }
function InWsl($cmd) {
$w = (wsl -d Debian --exec wslpath -a ($work -replace '\\', '/')).Trim()
wsl -d Debian --exec bash -lc "cd '$w' && $cmd"
}
try {
Push-Location $root
cargo build -q --release -p custos-sign --example interop
if ($LASTEXITCODE -ne 0) { throw "cargo build failed" }
$tool = Join-Path $root "target\release\examples\interop.exe"
Pop-Location
# minisign
Set-Content -NoNewline -Encoding ascii (Join-Path $work "payload.bin") "Domi interop payload"
& $tool minisign $work (Join-Path $work "payload.bin")
InWsl "nix shell nixpkgs#minisign -c minisign -Vm payload.bin -p minisign.pub" | Out-Host
Check "minisign -V accepts a custos-sign signature" ($LASTEXITCODE -eq 0)
InWsl "printf 'tampered' >> payload.bin; nix shell nixpkgs#minisign -c minisign -Vm payload.bin -p minisign.pub" 2>$null | Out-Null
Check "minisign -V rejects it on a changed file" ($LASTEXITCODE -ne 0)
$sums = "{0} a.exe`n{1} b.exe`n" -f ('a' * 64), ('b' * 64)
[System.IO.File]::WriteAllText((Join-Path $work "SHA256SUMS"), $sums)
& $tool manifest $work (Join-Path $work "SHA256SUMS")
InWsl "nix shell nixpkgs#minisign -c minisign -Vm SHA256SUMS -p minisign.pub" | Out-Host
Check "minisign -V accepts a signed SHA256SUMS" ($LASTEXITCODE -eq 0)
# Authenticode through signtool's digest signing
$ca = Join-Path $work "ca"
& $tool ca $ca
if (-not $Exe) { $Exe = (Get-Command cargo).Source }
$target = Join-Path $work "app.exe"
Copy-Item $Exe $target
$dg = Join-Path $work "dg"
New-Item -ItemType Directory $dg | Out-Null
& $signtool.FullName sign /dg $dg /fd sha256 /f (Join-Path $ca "leaf.cer") $target | Out-Host
Check "signtool /dg wrote the digest" (Test-Path (Join-Path $dg "app.exe.dig"))
& $tool authenticode (Join-Path $ca "leaf.key.der") (Join-Path $dg "app.exe.dig")
& $signtool.FullName sign /di $dg $target | Out-Host
Check "signtool /di took the signed digest" ($LASTEXITCODE -eq 0)
InWsl "nix shell nixpkgs#osslsigncode -c osslsigncode verify -CAfile ca/root.pem -in app.exe" | Out-Host
Check "osslsigncode verifies the signature to the test root" ($LASTEXITCODE -eq 0)
$v = & $signtool.FullName verify /pa $target 2>&1 | Out-String
$trusted = $LASTEXITCODE -eq 0
if ($trusted) { "PASS signtool verify /pa (the test root is trusted here)" }
elseif ($v -match "not trusted by the trust provider|could not be built to a trusted root") { "NOTE signtool verify /pa: the signature is whole; the test root is not trusted on this machine" }
else { Check "signtool verify /pa" $false; $v }
} finally {
Remove-Item -Recurse -Force $work -ErrorAction SilentlyContinue
}
if ($failed) { "$failed check(s) failed"; exit 1 } else { "all checks passed" }