Skip to main content

sys_lib/device/
mod.rs

1//! Device identity: an id for "this device" that an application can store and
2//! recognise later.
3//!
4//! **A device id is not authentication.** It is a claim, not proof: root or
5//! Administrator can set the machine id to anything, and hypervisors set
6//! firmware UUIDs freely. Never use it as the only check for anything that
7//! matters; for proof of a device, use a key held in a TPM or Secure Enclave.
8//! It is personal data in client software: an application storing one needs a
9//! lawful basis, a retention period, and a way to delete it. See
10//! `docs/DEVICE-ID.md`.
11//!
12//! The id is a keyed BLAKE3 hash of **one** identifier the OS keeps, keyed by a
13//! key derived from your application id. Two applications on one machine get
14//! unrelated ids, and nobody can turn an id back into the machine id or the
15//! serial numbers behind it. The raw identifier is read into a fixed buffer,
16//! hashed, and wiped; it never appears in a return value, an error, `Debug`,
17//! `Display`, or a log.
18//!
19//! ```no_run
20//! use sys_lib as sys;
21//!
22//! let id = sys::device::id("com.hivedb.server")?;
23//! println!("device {id}");
24//! let again: sys::device::DeviceId = id.to_string().parse()?;
25//! assert!(id.ct_eq(&again));
26//! # Ok::<(), sys_lib::Error>(())
27//! ```
28
29pub(crate) mod canon;
30mod fingerprint;
31mod report;
32
33use core::{fmt, str::FromStr};
34
35use crypt_io::{
36    hash::blake3,
37    mac::{BLAKE3_MAC_KEY_LEN, Blake3Mac},
38    wipe,
39};
40
41pub use fingerprint::{Comparison, FINGERPRINT_LEN, Fingerprint, Verdict};
42pub use report::{ChangeEvent, CloneRisk, SourceState, SourceStatus, StabilityReport, report};
43
44use crate::{Error, Result};
45
46/// The derivation's version. Frozen for all of 1.x: a change would silently
47/// move every stored id, so it can only arrive as a new [`Basis`] or a new tag.
48const DOMAIN: &[u8] = b"sys-lib/device/v1";
49const KEY_DOMAIN: &[u8] = b"sys-lib/device/v1/app-key";
50/// The basis tag of a fingerprint entry: ids and entries never collide.
51const FINGERPRINT_TAG: u8 = 0;
52/// The longest application id.
53const MAX_APP: usize = 255;
54
55/// The buffer a platform reads one identifier into.
56pub(crate) const ANCHOR_BUF: usize = 256;
57
58/// What a platform found for an anchor; with `Value(n)`, the first `n` bytes
59/// of its buffer are the identifier in canonical form.
60#[cfg_attr(target_vendor = "apple", allow(dead_code))]
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub(crate) enum Reading {
63    Value(usize),
64    Absent,
65    Placeholder,
66    PermissionDenied,
67    Unsupported,
68}
69
70/// A buffer holding a raw identifier, wiped when it goes (threat T1).
71pub(crate) struct Raw(pub(crate) [u8; ANCHOR_BUF]);
72
73impl Raw {
74    pub(crate) const fn new() -> Self {
75        Self([0; ANCHOR_BUF])
76    }
77}
78
79impl Drop for Raw {
80    fn drop(&mut self) {
81        wipe(&mut self.0);
82    }
83}
84
85/// What an id is anchored to.
86#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
87#[non_exhaustive]
88pub enum Basis {
89    /// This OS installation. Unprivileged everywhere; changes on reinstall.
90    /// macOS has no installation id and uses the platform UUID (the report says
91    /// so).
92    Install,
93    /// The hardware: the firmware UUID, then the board serial. Survives
94    /// reinstalls. Linux needs root (the DMI identifier files are readable by
95    /// root only).
96    Hardware,
97}
98
99impl Basis {
100    const fn tag(self) -> u8 {
101        match self {
102            Self::Install => 1,
103            Self::Hardware => 2,
104        }
105    }
106
107    /// The anchors this basis may use, first choice first.
108    const fn anchors(self) -> &'static [Anchor] {
109        match self {
110            Self::Install if cfg!(any(target_os = "macos", target_os = "ios")) => {
111                &[Anchor::PlatformUuid]
112            }
113            Self::Install => &[Anchor::InstallId],
114            Self::Hardware => &[Anchor::PlatformUuid, Anchor::BoardSerial],
115        }
116    }
117}
118
119/// An identifier a device id or a fingerprint can rest on.
120#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
121#[non_exhaustive]
122pub enum Anchor {
123    /// The OS installation id.
124    InstallId,
125    /// The firmware's UUID.
126    PlatformUuid,
127    /// The main board's serial number.
128    BoardSerial,
129    /// The product's serial number.
130    ProductSerial,
131    /// The CPU's vendor, family, model, stepping, and brand. Not unique:
132    /// identical CPUs share it.
133    CpuSignature,
134    /// The lowest permanent MAC address of a built-in interface.
135    PermanentMac,
136}
137
138impl Anchor {
139    /// Every anchor, in bitmap order.
140    pub(crate) const ALL: [Anchor; 6] = [
141        Anchor::InstallId,
142        Anchor::PlatformUuid,
143        Anchor::BoardSerial,
144        Anchor::ProductSerial,
145        Anchor::CpuSignature,
146        Anchor::PermanentMac,
147    ];
148
149    const fn tag(self) -> u8 {
150        match self {
151            Self::InstallId => 1,
152            Self::PlatformUuid => 2,
153            Self::BoardSerial => 3,
154            Self::ProductSerial => 4,
155            Self::CpuSignature => 5,
156            Self::PermanentMac => 6,
157        }
158    }
159
160    pub(crate) const fn name(self) -> &'static str {
161        match self {
162            Self::InstallId => "install id",
163            Self::PlatformUuid => "platform UUID",
164            Self::BoardSerial => "board serial",
165            Self::ProductSerial => "product serial",
166            Self::CpuSignature => "CPU signature",
167            Self::PermanentMac => "permanent MAC",
168        }
169    }
170}
171
172/// Reads one anchor into `raw`.
173pub(crate) fn read_anchor(anchor: Anchor, raw: &mut Raw) -> Reading {
174    match anchor {
175        Anchor::CpuSignature => canon::cpu_signature(&mut raw.0),
176        Anchor::PermanentMac => canon::permanent_mac(&mut raw.0),
177        _ => crate::sys::device_anchor(anchor, &mut raw.0),
178    }
179}
180
181/// The key an application's ids are hashed under, wiped when it goes.
182struct AppKey([u8; BLAKE3_MAC_KEY_LEN]);
183
184impl AppKey {
185    /// `BLAKE3(domain || 0x00 || u16_be(len) || app)`, or the caller's secret.
186    fn new(app: &str, secret: Option<&[u8; BLAKE3_MAC_KEY_LEN]>) -> Result<Self> {
187        if app.is_empty() || app.len() > MAX_APP {
188            return Err(Error::InvalidInput {
189                what: "application id",
190                reason: "must be 1 to 255 bytes",
191            });
192        }
193        if let Some(secret) = secret {
194            return Ok(Self(*secret));
195        }
196        let mut message = [0u8; KEY_DOMAIN.len() + 3 + MAX_APP];
197        let (domain, rest) = message.split_at_mut(KEY_DOMAIN.len());
198        domain.copy_from_slice(KEY_DOMAIN);
199        rest[1..3].copy_from_slice(&(app.len() as u16).to_be_bytes());
200        rest[3..3 + app.len()].copy_from_slice(app.as_bytes());
201        Ok(Self(blake3(&message[..KEY_DOMAIN.len() + 3 + app.len()])))
202    }
203
204    /// `BLAKE3-keyed(key, domain || 0x00 || basis || anchor || u16_be(len) || canonical)`.
205    fn tag(&self, basis_tag: u8, anchor: Anchor, canonical: &[u8]) -> [u8; 32] {
206        let mut mac = Blake3Mac::new(&self.0);
207        mac.update(DOMAIN);
208        mac.update(&[0, basis_tag, anchor.tag()]);
209        mac.update(&(canonical.len() as u16).to_be_bytes());
210        mac.update(canonical);
211        mac.finalize()
212    }
213}
214
215impl Drop for AppKey {
216    fn drop(&mut self) {
217        wipe(&mut self.0);
218    }
219}
220
221/// An application-specific device id: 122 bits of a keyed hash, shown as an
222/// RFC 9562 version 8 UUID. Already a keyed hash, so it is safe to show.
223#[derive(Clone, Copy, PartialEq, Eq, Hash)]
224pub struct DeviceId([u8; 16]);
225
226impl DeviceId {
227    /// The first 16 bytes of a tag, with the version and variant bits set.
228    fn from_tag(tag: &[u8; 32]) -> Self {
229        let mut b = [0u8; 16];
230        b.copy_from_slice(&tag[..16]);
231        b[6] = (b[6] & 0x0F) | 0x80;
232        b[8] = (b[8] & 0x3F) | 0x80;
233        Self(b)
234    }
235
236    /// The 16 bytes.
237    #[must_use]
238    pub const fn as_bytes(&self) -> &[u8; 16] {
239        &self.0
240    }
241
242    /// Parses this type's own [`Display`](fmt::Display) format only.
243    ///
244    /// ```
245    /// use sys_lib::device::DeviceId;
246    ///
247    /// let text = "6f1c2a4e-9b3d-8e21-a7c4-0123456789ab";
248    /// assert_eq!(DeviceId::parse(text)?.to_string(), text);
249    /// assert!(DeviceId::parse("6F1C2A4E-9B3D-8E21-A7C4-0123456789AB").is_err());
250    /// # Ok::<(), sys_lib::Error>(())
251    /// ```
252    ///
253    /// # Errors
254    ///
255    /// `InvalidInput` for anything else: a wrong length, capitals, a misplaced
256    /// dash, or a version or variant that is not this type's.
257    pub fn parse(text: &str) -> Result<DeviceId> {
258        const BAD: Error = Error::InvalidInput {
259            what: "device id",
260            reason: "expected the 36-character lowercase form this type prints",
261        };
262        let s = text.as_bytes();
263        if s.len() != 36 {
264            return Err(BAD);
265        }
266        let mut out = [0u8; 16];
267        let (mut i, mut n) = (0, 0);
268        while i < 36 {
269            if matches!(i, 8 | 13 | 18 | 23) {
270                if s[i] != b'-' {
271                    return Err(BAD);
272                }
273                i += 1;
274                continue;
275            }
276            let (hi, lo) = match (hex(s[i]), hex(s[i + 1])) {
277                (Some(h), Some(l)) => (h, l),
278                _ => return Err(BAD),
279            };
280            out[n] = hi << 4 | lo;
281            n += 1;
282            i += 2;
283        }
284        if out[6] & 0xF0 != 0x80 || out[8] & 0xC0 != 0x80 {
285            return Err(BAD);
286        }
287        Ok(Self(out))
288    }
289
290    /// Compares in constant time.
291    #[must_use]
292    pub fn ct_eq(&self, other: &DeviceId) -> bool {
293        ct_eq(&self.0, &other.0)
294    }
295}
296
297fn hex(b: u8) -> Option<u8> {
298    match b {
299        b'0'..=b'9' => Some(b - b'0'),
300        b'a'..=b'f' => Some(b - b'a' + 10),
301        _ => None,
302    }
303}
304
305/// Equality that does not stop at the first difference.
306pub(crate) fn ct_eq(a: &[u8; 16], b: &[u8; 16]) -> bool {
307    let mut diff = 0u8;
308    for (x, y) in a.iter().zip(b) {
309        diff |= x ^ y;
310    }
311    core::hint::black_box(diff) == 0
312}
313
314impl fmt::Display for DeviceId {
315    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316        for (i, b) in self.0.iter().enumerate() {
317            if matches!(i, 4 | 6 | 8 | 10) {
318                f.write_str("-")?;
319            }
320            write!(f, "{b:02x}")?;
321        }
322        Ok(())
323    }
324}
325
326impl fmt::Debug for DeviceId {
327    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328        write!(f, "DeviceId({self})")
329    }
330}
331
332impl FromStr for DeviceId {
333    type Err = Error;
334
335    fn from_str(s: &str) -> Result<Self> {
336        Self::parse(s)
337    }
338}
339
340/// An application's device id, from the OS installation. `app` is a stable,
341/// application-unique string such as a reverse domain name, 1 to 255 bytes.
342///
343/// **Not authentication**: see the [module documentation](self). sys-lib does
344/// not cache the id; store it if you need it often.
345///
346/// # Errors
347///
348/// `InvalidInput` for an empty or oversized `app`; `NoIdentifierSource` when
349/// the OS keeps no usable identifier ([`report`] says why).
350pub fn id(app: &str) -> Result<DeviceId> {
351    builder(app).id()
352}
353
354/// A [`Fingerprint`] of this device: every available anchor, hashed separately.
355///
356/// # Errors
357///
358/// `InvalidInput` for an empty or oversized `app`.
359pub fn fingerprint(app: &str) -> Result<Fingerprint> {
360    builder(app).fingerprint()
361}
362
363/// Options for an id or a fingerprint.
364///
365/// ```no_run
366/// use sys_lib::device::{self, Basis};
367///
368/// let secret: [u8; 32] = [7; 32];   // the application's own, never shipped in clients
369/// let id = device::builder("com.example.licensing")
370///     .basis(Basis::Hardware)
371///     .secret(secret)
372///     .id()?;
373/// # let _ = id;
374/// # Ok::<(), sys_lib::Error>(())
375/// ```
376#[must_use]
377pub fn builder(app: &str) -> Builder {
378    Builder {
379        app: app.to_owned(),
380        basis: Basis::Install,
381        secret: None,
382        fallback: false,
383    }
384}
385
386/// See [`builder`].
387pub struct Builder {
388    app: String,
389    basis: Basis,
390    secret: Option<[u8; BLAKE3_MAC_KEY_LEN]>,
391    fallback: bool,
392}
393
394impl fmt::Debug for Builder {
395    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396        f.debug_struct("Builder")
397            .field("app", &self.app)
398            .field("basis", &self.basis)
399            .field("secret", &self.secret.is_some())
400            .field("fallback", &self.fallback)
401            .finish()
402    }
403}
404
405impl Builder {
406    /// What the id rests on; the default is [`Basis::Install`].
407    pub fn basis(mut self, basis: Basis) -> Self {
408        self.basis = basis;
409        self
410    }
411
412    /// An application secret. With one, nobody without it can compute or
413    /// correlate the id, even with root on the machine: use one when ids are
414    /// sent to a server. Wiped when the builder is dropped.
415    pub fn secret(mut self, key: [u8; 32]) -> Self {
416        self.secret = Some(key);
417        self
418    }
419
420    /// Lets [`Basis::Hardware`] fall back to [`Basis::Install`] when hardware
421    /// sources are denied. The id is then a different one, which is why this
422    /// is off by default.
423    pub fn fallback(mut self, on: bool) -> Self {
424        self.fallback = on;
425        self
426    }
427
428    /// The device id.
429    ///
430    /// # Errors
431    ///
432    /// As [`id`].
433    pub fn id(&self) -> Result<DeviceId> {
434        let key = AppKey::new(&self.app, self.secret.as_ref())?;
435        if let Some(id) = id_on(&key, self.basis) {
436            return Ok(id);
437        }
438        if self.fallback
439            && self.basis != Basis::Install
440            && let Some(id) = id_on(&key, Basis::Install)
441        {
442            return Ok(id);
443        }
444        Err(Error::NoIdentifierSource { basis: self.basis })
445    }
446
447    /// The fingerprint.
448    ///
449    /// # Errors
450    ///
451    /// As [`fingerprint`].
452    pub fn fingerprint(&self) -> Result<Fingerprint> {
453        let key = AppKey::new(&self.app, self.secret.as_ref())?;
454        let mut out = Fingerprint::empty();
455        for (slot, anchor) in Anchor::ALL.into_iter().enumerate() {
456            let mut raw = Raw::new();
457            if let Reading::Value(n) = read_anchor(anchor, &mut raw) {
458                let tag = key.tag(FINGERPRINT_TAG, anchor, &raw.0[..n]);
459                out.set(slot, &tag);
460            }
461        }
462        Ok(out)
463    }
464}
465
466impl Drop for Builder {
467    fn drop(&mut self) {
468        if let Some(secret) = &mut self.secret {
469            wipe(secret);
470        }
471    }
472}
473
474/// The id on `basis`, from its first anchor that has a value.
475fn id_on(key: &AppKey, basis: Basis) -> Option<DeviceId> {
476    basis.anchors().iter().find_map(|&anchor| {
477        let mut raw = Raw::new();
478        match read_anchor(anchor, &mut raw) {
479            Reading::Value(n) => Some(DeviceId::from_tag(&key.tag(
480                basis.tag(),
481                anchor,
482                &raw.0[..n],
483            ))),
484            _ => None,
485        }
486    })
487}
488
489#[cfg(test)]
490mod tests {
491    use super::*;
492
493    fn key(app: &str) -> AppKey {
494        AppKey::new(app, None).unwrap()
495    }
496
497    fn id_of(app: &str, canonical: &[u8]) -> DeviceId {
498        DeviceId::from_tag(&key(app).tag(Basis::Install.tag(), Anchor::InstallId, canonical))
499    }
500
501    #[test]
502    fn test_device_derivation_is_frozen() {
503        // Changing this value moves every stored id: the derivation is frozen
504        // for 1.x. A failure here is a breaking change, never a test to update.
505        let id = id_of("com.example.app", &[0x42; 16]);
506        assert_eq!(id.to_string(), FROZEN_ID);
507    }
508    const FROZEN_ID: &str = "3d60c97f-d1b1-88ed-8a4c-fceff1480bb5";
509
510    #[test]
511    fn test_device_id_shape() {
512        let id = id_of("a", &[1; 16]);
513        assert_eq!(id.as_bytes()[6] >> 4, 8, "version 8");
514        assert_eq!(id.as_bytes()[8] >> 6, 0b10, "variant");
515        let text = id.to_string();
516        assert_eq!(text.len(), 36);
517        assert_eq!(text.parse::<DeviceId>().unwrap(), id);
518        assert_eq!(format!("{id:?}"), format!("DeviceId({text})"));
519        assert!(id.ct_eq(&DeviceId::parse(&text).unwrap()));
520        assert!(!id.ct_eq(&id_of("b", &[1; 16])));
521    }
522
523    #[test]
524    fn test_device_parse_rejects_every_other_form() {
525        let good = id_of("a", &[1; 16]).to_string();
526        for bad in [
527            String::new(),
528            good.to_uppercase(),
529            good.replace('-', ""),
530            format!("{good} "),
531            format!("{{{good}}}"),
532            good.replacen('-', "+", 1),
533            // Version 4, wrong variant.
534            format!("{}4{}", &good[..14], &good[15..]),
535            format!("{}0{}", &good[..19], &good[20..]),
536            "g".repeat(36),
537        ] {
538            assert!(
539                matches!(DeviceId::parse(&bad), Err(Error::InvalidInput { .. })),
540                "{bad:?}"
541            );
542        }
543    }
544
545    #[test]
546    fn test_device_t2_apps_do_not_correlate() {
547        // T2: over many pairs, ids of two apps differ in about 61 of 122 bits.
548        let mut bits = 0u64;
549        let pairs = 2000u32;
550        for i in 0..pairs {
551            let a = id_of("com.example.one", &i.to_be_bytes());
552            let b = id_of("com.example.two", &i.to_be_bytes());
553            bits +=
554                a.0.iter()
555                    .zip(&b.0)
556                    .map(|(x, y)| u64::from((x ^ y).count_ones()))
557                    .sum::<u64>();
558        }
559        let mean = bits as f64 / f64::from(pairs);
560        assert!((59.0..=63.0).contains(&mean), "mean distance {mean}");
561    }
562
563    #[test]
564    fn test_device_domain_separation() {
565        let k = key("a");
566        let c = [9u8; 16];
567        let tags = [
568            k.tag(Basis::Install.tag(), Anchor::InstallId, &c),
569            k.tag(Basis::Hardware.tag(), Anchor::InstallId, &c),
570            k.tag(Basis::Install.tag(), Anchor::PlatformUuid, &c),
571            k.tag(FINGERPRINT_TAG, Anchor::InstallId, &c),
572        ];
573        for (i, a) in tags.iter().enumerate() {
574            for b in &tags[i + 1..] {
575                assert_ne!(a, b);
576            }
577        }
578    }
579
580    #[test]
581    fn test_device_secret_replaces_the_derived_key() {
582        let plain = key("a").tag(1, Anchor::InstallId, &[1]);
583        let keyed = AppKey::new("a", Some(&[7; 32]))
584            .unwrap()
585            .tag(1, Anchor::InstallId, &[1]);
586        assert_ne!(plain, keyed);
587    }
588
589    #[test]
590    fn test_device_app_id_bounds() {
591        for app in [String::new(), "a".repeat(MAX_APP + 1)] {
592            assert!(matches!(
593                id(&app),
594                Err(Error::InvalidInput {
595                    what: "application id",
596                    ..
597                })
598            ));
599        }
600        assert!(AppKey::new(&"a".repeat(MAX_APP), None).is_ok());
601    }
602
603    #[test]
604    fn test_device_builder_debug_hides_the_secret() {
605        let b = builder("a").secret([0xAB; 32]);
606        let text = format!("{b:?}");
607        assert!(text.contains("secret: true") && !text.contains("171"));
608    }
609
610    #[test]
611    fn test_device_raw_is_wiped() {
612        // T1: the buffer is zero after use. The bytes are looked at through a
613        // pointer the drop cannot have been optimised around.
614        let mut raw = Raw::new();
615        raw.0[..4].copy_from_slice(b"SECR");
616        let mut held = core::mem::ManuallyDrop::new(raw);
617        // SAFETY of the test: dropped once, and read only afterwards in place.
618        wipe_for_test(&mut held);
619        assert_eq!(&held.0[..4], &[0; 4]);
620    }
621
622    fn wipe_for_test(raw: &mut Raw) {
623        wipe(&mut raw.0);
624    }
625
626    #[test]
627    fn test_device_live_ids_are_stable_or_explain_themselves() {
628        match (id("com.example.test"), id("com.example.test")) {
629            (Ok(a), Ok(b)) => {
630                assert_eq!(a, b);
631                assert_ne!(a, id("com.example.other").unwrap());
632            }
633            (Err(Error::NoIdentifierSource { .. }), _) => {}
634            other => panic!("{other:?}"),
635        }
636        let f = fingerprint("com.example.test").unwrap();
637        assert_eq!(
638            f.compare(&f).verdict == Verdict::Different,
639            f.anchors().next().is_none() || f.anchors().all(|a| a == Anchor::CpuSignature)
640        );
641    }
642}