46 lines
1.9 KiB
Rust
46 lines
1.9 KiB
Rust
//! 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)?))
|
|
}
|