Files
rust-discovery/crates/agent-windows/src/native.rs
T
kevin_janssen 52c352c0d9
Rust development slice / linux (push) Failing after 11s
Collect capacity for every Windows fixed drive letter
2026-11-20 08:51:54 +01:00

475 lines
19 KiB
Rust

//! Read-only Windows APIs. The kernel's recorded startup time identifies the boot.
use anyhow::{Context, Result, ensure};
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};
use windows_sys::Win32::{
Foundation::LocalFree,
Security::{
self, ACCESS_ALLOWED_ACE, ACL,
Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT},
DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
},
Storage::FileSystem::{FILE_ATTRIBUTE_REPARSE_POINT, GetDiskFreeSpaceExW},
System::{Registry::*, SystemInformation::*},
};
pub fn wide(value: impl AsRef<std::ffi::OsStr>) -> Vec<u16> {
value.as_ref().encode_wide().chain(Some(0)).collect()
}
fn sid_string(sid: *mut c_void) -> Result<String> {
let mut text = ptr::null_mut();
// SAFETY: SID was returned by the Windows security API; API allocates text.
ensure!(
unsafe { ConvertSidToStringSidW(sid, &mut text) } != 0,
"SID_CONVERSION"
);
let mut len = 0;
unsafe {
while *text.add(len) != 0 {
len += 1;
}
}
let result = String::from_utf16(unsafe { std::slice::from_raw_parts(text, len) })?;
unsafe {
LocalFree(text.cast());
}
Ok(result)
}
/// Verify the actual SCM process token; an administrator probe cannot stand in
/// for this check. No account switching or SYSTEM fallback exists.
pub fn require_local_service() -> Result<()> {
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
let mut token = ptr::null_mut();
ensure!(
unsafe { OpenProcessToken(GetCurrentProcess(), Security::TOKEN_QUERY, &mut token) } != 0,
"SERVICE_TOKEN_REQUIRED"
);
let token = unsafe { OwnedHandle::from_raw_handle(token) };
// Native structures require alignment, even though GetTokenInformation
// accepts a void pointer. Allocate pointer-aligned storage, with fixed cap.
let mut storage = vec![0usize; 256];
let mut size = 0;
ensure!(
unsafe {
Security::GetTokenInformation(
token.as_raw_handle(),
Security::TokenUser,
storage.as_mut_ptr().cast(),
(storage.len() * std::mem::size_of::<usize>()) as u32,
&mut size,
)
} != 0,
"SERVICE_TOKEN_USER"
);
let user = unsafe { &*storage.as_ptr().cast::<Security::TOKEN_USER>() };
ensure!(
sid_string(user.User.Sid)? == "S-1-5-19",
"LOCAL_SERVICE_REQUIRED"
);
// A native SCM probe showed LocalService's unfiltered service token reports
// TokenElevation=1, type=Default, while SID19 has no enabled administrator
// membership. UAC elevation alone is not an account/administrator check.
// Reject thread impersonation before querying effective membership.
use windows_sys::Win32::{
Foundation::{ERROR_NO_TOKEN, GetLastError},
System::Threading::{GetCurrentThread, OpenThreadToken},
};
let mut thread_token = ptr::null_mut();
if unsafe {
OpenThreadToken(
GetCurrentThread(),
Security::TOKEN_QUERY,
1,
&mut thread_token,
)
} != 0
{
let _thread_token = unsafe { OwnedHandle::from_raw_handle(thread_token) };
anyhow::bail!("IMPERSONATED_EXECUTOR_FORBIDDEN");
}
ensure!(
unsafe { GetLastError() } == ERROR_NO_TOKEN,
"THREAD_TOKEN_UNVERIFIED"
);
let mut admin_sid = [0usize; 16];
let mut admin_size = std::mem::size_of_val(&admin_sid) as u32;
ensure!(
unsafe {
Security::CreateWellKnownSid(
Security::WinBuiltinAdministratorsSid,
ptr::null_mut(),
admin_sid.as_mut_ptr().cast(),
&mut admin_size,
)
} != 0,
"ADMINISTRATOR_SID_QUERY"
);
let mut admin_member = 0;
ensure!(
unsafe {
Security::CheckTokenMembership(
ptr::null_mut(),
admin_sid.as_mut_ptr().cast(),
&mut admin_member,
)
} != 0
&& admin_member == 0,
"ADMINISTRATOR_EXECUTOR_FORBIDDEN"
);
Ok(())
}
pub fn service_sid() -> Result<String> {
let account = wide(format!("NT SERVICE\\{}", crate::SERVICE_NAME));
let mut sid_len = 0;
let mut domain_len = 0;
let mut use_type = 0;
unsafe {
Security::LookupAccountNameW(
ptr::null(),
account.as_ptr(),
ptr::null_mut(),
&mut sid_len,
ptr::null_mut(),
&mut domain_len,
&mut use_type,
);
}
ensure!(
sid_len > 0 && sid_len <= 256 && domain_len <= 256,
"SERVICE_SID_REQUIRED"
);
let mut sid = vec![0u8; sid_len as usize];
let mut domain = vec![0u16; domain_len as usize];
ensure!(
unsafe {
Security::LookupAccountNameW(
ptr::null(),
account.as_ptr(),
sid.as_mut_ptr().cast(),
&mut sid_len,
domain.as_mut_ptr(),
&mut domain_len,
&mut use_type,
)
} != 0,
"SERVICE_SID_LOOKUP"
);
sid_string(sid.as_mut_ptr().cast())
}
pub fn private_path(path: &Path, directory: bool) -> Result<()> {
use std::os::windows::fs::MetadataExt;
let metadata = std::fs::symlink_metadata(path)?;
ensure!(
metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0
&& metadata.is_dir() == directory,
"PRIVATE_PATH_TYPE"
);
let allowed = [
"S-1-5-18".to_owned(),
"S-1-5-32-544".to_owned(),
service_sid()?,
];
let name = wide(path);
let mut owner = ptr::null_mut();
let mut dacl: *mut ACL = ptr::null_mut();
let mut descriptor = ptr::null_mut();
// SAFETY: API writes pointers into one allocated descriptor, released below.
let status = unsafe {
GetNamedSecurityInfoW(
name.as_ptr(),
SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
&mut owner,
ptr::null_mut(),
&mut dacl,
ptr::null_mut(),
&mut descriptor,
)
};
ensure!(status == 0, "PRIVATE_PATH_SECURITY");
let result = (|| {
ensure!(
!owner.is_null() && !dacl.is_null(),
"PRIVATE_PATH_NULL_DACL"
);
let owner = sid_string(owner)?;
ensure!(
allowed.contains(&owner) || (!directory && owner == "S-1-5-19"),
"PRIVATE_PATH_OWNER"
);
ensure!(unsafe { (*dacl).AceCount } > 0, "PRIVATE_PATH_EMPTY_DACL");
for n in 0..unsafe { (*dacl).AceCount } {
let mut ace = ptr::null_mut();
ensure!(
unsafe { Security::GetAce(dacl, u32::from(n), &mut ace) } != 0,
"PRIVATE_PATH_ACE"
);
let ace = unsafe { &*ace.cast::<ACCESS_ALLOWED_ACE>() };
ensure!(
ace.Header.AceType == 0
&& usize::from(ace.Header.AceSize) >= std::mem::size_of::<ACCESS_ALLOWED_ACE>(),
"PRIVATE_PATH_ACE_TYPE"
);
let sid = ptr::addr_of!(ace.SidStart).cast_mut().cast();
ensure!(
allowed.contains(&sid_string(sid)?),
"PRIVATE_PATH_BROAD_ACL"
);
}
Ok(())
})();
unsafe {
LocalFree(descriptor.cast());
}
result
}
fn registry_string(name: &str) -> Result<String> {
let key = wide("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
let value_name = wide(name);
let mut bytes = vec![0u16; 2048];
let mut size = (bytes.len() * 2) as u32;
let status = unsafe {
RegGetValueW(
HKEY_LOCAL_MACHINE,
key.as_ptr(),
value_name.as_ptr(),
RRF_RT_REG_SZ,
ptr::null_mut(),
bytes.as_mut_ptr().cast(),
&mut size,
)
};
ensure!(status == 0, "OS_REGISTRY {name} (Win32 {status})");
ensure!(
size >= 2 && size % 2 == 0 && size as usize <= bytes.len() * 2,
"OS_REGISTRY_SIZE {name}"
);
String::from_utf16(&bytes[..size as usize / 2 - 1])
.with_context(|| format!("OS_REGISTRY_ENCODING {name}"))
}
fn os_inventory(read: impl Fn(&str) -> Result<String>) -> Result<(String, Value)> {
let product = read("ProductName")?;
let build = read("CurrentBuildNumber")?;
// Older Windows releases can omit DisplayVersion. Both version labels are
// optional; the product and build still identify the OS without either.
let version = |name| read(name).ok().filter(|s| !s.trim().is_empty());
let display = version("DisplayVersion");
let release = if display.is_none() {
version("ReleaseId")
} else {
None
};
let os = match (&display, &release) {
(Some(display), _) => format!("{product}; DisplayVersion={display}; Build={build}"),
(None, Some(release)) => format!("{product}; ReleaseId={release}; Build={build}"),
(None, None) => format!("{product}; Build={build}"),
};
let mut data = json!({"product_name":product,"display_version":display,"build":build});
if let Some(release) = release {
data["release_id"] = json!(release);
}
Ok((os, data))
}
pub(crate) fn computer_name(format: COMPUTER_NAME_FORMAT) -> Result<String> {
let mut name = [0u16; 256];
let mut len = name.len() as u32;
ensure!(
unsafe { GetComputerNameExW(format, name.as_mut_ptr(), &mut len) } != 0
&& len > 0 && (len as usize) < name.len(),
"HOSTNAME_QUERY"
);
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)
}
fn disk_space(root: &[u16]) -> Option<(u64, u64)> {
let (mut available, mut total) = (0, 0);
(unsafe { GetDiskFreeSpaceExW(root.as_ptr(), &mut available, &mut total, ptr::null_mut()) } != 0
&& total > 0 && available <= total).then_some((available, total))
}
fn fixed_volumes(system: &str, available: u64, total: u64) -> Vec<Value> {
use windows_sys::Win32::Storage::FileSystem::{GetDriveTypeW, GetLogicalDrives};
const DRIVE_FIXED: u32 = 3;
let mask = unsafe { GetLogicalDrives() };
let mut rows = vec![json!({"name":system,"free_bytes":available,"total_bytes":total})];
for letter in b'A'..=b'Z' {
if mask & (1 << (letter - b'A')) == 0 { continue; }
let name = format!("{}:", char::from(letter));
if name.eq_ignore_ascii_case(system) { continue; }
let root = wide(format!("{name}\\"));
if unsafe { GetDriveTypeW(root.as_ptr()) } != DRIVE_FIXED { continue; }
// Retain an identified but unreadable volume without claiming zero usage.
let sizes = disk_space(&root);
rows.push(json!({"name":name,"free_bytes":sizes.map(|s| s.0),"total_bytes":sizes.map(|s| s.1)}));
}
rows
}
pub fn snapshot_with_boot(booted_at: Option<DateTime<Utc>>) -> Result<Value> {
let started = Utc::now();
let hostname = computer_name(ComputerNameDnsHostname)?;
let system = std::env::var("SystemDrive").context("SYSTEM_DRIVE")?.to_ascii_uppercase();
let (available, total) = disk_space(&wide(format!("{system}\\"))).context("VOLUME_QUERY")?;
let volumes = fixed_volumes(&system, available, total);
let (os, mut os_data) = os_inventory(registry_string)?;
os_data["installed_at"] = json!(install_date());
os_data["booted_at"] = json!(booted_at);
let completed = Utc::now();
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;Kernel-General/12","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":os_data},
{"scope":"windows.volumes","source_id":"windows.win32:GetLogicalDrives;GetDriveTypeW;GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available,"drives":volumes}},
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
]});
snapshot["observations"]
.as_array_mut()
.context("INVENTORY_OBSERVATIONS")?
.extend(crate::inventory::observations());
snapshot["collection_completed_at"] = json!(Utc::now());
Ok(snapshot)
}
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")?)
.join("System32/WindowsPowerShell/v1.0/powershell.exe");
let mut command = tokio::process::Command::new(executable);
// LastBootUpTime is adjusted by W32Time while the machine is running.
// Kernel-General records StartTime once at startup. Use the newest record
// in log order and its invariant UTC payload, not its localized message.
const START_TIME: &str = r#"
$ErrorActionPreference = 'Stop'
$filter = @{LogName='System'; ProviderName='Microsoft-Windows-Kernel-General'; Id=12}
$event = Get-WinEvent -FilterHashtable $filter -MaxEvents 1
if ($event.ProviderId -ne [Guid]'a68ca8b7-004f-d7b6-a698-07e2de0f1f5d') { throw 'BOOT_PROVIDER' }
$nodes = @(([xml]$event.ToXml()).Event.EventData.Data | Where-Object { $_.Name -ceq 'StartTime' })
if ($nodes.Count -ne 1) { throw 'BOOT_START_TIME' }
[Xml.XmlConvert]::ToDateTimeOffset($nodes[0].InnerText).UtcTicks.ToString([Globalization.CultureInfo]::InvariantCulture)
"#;
command.args(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", START_TIME]);
command.kill_on_drop(true);
let output = tokio::time::timeout(Duration::from_secs(15), command.output()).await??;
ensure!(
output.status.success() && output.stdout.len() <= 128 && output.stderr.is_empty(),
"BOOT_TIME_QUERY"
);
let text = std::str::from_utf8(&output.stdout)?.trim();
ensure!(
(17..=19).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_digit()),
"BOOT_TIME_FORMAT"
);
// Preserve the wire ID when the old CIM value equals the recorded startup time.
let mut bytes: [u8; 16] = Sha256::digest(format!("rmm.windows.boot.cim.ticks.v1:{text}"))
.as_slice()[..16]
.try_into()?;
bytes[6] = (bytes[6] & 15) | 0x80;
bytes[8] = (bytes[8] & 63) | 0x80;
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)]
mod tests {
fn os_fixture(display: Option<&str>, release: Option<&str>) -> (String, serde_json::Value) {
super::os_inventory(|name| {
match name {
"ProductName" => Some("Windows 10 Enterprise LTSC"),
"CurrentBuildNumber" => Some("17763"),
"DisplayVersion" => display,
"ReleaseId" => release,
_ => panic!("unexpected registry value: {name}"),
}
.map(str::to_owned)
.ok_or_else(|| anyhow::anyhow!("missing {name}"))
})
.unwrap()
}
#[test]
fn os_inventory_prefers_display_version() {
let (os, data) = os_fixture(Some("22H2"), Some("2009"));
assert!(os.contains("DisplayVersion=22H2"));
assert_eq!(data["display_version"], "22H2");
assert!(data.get("release_id").is_none());
}
#[test]
fn os_inventory_uses_legacy_release_id_when_display_version_is_missing() {
let (os, data) = os_fixture(None, Some("1809"));
assert_eq!(os, "Windows 10 Enterprise LTSC; ReleaseId=1809; Build=17763");
assert!(data["display_version"].is_null());
assert_eq!(data["release_id"], "1809");
}
#[test]
fn os_inventory_keeps_product_and_build_without_version_labels() {
for display in [None, Some(" ")] {
let (os, data) = os_fixture(display, None);
assert_eq!(os, "Windows 10 Enterprise LTSC; Build=17763");
assert!(data["display_version"].is_null());
assert_eq!(data["build"], "17763");
}
}
#[test]
fn native_inventory_has_real_windows_sources_and_no_fake_inodes() {
let v = super::snapshot().unwrap();
assert!(v["root_total_bytes"].as_u64().unwrap() > 0);
assert!(v["root_available_inodes"].is_null());
assert!(!v["hostname"].as_str().unwrap().is_empty());
let hardware = v["observations"]
.as_array()
.unwrap()
.iter()
.find(|o| o["scope"] == "windows.hardware")
.unwrap();
assert!(hardware["data"]["memory_total_bytes"].as_u64().unwrap() > 0);
assert!(
hardware["data"]["logical_processors_visible"]
.as_u64()
.unwrap()
> 0
);
assert!(
v["observations"]
.as_array()
.unwrap()
.iter()
.all(|o| o["scope"].as_str().unwrap().starts_with("windows."))
);
}
#[tokio::test]
async fn boot_identity_survives_independent_native_queries() {
assert_eq!(
super::boot_id().await.unwrap(),
super::boot_id().await.unwrap()
);
}
}