Expand the passive inventory shown in device details
Rust development slice / linux (push) Failing after 9s
Rust development slice / linux (push) Failing after 9s
This commit is contained in:
@@ -4,7 +4,7 @@ use crate::{
|
||||
actions::{ServiceUnit, reboot_required},
|
||||
process,
|
||||
};
|
||||
use rmm_domain::inventory_document::{CpuTimes, DeviceType};
|
||||
use rmm_domain::inventory_document::{CpuTimes, DeviceType, firmware_identifier};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
ffi::{CStr, CString},
|
||||
@@ -169,6 +169,9 @@ pub struct OperatingSystem {
|
||||
pub hostname: String,
|
||||
pub boot_id: String,
|
||||
pub uptime_seconds: f64,
|
||||
pub booted_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
pub installed_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
pub install_date_source: Option<&'static str>,
|
||||
}
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct Interface {
|
||||
@@ -260,6 +263,8 @@ pub struct Hardware {
|
||||
pub readable_dmi: BTreeMap<String, String>,
|
||||
pub device_type: Option<DeviceType>,
|
||||
pub proxmox_ve: bool,
|
||||
pub manufacturer: Option<String>,
|
||||
pub bios_serial_number: Option<String>,
|
||||
}
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct LinuxInventory {
|
||||
@@ -271,6 +276,7 @@ pub struct LinuxInventory {
|
||||
pub dns: Observation<Dns>,
|
||||
pub volumes: Observation<Vec<Observation<Volume>>>,
|
||||
pub software: Observation<Vec<SoftwarePackage>>,
|
||||
pub users: Observation<Vec<String>>,
|
||||
pub updates: Observation<UpdateStatus>,
|
||||
pub hardware: Observation<Hardware>,
|
||||
pub smart: Observation<()>,
|
||||
@@ -285,6 +291,7 @@ pub fn collect_native() -> LinuxInventory {
|
||||
dns: dns(),
|
||||
volumes: volumes(),
|
||||
software: software(),
|
||||
users: logged_in_users(),
|
||||
updates: updates(),
|
||||
hardware: hardware(),
|
||||
smart: Observation::unavailable(
|
||||
@@ -380,6 +387,22 @@ pub fn capabilities() -> BTreeMap<String, Observation<bool>> {
|
||||
);
|
||||
result
|
||||
}
|
||||
fn installed_at() -> Option<(chrono::DateTime<chrono::Utc>, &'static str)> {
|
||||
for (path, source) in [
|
||||
("/var/log/installer", "installer_directory"),
|
||||
("/", "root_filesystem"),
|
||||
] {
|
||||
if let Some(time) = fs::metadata(path)
|
||||
.ok()
|
||||
.and_then(|data| data.created().ok())
|
||||
.filter(|time| *time > SystemTime::UNIX_EPOCH && *time <= SystemTime::now())
|
||||
{
|
||||
return Some((time.into(), source));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn operating_system() -> Observation<OperatingSystem> {
|
||||
let release = read("/etc/os-release", 32 * 1024);
|
||||
let kernel = read("/proc/sys/kernel/osrelease", 4096);
|
||||
@@ -417,8 +440,21 @@ pub fn operating_system() -> Observation<OperatingSystem> {
|
||||
.map(|(k, v)| (k.into(), v.trim_matches('"').into()))
|
||||
})
|
||||
.collect();
|
||||
let booted_at = read("/proc/stat", 256 * 1024)
|
||||
.data
|
||||
.as_deref()
|
||||
.and_then(|stat| {
|
||||
let seconds = stat
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("btime "))?
|
||||
.trim()
|
||||
.parse()
|
||||
.ok()?;
|
||||
chrono::DateTime::from_timestamp(seconds, 0)
|
||||
});
|
||||
let installed = installed_at();
|
||||
Observation::valid(
|
||||
"linux.os:/etc/os-release,/proc",
|
||||
"linux.os:/etc/os-release,/proc,filesystem-birth",
|
||||
OperatingSystem {
|
||||
release,
|
||||
kernel: kernel.trim().into(),
|
||||
@@ -426,12 +462,74 @@ pub fn operating_system() -> Observation<OperatingSystem> {
|
||||
hostname: hostname.trim().into(),
|
||||
boot_id,
|
||||
uptime_seconds,
|
||||
booted_at,
|
||||
installed_at: installed.map(|(time, _)| time),
|
||||
install_date_source: installed.map(|(_, source)| source),
|
||||
},
|
||||
)
|
||||
} else {
|
||||
Observation::unavailable("linux.os", Quality::Error, "OS_SOURCE_UNAVAILABLE")
|
||||
}
|
||||
}
|
||||
|
||||
fn logged_in_users() -> Observation<Vec<String>> {
|
||||
const LOGINCTL: &str = "/usr/bin/loginctl";
|
||||
let listed = command(
|
||||
LOGINCTL,
|
||||
&["--no-legend", "--no-pager", "list-sessions"],
|
||||
16 * 1024,
|
||||
);
|
||||
let Some(rows) = &listed.data else {
|
||||
return map(listed, |_| None);
|
||||
};
|
||||
let mut ids = rows
|
||||
.lines()
|
||||
.filter_map(|line| line.split_whitespace().next());
|
||||
let mut args = vec![
|
||||
"--no-pager",
|
||||
"--all",
|
||||
"--property=Name,Class,State",
|
||||
"show-session",
|
||||
"--",
|
||||
];
|
||||
args.extend(
|
||||
ids.by_ref()
|
||||
.take(64)
|
||||
.filter(|id| id.bytes().all(|c| c.is_ascii_alphanumeric())),
|
||||
);
|
||||
let limited = listed.truncated || ids.next().is_some();
|
||||
if args.len() == 5 {
|
||||
return Observation::valid("linux.logind:loginctl", Vec::new());
|
||||
}
|
||||
let mut report = map(command(LOGINCTL, &args, 16 * 1024), |text| {
|
||||
let users: std::collections::BTreeSet<_> = text
|
||||
.split("\n\n")
|
||||
.filter_map(|block| {
|
||||
let fields: BTreeMap<_, _> = block
|
||||
.lines()
|
||||
.filter_map(|line| line.split_once('='))
|
||||
.collect();
|
||||
let class = *fields.get("Class")?;
|
||||
let state = *fields.get("State")?;
|
||||
let name = *fields.get("Name")?;
|
||||
(matches!(
|
||||
class,
|
||||
"user" | "user-early" | "user-light" | "user-early-light"
|
||||
) && matches!(state, "online" | "active")
|
||||
&& !name.is_empty()
|
||||
&& name.len() <= 255)
|
||||
.then(|| name.to_owned())
|
||||
})
|
||||
.collect();
|
||||
Some(users.into_iter().collect())
|
||||
});
|
||||
report.source_id = "linux.logind:loginctl".into();
|
||||
if limited && report.data.is_some() {
|
||||
report = report.partial("SESSION_LIMIT");
|
||||
report.truncated = true;
|
||||
}
|
||||
report
|
||||
}
|
||||
fn aggregate_jiffies(stat: &str) -> Option<Vec<u64>> {
|
||||
stat.lines()
|
||||
.find(|line| line.starts_with("cpu "))
|
||||
@@ -583,11 +681,12 @@ pub fn interfaces() -> Observation<Vec<Interface>> {
|
||||
}
|
||||
libc::AF_INET6 => {
|
||||
let addr = &*item.ifa_addr.cast::<libc::sockaddr_in6>();
|
||||
addresses.push(format!(
|
||||
"{}%{}",
|
||||
Ipv6Addr::from(addr.sin6_addr.s6_addr),
|
||||
addr.sin6_scope_id
|
||||
));
|
||||
let ip = Ipv6Addr::from(addr.sin6_addr.s6_addr);
|
||||
addresses.push(if addr.sin6_scope_id == 0 {
|
||||
ip.to_string()
|
||||
} else {
|
||||
format!("{ip}%{}", addr.sin6_scope_id)
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -1194,7 +1293,20 @@ pub fn hardware() -> Observation<Hardware> {
|
||||
let proxmox_ve =
|
||||
Path::new("/usr/bin/pveversion").is_file() && Path::new("/usr/bin/pvedaemon").is_file();
|
||||
let device_type = machine_type(proxmox_ve);
|
||||
if readable_dmi.is_empty() && device_type.is_none() {
|
||||
let manufacturer = readable_dmi
|
||||
.get("sys_vendor")
|
||||
.and_then(|value| firmware_identifier(value));
|
||||
let serial_credential = std::env::var_os("CREDENTIALS_DIRECTORY")
|
||||
.map(|directory| std::path::PathBuf::from(directory).join("rmm-bios-serial"));
|
||||
let bios_serial_number = [
|
||||
Some("/sys/class/dmi/id/product_serial"),
|
||||
Some("/proc/device-tree/serial-number"),
|
||||
serial_credential.as_deref().and_then(Path::to_str),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find_map(|path| sys_text(path).and_then(|value| firmware_identifier(&value)));
|
||||
if readable_dmi.is_empty() && device_type.is_none() && bios_serial_number.is_none() {
|
||||
Observation::unavailable(SOURCE, Quality::Unsupported, "HARDWARE_UNAVAILABLE")
|
||||
} else {
|
||||
Observation::valid(
|
||||
@@ -1203,6 +1315,8 @@ pub fn hardware() -> Observation<Hardware> {
|
||||
readable_dmi,
|
||||
device_type,
|
||||
proxmox_ve,
|
||||
manufacturer,
|
||||
bios_serial_number,
|
||||
},
|
||||
)
|
||||
.partial("NO_SMART_OR_ENCRYPTION_PROOF")
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Additive JSON observation mapping inside the existing snapshot payload. This
|
||||
//! does not introduce a protobuf tag, a fabricated receive time or a new scope.
|
||||
//! does not introduce a protobuf tag or a fabricated receive time.
|
||||
use anyhow::Result;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -14,7 +14,12 @@ pub fn observations(inventory: &crate::inventory::LinuxInventory) -> Result<Vec<
|
||||
observation["scope"] = json!(format!("linux.{name}"));
|
||||
// Bound each scope independently. Never drop unsupported/error metadata
|
||||
// or imply that absent/truncated rows were deleted from a device.
|
||||
while serde_json::to_vec(&observation)?.len() > 32768 {
|
||||
let max_bytes = if name == "software" {
|
||||
rmm_domain::inventory_document::SOFTWARE_OBSERVATION_MAX_BYTES
|
||||
} else {
|
||||
32768
|
||||
};
|
||||
while serde_json::to_vec(&observation)?.len() > max_bytes {
|
||||
observation["truncated"] = json!(true);
|
||||
observation["completeness"] = json!("partial");
|
||||
observation["error_code"] = json!("WIRE_SCOPE_LIMIT");
|
||||
@@ -49,7 +54,7 @@ mod tests {
|
||||
fn native_wire_scopes_preserve_quality_time_and_unsupported() {
|
||||
let native = crate::inventory::collect_native();
|
||||
let mapped = observations(&native).unwrap();
|
||||
assert_eq!(mapped.len(), 11);
|
||||
assert_eq!(mapped.len(), 12);
|
||||
let smart = mapped.iter().find(|v| v["scope"] == "linux.smart").unwrap();
|
||||
assert_eq!(smart["quality"], "unsupported");
|
||||
assert!(smart["data"].is_null());
|
||||
@@ -61,7 +66,12 @@ mod tests {
|
||||
);
|
||||
assert!(!observation["source_id"].as_str().unwrap().is_empty());
|
||||
assert!(observation.get("received_at").is_none());
|
||||
assert!(serde_json::to_vec(observation).unwrap().len() <= 32768);
|
||||
let limit = if observation["scope"] == "linux.software" {
|
||||
rmm_domain::inventory_document::SOFTWARE_OBSERVATION_MAX_BYTES
|
||||
} else {
|
||||
32768
|
||||
};
|
||||
assert!(serde_json::to_vec(observation).unwrap().len() <= limit);
|
||||
}
|
||||
let base = snapshot(false).unwrap();
|
||||
assert!(serde_json::from_value::<rmm_domain::Inventory>(base).is_ok());
|
||||
|
||||
@@ -52,7 +52,7 @@ rcgen = { version = "=0.14.10", default-features = false, features = ["crypto",
|
||||
cc = "=1.11.1"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading", "Win32_System_Shutdown"] }
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_RemoteDesktop", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading", "Win32_System_Shutdown"] }
|
||||
|
||||
[[example]]
|
||||
name = "windows_reviewed_recovery"
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
//! uninstall commands; registry entries are evidence, not verified MSI state.
|
||||
use anyhow::{Result, ensure};
|
||||
use chrono::Utc;
|
||||
use rmm_domain::inventory_document::{CpuTimes, DeviceType};
|
||||
use rmm_domain::inventory_document::{
|
||||
CpuTimes, DeviceType, SOFTWARE_OBSERVATION_MAX_BYTES, firmware_identifier,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
mem::{size_of, zeroed},
|
||||
@@ -120,28 +122,18 @@ fn classify_machine(
|
||||
(!manufacturer.is_empty() && !product.is_empty()).then_some(DeviceType::Physical)
|
||||
}
|
||||
|
||||
fn machine_type() -> Option<DeviceType> {
|
||||
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();
|
||||
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())
|
||||
};
|
||||
classify_machine(
|
||||
hyper_v_host,
|
||||
non_microsoft_hypervisor(),
|
||||
read("SystemManufacturer").as_deref(),
|
||||
read("SystemProductName").as_deref(),
|
||||
manufacturer,
|
||||
product,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -201,16 +193,34 @@ fn hardware() -> Result<Value> {
|
||||
.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()}),
|
||||
"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;
|
||||
@@ -232,7 +242,7 @@ fn software() -> Result<Value> {
|
||||
}
|
||||
};
|
||||
for index in 0..2048 {
|
||||
if began.elapsed() > Duration::from_millis(250) || entries.len() >= 64 {
|
||||
if began.elapsed() > Duration::from_millis(250) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
@@ -274,12 +284,12 @@ fn software() -> Result<Value> {
|
||||
})();
|
||||
match entry {
|
||||
Ok(Some(entry)) => {
|
||||
entries.push(entry);
|
||||
if serde_json::to_vec(&entries)?.len() > 12288 {
|
||||
entries.pop();
|
||||
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,
|
||||
@@ -310,7 +320,7 @@ pub fn observations() -> Vec<Value> {
|
||||
[
|
||||
(
|
||||
"windows.hardware",
|
||||
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx;registry:CentralProcessor,BIOS,vmms;cpuid",
|
||||
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx+GetSystemFirmwareTable;registry:CentralProcessor,BIOS,vmms;cpuid",
|
||||
hardware as Provider,
|
||||
),
|
||||
(
|
||||
@@ -318,6 +328,8 @@ pub fn observations() -> Vec<Value> {
|
||||
"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)| {
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
//! Local read-only inventory providers. Each result is bounded independently.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_domain::inventory_document::firmware_identifier;
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
ffi::c_void,
|
||||
mem::size_of,
|
||||
net::{Ipv4Addr, Ipv6Addr},
|
||||
ptr, slice,
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{ERROR_BUFFER_OVERFLOW, ERROR_NO_DATA, ERROR_SUCCESS},
|
||||
NetworkManagement::IpHelper::*,
|
||||
Networking::WinSock::{
|
||||
AF_INET, AF_INET6, AF_UNSPEC, SOCKADDR_IN, SOCKADDR_IN6, SOCKET_ADDRESS,
|
||||
},
|
||||
System::{
|
||||
RemoteDesktop::*,
|
||||
SystemInformation::{GetSystemFirmwareTable, RSMB},
|
||||
},
|
||||
};
|
||||
|
||||
pub(crate) fn bios_serial() -> Option<String> {
|
||||
let length = unsafe { GetSystemFirmwareTable(RSMB, 0, ptr::null_mut(), 0) };
|
||||
if !(8..=1024 * 1024).contains(&length) {
|
||||
return None;
|
||||
}
|
||||
let mut data = vec![0; length as usize];
|
||||
if unsafe { GetSystemFirmwareTable(RSMB, 0, data.as_mut_ptr(), length) } != length {
|
||||
return None;
|
||||
}
|
||||
let count = u32::from_le_bytes(data[4..8].try_into().ok()?) as usize;
|
||||
smbios_serial(data.get(8..)?.get(..count)?)
|
||||
}
|
||||
|
||||
fn smbios_serial(mut table: &[u8]) -> Option<String> {
|
||||
while let Some(header) = table.get(..4) {
|
||||
let length = usize::from(header[1]);
|
||||
if length < 4 || header[0] == 127 {
|
||||
break;
|
||||
}
|
||||
let strings = table.get(length..)?;
|
||||
let end = strings.windows(2).position(|pair| pair == [0, 0])?;
|
||||
if header[0] == 1 {
|
||||
let offset = usize::from(*table.get(..length)?.get(7)?).checked_sub(1)?;
|
||||
let serial = strings[..end].split(|&c| c == 0).nth(offset)?;
|
||||
return firmware_identifier(std::str::from_utf8(serial).ok()?);
|
||||
}
|
||||
table = strings.get(end + 2..)?;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// Pointer fields returned by IP Helper refer into its caller-provided buffer.
|
||||
fn at<T>(buffer: &[u64], pointer: *const T) -> Option<&T> {
|
||||
let offset = (pointer as usize).checked_sub(buffer.as_ptr() as usize)?;
|
||||
if offset.checked_add(size_of::<T>())? > std::mem::size_of_val(buffer) || !pointer.is_aligned()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(unsafe { &*pointer })
|
||||
}
|
||||
|
||||
fn wide_name(buffer: &[u64], pointer: *const u16) -> Option<String> {
|
||||
let mut text = Vec::new();
|
||||
for i in 0..256 {
|
||||
let character = *at(buffer, pointer.wrapping_add(i))?;
|
||||
if character == 0 {
|
||||
return (!text.is_empty()).then(|| String::from_utf16_lossy(&text));
|
||||
}
|
||||
text.push(character);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn ip_address(buffer: &[u64], address: SOCKET_ADDRESS) -> Option<String> {
|
||||
let sockaddr = at(buffer, address.lpSockaddr)?;
|
||||
match sockaddr.sa_family {
|
||||
AF_INET if address.iSockaddrLength >= size_of::<SOCKADDR_IN>() as i32 => {
|
||||
let ipv4 = at(buffer, address.lpSockaddr.cast::<SOCKADDR_IN>())?;
|
||||
Some(Ipv4Addr::from(unsafe { ipv4.sin_addr.S_un.S_addr }.to_ne_bytes()).to_string())
|
||||
}
|
||||
AF_INET6 if address.iSockaddrLength >= size_of::<SOCKADDR_IN6>() as i32 => {
|
||||
let ipv6 = at(buffer, address.lpSockaddr.cast::<SOCKADDR_IN6>())?;
|
||||
let ip = Ipv6Addr::from(unsafe { ipv6.sin6_addr.u.Byte });
|
||||
let scope = unsafe { ipv6.Anonymous.sin6_scope_id };
|
||||
Some(if scope == 0 {
|
||||
ip.to_string()
|
||||
} else {
|
||||
format!("{ip}%{scope}")
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn interfaces() -> Result<Value> {
|
||||
let mut bytes = 15360_u32;
|
||||
let mut buffer = vec![0_u64; (bytes as usize).div_ceil(8)];
|
||||
let flags = GAA_FLAG_SKIP_ANYCAST
|
||||
| GAA_FLAG_SKIP_MULTICAST
|
||||
| GAA_FLAG_SKIP_DNS_SERVER
|
||||
| GAA_FLAG_INCLUDE_ALL_INTERFACES;
|
||||
let mut status = unsafe {
|
||||
GetAdaptersAddresses(
|
||||
u32::from(AF_UNSPEC),
|
||||
flags,
|
||||
ptr::null(),
|
||||
buffer.as_mut_ptr().cast(),
|
||||
&mut bytes,
|
||||
)
|
||||
};
|
||||
if status == ERROR_BUFFER_OVERFLOW && bytes <= 1024 * 1024 {
|
||||
buffer.resize((bytes as usize).div_ceil(8), 0);
|
||||
status = unsafe {
|
||||
GetAdaptersAddresses(
|
||||
u32::from(AF_UNSPEC),
|
||||
flags,
|
||||
ptr::null(),
|
||||
buffer.as_mut_ptr().cast(),
|
||||
&mut bytes,
|
||||
)
|
||||
};
|
||||
}
|
||||
if status == ERROR_NO_DATA {
|
||||
return Ok(json!({"entries":[],"truncated":false}));
|
||||
}
|
||||
ensure!(status == ERROR_SUCCESS, "ADAPTER_ADDRESSES");
|
||||
let mut current = buffer.as_ptr().cast::<IP_ADAPTER_ADDRESSES_LH>();
|
||||
let mut entries = Vec::new();
|
||||
let mut truncated = false;
|
||||
let mut size = 0;
|
||||
while !current.is_null() && entries.len() < 128 {
|
||||
let adapter = at(&buffer, current).context("ADAPTER_POINTER")?;
|
||||
let mut next = adapter.FirstUnicastAddress.cast_const();
|
||||
let mut addresses = BTreeSet::new();
|
||||
for _ in 0..64 {
|
||||
if next.is_null() {
|
||||
break;
|
||||
}
|
||||
let address = at(&buffer, next).context("ADAPTER_ADDRESS_POINTER")?;
|
||||
if let Some(ip) = ip_address(&buffer, address.Address) {
|
||||
addresses.insert(ip);
|
||||
}
|
||||
next = address.Next.cast_const();
|
||||
}
|
||||
truncated |= !next.is_null();
|
||||
let name = wide_name(&buffer, adapter.FriendlyName)
|
||||
.or_else(|| wide_name(&buffer, adapter.Description))
|
||||
.unwrap_or_else(|| {
|
||||
format!("Adapter {}", unsafe {
|
||||
adapter.Anonymous1.Anonymous.IfIndex
|
||||
})
|
||||
});
|
||||
let mac = adapter
|
||||
.PhysicalAddress
|
||||
.get(..adapter.PhysicalAddressLength as usize)
|
||||
.filter(|bytes| !bytes.is_empty())
|
||||
.map(|bytes| {
|
||||
bytes
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(":")
|
||||
});
|
||||
let entry = json!({"name":name,"addresses":addresses,"mac":mac});
|
||||
size += serde_json::to_vec(&entry)?.len() + 1;
|
||||
if size > 30 * 1024 {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
entries.push(entry);
|
||||
current = adapter.Next.cast_const();
|
||||
}
|
||||
Ok(json!({"entries":entries,"truncated":truncated || !current.is_null()}))
|
||||
}
|
||||
|
||||
struct WtsMemory(*mut c_void);
|
||||
impl Drop for WtsMemory {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
unsafe { WTSFreeMemory(self.0) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn session_text(id: u32, class: WTS_INFO_CLASS) -> Option<String> {
|
||||
let mut text = ptr::null_mut();
|
||||
let mut bytes = 0;
|
||||
if unsafe { WTSQuerySessionInformationW(ptr::null_mut(), id, class, &mut text, &mut bytes) }
|
||||
== 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let _guard = WtsMemory(text.cast());
|
||||
if text.is_null() || !(2..=512).contains(&bytes) || bytes % 2 != 0 {
|
||||
return None;
|
||||
}
|
||||
let units = unsafe { slice::from_raw_parts(text, (bytes / 2) as usize) };
|
||||
String::from_utf16(units.split(|c| *c == 0).next()?).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn users() -> Result<Value> {
|
||||
let mut list = ptr::null_mut();
|
||||
let mut count = 0;
|
||||
ensure!(
|
||||
unsafe { WTSEnumerateSessionsW(ptr::null_mut(), 0, 1, &mut list, &mut count) } != 0,
|
||||
"SESSION_QUERY"
|
||||
);
|
||||
let _guard = WtsMemory(list.cast());
|
||||
let mut entries = BTreeSet::new();
|
||||
let mut errors = 0;
|
||||
let mut truncated = count > 256;
|
||||
if count != 0 {
|
||||
ensure!(!list.is_null(), "SESSION_LIST");
|
||||
for session in unsafe { slice::from_raw_parts(list, count.min(256) as usize) } {
|
||||
if session.SessionId == 0
|
||||
|| ![WTSActive, WTSConnected, WTSDisconnected].contains(&session.State)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match session_text(session.SessionId, WTSUserName) {
|
||||
Some(name) if !name.is_empty() => {
|
||||
let account = match session_text(session.SessionId, WTSDomainName) {
|
||||
Some(domain) if !domain.is_empty() => format!("{domain}\\{name}"),
|
||||
_ => name,
|
||||
};
|
||||
if entries.len() >= 64 {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
if account.len() <= 255 && !account.chars().any(char::is_control) {
|
||||
entries.insert(account);
|
||||
} else {
|
||||
errors += 1;
|
||||
}
|
||||
}
|
||||
Some(_) => {}
|
||||
None => errors += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
errors == 0 || !entries.is_empty(),
|
||||
"SESSION_INFORMATION_UNAVAILABLE"
|
||||
);
|
||||
Ok(json!({"entries":entries,"read_errors":errors,"truncated":truncated}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::smbios_serial;
|
||||
|
||||
#[test]
|
||||
fn reads_the_system_serial_and_rejects_incomplete_entries() {
|
||||
assert_eq!(
|
||||
smbios_serial(b"\x01\x08\x00\x00\x01\x00\x00\x02Vendor\0ABC-123\0\0").as_deref(),
|
||||
Some("ABC-123")
|
||||
);
|
||||
assert_eq!(
|
||||
smbios_serial(b"\x01\x08\x00\x00\x01\x00\x00\x02Vendor\0ABC-123\0"),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ pub mod helper_system;
|
||||
pub mod windows_update_setup;
|
||||
#[cfg(windows)]
|
||||
pub mod inventory;
|
||||
mod inventory_sources;
|
||||
#[cfg(windows)]
|
||||
pub mod job_binding;
|
||||
pub mod journal;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Read-only Windows APIs. The kernel's recorded startup time identifies the boot.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use chrono::Utc;
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{ffi::c_void, os::windows::ffi::OsStrExt, path::Path, ptr, time::Duration};
|
||||
@@ -261,7 +261,23 @@ pub(crate) fn computer_name(format: COMPUTER_NAME_FORMAT) -> Result<String> {
|
||||
Ok(String::from_utf16(&name[..len as usize])?)
|
||||
}
|
||||
|
||||
fn install_date() -> Option<DateTime<Utc>> {
|
||||
let key = wide(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
|
||||
let name = wide("InstallDate");
|
||||
let mut seconds = 0_u32;
|
||||
let mut bytes = size_of::<u32>() as u32;
|
||||
let status = unsafe { RegGetValueW(HKEY_LOCAL_MACHINE,key.as_ptr(),name.as_ptr(),RRF_RT_REG_DWORD,
|
||||
ptr::null_mut(),ptr::from_mut(&mut seconds).cast(),&mut bytes) };
|
||||
(status == 0 && bytes as usize == size_of::<u32>() && seconds > 0)
|
||||
.then(|| DateTime::from_timestamp(i64::from(seconds), 0))
|
||||
.flatten().filter(|time| *time <= Utc::now())
|
||||
}
|
||||
|
||||
pub fn snapshot() -> Result<Value> {
|
||||
snapshot_with_boot(None)
|
||||
}
|
||||
|
||||
pub fn snapshot_with_boot(booted_at: Option<DateTime<Utc>>) -> Result<Value> {
|
||||
let started = Utc::now();
|
||||
let hostname = computer_name(ComputerNameDnsHostname)?;
|
||||
let volume = wide(std::env::var("SystemDrive").context("SYSTEM_DRIVE")? + "\\");
|
||||
@@ -281,7 +297,7 @@ pub fn snapshot() -> Result<Value> {
|
||||
let mut snapshot = json!({"os":os,"hostname":hostname,"architecture":std::env::consts::ARCH,"root_total_bytes":total,"root_available_bytes":available,"root_available_inodes":null,
|
||||
"collection_started_at":started,"collection_completed_at":completed,
|
||||
"observations":[
|
||||
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build}},
|
||||
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW;Kernel-General/12","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build,"installed_at":install_date(),"booted_at":booted_at}},
|
||||
{"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}},
|
||||
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
|
||||
]});
|
||||
@@ -292,7 +308,7 @@ pub fn snapshot() -> Result<Value> {
|
||||
snapshot["collection_completed_at"] = json!(Utc::now());
|
||||
Ok(snapshot)
|
||||
}
|
||||
pub async fn boot_id() -> Result<String> {
|
||||
pub async fn boot_identity() -> Result<(String, DateTime<Utc>)> {
|
||||
// Fixed passive query only. Never interpolates a job or caller-supplied code.
|
||||
// Avoid Win32_Product: it can cause MSI consistency checks and repairs.
|
||||
let executable = Path::new(&std::env::var("SystemRoot")?)
|
||||
@@ -328,7 +344,14 @@ if ($nodes.Count -ne 1) { throw 'BOOT_START_TIME' }
|
||||
.try_into()?;
|
||||
bytes[6] = (bytes[6] & 15) | 0x80;
|
||||
bytes[8] = (bytes[8] & 63) | 0x80;
|
||||
Ok(uuid::Uuid::from_bytes(bytes).to_string())
|
||||
let ticks = text.parse::<i64>()?.checked_sub(621_355_968_000_000_000).context("BOOT_EPOCH")?;
|
||||
let time = DateTime::from_timestamp(ticks.div_euclid(10_000_000), ticks.rem_euclid(10_000_000) as u32 * 100)
|
||||
.context("BOOT_EPOCH")?;
|
||||
Ok((uuid::Uuid::from_bytes(bytes).to_string(),time))
|
||||
}
|
||||
|
||||
pub async fn boot_id() -> Result<String> {
|
||||
boot_identity().await.map(|(id, _)| id)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -631,6 +631,7 @@ struct Agent {
|
||||
certificates: RotationStore,
|
||||
key_files: ProtectedKeyFiles,
|
||||
boot: String,
|
||||
booted_at: chrono::DateTime<Utc>,
|
||||
instance: String,
|
||||
started: Instant,
|
||||
binding: Option<Binding>,
|
||||
@@ -2420,8 +2421,8 @@ impl Agent {
|
||||
if self.journal.count()? > 0 || !jobs::events(self.journal.connection())?.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let data = serde_json::to_vec(&native::snapshot()?)?;
|
||||
ensure!(data.len() <= 32768, "WINDOWS_INVENTORY_LIMIT");
|
||||
let data = serde_json::to_vec(&native::snapshot_with_boot(Some(self.booted_at))?)?;
|
||||
ensure!(data.len() <= 256 * 1024, "WINDOWS_INVENTORY_LIMIT");
|
||||
let envelope = self.envelope(
|
||||
generation,
|
||||
Payload::InventorySnapshot(InventorySnapshot {
|
||||
@@ -2537,7 +2538,7 @@ impl Agent {
|
||||
};
|
||||
self.renew_certificate(admission.as_deref()).await?;
|
||||
}
|
||||
self.boot = native::boot_id().await?;
|
||||
(self.boot, self.booted_at) = native::boot_identity().await?;
|
||||
let advertised = self.capabilities();
|
||||
let hello = self.envelope(
|
||||
0,
|
||||
@@ -2819,7 +2820,7 @@ impl Agent {
|
||||
self.replay(&channel, generation).await?;
|
||||
replay = Instant::now();
|
||||
}
|
||||
if !stop.load(Ordering::SeqCst) && inventory.elapsed() >= Duration::from_secs(86400) {
|
||||
if !stop.load(Ordering::SeqCst) && inventory.elapsed() >= Duration::from_secs(300) {
|
||||
self.queue_inventory(generation)?;
|
||||
inventory = Instant::now();
|
||||
}
|
||||
@@ -2929,7 +2930,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
let identity = enrollment(&config, &ca).await?;
|
||||
let mut journal=journal;
|
||||
journal.pin_identity(&identity.agent_id)?;
|
||||
let boot = native::boot_id().await?;
|
||||
let (boot, booted_at) = native::boot_identity().await?;
|
||||
let binding=config.job_binding_file.as_deref().map(readonly_binding).transpose()?;
|
||||
#[cfg(feature = "system-helper")]
|
||||
let binding = if let Some(policy) = &config.localservice_time_policy {
|
||||
@@ -2979,6 +2980,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
certificates,
|
||||
key_files,
|
||||
boot,
|
||||
booted_at,
|
||||
instance: Uuid::new_v4().to_string(),
|
||||
started: Instant::now(), binding, ledger, _ledger_file:ledger_file, clock, sync,
|
||||
#[cfg(feature="system-helper")]
|
||||
@@ -3075,8 +3077,8 @@ pub fn main() -> Result<()> {
|
||||
}
|
||||
if args == ["--native-probe"] {
|
||||
let runtime = tokio::runtime::Runtime::new()?;
|
||||
let boot = runtime.block_on(native::boot_id())?;
|
||||
let inventory = native::snapshot()?;
|
||||
let (boot, booted_at) = runtime.block_on(native::boot_identity())?;
|
||||
let inventory = native::snapshot_with_boot(Some(booted_at))?;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"platform":"windows","architecture":std::env::consts::ARCH,"hostname_available":!inventory["hostname"].as_str().unwrap_or("").is_empty(),"system_volume_available":inventory["root_available_bytes"].as_u64().is_some(),"inodes":null,"boot_id":boot,"capabilities":CAPABILITIES,"jobs_supported":false})
|
||||
|
||||
@@ -3,6 +3,20 @@ use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
pub const SOFTWARE_OBSERVATION_MAX_BYTES: usize = 128 * 1024;
|
||||
|
||||
pub fn firmware_identifier(value: &str) -> Option<String> {
|
||||
let value = value.trim_matches(|c: char| c == '\0' || c.is_whitespace());
|
||||
let lower = value.to_ascii_lowercase();
|
||||
(!value.is_empty()
|
||||
&& value.len() <= 255
|
||||
&& !value.chars().any(char::is_control)
|
||||
&& !matches!(lower.as_str(), "none" | "unknown" | "not specified" | "not applicable"
|
||||
| "default string" | "to be filled by o.e.m." | "system serial number")
|
||||
&& !value.bytes().all(|b| b == b'0'))
|
||||
.then(|| value.to_owned())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum DeviceType {
|
||||
@@ -152,10 +166,15 @@ pub fn validate_for_scope(
|
||||
}
|
||||
let mut scopes = std::collections::BTreeSet::new();
|
||||
for item in observations {
|
||||
let max_bytes = match (scope, item["scope"].as_str()) {
|
||||
("linux.base", Some("linux.software")) | ("windows.base", Some("windows.software")) =>
|
||||
SOFTWARE_OBSERVATION_MAX_BYTES,
|
||||
_ => 32768,
|
||||
};
|
||||
if serde_json::to_vec(item)
|
||||
.map_err(|_| "INVALID_OBSERVATION")?
|
||||
.len()
|
||||
> 32768
|
||||
> max_bytes
|
||||
{
|
||||
return Err("OBSERVATION_SIZE");
|
||||
}
|
||||
|
||||
@@ -470,6 +470,30 @@ WantedBy=timers.target
|
||||
}
|
||||
|
||||
|
||||
def provision_serial_credential():
|
||||
# DMI serial files usually require root. Pass this one value to the agent
|
||||
# through systemd's read-only per-service credentials directory.
|
||||
source = Path('/sys/class/dmi/id/product_serial')
|
||||
try:
|
||||
with source.open('rb') as stream:
|
||||
serial = stream.read(256).strip()
|
||||
except OSError:
|
||||
return
|
||||
if not serial or len(serial) >= 255:
|
||||
return
|
||||
target = ROOT / 'bios-serial'
|
||||
dropin = UNIT_DIR / (SERVICE + '.d') / '40-inventory-serial.conf'
|
||||
content = f'[Service]\nLoadCredential=rmm-bios-serial:{target}\n'.encode()
|
||||
require(not dropin.parent.is_symlink(), 'hardware credential directory conflict')
|
||||
if dropin.exists() or dropin.is_symlink():
|
||||
require(not dropin.is_symlink() and dropin.read_bytes() == content, 'hardware credential configuration conflict')
|
||||
else:
|
||||
dropin.parent.mkdir(mode=0o755, exist_ok=True)
|
||||
save(target, serial, 0o600)
|
||||
if not dropin.exists():
|
||||
save(dropin, content)
|
||||
|
||||
|
||||
def enable():
|
||||
for name, data in units().items():
|
||||
path = UNIT_DIR / name
|
||||
@@ -477,6 +501,7 @@ def enable():
|
||||
require(path.read_bytes() == data.encode(), 'service file conflict: ' + name)
|
||||
else:
|
||||
save(path, data.encode())
|
||||
provision_serial_credential()
|
||||
service('daemon-reload')
|
||||
service('enable', '--now', SERVICE)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user