Skip to main content

sys_lib/device/
fingerprint.rs

1//! A fingerprint hashes every available anchor separately, so a stored one can
2//! tell "this machine, one part changed" from "another machine". Concatenating
3//! anchors into one id would do the opposite: any one change would change
4//! everything.
5
6use core::fmt;
7
8use crypt_io::hash::blake3;
9
10use super::{Anchor, ct_eq};
11use crate::{Error, Result};
12
13/// The length of a stored fingerprint.
14pub const FINGERPRINT_LEN: usize = 112;
15
16const MAGIC: &[u8; 4] = b"SLFP";
17const VERSION: u8 = 1;
18const ANCHORS: usize = Anchor::ALL.len();
19const HASHES_AT: usize = 8;
20const CHECKSUM_AT: usize = HASHES_AT + ANCHORS * 16;
21
22/// How much an anchor counts in a comparison.
23const fn weight(anchor: Anchor) -> u32 {
24    match anchor {
25        Anchor::InstallId | Anchor::PlatformUuid => 3,
26        Anchor::BoardSerial | Anchor::ProductSerial => 2,
27        Anchor::CpuSignature | Anchor::PermanentMac => 1,
28    }
29}
30
31/// An app-keyed 16-byte hash per anchor, or absent.
32///
33/// ```no_run
34/// use sys_lib::device::{self, Fingerprint, Verdict};
35///
36/// let now = device::fingerprint("com.example.app")?;
37/// let stored = Fingerprint::from_bytes(&now.to_bytes())?;
38/// match now.compare(&stored).verdict {
39///     Verdict::Same => {}
40///     Verdict::LikelySame => { /* one part changed: update the record */ }
41///     Verdict::Different => { /* treat as a new device */ }
42///     _ => {}
43/// }
44/// # Ok::<(), sys_lib::Error>(())
45/// ```
46#[derive(Clone, PartialEq, Eq)]
47pub struct Fingerprint {
48    present: u8,
49    hashes: [[u8; 16]; ANCHORS],
50}
51
52impl fmt::Debug for Fingerprint {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        f.debug_list().entries(self.anchors()).finish()
55    }
56}
57
58impl Fingerprint {
59    pub(super) const fn empty() -> Self {
60        Self {
61            present: 0,
62            hashes: [[0; 16]; ANCHORS],
63        }
64    }
65
66    pub(super) fn set(&mut self, slot: usize, tag: &[u8; 32]) {
67        self.hashes[slot].copy_from_slice(&tag[..16]);
68        self.present |= 1 << slot;
69    }
70
71    fn has(&self, slot: usize) -> bool {
72        self.present & (1 << slot) != 0
73    }
74
75    /// Which anchors are present.
76    pub fn anchors(&self) -> impl Iterator<Item = Anchor> + '_ {
77        Anchor::ALL
78            .into_iter()
79            .enumerate()
80            .filter(|&(slot, _)| self.has(slot))
81            .map(|(_, a)| a)
82    }
83
84    /// Compares with a stored fingerprint, each hash in constant time.
85    #[must_use]
86    pub fn compare(&self, stored: &Fingerprint) -> Comparison {
87        let (mut matched, mut changed, mut missing) = (Vec::new(), Vec::new(), Vec::new());
88        for (slot, anchor) in Anchor::ALL.into_iter().enumerate() {
89            match (self.has(slot), stored.has(slot)) {
90                (true, true) if ct_eq(&self.hashes[slot], &stored.hashes[slot]) => {
91                    matched.push(anchor);
92                }
93                (true, true) => changed.push(anchor),
94                (false, false) => {}
95                _ => missing.push(anchor),
96            }
97        }
98        let weight_of = |list: &[Anchor]| list.iter().map(|&a| weight(a)).sum::<u32>();
99        let strong_changed = changed.iter().filter(|&&a| weight(a) >= 2).count();
100        // Identical CPUs share a signature, so it alone proves nothing.
101        let identifies = matched.iter().any(|&a| a != Anchor::CpuSignature);
102        let verdict = if identifies && changed.is_empty() {
103            Verdict::Same
104        } else if identifies && weight_of(&matched) >= 5 && strong_changed <= 1 {
105            Verdict::LikelySame
106        } else {
107            Verdict::Different
108        };
109        Comparison {
110            verdict,
111            matched,
112            changed,
113            missing,
114        }
115    }
116
117    /// The stored form: magic, version, anchor bitmap, two reserved bytes, six
118    /// 16-byte hashes, and an 8-byte checksum.
119    #[must_use]
120    pub fn to_bytes(&self) -> [u8; FINGERPRINT_LEN] {
121        let mut out = [0u8; FINGERPRINT_LEN];
122        out[..4].copy_from_slice(MAGIC);
123        out[4] = VERSION;
124        out[5] = self.present;
125        for (slot, hash) in self.hashes.iter().enumerate() {
126            out[HASHES_AT + slot * 16..HASHES_AT + (slot + 1) * 16].copy_from_slice(hash);
127        }
128        let sum = blake3(&out[..CHECKSUM_AT]);
129        out[CHECKSUM_AT..].copy_from_slice(&sum[..8]);
130        out
131    }
132
133    /// Reads the stored form. The checksum catches storage corruption, not
134    /// tampering.
135    ///
136    /// # Errors
137    ///
138    /// `Malformed` for a wrong length, magic, or version, non-zero reserved
139    /// bytes, a bitmap that disagrees with the hashes, or a bad checksum,
140    /// checked in that order (E-78).
141    pub fn from_bytes(bytes: &[u8]) -> Result<Fingerprint> {
142        const BAD: Error = Error::Malformed {
143            what: "device fingerprint",
144            source: "stored fingerprint",
145            line: None,
146        };
147        if bytes.len() != FINGERPRINT_LEN
148            || bytes[..4] != *MAGIC
149            || bytes[4] != VERSION
150            || bytes[6..8] != [0, 0]
151            || bytes[5] >> ANCHORS != 0
152        {
153            return Err(BAD);
154        }
155        let mut out = Self {
156            present: bytes[5],
157            ..Self::empty()
158        };
159        for slot in 0..ANCHORS {
160            let at = HASHES_AT + slot * 16;
161            out.hashes[slot].copy_from_slice(&bytes[at..at + 16]);
162            if !out.has(slot) && out.hashes[slot] != [0; 16] {
163                return Err(BAD);
164            }
165        }
166        if blake3(&bytes[..CHECKSUM_AT])[..8] != bytes[CHECKSUM_AT..] {
167            return Err(BAD);
168        }
169        Ok(out)
170    }
171}
172
173/// What [`Fingerprint::compare`] found.
174#[derive(Clone, Debug, PartialEq, Eq)]
175#[non_exhaustive]
176pub struct Comparison {
177    /// The answer.
178    pub verdict: Verdict,
179    /// Anchors present in both and equal.
180    pub matched: Vec<Anchor>,
181    /// Anchors present in both and different.
182    pub changed: Vec<Anchor>,
183    /// Anchors present in only one.
184    pub missing: Vec<Anchor>,
185}
186
187/// Whether two fingerprints are of one machine.
188#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
189#[non_exhaustive]
190pub enum Verdict {
191    /// Every anchor present in both matches, and more than the CPU signature
192    /// (which identical CPUs share) was compared.
193    Same,
194    /// Matched weight of at least 5, with at most one strong anchor changed.
195    LikelySame,
196    /// Neither.
197    Different,
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    fn with(entries: &[(Anchor, u8)]) -> Fingerprint {
205        let mut f = Fingerprint::empty();
206        for &(anchor, byte) in entries {
207            let slot = Anchor::ALL.iter().position(|&a| a == anchor).unwrap();
208            f.set(slot, &[byte; 32]);
209        }
210        f
211    }
212
213    const FULL: &[(Anchor, u8)] = &[
214        (Anchor::InstallId, 1),
215        (Anchor::PlatformUuid, 2),
216        (Anchor::BoardSerial, 3),
217        (Anchor::ProductSerial, 4),
218        (Anchor::CpuSignature, 5),
219        (Anchor::PermanentMac, 6),
220    ];
221
222    #[test]
223    fn test_fingerprint_verdicts() {
224        let a = with(FULL);
225        assert_eq!(a.compare(&a).verdict, Verdict::Same);
226        // A NIC swap: one weak anchor changed.
227        let mut parts = FULL.to_vec();
228        parts[5].1 = 66;
229        let c = a.compare(&with(&parts));
230        assert_eq!(c.verdict, Verdict::LikelySame);
231        assert_eq!(c.changed, vec![Anchor::PermanentMac]);
232        // A reinstall: one strong anchor changed.
233        let mut parts = FULL.to_vec();
234        parts[0].1 = 11;
235        assert_eq!(a.compare(&with(&parts)).verdict, Verdict::LikelySame);
236        // Two strong anchors changed.
237        parts[1].1 = 22;
238        assert_eq!(a.compare(&with(&parts)).verdict, Verdict::Different);
239        // Nothing in common.
240        let other: Vec<_> = FULL.iter().map(|&(a, b)| (a, b + 100)).collect();
241        assert_eq!(a.compare(&with(&other)).verdict, Verdict::Different);
242    }
243
244    #[test]
245    fn test_fingerprint_cpu_alone_proves_nothing() {
246        let a = with(&[(Anchor::CpuSignature, 5)]);
247        assert_eq!(a.compare(&a).verdict, Verdict::Different);
248        assert_eq!(
249            Fingerprint::empty().compare(&Fingerprint::empty()).verdict,
250            Verdict::Different
251        );
252    }
253
254    #[test]
255    fn test_fingerprint_missing_anchors_do_not_count_against() {
256        let a = with(&FULL[..2]);
257        let b = with(FULL);
258        let c = a.compare(&b);
259        assert_eq!(c.verdict, Verdict::Same);
260        assert_eq!(c.missing.len(), 4);
261    }
262
263    #[test]
264    fn test_fingerprint_round_trip() {
265        let f = with(&FULL[1..4]);
266        let bytes = f.to_bytes();
267        assert_eq!(&bytes[..5], b"SLFP\x01");
268        assert_eq!(bytes[5], 0b1110);
269        let back = Fingerprint::from_bytes(&bytes).unwrap();
270        assert_eq!(back, f);
271        assert_eq!(
272            back.anchors().collect::<Vec<_>>(),
273            vec![
274                Anchor::PlatformUuid,
275                Anchor::BoardSerial,
276                Anchor::ProductSerial
277            ]
278        );
279        assert_eq!(
280            format!("{f:?}"),
281            "[PlatformUuid, BoardSerial, ProductSerial]"
282        );
283    }
284
285    #[test]
286    fn test_fingerprint_e78_every_bad_form_is_malformed() {
287        let good = with(FULL).to_bytes();
288        let reject = |bytes: &[u8], why: &str| {
289            assert!(
290                matches!(Fingerprint::from_bytes(bytes), Err(Error::Malformed { .. })),
291                "{why}"
292            );
293        };
294        reject(&good[..FINGERPRINT_LEN - 1], "truncated");
295        reject(&[good.as_slice(), &[0]].concat(), "extended");
296        reject(&[], "empty");
297        for (at, why) in [
298            (0, "magic"),
299            (4, "version"),
300            (6, "reserved"),
301            (7, "reserved"),
302            (20, "hash without a checksum"),
303            (FINGERPRINT_LEN - 1, "checksum"),
304        ] {
305            let mut bad = good;
306            bad[at] ^= 0xFF;
307            reject(&bad, why);
308        }
309        // A bitmap bit past the anchors.
310        let mut bad = good;
311        bad[5] |= 0x80;
312        reject(&bad, "bitmap");
313        // A hash where the bitmap says absent, even with a fresh checksum.
314        let mut f = with(&FULL[..1]).to_bytes();
315        f[HASHES_AT + 16] = 1;
316        let sum = blake3(&f[..CHECKSUM_AT]);
317        f[CHECKSUM_AT..].copy_from_slice(&sum[..8]);
318        reject(&f, "inconsistent bitmap");
319    }
320}