1pub(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
46const DOMAIN: &[u8] = b"sys-lib/device/v1";
49const KEY_DOMAIN: &[u8] = b"sys-lib/device/v1/app-key";
50const FINGERPRINT_TAG: u8 = 0;
52const MAX_APP: usize = 255;
54
55pub(crate) const ANCHOR_BUF: usize = 256;
57
58#[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
70pub(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#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
87#[non_exhaustive]
88pub enum Basis {
89 Install,
93 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 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#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
121#[non_exhaustive]
122pub enum Anchor {
123 InstallId,
125 PlatformUuid,
127 BoardSerial,
129 ProductSerial,
131 CpuSignature,
134 PermanentMac,
136}
137
138impl Anchor {
139 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
172pub(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
181struct AppKey([u8; BLAKE3_MAC_KEY_LEN]);
183
184impl AppKey {
185 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 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#[derive(Clone, Copy, PartialEq, Eq, Hash)]
224pub struct DeviceId([u8; 16]);
225
226impl DeviceId {
227 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 #[must_use]
238 pub const fn as_bytes(&self) -> &[u8; 16] {
239 &self.0
240 }
241
242 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 #[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
305pub(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
340pub fn id(app: &str) -> Result<DeviceId> {
351 builder(app).id()
352}
353
354pub fn fingerprint(app: &str) -> Result<Fingerprint> {
360 builder(app).fingerprint()
361}
362
363#[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
386pub 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 pub fn basis(mut self, basis: Basis) -> Self {
408 self.basis = basis;
409 self
410 }
411
412 pub fn secret(mut self, key: [u8; 32]) -> Self {
416 self.secret = Some(key);
417 self
418 }
419
420 pub fn fallback(mut self, on: bool) -> Self {
424 self.fallback = on;
425 self
426 }
427
428 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 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
474fn 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 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 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 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 let mut raw = Raw::new();
615 raw.0[..4].copy_from_slice(b"SECR");
616 let mut held = core::mem::ManuallyDrop::new(raw);
617 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}