Skip to main content

capsule_core/crypto/keys/
keystore.rs

1//! The device keystore: an [`Account`] (master key + user identity key + this device's
2//! keys) and its encrypted-at-rest form [`AccountFile`].
3//!
4//! The master key is wrapped under a passphrase via [`pwkdf`], and the device identity private
5//! keys are sealed under the master key (the design's "master key wraps device identity private
6//! keys"). SSoT: [Cryptography — Keys].
7//!
8//! ## The DEK's classical half
9//!
10//! The design binds the **classical half** of each device key to a per-platform secure element.
11//! For the Device Encryption Key that means ECDH-P256 inside a Secure Enclave / StrongBox / TPM,
12//! composed with a software ML-KEM-768 half — the [`P256HybridDek`].
13//! [`DeviceDek`] is the seam that puts it in a *real* account rather than only in the FFI smoke:
14//! an account is created either [software-DEK](Account::create) (the fallback for hosts with no
15//! element — explicitly retained by the design's "the software composition is what integrates
16//! end-to-end today") or [hardware-DEK](Account::create_with_hardware_dek).
17//!
18//! The [`AccountFile`] records which, in [`DekBinding`]. Only the **software-sealed** half is
19//! ever written: an X-Wing seed for the software DEK, the ML-KEM seed for the hardware one. The
20//! hardware classical half is non-exportable by contract, so a hardware-bound account cannot be
21//! unlocked without the element that holds it — [`AccountFile::unlock`] says so rather than
22//! silently degrading to software, and [`AccountFile::unlock_with_element`] supplies it. That
23//! asymmetry *is* the binding; without it the "hardware-bound" claim would be decorative.
24//!
25//! [Cryptography — Keys]: https://docs/design/cryptography/keys/
26
27use std::sync::Arc;
28
29use serde::{Deserialize, Serialize};
30use uuid::Uuid;
31
32use super::hardware::{HardwareKeyAgreement, HardwareSignerError};
33use super::hybrid_sig::HybridSigningKey;
34use super::kem::DekKeypair;
35use super::kem_p256::P256HybridDek;
36use super::master::MasterKey;
37use crate::ambient::IdSource;
38use crate::crypto::primitives::{Argon2Params, DeviceTier};
39use crate::crypto::{CryptoError, pwkdf};
40
41/// Prefix sealed in front of the user IK seeds by [`Account::sealed_identity`], so no other
42/// 64-byte seed sealed under the same master key (an `AccountFile`'s DSK) opens as an identity.
43const SEALED_IDENTITY_DOMAIN: &[u8] = b"capsule-sealed-user-ik/v1\0";
44
45/// This device's Device Encryption Key, in whichever of the two compositions the design allows.
46///
47/// Both expose the same two operations — publish a public encapsulation key, decapsulate a
48/// ciphertext sealed to it — so every caller is agnostic to where the classical half lives. The
49/// two byte formats are length-disjoint — X-Wing's [`DekKeypair`] and the P-256 hybrid's
50/// [`P256HybridDek`] publish and accept different lengths — so a ciphertext for one is rejected
51/// outright by the other rather than silently recovering a wrong secret.
52pub enum DeviceDek {
53    /// **Software fallback.** X-Wing (X25519 + ML-KEM-768), both halves in software. The
54    /// composition every host can run, including those with no secure element and the TPM-1.2 /
55    /// no-TPM tail the design excludes from hardware binding by name.
56    Software(DekKeypair),
57    /// **Hardware-bound.** P-256 ECDH inside the secure element + a software-sealed ML-KEM-768
58    /// half ([`P256HybridDek`]). The private P-256 scalar never leaves hardware, so this
59    /// variant cannot be reconstructed from the account file alone.
60    Hardware(P256HybridDek),
61}
62
63impl DeviceDek {
64    /// The published public encapsulation-key bytes a sender wraps to. `pk_M ‖ pk_X` (1216 bytes)
65    /// for the software X-Wing DEK; `ek_M ‖ pk_P` (1249 bytes) for the hardware P-256 hybrid.
66    pub fn public_bytes(&self) -> Vec<u8> {
67        match self {
68            Self::Software(dek) => dek.public_bytes(),
69            Self::Hardware(dek) => dek.public_bytes(),
70        }
71    }
72
73    /// Recover the 32-byte shared secret from a ciphertext sealed to [`public_bytes`](Self::public_bytes).
74    /// For [`Hardware`](Self::Hardware) the classical half of this call happens **inside the
75    /// element**, so it can fail on a cancelled biometric or a missing key.
76    pub fn decapsulate(&self, ciphertext: &[u8]) -> Result<[u8; 32], CryptoError> {
77        match self {
78            Self::Software(dek) => dek.decapsulate(ciphertext),
79            Self::Hardware(dek) => dek.decapsulate(ciphertext),
80        }
81    }
82
83    /// Whether the classical half of this DEK lives in a secure element.
84    pub fn is_hardware_bound(&self) -> bool {
85        matches!(self, Self::Hardware(_))
86    }
87
88    /// How this DEK is recorded in the [`AccountFile`].
89    pub fn binding(&self) -> DekBinding {
90        match self {
91            Self::Software(_) => DekBinding::Software,
92            Self::Hardware(dek) => DekBinding::Hardware {
93                key_alias: dek.key_alias().to_owned(),
94            },
95        }
96    }
97
98    /// The 32-byte software seed sealed under the master key: the X-Wing seed for
99    /// [`Software`](Self::Software), the ML-KEM seed for [`Hardware`](Self::Hardware).
100    fn sealed_seed(&self) -> [u8; 32] {
101        match self {
102            Self::Software(dek) => dek.to_seed_bytes(),
103            Self::Hardware(dek) => dek.to_ml_seed_bytes(),
104        }
105    }
106}
107
108impl std::fmt::Debug for DeviceDek {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        match self {
111            Self::Software(_) => f.write_str("DeviceDek::Software(****)"),
112            Self::Hardware(dek) => {
113                write!(f, "DeviceDek::Hardware(alias={}, ****)", dek.key_alias())
114            }
115        }
116    }
117}
118
119/// Where the DEK's classical half lives, as recorded in the [`AccountFile`].
120///
121/// Persisted in the clear: it is a routing decision plus a lookup handle, never key material. It
122/// is what lets `open` know an element must be attached *before* it tries — the alternative
123/// (guess, fail to decapsulate later) turns a clear "attach the element" into an opaque
124/// authentication error deep in a data-plane path.
125#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
126pub enum DekBinding {
127    /// Both halves in software (X-Wing). The default, and what every account file
128    /// that omits the field means.
129    #[default]
130    Software,
131    /// The classical half is a hardware P-256 key under `key_alias`.
132    Hardware {
133        /// The secure element's alias for this device's P-256 key-agreement key.
134        key_alias: String,
135    },
136}
137
138/// This device's key material: a stable id, a hybrid Device Signing Key (DSK), and a
139/// Device Encryption Key (DEK).
140pub struct DeviceKeys {
141    /// Stable per-device identifier (UUIDv7), published in the device directory.
142    pub device_id: Uuid,
143    /// Hybrid device signing key — signs asset manifests (`device_sig`).
144    pub dsk: HybridSigningKey,
145    /// Device encryption key (KEM) — receives key wraps. Software or hardware-bound; see
146    /// [`DeviceDek`].
147    pub dek: DeviceDek,
148}
149
150/// A fully unlocked account in memory.
151pub struct Account {
152    /// The account owner's user id (UUIDv7).
153    pub user_id: Uuid,
154    /// The backed-up root key.
155    pub master: MasterKey,
156    /// The user identity key (root of signing trust). Signs the device directory.
157    pub user_ik: HybridSigningKey,
158    /// This device's keys.
159    pub device: DeviceKeys,
160}
161
162/// The encrypted-at-rest account: the master key wrapped under a passphrase, and the
163/// device/identity private keys sealed under the master key. Safe to persist to disk.
164#[derive(Debug, Clone, Serialize, Deserialize)]
165pub struct AccountFile {
166    /// Account owner id.
167    pub user_id: Uuid,
168    /// This device's id.
169    pub device_id: Uuid,
170    /// Master key wrapped under the passphrase (Argon2id + AES-256-GCM).
171    pub wrapped_master: pwkdf::WrappedSecret,
172    /// User IK seeds (64 bytes) sealed under the master key.
173    #[serde(with = "serde_bytes")]
174    pub sealed_ik: Vec<u8>,
175    /// Device DSK seeds (64 bytes) sealed under the master key.
176    #[serde(with = "serde_bytes")]
177    pub sealed_dsk: Vec<u8>,
178    /// The DEK's **software-sealed** 32-byte seed under the master key: the X-Wing seed for a
179    /// software DEK, the ML-KEM-768 seed for a hardware-bound one. A hardware classical half is
180    /// never here — it is non-exportable by contract.
181    #[serde(with = "serde_bytes")]
182    pub sealed_dek: Vec<u8>,
183    /// Where the DEK's classical half lives. Absent in account files that predate
184    /// hardware DEKs, which are software-DEK by construction — hence the `default`, which is
185    /// what keeps every existing library on disk openable.
186    #[serde(default)]
187    pub dek_binding: DekBinding,
188}
189
190impl Account {
191    /// Create a brand-new account with a fresh master key, user IK, and first device, using the
192    /// **software** DEK composition. The fallback the design keeps for hosts with no secure
193    /// element; [`create_with_hardware_dek`](Self::create_with_hardware_dek) is the bound form.
194    ///
195    /// The user and device ids are UUIDv7s minted from `ids`.
196    pub fn create(ids: IdSource<'_>) -> Self {
197        Self::generate(ids, DeviceDek::Software(DekKeypair::generate()))
198    }
199
200    /// Create a brand-new account whose **DEK's classical half is generated inside `element`**
201    /// under `key_alias` and never leaves it. The ML-KEM-768
202    /// half is drawn fresh here and sealed under the master key like any software seed.
203    ///
204    /// Fails only if the element refuses enrollment (unavailable, biometric cancelled, bad key) —
205    /// deliberately *not* silently falling back to software, because a caller that asked for
206    /// hardware binding and got software would believe a guarantee it does not have. A caller
207    /// that wants best-effort binding probes the element first and calls
208    /// [`create`](Self::create) itself.
209    pub fn create_with_hardware_dek(
210        ids: IdSource<'_>,
211        element: Arc<dyn HardwareKeyAgreement>,
212        key_alias: String,
213    ) -> Result<Self, HardwareSignerError> {
214        let ml_seed = crate::crypto::rng::random_array::<32>();
215        let dek = P256HybridDek::enroll(element, key_alias, &ml_seed)?;
216        Ok(Self::generate(ids, DeviceDek::Hardware(dek)))
217    }
218
219    fn generate(ids: IdSource<'_>, dek: DeviceDek) -> Self {
220        Self::from_parts(
221            ids,
222            ids.uuid_v7(),
223            MasterKey::generate(),
224            HybridSigningKey::generate(),
225            dek,
226        )
227    }
228
229    /// Assemble an account from **existing** account-level material on a **new** device: the
230    /// account's `user_id`, its `master` key (e.g. recovered from the server escrow with
231    /// [`recover_master_key`](crate::backup::recover_master_key)), and its user identity key
232    /// (e.g. opened from a [sealed identity](Self::sealed_identity) with
233    /// [`open_sealed_identity`](Self::open_sealed_identity)).
234    ///
235    /// Everything per-device is fresh: a new `device_id` and DSK, plus the caller's `dek`. A
236    /// recovered device is a new device — it never resumes a lost device's keys, whose
237    /// classical halves may have been hardware-bound and are gone with it. The `device_id` is a
238    /// UUIDv7 minted from `ids`.
239    pub fn from_parts(
240        ids: IdSource<'_>,
241        user_id: Uuid,
242        master: MasterKey,
243        user_ik: HybridSigningKey,
244        dek: DeviceDek,
245    ) -> Self {
246        Self {
247            user_id,
248            master,
249            user_ik,
250            device: DeviceKeys {
251                device_id: ids.uuid_v7(),
252                dsk: HybridSigningKey::generate(),
253                dek,
254            },
255        }
256    }
257
258    /// The user identity key's private seeds sealed under the master key, in a
259    /// domain-separated form a client may store off-device (e.g. beside the master-key escrow).
260    ///
261    /// The user IK is drawn at random at account creation, not derived from the master key —
262    /// rotating the master key must not rotate the identity, and the server pins the identity
263    /// public key on the first directory publish. So a device that recovers only the
264    /// master key would otherwise have to mint a *new* IK, which the server refuses for an
265    /// account it has already anchored. This blob is a wrap *reachable from* the master key, not
266    /// a second root: whoever recovers the master key opens it, nobody else can.
267    pub fn sealed_identity(&self) -> Vec<u8> {
268        let seed = self.user_ik.to_seed_bytes();
269        let mut plaintext = Vec::with_capacity(SEALED_IDENTITY_DOMAIN.len() + seed.len());
270        plaintext.extend_from_slice(SEALED_IDENTITY_DOMAIN);
271        plaintext.extend_from_slice(&seed);
272        self.master.seal(&plaintext)
273    }
274
275    /// Open a [`sealed_identity`](Self::sealed_identity) blob under `master`.
276    ///
277    /// Returns [`CryptoError::Auth`] when `master` is not the key that sealed it (or the blob was
278    /// tampered with), and [`CryptoError::Malformed`] when it opens but is not a sealed user IK —
279    /// e.g. an `AccountFile`'s sealed *device* key, which the domain prefix keeps from being
280    /// accepted as an identity.
281    pub fn open_sealed_identity(
282        master: &MasterKey,
283        sealed: &[u8],
284    ) -> Result<HybridSigningKey, CryptoError> {
285        let plaintext = master.open(sealed)?;
286        let seed = plaintext
287            .strip_prefix(SEALED_IDENTITY_DOMAIN)
288            .ok_or(CryptoError::Malformed(
289                "sealed identity lacks its domain prefix",
290            ))?;
291        Ok(HybridSigningKey::from_seed64(&seed64(seed.to_vec())?))
292    }
293
294    /// Encrypt the account for persistence: master under `passphrase` (cost = `tier`),
295    /// identity/device private keys under the master key.
296    pub fn to_file(&self, passphrase: &[u8], tier: DeviceTier) -> Result<AccountFile, CryptoError> {
297        self.to_file_with(passphrase, tier.params())
298    }
299
300    /// As [`to_file`](Self::to_file) but with explicit Argon2id parameters (used by tests
301    /// to avoid the multi-hundred-MiB production cost).
302    pub fn to_file_with(
303        &self,
304        passphrase: &[u8],
305        params: Argon2Params,
306    ) -> Result<AccountFile, CryptoError> {
307        Ok(AccountFile {
308            user_id: self.user_id,
309            device_id: self.device.device_id,
310            wrapped_master: pwkdf::wrap_with(self.master.as_bytes(), passphrase, params)?,
311            sealed_ik: self.master.seal(&self.user_ik.to_seed_bytes()),
312            sealed_dsk: self.master.seal(&self.device.dsk.to_seed_bytes()),
313            sealed_dek: self.master.seal(&self.device.dek.sealed_seed()),
314            dek_binding: self.device.dek.binding(),
315        })
316    }
317}
318
319fn seed64(bytes: Vec<u8>) -> Result<[u8; 64], CryptoError> {
320    bytes
321        .as_slice()
322        .try_into()
323        .map_err(|_| CryptoError::Malformed("sealed key seed wrong length"))
324}
325
326fn seed32(bytes: Vec<u8>) -> Result<[u8; 32], CryptoError> {
327    bytes
328        .as_slice()
329        .try_into()
330        .map_err(|_| CryptoError::Malformed("sealed key seed wrong length"))
331}
332
333impl AccountFile {
334    /// Decrypt the account with `passphrase`. Returns [`CryptoError::Auth`] on a wrong
335    /// passphrase (master unwrap fails) or tampering.
336    ///
337    /// A **hardware-bound** account ([`DekBinding::Hardware`]) cannot be unlocked this way — its
338    /// DEK's classical half lives in an element this call was given no handle to — and returns
339    /// [`CryptoError::Key`]. Use [`unlock_with_element`](Self::unlock_with_element).
340    pub fn unlock(&self, passphrase: &[u8]) -> Result<Account, CryptoError> {
341        self.unlock_with_element(passphrase, None)
342    }
343
344    /// As [`unlock`](Self::unlock), re-binding a [`DekBinding::Hardware`] account's DEK to
345    /// `element` (the same secure element that enrolled it, e.g. a real Secure Enclave or a test
346    /// mock). The alias comes from the file, so the caller supplies only the element.
347    ///
348    /// Passing an element for a software-DEK account is harmless and ignored: the binding
349    /// recorded at creation decides, never the caller, so an attacker who can hand us an element
350    /// cannot thereby move a software account onto a key they control.
351    pub fn unlock_with_element(
352        &self,
353        passphrase: &[u8],
354        element: Option<Arc<dyn HardwareKeyAgreement>>,
355    ) -> Result<Account, CryptoError> {
356        let master_bytes: [u8; 32] = pwkdf::unwrap(&self.wrapped_master, passphrase)?
357            .as_slice()
358            .try_into()
359            .map_err(|_| CryptoError::Malformed("master key wrong length"))?;
360        let master = MasterKey::from_bytes(master_bytes);
361
362        let user_ik = HybridSigningKey::from_seed64(&seed64(master.open(&self.sealed_ik)?)?);
363        let dsk = HybridSigningKey::from_seed64(&seed64(master.open(&self.sealed_dsk)?)?);
364        let dek_seed = seed32(master.open(&self.sealed_dek)?)?;
365        let dek = match &self.dek_binding {
366            DekBinding::Software => DeviceDek::Software(DekKeypair::from_seed(&dek_seed)),
367            DekBinding::Hardware { key_alias } => {
368                let element = element.ok_or(CryptoError::Key(
369                    "this account's DEK is hardware-bound: a HardwareKeyAgreement element is \
370                     required to unlock it",
371                ))?;
372                tracing::debug!(
373                    device = %self.device_id,
374                    key_alias = %key_alias,
375                    "keystore unlock: re-binding the DEK's classical half to the secure element"
376                );
377                DeviceDek::Hardware(
378                    P256HybridDek::enroll(element, key_alias.clone(), &dek_seed)
379                        .map_err(|_| CryptoError::Key("hardware DEK re-binding failed"))?,
380                )
381            }
382        };
383
384        Ok(Account {
385            user_id: self.user_id,
386            master,
387            user_ik,
388            device: DeviceKeys {
389                device_id: self.device_id,
390                dsk,
391                dek,
392            },
393        })
394    }
395}
396
397#[cfg(test)]
398mod tests;