dig_keystore/hardware/backend.rs
1//! [`HardwareBoundBackend`] — a [`KeychainBackend`] decorator that binds stored
2//! blobs to the host's hardware trusted component.
3//!
4//! # A tier above, not a replacement
5//!
6//! This wraps any existing backend (file, OS credential store, memory). What it
7//! stores is the *already sealed* keystore blob inside a hardware-wrapped
8//! envelope, so the AES-256-GCM + Argon2id passphrase envelope stays the floor
9//! on every path — a degraded host writes the same bytes it always wrote, never
10//! a bare secret.
11//!
12//! # The tier is decided once, by use
13//!
14//! [`HardwareBoundBackend::new`] probes the provider **and then self-tests it**
15//! (wrap a random key, unwrap it, require the round-trip) before it will report
16//! [`ProtectionTier::Hardware`]. A probe is a claim; the self-test is what makes
17//! the claim refutable. Resolving at construction also means "is this keystore
18//! hardware-bound?" is a settled fact rather than a failure that surfaces
19//! mid-`unlock`.
20
21use std::sync::Arc;
22
23use super::envelope::{self, Envelope};
24use super::provider::{ContentKey, HardwareProvider};
25use super::tier::{DegradeReason, HardwareKind, HardwarePolicy, HardwareProbe, ProtectionTier};
26use crate::backend::{BackendKey, KeychainBackend};
27use crate::error::{KeystoreError, Result};
28
29/// A [`KeychainBackend`] that hardware-binds every blob it stores, degrading to
30/// the underlying software envelope when the host has no usable hardware.
31///
32/// # Example
33///
34/// ```no_run
35/// use std::sync::Arc;
36/// use dig_keystore::backend::{BackendKey, FileBackend, KeychainBackend};
37/// use dig_keystore::hardware::{HardwareBoundBackend, HardwarePolicy};
38///
39/// let inner = FileBackend::new("/var/lib/dig/keys");
40/// // No provider available in this build: opens, and says so honestly.
41/// let backend = HardwareBoundBackend::new(inner, None, HardwarePolicy::Optional)?;
42///
43/// // What the HOST can do — the tier a new write would get.
44/// println!("host: {}", backend.tier());
45///
46/// // What protects THIS key — the only answer fit to show a user, because a
47/// // capable host can still hold a keystore that was never wrapped.
48/// let key = BackendKey::new("identity");
49/// let tier = backend.blob_tier(&key)?;
50/// if tier.is_hardware_bound() {
51/// println!("this key is {tier}");
52/// } else {
53/// // Never claim protection this key does not have.
54/// println!("this key is {tier}");
55/// }
56/// # Ok::<(), dig_keystore::KeystoreError>(())
57/// ```
58pub struct HardwareBoundBackend {
59 /// The storage this decorates.
60 inner: Arc<dyn KeychainBackend>,
61 /// The self-tested provider — present only when [`tier`](Self::tier) is
62 /// [`ProtectionTier::Hardware`], so the two can never disagree.
63 provider: Option<Arc<dyn HardwareProvider>>,
64 /// The truthful, settled protection tier.
65 tier: ProtectionTier,
66}
67
68impl HardwareBoundBackend {
69 /// Decorate `inner`, resolving the protection tier once.
70 ///
71 /// Pass `provider = None` to store through `inner` unchanged while reporting
72 /// [`DegradeReason::NotRequested`].
73 ///
74 /// # Errors
75 ///
76 /// Fails closed rather than silently degrading, per `policy`:
77 /// - [`HardwarePolicy::Required`] — any outcome short of self-tested hardware
78 /// is [`KeystoreError::HardwareRequired`].
79 /// - [`HardwarePolicy::Preferred`] (default) — a *confident* absence degrades,
80 /// but an [`Indeterminate`](HardwareProbe::Indeterminate) probe is
81 /// [`KeystoreError::HardwareProbeIndeterminate`]: "I could not determine
82 /// whether this host has hardware" must not be downgraded into "it has
83 /// none", which would quietly strip protection from a machine that has it.
84 /// - [`HardwarePolicy::Optional`] — always opens, always reports the reason.
85 pub fn new<B: KeychainBackend>(
86 inner: B,
87 provider: Option<Arc<dyn HardwareProvider>>,
88 policy: HardwarePolicy,
89 ) -> Result<Self> {
90 Self::with_inner(Arc::new(inner), provider, policy)
91 }
92
93 /// As [`new`](Self::new), for an already shared backend.
94 pub fn with_inner(
95 inner: Arc<dyn KeychainBackend>,
96 provider: Option<Arc<dyn HardwareProvider>>,
97 policy: HardwarePolicy,
98 ) -> Result<Self> {
99 let tier = resolve_tier(provider.as_deref(), policy)?;
100 // Hold the provider only where the tier actually claims hardware, so a
101 // degraded backend cannot accidentally reach for it later.
102 let provider = if tier.is_hardware_bound() {
103 provider
104 } else {
105 None
106 };
107 Ok(Self {
108 inner,
109 provider,
110 tier,
111 })
112 }
113
114 /// What this **host** is bound to — the tier every *newly written* blob gets.
115 ///
116 /// This is a statement about the machine, not about any particular stored
117 /// key. On a hardware-capable host it reports `Hardware` even if a given
118 /// keystore predates hardware binding and is still a bare §3 blob, because a
119 /// capable host does not retroactively protect bytes already at rest.
120 ///
121 /// **Before telling a user that a specific key is hardware-protected, ask
122 /// [`blob_tier`](Self::blob_tier) instead.** Rendering "protected by your
123 /// TPM" from this method would claim copy-resistance that an unwrapped
124 /// legacy blob does not have.
125 pub fn tier(&self) -> &ProtectionTier {
126 &self.tier
127 }
128
129 /// What protects **the key material stored at `key`**, read from the blob
130 /// itself.
131 ///
132 /// This is the question a UI actually has, and it is not the same as
133 /// [`tier`](Self::tier): a hardware-capable host can hold a keystore written
134 /// before hardware binding existed, which is protected by the passphrase
135 /// envelope alone and *does* open on another machine. Answering from the
136 /// stored bytes is what keeps that distinction honest.
137 ///
138 /// The tier reported is the blob's own, independent of this host: a blob
139 /// sealed by an Apple Secure Enclave reads as `Hardware(MacSecureEnclave)`
140 /// even on Windows. Whether *this* host can open it is a separate question,
141 /// answered by [`read`](KeychainBackend::read).
142 ///
143 /// # Errors
144 ///
145 /// - The inner backend's error if `key` cannot be read (e.g. `NotFound`).
146 /// - [`KeystoreError::MalformedEnvelope`] if the blob claims to be an
147 /// envelope but is structurally invalid.
148 /// - [`KeystoreError::UnknownHardwareClass`] if it was sealed by hardware
149 /// this build cannot name.
150 ///
151 /// Both error cases **fail closed**: a wrapped blob is never reported as
152 /// software-protected just because this build cannot fully classify it.
153 /// Guessing in either direction is what this method exists to avoid.
154 pub fn blob_tier(&self, key: &BackendKey) -> Result<ProtectionTier> {
155 let bytes = self.inner.read(key)?;
156
157 // Not an envelope — the passphrase envelope is all that protects it,
158 // whatever this host is capable of.
159 if !envelope::is_envelope(&bytes) {
160 return Ok(ProtectionTier::Software(DegradeReason::BlobNotWrapped));
161 }
162
163 let env = envelope::decode(&bytes)?;
164 match env.hardware_kind() {
165 Some(kind) => Ok(ProtectionTier::Hardware(kind)),
166 None => Err(KeystoreError::UnknownHardwareClass {
167 wire_id: env.hardware_wire_id,
168 }),
169 }
170 }
171
172 /// The underlying storage, for callers that need it directly.
173 pub fn inner(&self) -> &Arc<dyn KeychainBackend> {
174 &self.inner
175 }
176
177 /// Seal `blob` into a hardware envelope. Only reachable in the hardware tier.
178 fn wrap_blob(&self, provider: &dyn HardwareProvider, blob: &[u8]) -> Result<Vec<u8>> {
179 let mut rng = rand_core::OsRng;
180 let content_key = envelope::random_content_key(&mut rng);
181 let nonce = envelope::random_nonce(&mut rng);
182 let wrapped_key = provider.wrap_key(&content_key)?;
183 envelope::encode(provider.kind(), &content_key, &wrapped_key, &nonce, blob)
184 }
185
186 /// Open a hardware envelope, requiring the hardware that sealed it.
187 fn unwrap_blob(&self, provider: &dyn HardwareProvider, bytes: &[u8]) -> Result<Vec<u8>> {
188 let env = envelope::decode(bytes)?;
189 require_matching_hardware(&env, provider.kind())?;
190 let content_key: ContentKey = provider.unwrap_key(&env.wrapped_key)?;
191 Ok(env.open(&content_key)?.to_vec())
192 }
193}
194
195/// Reject an envelope sealed by hardware other than ours before spending a
196/// hardware round-trip on it.
197///
198/// Covers the unrecognised-wire-id case as well as a known-but-different class:
199/// both mean "not openable by this host's component", which is a different fact
200/// from a corrupt file.
201fn require_matching_hardware(env: &Envelope, ours: HardwareKind) -> Result<()> {
202 match env.hardware_kind() {
203 Some(kind) if kind == ours => Ok(()),
204 Some(kind) => Err(KeystoreError::HardwareKindMismatch {
205 expected: ours.label(),
206 found: kind.label(),
207 }),
208 // Not a hardware refusal and not corruption — a class this build cannot
209 // name. Reported as such so `HardwareUnwrapFailed` keeps meaning exactly
210 // "the hardware refused".
211 None => Err(KeystoreError::UnknownHardwareClass {
212 wire_id: env.hardware_wire_id,
213 }),
214 }
215}
216
217/// Decide the protection tier from a provider's probe, its custody claim, and a
218/// live self-test — then apply `policy` to any negative outcome.
219fn resolve_tier(
220 provider: Option<&dyn HardwareProvider>,
221 policy: HardwarePolicy,
222) -> Result<ProtectionTier> {
223 let Some(provider) = provider else {
224 return degrade(DegradeReason::NotRequested, policy);
225 };
226
227 match provider.probe() {
228 HardwareProbe::Absent => degrade(DegradeReason::NoHardwarePresent, policy),
229
230 // "Could not determine" is its own outcome, and the only one that is an
231 // error under the default policy.
232 HardwareProbe::Indeterminate { detail } => {
233 if policy.allows_indeterminate_degrade() {
234 degrade(DegradeReason::ProbeIndeterminate { detail }, policy)
235 } else {
236 Err(KeystoreError::HardwareProbeIndeterminate { detail })
237 }
238 }
239
240 HardwareProbe::Available(kind) => match verify_hardware(provider, kind) {
241 Ok(()) => Ok(ProtectionTier::Hardware(kind)),
242 Err(detail) => degrade(DegradeReason::HardwareUnusable { detail }, policy),
243 },
244 }
245}
246
247/// Refute or confirm a provider's "hardware is available" claim.
248///
249/// Three ways the claim fails, all of which must land on
250/// [`DegradeReason::HardwareUnusable`] rather than a hardware tier:
251/// a provider that disagrees with itself about which component it binds to; a
252/// wrapping key that is not actually non-exportable (which buys none of the
253/// cross-machine binding the tier promises); and a wrap/unwrap round-trip that
254/// does not reproduce the key.
255fn verify_hardware(
256 provider: &dyn HardwareProvider,
257 probed: HardwareKind,
258) -> std::result::Result<(), String> {
259 if provider.kind() != probed {
260 return Err(format!(
261 "provider binds {} but probed {}",
262 provider.kind().label(),
263 probed.label()
264 ));
265 }
266
267 if !provider.custody().is_hardware_grade() {
268 return Err(format!(
269 "wrapping key custody is {:?}, not NonExportable",
270 provider.custody()
271 ));
272 }
273
274 let mut rng = rand_core::OsRng;
275 let probe_key = envelope::random_content_key(&mut rng);
276 let wrapped = provider
277 .wrap_key(&probe_key)
278 .map_err(|e| format!("self-test wrap failed: {e}"))?;
279 if wrapped.is_empty() {
280 return Err("self-test wrap produced no wrapped key".to_owned());
281 }
282 if wrapped.as_slice() == probe_key.as_slice() {
283 return Err("self-test wrap returned the content key verbatim".to_owned());
284 }
285 let recovered = provider
286 .unwrap_key(&wrapped)
287 .map_err(|e| format!("self-test unwrap failed: {e}"))?;
288 if recovered.as_slice() != probe_key.as_slice() {
289 return Err("self-test round-trip did not reproduce the key".to_owned());
290 }
291 Ok(())
292}
293
294/// Apply `policy` to a negative outcome: degrade with the reason, or fail closed.
295fn degrade(reason: DegradeReason, policy: HardwarePolicy) -> Result<ProtectionTier> {
296 if policy.allows_degrade() {
297 Ok(ProtectionTier::Software(reason))
298 } else {
299 Err(KeystoreError::HardwareRequired { reason })
300 }
301}
302
303impl std::fmt::Debug for HardwareBoundBackend {
304 /// Redacted: reports the tier (which is not sensitive and is the point of
305 /// the type) but never the inner store or any key material.
306 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
307 f.debug_struct("HardwareBoundBackend")
308 .field("tier", &self.tier)
309 .field("inner", &"<redacted>")
310 .finish()
311 }
312}
313
314impl KeychainBackend for HardwareBoundBackend {
315 /// Read a blob, unwrapping it when it carries a hardware envelope.
316 ///
317 /// A blob **without** the envelope prefix is returned untouched, which is
318 /// what lets every keystore written before this feature — and any future
319 /// inner format — keep opening (§5.1).
320 ///
321 /// A blob **with** an envelope that this host cannot open is an error, never
322 /// the raw envelope bytes: an envelope copied to a machine without the
323 /// sealing hardware must fail loudly rather than hand back ciphertext that a
324 /// caller would then try to parse as a keystore.
325 fn read(&self, key: &BackendKey) -> Result<Vec<u8>> {
326 let bytes = self.inner.read(key)?;
327 if !envelope::is_envelope(&bytes) {
328 return Ok(bytes);
329 }
330 match self.provider.as_deref() {
331 Some(provider) => self.unwrap_blob(provider, &bytes),
332 None => Err(KeystoreError::NotHardwareBound {
333 tier: self.tier.to_string(),
334 }),
335 }
336 }
337
338 /// Write a blob, sealing it into a hardware envelope in the hardware tier
339 /// and passing the software-sealed bytes straight through otherwise.
340 fn write(&self, key: &BackendKey, data: &[u8]) -> Result<()> {
341 match self.provider.as_deref() {
342 Some(provider) => {
343 let sealed = self.wrap_blob(provider, data)?;
344 self.inner.write(key, &sealed)
345 }
346 None => self.inner.write(key, data),
347 }
348 }
349
350 fn delete(&self, key: &BackendKey) -> Result<()> {
351 self.inner.delete(key)
352 }
353
354 fn list(&self, prefix: &str) -> Result<Vec<BackendKey>> {
355 self.inner.list(prefix)
356 }
357
358 fn exists(&self, key: &BackendKey) -> Result<bool> {
359 self.inner.exists(key)
360 }
361}