Skip to main content

yb_core/
nvm.rs

1// SPDX-FileCopyrightText: 2025 - 2026 Frederic Ruget <fred@atlant.is> (GitHub: @douzebis)
2//
3// SPDX-License-Identifier: MIT
4
5//! NVM free-space measurement.
6//!
7//! This module contains two functions with very different risk profiles:
8//!
9//! - [`scan_nvm`] — **read-only**: reads every occupied PIV object once and
10//!   tallies store / other / free bytes.  Safe to call at any time.
11//!
12//! - [`measure_free_nvm`] — **destructive probe**: fills every empty PIV slot
13//!   to its maximum capacity via binary search, sums the totals, then restores
14//!   all probe slots to empty.  The device is left in exactly the state it was
15//!   found in, but the probe writes are real and count against YubiKey NVM
16//!   wear.  Never call this function in a tight loop or in production hot paths.
17
18use crate::piv::session::PcscSession;
19use crate::piv::PivBackend;
20use crate::store::constants::OBJECT_ID_ZERO;
21use anyhow::Result;
22
23/// Maximum number of 3-byte PIV object IDs in the range 0x5F0000..0x5F00FF.
24const MAX_SLOTS: usize = 256;
25
26/// Upper bound for binary-search probing — above the empirically measured
27/// maximum (3063) to be safe across firmware versions.
28const PROBE_MAX: usize = 4095;
29
30/// Measure total free NVM on the device without altering its state.
31///
32/// Only slots that GET DATA reports as empty (SW 6A82 → size 0) are touched.
33/// Each empty slot is filled to its maximum capacity via binary search, the
34/// total is summed, and all probe slots are then freed (0-byte PUT DATA).
35///
36/// Returns the total number of bytes available for new allocations.
37///
38/// If `verbose` is true, prints per-slot progress to stderr.  Stops as soon
39/// as the first probe yields 0 bytes (NVM already full).
40pub fn measure_free_nvm(reader: &str, mgmt_key: &str, verbose: bool) -> Result<usize> {
41    let mut session = PcscSession::open(reader)?;
42
43    // Identify empty slots.
44    let mut empty_slots = Vec::new();
45    for i in 0..MAX_SLOTS {
46        let id = OBJECT_ID_ZERO + i as u32;
47        if session.try_get_data_size(id)?.unwrap_or(0) == 0 {
48            empty_slots.push(i);
49        }
50    }
51    if verbose {
52        eprintln!(
53            "  measure_free_nvm: {} empty slots out of {MAX_SLOTS}.",
54            empty_slots.len()
55        );
56    }
57
58    // Fill each empty slot to maximum via binary search.
59    let mut total = 0usize;
60    let mut filled: Vec<usize> = Vec::new();
61    for &slot in &empty_slots {
62        let id = OBJECT_ID_ZERO + slot as u32;
63        let size = dichotomy_fill(&mut session, mgmt_key, id)?;
64        if verbose {
65            eprintln!("    slot {slot:3}: {size} bytes");
66        }
67        if size == 0 {
68            if verbose {
69                eprintln!("    NVM full — stopping early.");
70            }
71            break;
72        }
73        total += size;
74        filled.push(slot);
75    }
76
77    // Restore all probe slots to empty.
78    for &slot in &filled {
79        let id = OBJECT_ID_ZERO + slot as u32;
80        session.authenticate_management_key(mgmt_key)?;
81        session.try_put_data(id, &[])?;
82    }
83
84    if verbose {
85        eprintln!("  measure_free_nvm: total free = {total} bytes.");
86    }
87    Ok(total)
88}
89
90/// Fill slot `id` to the largest payload that fits using binary search.
91///
92/// The slot must be empty on entry.  On return the slot holds `committed`
93/// bytes (the largest size that succeeded).  A failed PUT DATA clears the
94/// slot on the YubiKey, so after each failure we re-commit the last known
95/// good size before narrowing the search.
96fn dichotomy_fill(session: &mut PcscSession, mgmt_key: &str, id: u32) -> Result<usize> {
97    let mut lo = 1usize;
98    let mut hi = PROBE_MAX;
99    let mut committed = 0usize;
100
101    while lo <= hi {
102        let mid = (lo + hi) / 2;
103        session.authenticate_management_key(mgmt_key)?;
104        if session.try_put_data(id, &vec![0xEEu8; mid])? {
105            committed = mid;
106            lo = mid + 1;
107        } else {
108            // Failed write cleared the slot — re-commit last known good size.
109            if committed > 0 {
110                session.authenticate_management_key(mgmt_key)?;
111                session.try_put_data(id, &vec![0xEEu8; committed])?;
112            }
113            hi = mid - 1;
114        }
115    }
116    Ok(committed)
117}
118
119// ---------------------------------------------------------------------------
120// NVM usage scan
121// ---------------------------------------------------------------------------
122
123/// Total NVM budget of the YubiKey 5 PIV application (bytes).
124/// Used only as the denominator for the "free" estimate.
125const YUBIKEY_NVM_BYTES: usize = 51_200;
126
127/// NVM usage broken down into three buckets.
128pub struct NvmUsage {
129    /// Bytes consumed by yb store objects (the `0x5F_00xx` range).
130    pub store_bytes: usize,
131    /// Bytes consumed by other PIV objects (certificates, printed info, etc.).
132    pub other_bytes: usize,
133    /// Estimated free bytes (total budget minus store and other).
134    pub free_bytes: usize,
135}
136
137/// Well-known PIV data object IDs outside the `0x5F_00xx` yb store range.
138/// Sources: NIST SP 800-73-4 Table 3, Yubico extensions.
139const KNOWN_PIV_OBJECTS: &[u32] = &[
140    0x5F_C102, // Card Capability Container
141    0x5F_C100, // Card Holder Unique Identifier (CHUID)
142    0x5F_C101, // Card Authentication certificate
143    0x5F_C105, // PIV Authentication certificate (slot 9A)
144    0x5F_C10A, // Digital Signature certificate (slot 9C)
145    0x5F_C10B, // Key Management certificate (slot 9D)
146    0x5F_C10C, // Secure Messaging certificate
147    0x5F_C103, // Cardholder Fingerprints
148    0x5F_C106, // Security Object
149    0x5F_C108, // Cardholder Facial Image
150    0x5F_C109, // Printed Information (PIN-protected mgmt key)
151    0x5F_C10D, // Retired Key Management 1 certificate (slot 82)
152    0x5F_C10E, // Retired Key Management 2 certificate (slot 83)
153    0x5F_C10F, // Retired Key Management 3 certificate (slot 84)
154    0x5F_C110, // Retired Key Management 4 certificate (slot 85)
155    0x5F_C111, // Retired Key Management 5 certificate (slot 86)
156    0x5F_C112, // Retired Key Management 6 certificate (slot 87)
157    0x5F_C113, // Retired Key Management 7 certificate (slot 88)
158    0x5F_C114, // Retired Key Management 8 certificate (slot 89)
159    0x5F_C115, // Retired Key Management 9 certificate (slot 8A)
160    0x5F_C116, // Retired Key Management 10 certificate (slot 8B)
161    0x5F_C117, // Retired Key Management 11 certificate (slot 8C)
162    0x5F_C118, // Retired Key Management 12 certificate (slot 8D)
163    0x5F_C119, // Retired Key Management 13 certificate (slot 8E)
164    0x5F_C11A, // Retired Key Management 14 certificate (slot 8F)
165    0x5F_C11B, // Retired Key Management 15 certificate (slot 90)
166    0x5F_C11C, // Retired Key Management 16 certificate (slot 91)
167    0x5F_C11D, // Retired Key Management 17 certificate (slot 92)
168    0x5F_C11E, // Retired Key Management 18 certificate (slot 93)
169    0x5F_C11F, // Retired Key Management 19 certificate (slot 94)
170    0x5F_C120, // Retired Key Management 20 certificate (slot 95)
171    0x5F_C121, // Attestation certificate (Yubico extension)
172];
173
174/// Scan all known PIV object IDs and return NVM usage broken down by bucket.
175///
176/// Probes all 256 slots in `0x5F_0000..0x5F_00FF` (yb store range) plus the
177/// fixed set of well-known PIV object IDs.  No credentials required — only
178/// GET DATA (read-only) APDUs are issued.
179///
180/// `store_object_ids` identifies which `0x5F_00xx` slots are reachable yb
181/// store objects (counted as store bytes).  Any other occupied slot in the
182/// store range — i.e. orphaned chunks — is silently skipped so its bytes
183/// fall into the free estimate rather than polluting the "other" bucket.
184/// Occupied slots outside the store range go into the "other" bucket.
185pub fn scan_nvm(
186    reader: &str,
187    piv: &dyn PivBackend,
188    store_object_ids: &std::collections::HashSet<u32>,
189) -> Result<NvmUsage> {
190    let mut store_bytes = 0usize;
191    let mut other_bytes = 0usize;
192
193    // Scan the full yb store range: 0x5F_0000..0x5F_00FF.
194    for i in 0u32..256 {
195        let id = OBJECT_ID_ZERO + i;
196        if let Some(size) = piv.object_size(reader, id)? {
197            if store_object_ids.contains(&id) {
198                store_bytes += size;
199            }
200            // Orphaned store slots (occupied but not reachable) are skipped:
201            // they are treated as free space, not as "other".
202        }
203    }
204
205    // Scan well-known PIV objects outside the yb store range.
206    for &id in KNOWN_PIV_OBJECTS {
207        if let Some(size) = piv.object_size(reader, id)? {
208            other_bytes += size;
209        }
210    }
211
212    let used = store_bytes + other_bytes;
213    let free_bytes = YUBIKEY_NVM_BYTES.saturating_sub(used);
214
215    Ok(NvmUsage {
216        store_bytes,
217        other_bytes,
218        free_bytes,
219    })
220}