Skip to main content

capsule_library/
account.rs

1//! The library's record of a **hardware-bound device signing key**: the half of the account the
2//! library, not `capsule-core`, keeps on disk.
3//!
4//! A device whose signing key's classical half lives in a secure element (Secure Enclave,
5//! StrongBox, TPM) cannot rebuild that key from the account file: the account file holds the
6//! software DSK, and the element's P-256 key is non-exportable by contract. Reopening such a
7//! library needs three things the account file does not carry, and this record holds them in
8//! `{root}/.library/device_signer.cbor`:
9//!
10//! - the element's **alias** for the key, so reopening asks the element for the same key;
11//! - the **ML-DSA-65 seed** of the post-quantum half, sealed under the account master key with a
12//!   domain prefix, so the same hybrid key is rebuilt;
13//! - the **published hybrid verifying key**, so a reopen can prove the element still holds the
14//!   key this device published rather than one minted under the same alias since.
15//!
16//! The record's presence is the binding. A library without one signs with the account's software
17//! DSK, which is every library created before this record existed, and an element offered on
18//! reopen is ignored for it. A library with one refuses to open without its element: falling
19//! back to the software DSK would change the key the device directory publishes (SSoT:
20//! [Cryptography — Keys § Device Keys]).
21//!
22//! [Cryptography — Keys § Device Keys]: https://docs/design/cryptography/keys/#device-keys
23
24use std::fs;
25use std::path::{Path, PathBuf};
26use std::sync::Arc;
27
28use capsule_core::cbor;
29use capsule_core::crypto::CryptoError;
30use capsule_core::crypto::keys::{
31    HardwareSigner, HardwareSignerError, HybridVerifyingKey, MasterKey, P256HybridSigningKey,
32    Signer,
33};
34use serde::{Deserialize, Serialize};
35
36use crate::lifecycle::LifecycleError;
37
38type Result<T> = std::result::Result<T, LifecycleError>;
39
40/// The record's file under `{root}/.library/`.
41const DEVICE_SIGNER_FILE: &str = "device_signer.cbor";
42
43/// The only record version this build reads or writes.
44const DEVICE_SIGNER_VERSION: u32 = 1;
45
46/// Prefix sealed in front of the ML-DSA seed, so no other 32-byte value sealed under the same
47/// master key (the account file's sealed DEK seed) opens as this one.
48const SEALED_ML_SEED_DOMAIN: &[u8] = b"capsule-device-signer-ml-seed/v1\0";
49
50/// A request to bind this device's **signing key** to a secure element over ECDSA-P256: the
51/// element itself plus the alias its key is held under. The signer counterpart of
52/// [`HardwareDekBinding`](crate::lifecycle::HardwareDekBinding).
53///
54/// The alias is used only when the binding is **created**; on reopen the alias recorded in the
55/// library wins, so renaming it here can never re-bind an existing library to another key.
56#[derive(Clone)]
57pub struct HardwareSignerBinding {
58    /// The secure element producing the P-256 signatures.
59    pub element: Arc<dyn HardwareSigner>,
60    /// The element's alias for this device's signing key.
61    pub key_alias: String,
62}
63
64impl std::fmt::Debug for HardwareSignerBinding {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        f.debug_struct("HardwareSignerBinding")
67            .field("key_alias", &self.key_alias)
68            .finish_non_exhaustive()
69    }
70}
71
72/// The persisted binding of a hardware-held P-256 device signing key.
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74pub(crate) struct DeviceSignerRecord {
75    /// [`DEVICE_SIGNER_VERSION`]; anything else is refused rather than guessed at.
76    version: u32,
77    /// The element's alias for the P-256 key.
78    key_alias: String,
79    /// The ML-DSA-65 seed, domain-prefixed and sealed under the account master key.
80    #[serde(with = "serde_bytes")]
81    sealed_ml_seed: Vec<u8>,
82    /// The hybrid verifying key this device published when the binding was made.
83    dsk_public: HybridVerifyingKey,
84}
85
86impl DeviceSignerRecord {
87    /// Where a library at `root` keeps the record.
88    pub(crate) fn path(root: &Path) -> PathBuf {
89        root.join(".library").join(DEVICE_SIGNER_FILE)
90    }
91
92    /// Enroll `binding`'s key and compose it with the ML-DSA half from `ml_seed`, returning the
93    /// signer and the record that rebuilds it under `master`.
94    ///
95    /// Refused with [`CryptoError::Key`] when the element will not enroll; nothing falls back
96    /// to software here.
97    #[tracing::instrument(skip_all, fields(key_alias = %binding.key_alias))]
98    pub(crate) fn enroll(
99        binding: HardwareSignerBinding,
100        ml_seed: &[u8; 32],
101        master: &MasterKey,
102    ) -> Result<(P256HybridSigningKey, Self)> {
103        let signer =
104            P256HybridSigningKey::enroll(binding.element, binding.key_alias.clone(), ml_seed)
105                .map_err(|e| {
106                    // The element's own reason is the only thing that says whether a retry can
107                    // help, so it is logged before the crypto error flattens it.
108                    tracing::error!(error = %e, "device signer: hardware P-256 enrollment failed");
109                    CryptoError::Key("hardware device signing key enrollment failed")
110                })?;
111        let mut plaintext = Vec::with_capacity(SEALED_ML_SEED_DOMAIN.len() + ml_seed.len());
112        plaintext.extend_from_slice(SEALED_ML_SEED_DOMAIN);
113        plaintext.extend_from_slice(ml_seed);
114        let record = Self {
115            version: DEVICE_SIGNER_VERSION,
116            key_alias: binding.key_alias,
117            sealed_ml_seed: master.seal(&plaintext),
118            dsk_public: signer.verifying_key(),
119        };
120        tracing::info!("device signer: hardware P-256 signing key enrolled");
121        Ok((signer, record))
122    }
123
124    /// The element's alias the key is recorded under.
125    pub(crate) fn key_alias(&self) -> &str {
126        &self.key_alias
127    }
128
129    /// The record of the library at `root`, or `None` when it has none (a software-signed
130    /// library). A record that is present but unreadable, undecodable or of another version is
131    /// an error: treating it as absent would quietly move the library onto its software key.
132    pub(crate) fn load(root: &Path) -> Result<Option<Self>> {
133        let path = Self::path(root);
134        let bytes = match fs::read(&path) {
135            Ok(bytes) => bytes,
136            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
137            Err(e) => {
138                tracing::warn!(error = %e, "device signer: record unreadable");
139                return Err(LifecycleError::Io(format!("device signer record: {e}")));
140            }
141        };
142        let record: Self = cbor::from_slice(&bytes).map_err(|e| {
143            tracing::warn!(error = %e, "device signer: record does not decode");
144            LifecycleError::Cbor(format!("device signer record: {e}"))
145        })?;
146        if record.version != DEVICE_SIGNER_VERSION {
147            tracing::warn!(
148                version = record.version,
149                "device signer: record of an unknown version"
150            );
151            return Err(LifecycleError::Cbor(format!(
152                "device signer record version {} is not {DEVICE_SIGNER_VERSION}",
153                record.version
154            )));
155        }
156        Ok(Some(record))
157    }
158
159    /// Write the record for the library at `root`, temp-then-rename so a crash leaves either
160    /// no record or a whole one.
161    pub(crate) fn persist(&self, root: &Path) -> Result<()> {
162        let path = Self::path(root);
163        let bytes =
164            cbor::to_canonical_vec(self).map_err(|e| LifecycleError::Cbor(e.to_string()))?;
165        let tmp = crate::utils::paths::tmp_path(&path);
166        fs::write(&tmp, &bytes).map_err(|e| LifecycleError::Io(e.to_string()))?;
167        fs::rename(&tmp, &path).map_err(|e| LifecycleError::Io(e.to_string()))?;
168        tracing::debug!(key_alias = %self.key_alias, "device signer: record persisted");
169        Ok(())
170    }
171
172    /// Remove a record left by a creation that stopped before its account file was written. Such
173    /// a record is sealed under a master key that no account holds, so it can never open.
174    pub(crate) fn remove_stale(root: &Path) -> Result<()> {
175        match fs::remove_file(Self::path(root)) {
176            Ok(()) => {
177                tracing::warn!("device signer: removed a record left by an interrupted creation");
178                Ok(())
179            }
180            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
181            Err(e) => Err(LifecycleError::Io(format!("device signer record: {e}"))),
182        }
183    }
184
185    /// Rebuild the signer this record describes: open the ML-DSA seed under `master` and ask
186    /// `element` for the key under the recorded alias.
187    ///
188    /// The element is only asked for the key, never to make one: a key the element no longer
189    /// holds is refused, not replaced. The rebuilt key must equal the one this device
190    /// published, or the open is refused rather than signing under a key no peer trusts.
191    #[tracing::instrument(skip_all, fields(key_alias = %self.key_alias))]
192    pub(crate) fn reattach(
193        &self,
194        master: &MasterKey,
195        element: Arc<dyn HardwareSigner>,
196    ) -> Result<P256HybridSigningKey> {
197        let plaintext = master.open(&self.sealed_ml_seed)?;
198        let ml_seed: [u8; 32] = plaintext
199            .strip_prefix(SEALED_ML_SEED_DOMAIN)
200            .and_then(|seed| seed.try_into().ok())
201            .ok_or(CryptoError::Malformed(
202                "sealed device signer seed lacks its domain prefix or length",
203            ))?;
204        let signer = P256HybridSigningKey::enroll(
205            Arc::new(ExistingKeyOnly(element)),
206            self.key_alias.clone(),
207            &ml_seed,
208        )
209        .map_err(|e| {
210            tracing::error!(error = %e, "device signer: the element did not return the recorded key");
211            CryptoError::Key("hardware device signing key re-binding failed")
212        })?;
213        if signer.verifying_key() != self.dsk_public {
214            tracing::error!(
215                "device signer: the element's key under the recorded alias is not the one this \
216                 device published"
217            );
218            return Err(CryptoError::Key(
219                "the secure element's key is not this device's published signing key",
220            )
221            .into());
222        }
223        tracing::debug!("device signer: hardware P-256 signing key re-attached");
224        Ok(signer)
225    }
226}
227
228/// Presents an element whose `enroll` only looks the key up, so re-attaching a recorded key can
229/// never mint a fresh one under the same alias.
230struct ExistingKeyOnly(Arc<dyn HardwareSigner>);
231
232impl HardwareSigner for ExistingKeyOnly {
233    fn enroll(&self, key_alias: String) -> std::result::Result<Vec<u8>, HardwareSignerError> {
234        self.0.classical_public_key(key_alias)
235    }
236
237    fn classical_public_key(
238        &self,
239        key_alias: String,
240    ) -> std::result::Result<Vec<u8>, HardwareSignerError> {
241        self.0.classical_public_key(key_alias)
242    }
243
244    fn sign_classical(
245        &self,
246        key_alias: String,
247        msg: Vec<u8>,
248    ) -> std::result::Result<Vec<u8>, HardwareSignerError> {
249        self.0.sign_classical(key_alias, msg)
250    }
251
252    fn assert_non_exportable(
253        &self,
254        key_alias: String,
255    ) -> std::result::Result<(), HardwareSignerError> {
256        self.0.assert_non_exportable(key_alias)
257    }
258}
259
260#[cfg(test)]
261pub(crate) mod tests;