Files
rust-discovery/crates/agent-windows/src/inventory.rs
T
kevin_janssen aea2d5b379
Rust development slice / linux (push) Failing after 9s
Expand the passive inventory shown in device details
2026-11-18 20:02:41 +01:00

385 lines
12 KiB
Rust

//! Passive native machine inventory. Never queries Win32_Product or executes
//! uninstall commands; registry entries are evidence, not verified MSI state.
use anyhow::{Result, ensure};
use chrono::Utc;
use rmm_domain::inventory_document::{
CpuTimes, DeviceType, SOFTWARE_OBSERVATION_MAX_BYTES, firmware_identifier,
};
use serde_json::{Value, json};
use std::{
mem::{size_of, zeroed},
ptr,
time::{Duration, Instant},
};
use windows_sys::Win32::{
Foundation::{ERROR_FILE_NOT_FOUND, ERROR_NO_MORE_ITEMS, ERROR_SUCCESS, FILETIME},
System::{
Registry::*,
SystemInformation::*,
Threading::{GetActiveProcessorGroupCount, GetSystemTimes},
},
};
struct Registry(HKEY);
impl Drop for Registry {
fn drop(&mut self) {
unsafe {
RegCloseKey(self.0);
}
}
}
fn open(parent: HKEY, name: &str, flags: u32) -> Result<Registry> {
let mut key = ptr::null_mut();
let name = crate::native::wide(name);
ensure!(
unsafe { RegOpenKeyExW(parent, name.as_ptr(), 0, KEY_READ | flags, &mut key) }
== ERROR_SUCCESS,
"REGISTRY_INVENTORY_ACCESS"
);
Ok(Registry(key))
}
fn text(key: HKEY, name: &str) -> Result<Option<String>> {
let name = crate::native::wide(name);
let mut data = [0u16; 512];
let mut bytes = size_of::<[u16; 512]>() as u32;
let result = unsafe {
RegGetValueW(
key,
ptr::null(),
name.as_ptr(),
RRF_RT_REG_SZ,
ptr::null_mut(),
data.as_mut_ptr().cast(),
&mut bytes,
)
};
if result == ERROR_FILE_NOT_FOUND {
return Ok(None);
}
ensure!(
result == ERROR_SUCCESS
&& bytes >= 2
&& bytes as usize <= size_of::<[u16; 512]>()
&& bytes.is_multiple_of(2),
"REGISTRY_INVENTORY_STRING"
);
let count = bytes as usize / 2;
ensure!(
data[count - 1] == 0 && !data[..count - 1].contains(&0),
"REGISTRY_STRING_TERMINATION"
);
Ok(Some(String::from_utf16(&data[..count - 1])?))
}
#[cfg(target_arch = "x86_64")]
fn non_microsoft_hypervisor() -> bool {
use std::arch::x86_64::__cpuid;
if __cpuid(1).ecx & (1 << 31) == 0 {
return false;
}
let vendor = __cpuid(0x4000_0000);
// The Microsoft hypervisor can also be active on physical VBS machines.
[vendor.ebx, vendor.ecx, vendor.edx]
!= [
u32::from_le_bytes(*b"Micr"),
u32::from_le_bytes(*b"osof"),
u32::from_le_bytes(*b"t Hv"),
]
}
#[cfg(not(target_arch = "x86_64"))]
fn non_microsoft_hypervisor() -> bool {
false
}
fn classify_machine(
hyper_v_host: bool,
guest_hypervisor: bool,
manufacturer: Option<&str>,
product: Option<&str>,
) -> Option<DeviceType> {
if hyper_v_host {
return Some(DeviceType::Hypervisor);
}
let manufacturer = manufacturer.unwrap_or_default().trim().to_ascii_lowercase();
let product = product.unwrap_or_default().trim().to_ascii_lowercase();
let virtual_firmware = [
"qemu",
"vmware",
"virtualbox",
"xen",
"parallels",
"bhyve",
"kvm",
"virtual machine",
"virtual platform",
]
.iter()
.any(|prefix| manufacturer.starts_with(prefix) || product.starts_with(prefix));
if guest_hypervisor || virtual_firmware {
return Some(DeviceType::Virtual);
}
(!manufacturer.is_empty() && !product.is_empty()).then_some(DeviceType::Physical)
}
fn machine_type(manufacturer: Option<&str>, product: Option<&str>) -> Option<DeviceType> {
let hyper_v_host = open(
HKEY_LOCAL_MACHINE,
r"SYSTEM\CurrentControlSet\Services\vmms",
KEY_WOW64_64KEY,
)
.is_ok();
classify_machine(
hyper_v_host,
non_microsoft_hypervisor(),
manufacturer,
product,
)
}
fn memory_status() -> Result<MEMORYSTATUSEX> {
let mut memory: MEMORYSTATUSEX = unsafe { zeroed() };
memory.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
ensure!(
unsafe { GlobalMemoryStatusEx(&mut memory) } != 0
&& memory.ullTotalPhys > 0
&& memory.ullAvailPhys <= memory.ullTotalPhys
&& memory.dwMemoryLoad <= 100,
"NATIVE_HARDWARE_QUERY"
);
Ok(memory)
}
pub fn physical_memory() -> Option<(u64, u64)> {
let memory = memory_status().ok()?;
Some((memory.ullAvailPhys, memory.ullTotalPhys))
}
pub fn cpu_times() -> Option<CpuTimes> {
// GetSystemTimes on a multi-group machine only reports the caller's group.
if unsafe { GetActiveProcessorGroupCount() } != 1 {
return None;
}
let (mut idle, mut kernel, mut user) = (
FILETIME::default(),
FILETIME::default(),
FILETIME::default(),
);
if unsafe { GetSystemTimes(&mut idle, &mut kernel, &mut user) } == 0 {
return None;
}
let ticks =
|time: FILETIME| (u64::from(time.dwHighDateTime) << 32) | u64::from(time.dwLowDateTime);
// Windows includes idle time in the kernel counter.
Some(CpuTimes {
total: ticks(kernel).checked_add(ticks(user))?,
idle: ticks(idle),
})
}
fn hardware() -> Result<Value> {
let mut system: SYSTEM_INFO = unsafe { zeroed() };
unsafe {
GetNativeSystemInfo(&mut system);
}
ensure!(system.dwNumberOfProcessors > 0, "NATIVE_HARDWARE_QUERY");
let memory = memory_status()?;
let cpu_model = open(
HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\CentralProcessor\0",
KEY_WOW64_64KEY,
)
.ok()
.and_then(|key| text(key.0, "ProcessorNameString").ok().flatten())
.map(|name| name.trim().to_owned())
.filter(|name| !name.is_empty());
let bios = open(
HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\BIOS",
KEY_WOW64_64KEY,
)
.ok();
let read = |name| {
bios.as_ref()
.and_then(|key| text(key.0, name).ok().flatten())
};
let manufacturer = read("SystemManufacturer").and_then(|value| firmware_identifier(&value));
let product = read("SystemProductName");
let bios_serial_number = read("SystemSerialNumber")
.and_then(|value| firmware_identifier(&value))
.or_else(crate::inventory_sources::bios_serial);
Ok(
json!({"cpu_model":cpu_model, "logical_processors_visible":system.dwNumberOfProcessors,
"memory_total_bytes":memory.ullTotalPhys,"memory_available_bytes":memory.ullAvailPhys,
"memory_load_percent":memory.dwMemoryLoad,
"device_type":machine_type(manufacturer.as_deref(),product.as_deref()),
"manufacturer":manufacturer,"bios_serial_number":bios_serial_number}),
)
}
fn software() -> Result<Value> {
let began = Instant::now();
let mut entries = Vec::new();
let mut entry_bytes = 0;
let mut errors = 0u32;
let mut scanned = 0u32;
let mut truncated = false;
let mut views = Vec::new();
for (view, label) in [
(KEY_WOW64_64KEY, "machine_registry_64"),
(KEY_WOW64_32KEY, "machine_registry_32"),
] {
views.push(label);
let key = match open(
HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
view,
) {
Ok(key) => key,
Err(_) => {
errors += 1;
continue;
}
};
for index in 0..2048 {
if began.elapsed() > Duration::from_millis(250) {
truncated = true;
break;
}
let mut name = [0u16; 256];
let mut length = name.len() as u32;
let result = unsafe {
RegEnumKeyExW(
key.0,
index,
name.as_mut_ptr(),
&mut length,
ptr::null(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
)
};
if result == ERROR_NO_MORE_ITEMS {
break;
}
scanned += 1;
if result != ERROR_SUCCESS || length as usize >= name.len() {
errors += 1;
continue;
}
let entry = (|| -> Result<Option<Value>> {
let name = String::from_utf16(&name[..length as usize])?;
let child = open(key.0, &name, view)?;
let Some(display) = text(child.0, "DisplayName")?.filter(|v| !v.is_empty()) else {
return Ok(None);
};
// No arbitrary path, username, uninstall string or installer
// execution is inventoried. Missing version stays null.
Ok(Some(
json!({"display_name":display,"version":text(child.0,"DisplayVersion")?,
"publisher":text(child.0,"Publisher")?,"source":label,
"installation_context":"machine","installed_state":"registry_entry_only"}),
))
})();
match entry {
Ok(Some(entry)) => {
entry_bytes += serde_json::to_vec(&entry)?.len() + 1;
if entry_bytes > SOFTWARE_OBSERVATION_MAX_BYTES - 2048 {
truncated = true;
break;
}
entries.push(entry);
}
Ok(None) => {}
Err(_) => errors += 1,
}
if index == 2047 {
truncated = true;
}
}
if truncated {
break;
}
}
ensure!(
errors < 2 || !entries.is_empty(),
"SOFTWARE_REGISTRY_UNAVAILABLE"
);
Ok(
json!({"entries":entries,"scanned_keys":scanned,"read_errors":errors,"truncated":truncated,"views_queried":views,
"scope":"machine_registry_only","per_user_inventory":"unsupported",
"msi_state_verification":"not_collected","appx_inventory":"not_collected"}),
)
}
/// Each provider is isolated. Missing permissions never fabricate an empty,
/// complete software inventory or hide the last valid stored observation.
pub fn observations() -> Vec<Value> {
type Provider = fn() -> Result<Value>;
[
(
"windows.hardware",
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx+GetSystemFirmwareTable;registry:CentralProcessor,BIOS,vmms;cpuid",
hardware as Provider,
),
(
"windows.software",
"windows.registry:HKLM.Uninstall:64+32",
software as Provider,
),
("windows.interfaces", "windows.win32:GetAdaptersAddresses", crate::inventory_sources::interfaces as Provider),
("windows.users", "windows.win32:WTSEnumerateSessions", crate::inventory_sources::users as Provider),
]
.into_iter()
.map(|(scope, source, collect)| {
let data = collect();
let observed = Utc::now();
match data {
Ok(data) => {
let truncated = data
.get("truncated")
.and_then(Value::as_bool)
.unwrap_or(false);
json!({"scope":scope,"source_id":source,"observed_at":observed,"quality":"valid",
"completeness":"partial","truncated":truncated,"error_code":null,"data":data})
}
Err(_) => json!({"scope":scope,"source_id":source,"observed_at":observed,
"quality":"error","completeness":"unknown","truncated":false,
"error_code":"NATIVE_PROVIDER_UNAVAILABLE","data":null}),
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn machine_type_distinguishes_hyper_v_hosts_from_guests() {
let guest = (Some("Microsoft Corporation"), Some("Virtual Machine"));
assert_eq!(
classify_machine(false, false, guest.0, guest.1),
Some(DeviceType::Virtual)
);
assert_eq!(
classify_machine(true, false, guest.0, guest.1),
Some(DeviceType::Hypervisor)
);
assert_eq!(
classify_machine(false, false, Some("QEMU"), Some("Standard PC")),
Some(DeviceType::Virtual)
);
assert_eq!(
classify_machine(false, true, None, None),
Some(DeviceType::Virtual)
);
assert_eq!(
classify_machine(false, false, Some("Dell Inc."), Some("Precision")),
Some(DeviceType::Physical)
);
assert_eq!(classify_machine(false, false, None, None), None);
}
}