1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use std::error::Error;
use std::net::IpAddr;
use std::process::{Command, Output};
use std::str;
use std::str::FromStr;

use hmac_sha256::HMAC;
use uuid::Uuid;

use crate::error::NetzworkApiError;

// TODO: Replace "netzwork.tbd" with the appropriate domain name
const APP_DOMAIN: &[u8; 12] = b"netzwork.tbd";

#[cfg(target_os = "linux")]
fn get_machine_id() -> Result<Uuid, Box<dyn Error>> {
    let machine_id = std::fs::read_to_string("/etc/machine-id")?
        .trim()
        .to_string();
    Ok(Uuid::from_str(&machine_id)?)
}

#[cfg(target_os = "macos")]
fn get_machine_id() -> Result<Uuid, Box<dyn Error>> {
    let output: Output = Command::new("system_profiler")
        .arg("SPHardwareDataType")
        .output()?;

    let hardware_uuid = str::from_utf8(&output.stdout)?
        .lines()
        .find(|line| line.contains("Hardware UUID"))
        .and_then(|line| line.split_whitespace().nth(2))
        .map(str::to_string)
        .ok_or("Failed to retrieve Hardware UUID")?
        .trim()
        .to_string();

    Ok(Uuid::from_str(&hardware_uuid)?)
}

/// The get_secure_machine_id function calculates a secure machine ID by generating a v4 UUID based
/// on the provided app_id and the machine ID retrieved from the system.
fn get_secure_machine_id(app_id_opt: Option<Uuid>) -> Result<Uuid, Box<dyn Error>> {
    let app_id = match app_id_opt {
        Some(u) => u,
        None => Uuid::new_v5(&Uuid::NAMESPACE_DNS, APP_DOMAIN),
    };
    let hmac = HMAC::mac(app_id, get_machine_id()?);
    let mut id = Uuid::from_slice(&hmac[0..16])?.into_bytes();
    // Make this a v4 UUID, inspired by https://github.com/d-k-bo/app-machine-id/blob/main/src/lib.rs
    // Set UUID version to 4
    id[6] = (id[6] & 0x0F) | 0x40;
    // Set the UUID variant to DCE
    id[8] = (id[8] & 0x3F) | 0x80;
    Ok(Uuid::from_bytes(id))
}

pub fn host_uuid() -> Result<Uuid, NetzworkApiError> {
    match get_secure_machine_id(None) {
        Ok(uuid) => Ok(uuid),
        Err(_err) => Err(NetzworkApiError::HostIdentityError(
            "get_secure_machine_id call failed".to_string(),
        )),
    }
}

pub fn agent_uuid(host_uuid: &Uuid, name: &String) -> Uuid {
    Uuid::new_v5(host_uuid, name.as_bytes())
}

pub fn interface_uuid(host_uuid: &Uuid, mac_addr: &[u8]) -> Uuid {
    Uuid::new_v5(host_uuid, mac_addr)
}

pub fn interface_addr_uuid(iface_uuid: &Uuid, ip_addr: IpAddr) -> Uuid {
    Uuid::new_v5(iface_uuid, ip_addr.to_string().as_bytes())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_machineid() {
        assert_ne!(get_machine_id().unwrap(), Uuid::nil());
    }
    #[test]
    fn test_secure_machineid() {
        assert_ne!(get_secure_machine_id(None).unwrap(), Uuid::nil());
    }
}