use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use super::codec::hex_encode;
const HASH_DOMAIN: &str = "brinkhaus-licence-v1";
pub const DEFAULT_HOST_ROOT: &str = "/host";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum IdentifierKind {
MachineId,
Mac,
CpuSerial,
SerialFile,
}
impl IdentifierKind {
pub fn as_str(self) -> &'static str {
match self {
Self::MachineId => "machineId",
Self::Mac => "mac",
Self::CpuSerial => "cpuSerial",
Self::SerialFile => "serialFile",
}
}
pub fn parse(text: &str) -> Option<Self> {
[
Self::MachineId,
Self::Mac,
Self::CpuSerial,
Self::SerialFile,
]
.into_iter()
.find(|k| k.as_str() == text)
}
pub fn normalize(self, raw: &str) -> Option<String> {
let raw = raw.trim();
let value = match self {
Self::MachineId => raw
.chars()
.filter(|c| !matches!(c, '{' | '}' | '-'))
.collect::<String>()
.to_ascii_lowercase(),
Self::Mac => {
let octets: Vec<&str> = raw.split([':', '-']).collect();
if octets.len() != 6
|| octets
.iter()
.any(|o| o.len() != 2 || !o.chars().all(|c| c.is_ascii_hexdigit()))
{
return None;
}
let mac = octets.join(":").to_ascii_lowercase();
if mac == "00:00:00:00:00:00" || mac == "ff:ff:ff:ff:ff:ff" {
return None;
}
mac
}
Self::CpuSerial => raw.to_ascii_lowercase(),
Self::SerialFile => raw.to_ascii_uppercase(),
};
if value.is_empty() || value.chars().all(|c| c == '0') {
None
} else {
Some(value)
}
}
}
pub fn identifier_hash(kind: IdentifierKind, normalized: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(HASH_DOMAIN.as_bytes());
hasher.update([0]);
hasher.update(kind.as_str().as_bytes());
hasher.update([0]);
hasher.update(normalized.as_bytes());
hex_encode(&hasher.finalize())
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Binding {
#[serde(rename = "type")]
pub kind: IdentifierKind,
pub label: String,
pub sha256: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HardwareIdentifier {
#[serde(rename = "type")]
pub kind: IdentifierKind,
pub label: String,
pub value: String,
pub sha256: String,
}
impl HardwareIdentifier {
pub fn new(kind: IdentifierKind, label: impl Into<String>, raw: &str) -> Option<Self> {
let value = kind.normalize(raw)?;
Some(Self {
kind,
label: label.into(),
sha256: identifier_hash(kind, &value),
value,
})
}
pub fn binding(&self) -> Binding {
Binding {
kind: self.kind,
label: self.label.clone(),
sha256: self.sha256.clone(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "problem", rename_all = "camelCase")]
pub enum ProfileProblem {
ContainerWithoutHostRoot { expected: String },
#[serde(rename_all = "camelCase")]
SourceUnreadable {
kind: IdentifierKind,
path: String,
error: String,
},
DanglingInterfaces { path: String },
NoPhysicalInterface { path: String },
#[serde(rename_all = "camelCase")]
QueryFailed { kind: IdentifierKind, error: String },
NoSourceConfigured,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExplicitSource {
pub kind: IdentifierKind,
pub label: String,
pub path: PathBuf,
}
pub fn parse_source_spec(kind: IdentifierKind, spec: &str) -> Result<Vec<ExplicitSource>, String> {
let mut out = Vec::new();
for item in spec.split(',').map(str::trim).filter(|i| !i.is_empty()) {
let (label, path) = match item.split_once('=') {
Some((label, path)) => (label.trim().to_string(), path.trim()),
None => {
let label = Path::new(item)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| item.to_string());
(label, item)
}
};
if label.is_empty() || path.is_empty() {
return Err(format!(
"{}: invalid source {item:?} (expected label=path)",
kind.as_str()
));
}
out.push(ExplicitSource {
kind,
label,
path: PathBuf::from(path),
});
}
Ok(out)
}
#[must_use]
pub fn in_container() -> bool {
Path::new("/.dockerenv").exists() || Path::new("/run/.containerenv").exists()
}
#[derive(Debug, Clone)]
pub struct HardwareSources {
pub host_root: PathBuf,
pub proc_root: PathBuf,
pub serial_file: Option<PathBuf>,
pub in_container: bool,
}
impl HardwareSources {
pub fn detect(host_root: Option<&Path>, serial_file: Option<&Path>) -> Self {
let host_root = match host_root {
Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
_ if Path::new(DEFAULT_HOST_ROOT).is_dir() => PathBuf::from(DEFAULT_HOST_ROOT),
_ => PathBuf::from("/"),
};
Self {
host_root,
proc_root: PathBuf::from("/proc"),
serial_file: serial_file
.filter(|p| !p.as_os_str().is_empty())
.map(Path::to_path_buf),
in_container: in_container(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct HardwareProfile {
pub identifiers: Vec<HardwareIdentifier>,
pub problems: Vec<ProfileProblem>,
}
impl HardwareProfile {
pub fn collect(sources: &HardwareSources) -> Self {
let mut profile = Self::default();
platform::collect(sources, &mut profile);
collect_cpu_serial(&sources.proc_root, &mut profile);
if let Some(path) = &sources.serial_file {
collect_serial_file(path, &mut profile);
}
profile
}
pub fn collect_explicit(sources: &[ExplicitSource], proc_root: Option<&Path>) -> Self {
let mut profile = Self::default();
if sources.is_empty() {
profile.problems.push(ProfileProblem::NoSourceConfigured);
}
for source in sources {
match std::fs::read_to_string(&source.path) {
Ok(text) => {
let first = text.lines().map(str::trim).find(|l| !l.is_empty());
match first
.and_then(|v| HardwareIdentifier::new(source.kind, source.label.clone(), v))
{
Some(id) => profile.push(Some(id)),
None => profile.problems.push(ProfileProblem::SourceUnreadable {
kind: source.kind,
path: source.path.display().to_string(),
error: "empty or placeholder value".to_string(),
}),
}
}
Err(e) => profile.problems.push(ProfileProblem::SourceUnreadable {
kind: source.kind,
path: source.path.display().to_string(),
error: e.to_string(),
}),
}
}
if let Some(proc_root) = proc_root {
collect_cpu_serial(proc_root, &mut profile);
}
profile
}
pub fn matches(&self, binding: &Binding) -> bool {
self.identifiers
.iter()
.any(|id| id.kind == binding.kind && id.sha256 == binding.sha256)
}
pub fn digest(&self) -> String {
let mut hashes: Vec<String> = self
.identifiers
.iter()
.map(|id| format!("{}:{}", id.kind.as_str(), id.sha256))
.collect();
hashes.sort();
hex_encode(&Sha256::digest(hashes.join("\n").as_bytes()))
}
pub fn bindings_for(&self, hashes: &[String]) -> Vec<Binding> {
self.identifiers
.iter()
.filter(|id| hashes.contains(&id.sha256))
.map(HardwareIdentifier::binding)
.collect()
}
fn push(&mut self, id: Option<HardwareIdentifier>) {
if let Some(id) = id {
if !self.identifiers.contains(&id) {
self.identifiers.push(id);
}
}
}
}
fn collect_cpu_serial(proc_root: &Path, profile: &mut HardwareProfile) {
let path = proc_root.join("cpuinfo");
if let Ok(text) = std::fs::read_to_string(&path) {
if let Some(serial) = parse_cpuinfo_serial(&text) {
profile.push(HardwareIdentifier::new(
IdentifierKind::CpuSerial,
path.display().to_string(),
&serial,
));
}
}
}
pub fn parse_cpuinfo_serial(cpuinfo: &str) -> Option<String> {
cpuinfo.lines().find_map(|line| {
let (key, value) = line.split_once(':')?;
key.trim()
.eq_ignore_ascii_case("serial")
.then(|| value.trim().to_string())
})
}
fn collect_serial_file(path: &Path, profile: &mut HardwareProfile) {
match std::fs::read_to_string(path) {
Ok(text) => {
let first = text.lines().map(str::trim).find(|l| !l.is_empty());
profile.push(first.and_then(|line| {
HardwareIdentifier::new(
IdentifierKind::SerialFile,
path.display().to_string(),
line,
)
}));
}
Err(e) => profile.problems.push(ProfileProblem::SourceUnreadable {
kind: IdentifierKind::SerialFile,
path: path.display().to_string(),
error: e.to_string(),
}),
}
}
#[cfg(not(windows))]
mod platform {
use super::*;
pub(super) fn collect(sources: &HardwareSources, profile: &mut HardwareProfile) {
if sources.in_container && sources.host_root == Path::new("/") {
profile
.problems
.push(ProfileProblem::ContainerWithoutHostRoot {
expected: DEFAULT_HOST_ROOT.to_string(),
});
return;
}
collect_machine_id(&sources.host_root, profile);
collect_macs(&sources.host_root.join("sys/class/net"), profile);
}
fn collect_machine_id(root: &Path, profile: &mut HardwareProfile) {
let primary = root.join("etc/machine-id");
let fallback = root.join("var/lib/dbus/machine-id");
for path in [&primary, &fallback] {
if let Ok(text) = std::fs::read_to_string(path) {
if let Some(id) =
HardwareIdentifier::new(IdentifierKind::MachineId, "machine-id", &text)
{
profile.push(Some(id));
return;
}
}
}
let error = std::fs::read_to_string(&primary)
.err()
.map(|e| e.to_string())
.unwrap_or_else(|| "empty".to_string());
profile.problems.push(ProfileProblem::SourceUnreadable {
kind: IdentifierKind::MachineId,
path: primary.display().to_string(),
error,
});
}
pub(super) fn collect_macs(net_dir: &Path, profile: &mut HardwareProfile) {
let entries = match std::fs::read_dir(net_dir) {
Ok(e) => e,
Err(e) => {
profile.problems.push(ProfileProblem::SourceUnreadable {
kind: IdentifierKind::Mac,
path: net_dir.display().to_string(),
error: e.to_string(),
});
return;
}
};
let mut names: Vec<String> = entries
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
names.sort();
let (mut found, mut dangling) = (0usize, 0usize);
for name in &names {
let entry = net_dir.join(name);
if let Ok(link) = std::fs::read_link(&entry) {
if link.to_string_lossy().contains("devices/virtual/") {
continue;
}
} else if !entry.join("device").exists() {
continue;
}
let read = |file: &str| std::fs::read_to_string(entry.join(file));
let address = match read("address") {
Ok(a) => a,
Err(_) => {
dangling += 1;
continue;
}
};
if read("type").map(|t| t.trim() != "1").unwrap_or(true) {
continue;
}
if read("addr_assign_type")
.map(|t| t.trim() == "1")
.unwrap_or(false)
{
continue;
}
if let Some(id) = HardwareIdentifier::new(IdentifierKind::Mac, name.clone(), &address) {
profile.push(Some(id));
found += 1;
}
}
if found == 0 {
let path = net_dir.display().to_string();
profile.problems.push(if dangling > 0 {
ProfileProblem::DanglingInterfaces { path }
} else {
ProfileProblem::NoPhysicalInterface { path }
});
}
}
}
#[cfg(windows)]
mod platform {
use super::*;
use std::os::windows::process::CommandExt;
use std::process::Command;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
pub(super) fn collect(_sources: &HardwareSources, profile: &mut HardwareProfile) {
match run(
"reg",
&[
"query",
r"HKLM\SOFTWARE\Microsoft\Cryptography",
"/v",
"MachineGuid",
],
) {
Ok(out) => profile.push(parse_reg_query_value(&out, "MachineGuid").and_then(|guid| {
HardwareIdentifier::new(IdentifierKind::MachineId, "MachineGuid", &guid)
})),
Err(error) => profile.problems.push(ProfileProblem::QueryFailed {
kind: IdentifierKind::MachineId,
error,
}),
}
match run(
"powershell.exe",
&[
"-NoProfile",
"-NonInteractive",
"-Command",
"Get-NetAdapter -Physical | Select-Object Name,MacAddress | ConvertTo-Json -Compress",
],
) {
Ok(out) => {
let before = profile.identifiers.len();
for (name, mac) in parse_netadapter_json(&out) {
profile.push(HardwareIdentifier::new(IdentifierKind::Mac, name, &mac));
}
if profile.identifiers.len() == before {
profile.problems.push(ProfileProblem::NoPhysicalInterface {
path: "Get-NetAdapter -Physical".to_string(),
});
}
}
Err(error) => profile.problems.push(ProfileProblem::QueryFailed {
kind: IdentifierKind::Mac,
error,
}),
}
}
fn run(program: &str, args: &[&str]) -> Result<String, String> {
let output = Command::new(program)
.args(args)
.creation_flags(CREATE_NO_WINDOW)
.output()
.map_err(|e| format!("{program}: {e}"))?;
if !output.status.success() {
return Err(format!("{program}: exit {}", output.status));
}
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}
}
pub fn parse_reg_query_value(output: &str, name: &str) -> Option<String> {
output.lines().find_map(|line| {
let mut parts = line.split_whitespace();
if parts.next()? != name {
return None;
}
let _kind = parts.next()?;
parts.next().map(str::to_string)
})
}
pub fn parse_netadapter_json(output: &str) -> Vec<(String, String)> {
let value: serde_json::Value = match serde_json::from_str(output.trim()) {
Ok(v) => v,
Err(_) => return Vec::new(),
};
let items = match value {
serde_json::Value::Array(items) => items,
single => vec![single],
};
items
.iter()
.filter_map(|item| {
Some((
item.get("Name")?.as_str()?.to_string(),
item.get("MacAddress")?.as_str()?.to_string(),
))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalisation_per_kind() {
let n = |k: IdentifierKind, v: &str| k.normalize(v);
assert_eq!(
n(
IdentifierKind::MachineId,
"{0CD9A1AB-E0B8-40BB-A8A4-E848C070DF47}\n"
)
.unwrap(),
"0cd9a1abe0b840bba8a4e848c070df47"
);
assert_eq!(
n(IdentifierKind::Mac, "E0-8F-4C-82-40-7E").unwrap(),
"e0:8f:4c:82:40:7e"
);
assert_eq!(n(IdentifierKind::Mac, "00:00:00:00:00:00"), None);
assert_eq!(n(IdentifierKind::Mac, "e0:8f:4c:82:40"), None);
assert_eq!(n(IdentifierKind::CpuSerial, "0000000000000000"), None);
assert_eq!(
n(IdentifierKind::SerialFile, " sn00100 ").unwrap(),
"SN00100"
);
assert_eq!(n(IdentifierKind::MachineId, " "), None);
}
#[test]
fn hash_is_domain_and_kind_separated() {
let a = identifier_hash(IdentifierKind::CpuSerial, "abc");
let b = identifier_hash(IdentifierKind::SerialFile, "abc");
assert_ne!(a, b);
assert_eq!(a.len(), 64);
}
#[test]
fn cpuinfo_serial_only_on_arm() {
let arm = "processor\t: 0\nHardware\t: BCM2835\nSerial\t\t: 10000000abcdef01\n";
assert_eq!(parse_cpuinfo_serial(arm).unwrap(), "10000000abcdef01");
assert_eq!(parse_cpuinfo_serial("model name\t: Intel(R)\n"), None);
}
#[test]
fn windows_output_parsers() {
let reg = "\r\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography\r\n MachineGuid REG_SZ 0cd9a1ab-e0b8-40bb-a8a4-e848c070df47\r\n";
assert_eq!(
parse_reg_query_value(reg, "MachineGuid").unwrap(),
"0cd9a1ab-e0b8-40bb-a8a4-e848c070df47"
);
let single = r#"{"Name":"Ethernet","MacAddress":"E0-8F-4C-82-40-7E"}"#;
assert_eq!(parse_netadapter_json(single).len(), 1);
let many = r#"[{"Name":"Ethernet","MacAddress":"E0-8F-4C-82-40-7E"},{"Name":"WLAN","MacAddress":"74-D4-DD-C7-65-A0"}]"#;
assert_eq!(parse_netadapter_json(many)[1].0, "WLAN");
assert!(parse_netadapter_json("").is_empty());
}
#[cfg(unix)]
fn fake_sysfs(root: &Path, full_sys: bool) {
use std::os::unix::fs::symlink;
let net = root.join("sys/class/net");
std::fs::create_dir_all(&net).unwrap();
let mk = |rel: &str, name: &str, ty: &str, addr: &str, assign: &str| {
let dev = root.join("sys/devices").join(rel).join(name);
if full_sys {
std::fs::create_dir_all(&dev).unwrap();
std::fs::write(dev.join("address"), format!("{addr}\n")).unwrap();
std::fs::write(dev.join("type"), format!("{ty}\n")).unwrap();
std::fs::write(dev.join("addr_assign_type"), format!("{assign}\n")).unwrap();
}
symlink(format!("../../devices/{rel}/{name}"), net.join(name)).unwrap();
};
mk(
"pci0000:00/0000:00:1f.6/net",
"eth0",
"1",
"E0:8F:4C:82:40:7E",
"0",
);
mk(
"pci0000:00/0000:00:14.3/net",
"wlan0",
"1",
"02:11:22:33:44:55",
"1",
);
mk("virtual/net", "docker0", "1", "8e:37:58:94:aa:e2", "3");
mk("virtual/net", "lo", "772", "00:00:00:00:00:00", "0");
}
#[cfg(unix)]
#[test]
fn collects_physical_interfaces_and_machine_id_from_host_root() {
let dir = tempfile::tempdir().unwrap();
fake_sysfs(dir.path(), true);
std::fs::create_dir_all(dir.path().join("etc")).unwrap();
std::fs::write(
dir.path().join("etc/machine-id"),
"0cd9a1abe0b840bba8a4e848c070df47\n",
)
.unwrap();
let serial = dir.path().join("serial");
std::fs::write(&serial, "\nSN00100\n").unwrap();
let sources = HardwareSources {
host_root: dir.path().to_path_buf(),
proc_root: dir.path().join("no-proc"),
serial_file: Some(serial),
in_container: true,
};
let profile = HardwareProfile::collect(&sources);
let kinds: Vec<(IdentifierKind, &str)> = profile
.identifiers
.iter()
.map(|i| (i.kind, i.label.as_str()))
.collect();
assert!(kinds.contains(&(IdentifierKind::MachineId, "machine-id")));
assert!(kinds.contains(&(IdentifierKind::Mac, "eth0")));
assert!(!kinds
.iter()
.any(|(_, l)| *l == "docker0" || *l == "wlan0" || *l == "lo"));
assert!(kinds.iter().any(|(k, _)| *k == IdentifierKind::SerialFile));
assert!(profile.problems.is_empty(), "{:?}", profile.problems);
let mac = profile
.identifiers
.iter()
.find(|i| i.label == "eth0")
.unwrap();
assert!(profile.matches(&mac.binding()));
assert_eq!(
profile
.bindings_for(std::slice::from_ref(&mac.sha256))
.len(),
1
);
}
#[cfg(unix)]
#[test]
fn only_class_net_mounted_is_reported_as_dangling() {
let dir = tempfile::tempdir().unwrap();
fake_sysfs(dir.path(), false);
let mut profile = HardwareProfile::default();
platform::collect_macs(&dir.path().join("sys/class/net"), &mut profile);
assert!(profile.identifiers.is_empty());
assert!(matches!(
profile.problems[0],
ProfileProblem::DanglingInterfaces { .. }
));
}
#[cfg(unix)]
#[test]
fn container_without_host_root_refuses_image_identity() {
let sources = HardwareSources {
host_root: PathBuf::from("/"),
proc_root: PathBuf::from("/nonexistent"),
serial_file: None,
in_container: true,
};
let profile = HardwareProfile::collect(&sources);
assert!(profile.identifiers.is_empty());
assert!(matches!(
profile.problems[0],
ProfileProblem::ContainerWithoutHostRoot { .. }
));
}
#[test]
fn named_sources_are_read_and_nothing_else() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("machine-id"),
"0cd9a1abe0b840bba8a4e848c070df47\n",
)
.unwrap();
std::fs::write(dir.path().join("mac-eth0"), "E0:8F:4C:82:40:7E\n").unwrap();
std::fs::write(dir.path().join("leer"), "\n").unwrap();
let d = dir.path().display();
let mut sources =
parse_source_spec(IdentifierKind::MachineId, &format!("{d}/machine-id")).unwrap();
sources.extend(
parse_source_spec(
IdentifierKind::Mac,
&format!(" eth0={d}/mac-eth0 , eth1={d}/fehlt ,"),
)
.unwrap(),
);
sources.extend(
parse_source_spec(IdentifierKind::SerialFile, &format!("sn={d}/leer")).unwrap(),
);
assert_eq!(sources[0].label, "machine-id");
assert_eq!(sources[1].label, "eth0");
let profile = HardwareProfile::collect_explicit(&sources, None);
let ids: Vec<(IdentifierKind, &str)> = profile
.identifiers
.iter()
.map(|i| (i.kind, i.label.as_str()))
.collect();
assert_eq!(
ids,
vec![
(IdentifierKind::MachineId, "machine-id"),
(IdentifierKind::Mac, "eth0")
]
);
assert_eq!(
profile.problems.len(),
2,
"missing file and empty value: {:?}",
profile.problems
);
assert!(parse_source_spec(IdentifierKind::Mac, "eth0=").is_err());
assert!(parse_source_spec(IdentifierKind::Mac, "=x").is_err());
assert_eq!(
HardwareProfile::collect_explicit(&[], None).problems,
vec![ProfileProblem::NoSourceConfigured]
);
}
#[test]
fn digest_ignores_order() {
let a = HardwareIdentifier::new(IdentifierKind::Mac, "eth0", "e0:8f:4c:82:40:7e").unwrap();
let b = HardwareIdentifier::new(IdentifierKind::SerialFile, "sn", "SN1").unwrap();
let p1 = HardwareProfile {
identifiers: vec![a.clone(), b.clone()],
problems: vec![],
};
let p2 = HardwareProfile {
identifiers: vec![b, a],
problems: vec![],
};
assert_eq!(p1.digest(), p2.digest());
}
}