//! The importer's own vault key: mint once, publish, wait for the phone's
//! approval, then open sealed values for the length of a pass.
//!
//! ```text
//! first pass, no key mint an X25519 pair; the private half into the login Keychain
//! (this app's own service, never a file); publish the public
//! half as this Mac's `vault_key` row, with no wrap → Waiting
//! a pass, no wrap yet read the row back; still waiting → Waiting
//! a pass, wrapped unwrap the VMK with the private half, hold it for
//! this pass only, open `v2:` values with it → Open
//! ```
//!
//! OR BY THE RECOVERY CODE, typed once on this Mac (e2e rulings R7c): the
//! code is stretched here, proved to the object (which counts wrong tries),
//! and opens the wrap of the VMK the object keeps for it; this Mac then wraps
//! the VMK to its own key and writes its own row, approved, so every later
//! pass opens with the Keychain alone. The code is never kept, logged or sent.
//!
//! The waiting row on the object IS the record that this Mac waits: the phone's
//! Devices list draws it (pending, with its name and fingerprint) until the
//! owner approves or refuses it. The popover says the same with
//! [`VaultLine`].
//!
//! The private half leaves the Keychain only into this process's memory, the
//! VMK only into an [`OpenVault`] that is dropped (and wiped) at the end of the
//! pass. Neither is ever logged, written or sent; the object only ever sees the
//! public half.
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use cotton_core::keys::passkey::{Passkey, PasskeyError};
use cotton_core::keys::passkey_row;
use cotton_core::vault::{seal, wrap, Vmk};
use serde::Serialize;
use serde_json::{json, Map, Value};
use zeroize::Zeroizing;
use crate::object::{ObjectClient, ObjectError};
/// The object table a device's key row lives in (`cotton_vault_keys` on a phone).
pub const VAULT_KEY_TABLE: &str = "vault_key";
/// The login Keychain service this app keeps its vault key under.
pub const KEYCHAIN_SERVICE: &str = "com.cottondb.mac.vault-key";
/// Where the private half lives. The Mac's is the login Keychain
/// ([`LoginKeychain`]); a test holds it in memory.
pub trait Keyring: Send + Sync {
/// The private half, when one was kept.
fn load(&self) -> Result>, String>;
/// Keep the private half, replacing any held.
fn store(&self, secret: &[u8; 32]) -> Result<(), String>;
}
/// The login Keychain, under [`KEYCHAIN_SERVICE`] and the device's own id as
/// the account: a generic password item only this app's signature reads back
/// without asking.
#[cfg(target_os = "macos")]
pub struct LoginKeychain {
service: String,
account: String,
}
#[cfg(target_os = "macos")]
impl LoginKeychain {
pub fn new(device_id: &str) -> LoginKeychain {
LoginKeychain { service: KEYCHAIN_SERVICE.to_string(), account: device_id.to_string() }
}
/// The login Keychain under another `service` of this app's (its device key).
pub fn for_service(service: &str, account: &str) -> LoginKeychain {
LoginKeychain { service: service.to_string(), account: account.to_string() }
}
/// The same Keychain under a service of the test's own, so a test never
/// reads or writes the app's item.
#[cfg(test)]
fn under(service: &str, account: &str) -> LoginKeychain {
LoginKeychain { service: service.to_string(), account: account.to_string() }
}
}
#[cfg(target_os = "macos")]
impl Keyring for LoginKeychain {
fn load(&self) -> Result >, String> {
/// `errSecItemNotFound`: nothing kept yet.
const NOT_FOUND: i32 = -25300;
match security_framework::passwords::get_generic_password(&self.service, &self.account) {
Ok(bytes) => {
let bytes = Zeroizing::new(bytes);
let secret: [u8; 32] = bytes
.as_slice()
.try_into()
.map_err(|_| "the Keychain's vault key is not 32 bytes".to_string())?;
Ok(Some(Zeroizing::new(secret)))
}
Err(error) if error.code() == NOT_FOUND => Ok(None),
Err(error) => Err(format!("the Keychain would not answer for the vault key ({})", error.code())),
}
}
fn store(&self, secret: &[u8; 32]) -> Result<(), String> {
security_framework::passwords::set_generic_password(&self.service, &self.account, secret)
.map_err(|error| format!("the Keychain would not keep the vault key ({})", error.code()))
}
}
/// A keyring on a system with no Keychain: it holds nothing and keeps nothing,
/// so the vault waits with words rather than a key in a file.
pub struct NoKeyring;
impl Keyring for NoKeyring {
fn load(&self) -> Result >, String> {
Err("this system has no Keychain to keep the vault key in".to_string())
}
fn store(&self, _secret: &[u8; 32]) -> Result<(), String> {
Err("this system has no Keychain to keep the vault key in".to_string())
}
}
/// This system's keyring for `device_id`: the login Keychain on a Mac, none
/// elsewhere. The app's entry points hand it to [`crate::app::App::open`] and
/// the WhatsApp signer; a test hands its own and never touches the Keychain.
pub fn system_keyring(device_id: &str) -> Box {
#[cfg(target_os = "macos")]
return Box::new(LoginKeychain::new(device_id));
#[cfg(not(target_os = "macos"))]
{
let _ = device_id;
Box::new(NoKeyring)
}
}
/// A keyring in one file, mode 600: for the sealing tools run from a shell,
/// where no one sits at the Mac to answer the Keychain's prompt for a binary
/// it has not met. The app itself never uses it.
pub struct FileKeyring(pub std::path::PathBuf);
impl Keyring for FileKeyring {
fn load(&self) -> Result>, String> {
match std::fs::read(&self.0) {
Ok(bytes) => {
let bytes = Zeroizing::new(bytes);
let secret: [u8; 32] =
bytes.as_slice().try_into().map_err(|_| "the key file's vault key is not 32 bytes".to_string())?;
Ok(Some(Zeroizing::new(secret)))
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(format!("the key file could not be read: {error}")),
}
}
fn store(&self, secret: &[u8; 32]) -> Result<(), String> {
use std::io::Write;
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(&self.0).map_err(|error| format!("the key file could not be written: {error}"))?;
file.write_all(secret).map_err(|error| format!("the key file could not be written: {error}"))
}
}
/// The keyring a sealing tool uses: the file it was pointed at, or this
/// system's own.
pub fn tool_keyring(device_id: &str, key_file: Option<&std::path::Path>) -> Box {
match key_file {
Some(path) => Box::new(FileKeyring(path.to_path_buf())),
None => system_keyring(device_id),
}
}
/// A keyring in memory, for tests and nothing else.
#[derive(Default)]
pub struct MemoryKeyring(std::sync::Mutex>>);
impl Keyring for MemoryKeyring {
fn load(&self) -> Result >, String> {
Ok(self.0.lock().unwrap_or_else(|p| p.into_inner()).clone())
}
fn store(&self, secret: &[u8; 32]) -> Result<(), String> {
*self.0.lock().unwrap_or_else(|p| p.into_inner()) = Some(Zeroizing::new(*secret));
Ok(())
}
}
/// The object as this module reads and writes it: its own key row, by device.
pub trait KeyRows {
/// This device's `vault_key` row's data, with its id, if the object holds one.
fn key_row(&self, device_id: &str) -> Result )>, ObjectError>;
/// Write the row whole under `id` (create, or update when it is there).
fn put_key_row(&self, id: &str, data: &Value) -> Result<(), ObjectError>;
}
impl KeyRows for ObjectClient {
/// Read over `GET /v1/sync` of the one table, as a device session may (the
/// object's `/mcp` takes tokens, never a device's sign-in).
fn key_row(&self, device_id: &str) -> Result )>, ObjectError> {
let mut cursor: Option = None;
loop {
let page = self.sync_page(0, &[VAULT_KEY_TABLE], cursor.as_deref())?;
let found = page.get("rows").and_then(Value::as_array).into_iter().flatten().find_map(|row| {
if row.get("table").and_then(Value::as_str) != Some(VAULT_KEY_TABLE) || row.get("deleted").and_then(Value::as_bool) == Some(true) {
return None;
}
let data = row.get("data")?.as_object()?;
(data.get("device_id").and_then(Value::as_str) == Some(device_id)).then(|| Some((row.get("id")?.as_str()?.to_string(), data.clone())))?
});
if found.is_some() {
return Ok(found);
}
match page.get("next").and_then(Value::as_str) {
Some(next) => cursor = Some(next.to_string()),
None => return Ok(None),
}
}
}
fn put_key_row(&self, id: &str, data: &Value) -> Result<(), ObjectError> {
self.upsert(VAULT_KEY_TABLE, id, data).map(|_| ())
}
}
/// The object's way back in by a recovery code (`/v1/recovery`), as this
/// module asks it.
pub trait RecoveryDoor {
/// `GET /v1/recovery`: what ways back in the object holds, by kind.
fn held(&self) -> Result;
/// `POST /v1/recovery/open { kind: "code", auth }`: the wrap and its
/// version, or the object's refusal (`recovery_wrong`, `recovery_wait`).
fn open_code(&self, auth: &str) -> Result;
}
impl RecoveryDoor for ObjectClient {
fn held(&self) -> Result {
self.get_json("/v1/recovery", &[])
}
fn open_code(&self, auth: &str) -> Result {
self.post_route("/v1/recovery/open", &json!({ "kind": "code", "auth": auth }))
}
}
/// The vault master key, opened for one pass. Dropped (and wiped) when the
/// pass ends; never cloned, logged or sent.
pub struct OpenVault {
vmk: Vmk,
version: u32,
}
impl std::fmt::Debug for OpenVault {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OpenVault").field("version", &self.version).finish_non_exhaustive()
}
}
impl OpenVault {
/// A vault opened from a VMK already in hand: tests, which have no phone.
#[cfg(test)]
pub(crate) fn from_vmk(vmk: Vmk, version: u32) -> OpenVault {
OpenVault { vmk, version }
}
/// The version of the key this Mac was wrapped at.
pub fn version(&self) -> u32 {
self.version
}
/// One `v2:` value, sealed for `row_id` at `version`. `None` for every way
/// it does not open.
pub fn open(&self, row_id: &str, version: u32, sealed: &str) -> Option>> {
seal::open(&self.vmk, row_id, version, sealed).map(Zeroizing::new)
}
/// The database's data key out of its `seal_key` row `dk` (sealing plan
/// §2.1): what the seal migration seals with. A row wrapped under another
/// vault key version is refused by name.
pub fn data_key(&self, row: &Map) -> Result {
cotton_client::seal::open_data_key(&self.vmk, self.version, row)
}
/// A `passkey` row's passkey, its private half opened: what the WhatsApp
/// signer asserts with.
pub fn passkey(&self, row_id: &str, row: &Map) -> Result {
passkey_row::open(row, row_id, &self.vmk)
}
}
/// Where this Mac's vault stands after a pass, as the popover says it. Never a key.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VaultLine {
/// `waiting` (published, not approved yet), `open`, or `trouble`.
pub state: &'static str,
/// What the phone's Devices list shows for this Mac, to compare by eye.
#[serde(skip_serializing_if = "Option::is_none")]
pub fingerprint: Option,
/// One sentence.
pub detail: String,
/// While waiting: the button that asks a signed-in phone to let this Mac in, right here (the core's
/// `askApproval`; its card shows the six digits to type on the phone).
#[serde(skip_serializing_if = "Option::is_none")]
pub ask: Option,
/// While waiting: the button that signs this Mac out, to sign in again another way.
#[serde(rename = "signOut", skip_serializing_if = "Option::is_none")]
pub sign_out: Option,
}
/// The words of the waiting line's Sign out.
pub const SIGN_OUT: &str = "Sign out";
/// The vault line while this Mac is not let in. Since 19 Nov a phone lets a
/// device in only through an approval ask whose code the person typed (no
/// one-tap Approve in Keys › Devices), which a Mac makes at sign-in.
pub const WAITING_LINE: &str = "Open any Cotton app on another device that has your things, and scan the code on this Mac. No other device? Type your recovery code below.";
/// What a pass found.
pub enum Pass {
Waiting { fingerprint: String },
Open(OpenVault),
}
impl Pass {
pub fn line(&self, fingerprint: &str) -> VaultLine {
match self {
Pass::Waiting { fingerprint } => VaultLine {
state: "waiting",
fingerprint: Some(fingerprint.clone()),
detail: WAITING_LINE.to_string(),
ask: Some(crate::approval::ask_button()),
sign_out: Some(SIGN_OUT.to_string()),
},
Pass::Open(_) => VaultLine {
state: "open",
fingerprint: Some(fingerprint.to_string()),
detail: "This Mac opens your vault.".to_string(),
ask: None,
sign_out: None,
},
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum VaultError {
#[error("{0}")]
Keyring(String),
#[error(transparent)]
Object(#[from] ObjectError),
#[error("the vault key wrapped for this Mac does not open with its own key")]
WrapDoesNotOpen,
/// The typed code is not a recovery code (its length, a character, its check), said before anything is sent.
#[error("that is not a recovery code ({0}): it is 24 letters and digits, in six groups of four")]
Code(&'static str),
#[error("no recovery code was saved for this account: approve this Mac from a phone instead")]
NoCode,
#[error("the recovery code did not open the vault key; nothing was changed")]
CodeDoesNotOpen,
#[error("this Mac does not open the vault yet, so it cannot let another device in")]
NotOpen,
#[error("no device by that id is waiting on this account")]
NoSuchDevice,
#[error("that device already opens the vault; nothing was changed")]
AlreadyApproved,
#[error("that device published a key nothing can be wrapped for")]
Unwrappable,
}
/// This Mac's vault, for one device id and name.
pub struct ImporterVault<'a> {
keyring: &'a dyn Keyring,
device_id: &'a str,
device_name: &'a str,
}
impl<'a> ImporterVault<'a> {
pub fn new(keyring: &'a dyn Keyring, device_id: &'a str, device_name: &'a str) -> ImporterVault<'a> {
ImporterVault { keyring, device_id, device_name }
}
/// The `vault_key` row id this Mac publishes under.
pub fn row_id(&self) -> String {
format!("vault-key-{}", self.device_id)
}
/// The private half, minted and kept on the first pass that has none.
fn secret(&self) -> Result, VaultError> {
if let Some(secret) = self.keyring.load().map_err(VaultError::Keyring)? {
return Ok(secret);
}
let secret = wrap::mint_vault_key();
self.keyring.store(&secret).map_err(VaultError::Keyring)?;
Ok(secret)
}
/// This Mac's public half, base64url, minting the key if none is kept yet:
/// what an approval ask names, so the phone wraps the vault's key for it.
pub fn public_key(&self) -> Result {
Ok(URL_SAFE_NO_PAD.encode(wrap::public_of(&*self.secret()?)))
}
/// The fingerprint this Mac's public half shows, minting the key if none
/// is kept yet.
pub fn fingerprint(&self) -> Result {
let public = URL_SAFE_NO_PAD.encode(wrap::public_of(&*self.secret()?));
Ok(wrap::fingerprint(&public).unwrap_or_default())
}
/// Open the vault without minting or publishing anything: `None` while
/// this Mac holds no key, the object holds no row for it, or the phone
/// has not wrapped the VMK for it yet. The WhatsApp signer opens it so,
/// for one assertion; publishing stays the importer's pass.
pub fn open_only(&self, rows: &dyn KeyRows) -> Result, VaultError> {
let Some(secret) = self.keyring.load().map_err(VaultError::Keyring)? else {
return Ok(None);
};
let public = URL_SAFE_NO_PAD.encode(wrap::public_of(&secret));
let Some((_, data)) = rows.key_row(self.device_id)? else {
return Ok(None);
};
if data.get("public_key").and_then(Value::as_str) != Some(public.as_str()) {
return Ok(None);
}
let Some(wrapped) = data.get("wrapped_vmk").and_then(Value::as_str) else {
return Ok(None);
};
Ok(Some(open_wrap(&secret, wrapped, &data)?))
}
/// Open the vault with the recovery code the person typed (R7c), and make
/// this Mac a device of the vault: the code is checked and stretched
/// here, proved to the object, the VMK's wrap opened, and the VMK wrapped
/// to this Mac's own key on its own row, so later passes open with the
/// Keychain alone. A wrong code is the object's refusal, with its tries.
pub fn open_by_code(&self, rows: &dyn KeyRows, door: &dyn RecoveryDoor, typed: &str) -> Result {
use cotton_core::vault::recovery_code as code;
let secret_text = Zeroizing::new(code::normalize(typed).map_err(|problem| VaultError::Code(problem.code()))?);
let held = door.held()?;
let entry = held.get(code::Kind::Code.as_str()).filter(|entry| entry.is_object()).ok_or(VaultError::NoCode)?;
let salt = entry.get("salt").and_then(Value::as_str).and_then(|salt| URL_SAFE_NO_PAD.decode(salt).ok()).ok_or(VaultError::NoCode)?;
let kdf = entry.get("kdf").and_then(Value::as_str).and_then(code::Kdf::parse).ok_or(VaultError::NoCode)?;
let keys = code::derive(secret_text.as_bytes(), &salt, kdf).ok_or(VaultError::CodeDoesNotOpen)?;
let answer = door.open_code(&URL_SAFE_NO_PAD.encode(keys.auth.as_ref()))?;
let version = answer.get("vmk_version").and_then(Value::as_u64).unwrap_or(0) as u32;
let wrapped = answer.get("wrapped").and_then(Value::as_str).unwrap_or_default();
let vmk = code::unwrap(&keys.wrap, code::Kind::Code, version, wrapped).ok_or(VaultError::CodeDoesNotOpen)?;
// This Mac's own row, approved: the object lets the device that just proved the code write its own wrap.
let secret = self.secret()?;
let public = wrap::public_of(&secret);
let for_this_mac = wrap::wrap(&public, vmk.as_ref()).ok_or(VaultError::CodeDoesNotOpen)?;
let id = rows.key_row(self.device_id)?.map(|(id, _)| id).unwrap_or_else(|| self.row_id());
rows.put_key_row(
&id,
&json!({
"device_id": self.device_id,
"name": self.device_name,
"public_key": URL_SAFE_NO_PAD.encode(public),
"wrapped_vmk": for_this_mac,
"vmk_version": version,
}),
)?;
Ok(OpenVault { vmk: Vmk::from_bytes(*vmk), version })
}
/// Let a waiting device in from this Mac, as Keys › Devices › Approve does
/// on a phone: open the vault with this Mac's own key, wrap the VMK for
/// the other device's published key and write the wrap on its row, at the
/// version this Mac opened. Answers the fingerprint that was approved, so
/// the person can match it against the one the device shows. A Mac that
/// does not open the vault, a device with no row, and a device already let
/// in each change nothing.
pub fn approve(&self, rows: &dyn KeyRows, other_device: &str) -> Result {
let open = self.open_only(rows)?.ok_or(VaultError::NotOpen)?;
let (id, mut data) = rows.key_row(other_device)?.ok_or(VaultError::NoSuchDevice)?;
if data.get("wrapped_vmk").and_then(Value::as_str).is_some() {
return Err(VaultError::AlreadyApproved);
}
let public_text = data.get("public_key").and_then(Value::as_str).unwrap_or_default().to_string();
let public: [u8; 32] =
URL_SAFE_NO_PAD.decode(&public_text).ok().and_then(|bytes| bytes.try_into().ok()).ok_or(VaultError::Unwrappable)?;
let wrapped = wrap::wrap(&public, open.vmk.expose()).ok_or(VaultError::Unwrappable)?;
data.insert("wrapped_vmk".into(), Value::from(wrapped));
data.insert("vmk_version".into(), Value::from(open.version));
rows.put_key_row(&id, &Value::Object(data))?;
Ok(wrap::fingerprint(&public_text).unwrap_or_default())
}
/// One pass: publish when the object holds no row for this key, then open
/// the wrap once the phone has written one.
pub fn pass(&self, rows: &dyn KeyRows) -> Result {
let secret = self.secret()?;
let public = URL_SAFE_NO_PAD.encode(wrap::public_of(&secret));
let fingerprint = wrap::fingerprint(&public).unwrap_or_default();
let held = rows.key_row(self.device_id)?;
let data = match held {
Some((_, data)) if data.get("public_key").and_then(Value::as_str) == Some(public.as_str()) => data,
// No row, or a row for a key this Mac no longer holds (the
// Keychain item was lost and minted again): publish this key, with
// no wrap, so the phone is asked again.
other => {
let id = other.map(|(id, _)| id).unwrap_or_else(|| self.row_id());
rows.put_key_row(
&id,
&json!({
"device_id": self.device_id,
"name": self.device_name,
"public_key": public,
"wrapped_vmk": Value::Null,
"vmk_version": 0,
}),
)?;
return Ok(Pass::Waiting { fingerprint });
}
};
let Some(wrapped) = data.get("wrapped_vmk").and_then(Value::as_str) else {
return Ok(Pass::Waiting { fingerprint });
};
Ok(Pass::Open(open_wrap(&secret, wrapped, &data)?))
}
}
/// The VMK a row's wrap holds for this Mac's private half, at the row's version.
fn open_wrap(secret: &[u8; 32], wrapped: &str, data: &Map) -> Result {
let version = data
.get("vmk_version")
.and_then(|n| n.as_u64().or_else(|| n.as_f64().map(|n| n as u64)))
.unwrap_or(0) as u32;
let bytes = Zeroizing::new(wrap::unwrap(secret, wrapped).ok_or(VaultError::WrapDoesNotOpen)?);
let bytes: [u8; 32] = bytes.as_slice().try_into().map_err(|_| VaultError::WrapDoesNotOpen)?;
Ok(OpenVault { vmk: Vmk::from_bytes(bytes), version })
}
#[cfg(test)]
#[path = "vault_tests.rs"]
mod tests;