Compare commits

..

3 Commits

16 changed files with 667 additions and 3 deletions
+2
View File
@@ -8,6 +8,8 @@ The Windows app lives in the private `Custos` repo and depends on this one by gi
```
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-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
docs/FORMAT.md the vault file format (versioned; change it before the code)
docs/THREAT_MODEL.md what is and is not protected
```
Generated
+80 -2
View File
@@ -111,6 +111,12 @@ version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
[[package]]
name = "const-oid"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
[[package]]
name = "cpufeatures"
version = "0.3.1"
@@ -142,7 +148,7 @@ dependencies = [
[[package]]
name = "custos-gen"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"custos-vault",
"rand",
@@ -151,20 +157,45 @@ dependencies = [
"zeroize",
]
[[package]]
name = "custos-qr"
version = "0.2.0"
[[package]]
name = "custos-totp"
version = "0.2.0"
dependencies = [
"custos-vault",
"data-encoding",
"hmac",
"percent-encoding",
"sha1",
"sha2",
"zeroize",
]
[[package]]
name = "custos-vault"
version = "0.1.1"
version = "0.2.0"
dependencies = [
"argon2",
"chacha20poly1305",
"hkdf",
"rand",
"serde",
"serde_json",
"sha2",
"tempfile",
"thiserror",
"zeroize",
]
[[package]]
name = "data-encoding"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]]
name = "digest"
version = "0.11.3"
@@ -172,6 +203,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
"ctutils",
]
@@ -204,6 +236,24 @@ dependencies = [
"rand_core",
]
[[package]]
name = "hkdf"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
dependencies = [
"hmac",
]
[[package]]
name = "hmac"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
dependencies = [
"digest",
]
[[package]]
name = "hybrid-array"
version = "0.4.15"
@@ -261,6 +311,12 @@ dependencies = [
"phc",
]
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "phc"
version = "0.6.1"
@@ -407,6 +463,28 @@ dependencies = [
"zmij",
]
[[package]]
name = "sha1"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha2"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "syn"
version = "2.0.119"
+7 -1
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*"]
[workspace.package]
version = "0.1.1"
version = "0.2.0"
edition = "2024"
license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
@@ -17,3 +17,9 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
unicode-normalization = "0.1"
hmac = "0.13"
sha1 = "0.11"
sha2 = "0.11"
hkdf = "0.13"
data-encoding = "2"
percent-encoding = "2"
+2
View File
@@ -7,6 +7,8 @@ password and secret manager: everything that touches plaintext or keys.
|:--|:--|
| `custos-vault` | The `.custos` file: Argon2id → key slot → XChaCha20-Poly1305, atomic save, typed items |
| `custos-gen` | Memorable passwords (`Word7-Other3-Third9-Fourth2`), nicknames (`GitHub.Lantern.47`), random, PIN, strict-site |
| `custos-totp` | TOTP (RFC 6238) and HOTP (RFC 4226), `otpauth://` URIs |
| `custos-qr` | QR payloads: Wi-Fi join codes (escaped), plain secrets |
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).
+9
View File
@@ -0,0 +1,9 @@
[package]
name = "custos-qr"
description = "Custos QR payloads: Wi-Fi join codes and plain secrets (payload strings only, no rendering)"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
+58
View File
@@ -0,0 +1,58 @@
//! QR payload strings. Rendering happens in the app; this crate only decides what the code says.
/// Security of a Wi-Fi network as the `WIFI:` payload names it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WifiSecurity {
/// WPA, WPA2 or WPA3 (`T:WPA`).
Wpa,
Wep,
/// Open network (`T:nopass`).
None,
}
impl WifiSecurity {
/// From the vault's `security` field (`WPA`, `WEP`, `nopass`); anything else counts as WPA.
pub fn parse(s: &str) -> WifiSecurity {
match s.trim().to_ascii_uppercase().as_str() {
"WEP" => WifiSecurity::Wep,
"NOPASS" | "NONE" | "OPEN" => WifiSecurity::None,
_ => WifiSecurity::Wpa,
}
}
fn token(self) -> &'static str {
match self {
WifiSecurity::Wpa => "WPA",
WifiSecurity::Wep => "WEP",
WifiSecurity::None => "nopass",
}
}
}
/// Escapes `\`, `;`, `,`, `:` and `"` with a backslash, as the `WIFI:` format requires.
pub fn escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if matches!(c, '\\' | ';' | ',' | ':' | '"') {
out.push('\\');
}
out.push(c);
}
out
}
/// `WIFI:T:<WPA|WEP|nopass>;S:<ssid>;P:<password>;H:<true|false>;;` — a phone camera joins from it.
/// An open network gets no `P:` field.
pub fn wifi_payload(ssid: &str, password: &str, security: WifiSecurity, hidden: bool) -> String {
let mut p = format!("WIFI:T:{};S:{};", security.token(), escape(ssid));
if security != WifiSecurity::None {
p.push_str(&format!("P:{};", escape(password)));
}
p.push_str(&format!("H:{hidden};;"));
p
}
/// A QR code that shows a secret to a phone camera is the plain value, so it can be typed elsewhere.
pub fn secret_payload(value: &str) -> String {
value.to_owned()
}
+72
View File
@@ -0,0 +1,72 @@
//! Wi-Fi QR payloads: every special character escaped, so a phone reads back exactly what was stored.
use custos_qr::{WifiSecurity, escape, secret_payload, wifi_payload};
/// What a reader does: split on unescaped `;`, undo `\x` escapes.
fn parse(payload: &str) -> Vec<(String, String)> {
let body = payload.strip_prefix("WIFI:").expect("prefix").strip_suffix(";;").expect("suffix");
let mut fields = Vec::new();
let mut cur = String::new();
let mut chars = body.chars();
while let Some(c) = chars.next() {
match c {
'\\' => cur.push(chars.next().expect("escape at end")),
';' => fields.push(std::mem::take(&mut cur)),
c => cur.push(c),
}
}
fields.push(cur);
fields
.into_iter()
.map(|f| {
let (k, v) = f.split_once(':').expect("key:value");
(k.to_owned(), v.to_owned())
})
.collect()
}
#[test]
fn escapes_every_special_character() {
assert_eq!(escape(r#"\;,:""#), r#"\\\;\,\:\""#);
assert_eq!(escape("plain-text_123 ok"), "plain-text_123 ok");
}
#[test]
fn ssid_and_password_with_every_special_character_survive() {
let nasty = r#"My\Net;5G,"home":x"#;
let pass = r#"p\a;s,s:w"o"r;d\"#;
let p = wifi_payload(nasty, pass, WifiSecurity::Wpa, true);
assert_eq!(p, r#"WIFI:T:WPA;S:My\\Net\;5G\,\"home\"\:x;P:p\\a\;s\,s\:w\"o\"r\;d\\;H:true;;"#);
let f = parse(&p);
assert_eq!(
f,
vec![
("T".into(), "WPA".into()),
("S".into(), nasty.into()),
("P".into(), pass.into()),
("H".into(), "true".into()),
]
);
}
#[test]
fn security_kinds_and_hidden_flag() {
assert_eq!(wifi_payload("Cafe", "secret", WifiSecurity::Wep, false), "WIFI:T:WEP;S:Cafe;P:secret;H:false;;");
// An open network has no password field.
assert_eq!(wifi_payload("Open", "ignored", WifiSecurity::None, false), "WIFI:T:nopass;S:Open;H:false;;");
assert_eq!(WifiSecurity::parse("WPA"), WifiSecurity::Wpa);
assert_eq!(WifiSecurity::parse("nopass"), WifiSecurity::None);
assert_eq!(WifiSecurity::parse("WEP"), WifiSecurity::Wep);
assert_eq!(WifiSecurity::parse("anything else"), WifiSecurity::Wpa);
}
#[test]
fn unicode_ssid_is_kept() {
let p = wifi_payload("Žluťoučký kůň 📶", "heslo", WifiSecurity::Wpa, false);
assert_eq!(parse(&p)[1].1, "Žluťoučký kůň 📶");
}
#[test]
fn secret_payload_is_the_value_itself() {
assert_eq!(secret_payload("sk-test;with:specials"), "sk-test;with:specials");
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "custos-totp"
description = "Custos TOTP (RFC 6238) and HOTP (RFC 4226), otpauth:// URIs"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-vault = { path = "../custos-vault" }
hmac.workspace = true
sha1.workspace = true
sha2.workspace = true
data-encoding.workspace = true
percent-encoding.workspace = true
zeroize.workspace = true
+221
View File
@@ -0,0 +1,221 @@
//! TOTP (RFC 6238) and HOTP (RFC 4226) on RustCrypto's HMAC, and `otpauth://` URIs.
//!
//! ```
//! use custos_totp::Totp;
//! let t = Totp::parse("otpauth://totp/GitHub:mark?secret=JBSWY3DPEHPK3PXP&issuer=GitHub")?;
//! assert_eq!(t.code_at(1_700_000_000).len(), 6);
//! # Ok::<(), custos_totp::TotpError>(())
//! ```
use data_encoding::BASE32_NOPAD;
use hmac::{Hmac, KeyInit, Mac};
use percent_encoding::{NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
use std::fmt;
use zeroize::Zeroizing;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Algorithm {
Sha1,
Sha256,
Sha512,
}
impl Algorithm {
fn name(self) -> &'static str {
match self {
Algorithm::Sha1 => "SHA1",
Algorithm::Sha256 => "SHA256",
Algorithm::Sha512 => "SHA512",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TotpError(String);
impl fmt::Display for TotpError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for TotpError {}
fn err<T>(msg: &str) -> Result<T, TotpError> {
Err(TotpError(msg.into()))
}
fn mac(alg: Algorithm, key: &[u8], msg: &[u8]) -> Vec<u8> {
// HMAC accepts keys of any length; `new_from_slice` cannot fail for it.
match alg {
Algorithm::Sha1 => {
let mut m = <Hmac<sha1::Sha1> as KeyInit>::new_from_slice(key).expect("any key length");
m.update(msg);
m.finalize().into_bytes().to_vec()
}
Algorithm::Sha256 => {
let mut m = <Hmac<sha2::Sha256> as KeyInit>::new_from_slice(key).expect("any key length");
m.update(msg);
m.finalize().into_bytes().to_vec()
}
Algorithm::Sha512 => {
let mut m = <Hmac<sha2::Sha512> as KeyInit>::new_from_slice(key).expect("any key length");
m.update(msg);
m.finalize().into_bytes().to_vec()
}
}
}
/// RFC 4226: HMAC of the 8-byte big-endian counter, dynamic truncation, `digits` decimal digits.
pub fn hotp(secret: &[u8], counter: u64, digits: u32, alg: Algorithm) -> String {
let h = mac(alg, secret, &counter.to_be_bytes());
let off = (h[h.len() - 1] & 0x0f) as usize;
let bin = u32::from_be_bytes([h[off] & 0x7f, h[off + 1], h[off + 2], h[off + 3]]);
format!("{:0width$}", bin % 10u32.pow(digits), width = digits as usize)
}
/// A TOTP generator. The secret is wiped on drop and never printed.
#[derive(Clone)]
pub struct Totp {
secret: Zeroizing<Vec<u8>>,
algorithm: Algorithm,
digits: u32,
period: u64,
issuer: Option<String>,
account: Option<String>,
}
impl fmt::Debug for Totp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Totp")
.field("secret", &"[redacted]")
.field("algorithm", &self.algorithm)
.field("digits", &self.digits)
.field("period", &self.period)
.field("issuer", &self.issuer)
.finish_non_exhaustive()
}
}
fn decode_base32(s: &str) -> Result<Zeroizing<Vec<u8>>, TotpError> {
let clean: Zeroizing<String> = Zeroizing::new(
s.chars().filter(|c| !c.is_whitespace() && *c != '-' && *c != '=').collect::<String>().to_uppercase(),
);
if clean.is_empty() {
return err("the 2FA secret is empty");
}
BASE32_NOPAD
.decode(clean.as_bytes())
.map(Zeroizing::new)
.map_err(|_| TotpError("the 2FA secret is not valid base32".into()))
}
impl Totp {
/// `digits` 6..=8, `period` in seconds (at least 1).
pub fn new(secret: Vec<u8>, algorithm: Algorithm, digits: u32, period: u64) -> Result<Totp, TotpError> {
if !(6..=8).contains(&digits) {
return err("a 2FA code has 6 to 8 digits");
}
if period == 0 {
return err("the 2FA period must be at least one second");
}
if secret.is_empty() {
return err("the 2FA secret is empty");
}
Ok(Totp { secret: Zeroizing::new(secret), algorithm, digits, period, issuer: None, account: None })
}
/// An `otpauth://totp/…` URI, or a bare base32 secret (spaces, lower case and `=` are fine).
pub fn parse(input: &str) -> Result<Totp, TotpError> {
let input = input.trim();
let Some(rest) = input.strip_prefix("otpauth://") else {
return Totp::new(decode_base32(input)?.to_vec(), Algorithm::Sha1, 6, 30);
};
let Some(rest) = rest.strip_prefix("totp/") else {
return err("only time-based codes (otpauth://totp) are supported");
};
let (label, query) = rest.split_once('?').unwrap_or((rest, ""));
let label = percent_decode_str(label).decode_utf8_lossy().into_owned();
let (mut issuer, account) = match label.split_once(':') {
Some((i, a)) => (Some(i.trim().to_owned()), Some(a.trim().to_owned())),
None if label.is_empty() => (None, None),
None => (None, Some(label.trim().to_owned())),
};
let (mut secret, mut alg, mut digits, mut period) = (None, Algorithm::Sha1, 6u32, 30u64);
for pair in query.split('&').filter(|p| !p.is_empty()) {
let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
let v = Zeroizing::new(percent_decode_str(v).decode_utf8_lossy().into_owned());
match k.to_ascii_lowercase().as_str() {
"secret" => secret = Some(decode_base32(&v)?),
"issuer" => issuer = Some(v.to_string()),
"algorithm" => {
alg = match v.to_ascii_uppercase().as_str() {
"SHA1" => Algorithm::Sha1,
"SHA256" => Algorithm::Sha256,
"SHA512" => Algorithm::Sha512,
_ => return err("unsupported 2FA algorithm (use SHA1, SHA256 or SHA512)"),
}
}
"digits" => digits = v.parse().map_err(|_| TotpError("digits is not a number".into()))?,
"period" => period = v.parse().map_err(|_| TotpError("period is not a number".into()))?,
_ => {}
}
}
let secret = secret.ok_or_else(|| TotpError("the otpauth URI has no secret".into()))?;
let mut t = Totp::new(secret.to_vec(), alg, digits, period)?;
t.issuer = issuer.filter(|s| !s.is_empty());
t.account = account.filter(|s| !s.is_empty());
Ok(t)
}
/// The code for Unix time `unix_secs`.
pub fn code_at(&self, unix_secs: u64) -> String {
hotp(&self.secret, unix_secs / self.period, self.digits, self.algorithm)
}
/// Seconds until the code at `unix_secs` changes (1..=period).
pub fn seconds_left(&self, unix_secs: u64) -> u64 {
self.period - unix_secs % self.period
}
pub fn to_uri(&self) -> String {
let enc = |s: &str| utf8_percent_encode(s, NON_ALPHANUMERIC).to_string();
let label = match (&self.issuer, &self.account) {
(Some(i), Some(a)) => format!("{}:{}", enc(i), enc(a)),
(None, Some(a)) => enc(a),
(Some(i), None) => enc(i),
(None, None) => String::new(),
};
let mut uri = format!(
"otpauth://totp/{label}?secret={}&algorithm={}&digits={}&period={}",
BASE32_NOPAD.encode(&self.secret),
self.algorithm.name(),
self.digits,
self.period
);
if let Some(i) = &self.issuer {
uri.push_str(&format!("&issuer={}", enc(i)));
}
uri
}
pub fn issuer(&self) -> Option<&str> {
self.issuer.as_deref()
}
pub fn account(&self) -> Option<&str> {
self.account.as_deref()
}
pub fn digits(&self) -> u32 {
self.digits
}
pub fn period(&self) -> u64 {
self.period
}
pub fn algorithm(&self) -> Algorithm {
self.algorithm
}
}
+93
View File
@@ -0,0 +1,93 @@
//! RFC 6238 Appendix B and RFC 4226 Appendix D test vectors, exactly as published, plus otpauth parsing.
use custos_totp::{Algorithm, Totp, hotp};
const SEED_SHA1: &[u8] = b"12345678901234567890";
const SEED_SHA256: &[u8] = b"12345678901234567890123456789012";
const SEED_SHA512: &[u8] = b"1234567890123456789012345678901234567890123456789012345678901234";
#[test]
fn rfc6238_appendix_b() {
// Time (s), SHA1, SHA256, SHA512 — 8 digits, period 30, T0 = 0.
let table: [(u64, &str, &str, &str); 6] = [
(59, "94287082", "46119246", "90693936"),
(1111111109, "07081804", "68084774", "25091201"),
(1111111111, "14050471", "67062674", "99943326"),
(1234567890, "89005924", "91819424", "93441116"),
(2000000000, "69279037", "90698825", "38618901"),
(20000000000, "65353130", "77737706", "47863826"),
];
for (t, sha1, sha256, sha512) in table {
for (seed, alg, want) in [
(SEED_SHA1, Algorithm::Sha1, sha1),
(SEED_SHA256, Algorithm::Sha256, sha256),
(SEED_SHA512, Algorithm::Sha512, sha512),
] {
let totp = Totp::new(seed.to_vec(), alg, 8, 30).unwrap();
assert_eq!(totp.code_at(t), want, "T={t} {alg:?}");
}
}
}
#[test]
fn rfc4226_appendix_d() {
let want = ["755224", "287082", "359152", "969429", "338314", "254676", "287922", "162583", "399871", "520489"];
for (counter, code) in want.iter().enumerate() {
assert_eq!(hotp(SEED_SHA1, counter as u64, 6, Algorithm::Sha1), *code, "counter {counter}");
}
}
#[test]
fn otpauth_uri_and_base32() {
// "12345678901234567890" in base32.
let b32 = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
let t = Totp::parse(&format!(
"otpauth://totp/Example%20Co:alice%40example.com?secret={b32}&issuer=Example%20Co&algorithm=SHA1&digits=8&period=30"
))
.unwrap();
assert_eq!(t.code_at(59), "94287082");
assert_eq!(t.issuer(), Some("Example Co"));
assert_eq!(t.account(), Some("alice@example.com"));
assert_eq!((t.digits(), t.period(), t.algorithm()), (8, 30, Algorithm::Sha1));
// Defaults: SHA1, 6 digits, 30 s. A bare secret (lower case, spaces, padding) works too.
let bare = Totp::parse("gezd gnbv gy3t qojq gezd gnbv gy3t qojq").unwrap();
assert_eq!(bare.code_at(59), "287082");
assert_eq!((bare.digits(), bare.period()), (6, 30));
assert_eq!(Totp::parse(&format!("{b32}====")).unwrap().code_at(59), "287082");
let sha256 = Totp::parse(
"otpauth://totp/x?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA&algorithm=SHA256&digits=8",
)
.unwrap();
assert_eq!(sha256.code_at(59), "46119246");
for bad in [
"otpauth://hotp/x?secret=GEZDGNBV&counter=1",
"otpauth://totp/x?digits=6",
"otpauth://totp/x?secret=not*base32",
"otpauth://totp/x?secret=GEZDGNBV&digits=9",
"otpauth://totp/x?secret=GEZDGNBV&period=0",
"otpauth://totp/x?secret=GEZDGNBV&algorithm=MD5",
"",
] {
assert!(Totp::parse(bad).is_err(), "{bad} was accepted");
}
}
#[test]
fn round_trip_through_uri_and_countdown() {
let t = Totp::parse("otpauth://totp/GitHub:mark?secret=JBSWY3DPEHPK3PXP&issuer=GitHub").unwrap();
let back = Totp::parse(&t.to_uri()).unwrap();
assert_eq!(back.code_at(1_700_000_000), t.code_at(1_700_000_000));
assert_eq!(back.issuer(), Some("GitHub"));
assert_eq!(t.seconds_left(1_700_000_000), 30 - 1_700_000_000 % 30);
assert_eq!(t.seconds_left(60), 30);
}
#[test]
fn secret_is_redacted_in_debug() {
let t = Totp::parse("otpauth://totp/x?secret=JBSWY3DPEHPK3PXP").unwrap();
let out = format!("{t:?}");
assert!(!out.contains("JBSWY3DPEHPK3PXP") && !out.contains("72, 101") && out.contains("[redacted]"), "{out}");
}
+2
View File
@@ -14,6 +14,8 @@ rand.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
hkdf.workspace = true
sha2.workspace = true
[dev-dependencies]
tempfile = "3"
+45
View File
@@ -0,0 +1,45 @@
//! Device unlock (docs/FORMAT.md, "Device key wrap"): the vault key wrapped with a key derived from
//! material only this device can produce (the desktop app uses a Windows Hello signature). The blob is
//! kept on that device, never in the vault file.
use crate::Error;
use crate::crypto::{self, KEY_LEN, NONCE_LEN, TAG_LEN};
use hkdf::Hkdf;
use sha2::Sha256;
use zeroize::Zeroizing;
const MAGIC: &[u8; 4] = b"CDW1";
const SALT_LEN: usize = 32;
const INFO: &[u8] = b"custos device wrap v1";
pub const BLOB_LEN: usize = 4 + SALT_LEN + NONCE_LEN + KEY_LEN + TAG_LEN;
fn kek(material: &[u8], salt: &[u8]) -> Zeroizing<[u8; KEY_LEN]> {
let mut k = Zeroizing::new([0u8; KEY_LEN]);
Hkdf::<Sha256>::new(Some(salt), material).expand(INFO, k.as_mut()).expect("32 bytes is a valid HKDF length");
k
}
/// `CDW1 ‖ salt ‖ nonce ‖ XChaCha20-Poly1305(HKDF-SHA256(material, salt), vault key, aad = CDW1 ‖ salt ‖ nonce)`.
pub fn wrap(key: &[u8; KEY_LEN], material: &[u8]) -> Vec<u8> {
let mut salt = [0u8; SALT_LEN];
crypto::fill_random(&mut salt);
let nonce = crypto::random_nonce();
let mut blob = Vec::with_capacity(BLOB_LEN);
blob.extend_from_slice(MAGIC);
blob.extend_from_slice(&salt);
blob.extend_from_slice(&nonce);
let sealed = crypto::seal(&kek(material, &salt), &nonce, key, &blob);
blob.extend_from_slice(&sealed);
blob
}
pub fn unwrap(blob: &[u8], material: &[u8]) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
if blob.len() != BLOB_LEN || &blob[..4] != MAGIC {
return Err(Error::DeviceKeyRejected);
}
let salt = &blob[4..4 + SALT_LEN];
let nonce: [u8; NONCE_LEN] = blob[4 + SALT_LEN..4 + SALT_LEN + NONCE_LEN].try_into().unwrap();
let head = 4 + SALT_LEN + NONCE_LEN;
let k = crypto::open(&kek(material, salt), &nonce, &blob[head..], &blob[..head]).ok_or(Error::DeviceKeyRejected)?;
Ok(Zeroizing::new(k.as_slice().try_into().map_err(|_| Error::DeviceKeyRejected)?))
}
+17
View File
@@ -12,6 +12,7 @@
//! ```
mod crypto;
mod device;
mod format;
mod item;
mod save;
@@ -42,6 +43,8 @@ pub enum Error {
WrongPassword,
#[error("the vault file was changed or damaged after it was written")]
Corrupted,
#[error("this device's unlock key no longer opens the vault; use the master password")]
DeviceKeyRejected,
#[error("{0}")]
Io(#[from] std::io::Error),
}
@@ -160,6 +163,20 @@ impl Vault {
Ok(Vault { key, slots: header.slots, items: body.items })
}
/// 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".
pub fn wrap_for_device(&self, material: &[u8]) -> Result<Vec<u8>, Error> {
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.
pub fn open_with_device(bytes: &[u8], blob: &[u8], material: &[u8]) -> Result<Vault, Error> {
let (header, body_at) = Header::parse(bytes)?;
let key = device::unwrap(blob, material)?;
Vault::open_body(bytes, header, body_at, key)
}
/// The encrypted file contents, with a fresh body nonce.
pub fn to_bytes(&self) -> Result<Vec<u8>, Error> {
let body_nonce = crypto::random_nonce();
+24
View File
@@ -202,3 +202,27 @@ fn no_secret_in_debug_or_display() {
// Non-secret fields stay readable in Debug, which is what makes it useful.
assert!(format!("{item:?}").contains("Example"));
}
#[test]
fn device_wrap_opens_the_same_vault_and_nothing_else() {
// Windows Hello gives the desktop app a signature; the core turns it into a key wrap.
let v = sample_vault("pw");
let bytes = v.to_bytes().unwrap();
let material = b"signature bytes from the device key";
let blob = v.wrap_for_device(material).unwrap();
assert_ne!(v.wrap_for_device(material).unwrap(), blob, "fresh salt and nonce each time");
let back = Vault::open_with_device(&bytes, &blob, material).unwrap();
assert_eq!(back.items(), v.items());
assert!(matches!(Vault::open_with_device(&bytes, &blob, b"other signature"), Err(Error::DeviceKeyRejected)));
for i in 0..blob.len() {
let mut t = blob.clone();
t[i] ^= 1;
assert!(Vault::open_with_device(&bytes, &t, material).is_err(), "blob byte {i}");
}
// A blob made for another vault does not open this one.
let other = sample_vault("pw").wrap_for_device(material).unwrap();
assert!(Vault::open_with_device(&bytes, &other, material).is_err());
assert!(!format!("{:?}", Error::DeviceKeyRejected).contains("signature"));
}
+16
View File
@@ -162,6 +162,22 @@ become *protected* strings.
| `created`, `modified` | `Times/CreationTime`, `Times/LastModificationTime` |
| `history` entries | `History` entries (one per change, with that old password) |
## Device key wrap (not part of the file)
Quick unlock on one machine (the desktop app uses Windows Hello) keeps a separate 108-byte blob **on that
machine**, never in the vault file:
```
"CDW1" (4) ‖ salt (32) ‖ nonce (24) ‖ XChaCha20-Poly1305(KEK, vault key, aad = "CDW1" ‖ salt ‖ nonce) (48)
KEK = HKDF-SHA256(ikm = device material, salt, info = "custos device wrap v1")
```
The device material is something only that device can produce on request (for Windows Hello: the RSA
signature of a fixed challenge by a TPM-held key, which only Hello can unlock). A wrong material or a
changed blob gives `DeviceKeyRejected`; a blob from another vault unwraps a key that fails the body tag
(`Corrupted`). Changing the master password does not change the vault key, so the app deletes the blob
itself when the password changes.
## Saving
`custos-vault::save_atomic` never leaves a half-written vault in place of the old one:
+3
View File
@@ -31,6 +31,9 @@ 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
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.
Custos does not detect that (there is no trusted counter to compare against).
- **Shoulder surfing and QR codes.** A revealed password or a shown QR code is readable by anyone who