[core] TOTP, QR payloads, device key wrap: custos-totp, custos-qr, Vault::wrap_for_device (v0.2.0)
This commit is contained in:
@@ -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]
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -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)?))
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user