Cotton code
57 lines · 1.9 KB · RustRaw
//! Hardware identity survives losing the device signing key. Macs only: iOS//! has no app-readable hardware UUID independent of vendor installation state./// Read the Mac platform UUID. Never invent an identity when the OS is silent.pub fn hardware_id() -> Option<String> {    #[cfg(target_os = "macos")]    {        let output = std::process::Command::new("/usr/sbin/ioreg")            .args(["-rd1", "-c", "IOPlatformExpertDevice"])            .output()            .ok()?;        if !output.status.success() {            return None;        }        platform_uuid(&String::from_utf8(output.stdout).ok()?)    }    #[cfg(not(target_os = "macos"))]    {        None    }}#[cfg(any(test, target_os = "macos"))]fn platform_uuid(output: &str) -> Option<String> {    let raw = output.lines().find_map(|line| {        let (key, value) = line.split_once('=')?;        (key.trim().trim_matches('"') == "IOPlatformUUID").then_some(value.trim().trim_matches('"'))    })?;    if raw.len() != 36        || !raw.bytes().enumerate().all(|(i, ch)| {            if [8, 13, 18, 23].contains(&i) {                ch == b'-'            } else {                ch.is_ascii_hexdigit()            }        })        || raw.bytes().all(|ch| ch == b'0' || ch == b'-')    {        return None;    }    Some(raw.to_ascii_lowercase())}/// RULE: Hardware identity is an exact OS platform UUID, never a serial, name or vendor id, because only a stable hardware id may retire another device key.#[test]fn reads_only_a_valid_platform_uuid() {    assert_eq!(        platform_uuid(r#"    "IOPlatformUUID" = "11111111-2222-4333-8444-555555555555""#)            .as_deref(),        Some("11111111-2222-4333-8444-555555555555")    );    assert_eq!(platform_uuid(r#""IOPlatformUUID" = "garbage""#), None);    assert_eq!(        platform_uuid(r#""IOPlatformSerialNumber" = "11111111-2222-4333-8444-555555555555""#),        None    );}