From bde11186f80854d5beb18eb317838366dafd578e Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Tue, 17 Nov 2026 00:09:51 +0800 Subject: [PATCH] feat: collect native HIP facts and log redacted XML responses --- Cargo.lock | 2 + apps/gpservice/src/hip_source.rs | 32 +- crates/gpapi/Cargo.toml | 2 +- crates/gpapi/src/gateway/session.rs | 15 +- crates/gpapi/src/os_profile/desktop/mod.rs | 9 +- crates/gpapi/src/os_profile/desktop/tests.rs | 87 ++++- .../gpapi/src/os_profile/desktop/windows.rs | 78 +++- crates/gpapi/src/os_profile/profile.rs | 3 +- crates/gpapi/src/os_profile/tests.rs | 12 +- crates/gpapi/src/portal/config.rs | 4 +- crates/gpapi/src/portal/prelogin.rs | 6 +- crates/gpapi/src/session/transport/mod.rs | 1 + crates/gpapi/src/utils/mod.rs | 34 +- crates/gpapi/src/utils/response_log.rs | 221 +++++++++++ .../gpapi/tests/fixtures/portal-response.xml | 23 ++ crates/gpapi/tests/response_logging.rs | 123 ++++++ crates/gphip/Cargo.toml | 4 + crates/gphip/examples/windows_preview.rs | 12 + crates/gphip/src/domain_macos.rs | 53 +++ crates/gphip/src/domain_unix.rs | 120 ++++++ crates/gphip/src/lib.rs | 351 ++++++++++++++++-- crates/gphip/src/windows.rs | 96 +++++ crates/gphip/src/windows_report.rs | 298 +++++++++++++++ crates/gphip/templates/hip_report.xml | 106 +----- crates/gphip/templates/windows_emulation.xml | 77 ++++ packaging/windows/machine-install.ps1 | 4 +- 26 files changed, 1567 insertions(+), 206 deletions(-) create mode 100644 crates/gpapi/src/utils/response_log.rs create mode 100644 crates/gpapi/tests/fixtures/portal-response.xml create mode 100644 crates/gpapi/tests/response_logging.rs create mode 100644 crates/gphip/examples/windows_preview.rs create mode 100644 crates/gphip/src/domain_macos.rs create mode 100644 crates/gphip/src/domain_unix.rs create mode 100644 crates/gphip/src/windows.rs create mode 100644 crates/gphip/src/windows_report.rs create mode 100644 crates/gphip/templates/windows_emulation.xml diff --git a/Cargo.lock b/Cargo.lock index 8b67597..8e67435 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2271,12 +2271,14 @@ dependencies = [ "askama", "chrono", "gpapi", + "log", "netdev", "serde", "serde_json", "serde_urlencoded", "uuid", "uzers", + "windows", "xmltree", ] diff --git a/apps/gpservice/src/hip_source.rs b/apps/gpservice/src/hip_source.rs index cb9abb8..8a35dc4 100644 --- a/apps/gpservice/src/hip_source.rs +++ b/apps/gpservice/src/hip_source.rs @@ -158,19 +158,22 @@ pub(crate) fn profile( control: &dyn gpapi::collection::CollectionControl, ) -> io::Result { let identity = gpapi::os_profile::desktop::identity_from_parts( - hostname.unwrap_or_else(|| identity.computer().into()), - host_id.unwrap_or_else(|| identity.host_id().into()), + hostname.as_deref().unwrap_or(identity.computer()).into(), + host_id.as_deref().unwrap_or(identity.host_id()).into(), identity.serialno().into(), identity.mac_addr().into(), ); let mut builder = OsProfileBuilder::new(os).host_identity(identity); + if let Some(hostname) = hostname { + builder = builder.computer_name_override(hostname); + } if let Some(version) = version { builder = builder.client_version(version); } if let Some(os_version) = os_version { builder = builder.os_version(os_version); } - gpapi::os_profile::desktop::collect_profile_with_control(builder, None, control) + gpapi::os_profile::desktop::collect_profile_with_control(builder, host_id.as_deref(), control) } fn generation_error(error: anyhow::Error) -> io::Error { @@ -235,6 +238,29 @@ mod tests { assert_eq!(profile.host_identity().serialno(), "serial"); } + #[cfg(windows)] + #[test] + fn native_windows_profile_retains_negotiated_host_id() { + let identity = gpapi::os_profile::HostIdentity::from_parts( + "device".into(), + "hardware-seed".into(), + "serial".into(), + "00:11:22:33:44:55".into(), + ); + let profile = profile( + &identity, + ClientOs::Windows, + None, + None, + Some("negotiated-host".into()), + None, + &gpapi::collection::CollectionBudget::new(std::time::Duration::from_secs(60)), + ) + .unwrap(); + assert_eq!(profile.host_id(), "negotiated-host"); + assert_eq!(profile.host_identity().host_id(), "negotiated-host"); + } + #[test] fn callback_errors_preserve_cancellation() { let error = generation_error(io::Error::new(io::ErrorKind::Interrupted, "cancelled").into()); diff --git a/crates/gpapi/Cargo.toml b/crates/gpapi/Cargo.toml index 9440df7..8e0af06 100644 --- a/crates/gpapi/Cargo.toml +++ b/crates/gpapi/Cargo.toml @@ -98,7 +98,7 @@ uzers = { workspace = true, optional = true } [target.'cfg(windows)'.dependencies] file-rotate = { version = "0.8.0", optional = true } -windows-sys = { version = "0.61", features = ["Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Pipes", "Win32_System_Threading", "Win32_System_Services", "Win32_Globalization", "Win32_System_Environment", "Win32_System_JobObjects", "Win32_System_IO"] } +windows-sys = { version = "0.61", features = ["Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Pipes", "Win32_System_Threading", "Win32_System_Services", "Win32_Globalization", "Win32_System_Environment", "Win32_System_JobObjects", "Win32_System_IO", "Win32_System_Registry", "Win32_System_SystemInformation"] } [target.'cfg(windows)'.dev-dependencies] windows-sys = { version = "0.61", features = ["Win32_UI_Shell"] } diff --git a/crates/gpapi/src/gateway/session.rs b/crates/gpapi/src/gateway/session.rs index 21375b2..9537bf1 100644 --- a/crates/gpapi/src/gateway/session.rs +++ b/crates/gpapi/src/gateway/session.rs @@ -111,7 +111,7 @@ pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> { let response = client.post(&url).form(&form).send().await?; let response = parse_gp_response(response).await?; let root = Element::parse(response.as_bytes())?; - let status = parse_extend_session_status(&root, &response)?; + let status = parse_extend_session_status(&root)?; info!("Extend-session gateway response status: {}", status); @@ -151,11 +151,11 @@ fn build_extend_session_form(ctx: &SessionContext) -> anyhow::Result anyhow::Result { +fn parse_extend_session_status(root: &Element) -> anyhow::Result { match root.attr("status") { Some(status) => Ok(status.to_string()), None => { - warn!("Malformed extend-session response body: {}", response.trim()); + warn!("Extend-session response is missing status"); bail!("Malformed extend session response") } } @@ -231,10 +231,7 @@ mod tests { fn parses_extend_session_status_attribute() { let root = Element::parse(r#""#.as_bytes()).unwrap(); - assert_eq!( - parse_extend_session_status(&root, r#""#).unwrap(), - "success" - ); + assert_eq!(parse_extend_session_status(&root).unwrap(), "success"); } #[test] @@ -242,9 +239,7 @@ mod tests { let root = Element::parse("ok".as_bytes()).unwrap(); assert_eq!( - parse_extend_session_status(&root, "ok") - .unwrap_err() - .to_string(), + parse_extend_session_status(&root).unwrap_err().to_string(), "Malformed extend session response" ); } diff --git a/crates/gpapi/src/os_profile/desktop/mod.rs b/crates/gpapi/src/os_profile/desktop/mod.rs index 525cdb2..0ed88d4 100644 --- a/crates/gpapi/src/os_profile/desktop/mod.rs +++ b/crates/gpapi/src/os_profile/desktop/mod.rs @@ -173,6 +173,12 @@ pub fn collect_profile_with_control( Some(identity) => identity.clone(), None => collect_with_host_id_and_control(host_id_override, control)?, }; + #[cfg(windows)] + let identity = if builder.client_os == ClientOs::Windows { + windows::native_profile_identity(identity, host_id_override)? + } else { + identity + }; let runtime_os = runtime_client_os(); // Preserve the old behavior: only probe the native version when reporting it. let (os_version, software_version) = if builder.client_os == runtime_os { @@ -181,7 +187,8 @@ pub fn collect_profile_with_control( (defaults::os_version(runtime_os), defaults::software_version(runtime_os)) }; control.check()?; - Ok(builder.build(HostSnapshot { + // The builder may carry cached hardware identity; use the resolved profile identity. + Ok(builder.host_identity(identity.clone()).build(HostSnapshot { runtime_os, identity, os_version, diff --git a/crates/gpapi/src/os_profile/desktop/tests.rs b/crates/gpapi/src/os_profile/desktop/tests.rs index 85bce65..7454a34 100644 --- a/crates/gpapi/src/os_profile/desktop/tests.rs +++ b/crates/gpapi/src/os_profile/desktop/tests.rs @@ -137,14 +137,24 @@ fn assert_mac(value: &str, separator: char) { } #[test] -fn builder_delegates_default_identity_to_host_identity() { +fn builder_preserves_supplied_hardware_fields() { let expected = collect_identity(); let profile = collect_profile( OsProfileBuilder::new(runtime_client_os()).host_identity(expected.clone()), None, ); - assert_eq!(profile.host_identity(), &expected); + assert!( + profile + .host_identity() + .computer() + .eq_ignore_ascii_case(expected.computer()) + ); + assert_eq!(profile.host_identity().serialno(), expected.serialno()); + assert_eq!(profile.host_identity().mac_addr(), expected.mac_addr()); + if runtime_client_os() != ClientOs::Windows { + assert_eq!(profile.host_identity().host_id(), expected.host_id()); + } } #[test] @@ -178,3 +188,76 @@ fn controlled_profile_collection_propagates_cancellation_and_deadline() { let error = collect_profile_with_control(OsProfileBuilder::new(ClientOs::Linux), None, &expired).unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::TimedOut); } + +#[cfg(windows)] +#[test] +fn native_windows_profile_uses_installation_id_and_emulation_keeps_its_seed() { + let identity = HostIdentity::from_parts( + "test-host".into(), + "hardware-seed".into(), + "serial".into(), + "00:11:22:33:44:55".into(), + ); + let control = CollectionBudget::new(Duration::from_secs(60)); + let native = collect_profile_with_control( + OsProfile::builder(ClientOs::Windows).host_identity(identity.clone()), + None, + &control, + ) + .unwrap(); + // Read independently through the registry CLI to check the native API's source and view. + let output = std::process::Command::new("reg") + .args([ + "query", + r"HKLM\SOFTWARE\Microsoft\Cryptography", + "/v", + "MachineGuid", + "/reg:64", + ]) + .output() + .unwrap(); + assert!(output.status.success()); + let text = String::from_utf8(output.stdout).unwrap(); + let expected = text + .lines() + .find_map(|line| { + let mut parts = line.split_whitespace(); + (parts.next()? == "MachineGuid").then(|| parts.last().unwrap()) + }) + .unwrap(); + assert_eq!(native.host_id(), expected); + assert_eq!(native.host_identity().host_id(), expected); + assert!(native.computer().eq_ignore_ascii_case(&fallback_hostname())); + let with_host_id = collect_profile_with_control( + OsProfile::builder(ClientOs::Windows).host_identity(identity.clone()), + Some("explicit-host-id"), + &control, + ) + .unwrap(); + assert_eq!(with_host_id.host_id(), "explicit-host-id"); + assert_eq!(with_host_id.computer(), native.computer()); + let overridden = collect_profile_with_control( + OsProfile::builder(ClientOs::Windows) + .host_identity(identity.clone()) + .computer_name_override("Custom-Host"), + None, + &control, + ) + .unwrap(); + assert_eq!(overridden.computer(), "Custom-Host"); + + for client_os in [ClientOs::Mac, ClientOs::Linux] { + let builder = OsProfile::builder(client_os).host_identity(identity.clone()); + let expected = builder.clone().build(HostSnapshot { + runtime_os: ClientOs::Windows, + identity: identity.clone(), + os_version: String::new(), + software_version: String::new(), + }); + let actual = collect_profile_with_control(builder, None, &control).unwrap(); + assert_eq!(actual.host_identity(), &identity); + assert_eq!(actual.host_id(), expected.host_id()); + assert_eq!(actual.serialno(), expected.serialno()); + assert_eq!(actual.mac_addr(), expected.mac_addr()); + } +} diff --git a/crates/gpapi/src/os_profile/desktop/windows.rs b/crates/gpapi/src/os_profile/desktop/windows.rs index 904eb62..ab22eb4 100644 --- a/crates/gpapi/src/os_profile/desktop/windows.rs +++ b/crates/gpapi/src/os_profile/desktop/windows.rs @@ -1,4 +1,6 @@ -use std::{os::windows::process::CommandExt, process::Command}; +use std::{io, os::windows::process::CommandExt, process::Command}; +use windows_sys::Win32::System::Registry::{HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ, RRF_SUBKEY_WOW6464KEY, RegGetValueW}; +use windows_sys::Win32::System::SystemInformation::{ComputerNamePhysicalNetBIOS, GetComputerNameExW}; use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW; use super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id}; @@ -52,7 +54,7 @@ fn collect_windows_serial_number() -> Option { } fn windows_machine_seed() -> Option { - collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid) + collect_windows_csproduct_uuid().or_else(|| collect_windows_machine_guid().ok()) } fn collect_windows_csproduct_uuid() -> Option { @@ -71,25 +73,63 @@ fn collect_windows_csproduct_uuid() -> Option { .next() } -fn collect_windows_machine_guid() -> Option { - let output = Command::new("reg") - .creation_flags(CREATE_NO_WINDOW) - .args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"]) - .output() - .ok()?; - if !output.status.success() { - return None; +// Native Windows uses the OS installation ID and physical NetBIOS name. +// Keep the hardware identity used to seed other OS profiles unchanged. +pub(super) fn native_profile_identity( + identity: super::HostIdentity, + host_id_override: Option<&str>, +) -> io::Result { + let host_id = match host_id_override.filter(|id| !id.trim().is_empty()) { + Some(id) => id.to_owned(), + None => collect_windows_machine_guid()?, + }; + Ok(super::HostIdentity::from_parts( + collect_windows_computer_name()?, + host_id, + identity.serialno().into(), + identity.mac_addr().into(), + )) +} + +fn collect_windows_computer_name() -> io::Result { + let mut name = [0u16; 256]; + let mut size = name.len() as u32; + // SAFETY: the buffer and character count describe writable UTF-16 storage. + if unsafe { GetComputerNameExW(ComputerNamePhysicalNetBIOS, name.as_mut_ptr(), &mut size) } == 0 { + return Err(io::Error::last_os_error()); } - let stdout = String::from_utf8(output.stdout).ok()?; + String::from_utf16(&name[..size as usize]).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error)) +} - stdout.lines().find_map(|line| { - let mut parts = line.split_whitespace(); - if parts.next()? != "MachineGuid" { - return None; - } - - parts.last().map(str::to_string) - }) +fn collect_windows_machine_guid() -> io::Result { + let key: Vec = "SOFTWARE\\Microsoft\\Cryptography\0".encode_utf16().collect(); + let value: Vec = "MachineGuid\0".encode_utf16().collect(); + let mut buffer = [0u16; 128]; + let mut size = std::mem::size_of_val(&buffer) as u32; + // SAFETY: both names are NUL-terminated; buffer and byte length describe writable storage. + let status = unsafe { + RegGetValueW( + HKEY_LOCAL_MACHINE, + key.as_ptr(), + value.as_ptr(), + RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY, + std::ptr::null_mut(), + buffer.as_mut_ptr().cast(), + &mut size, + ) + }; + if status != 0 { + return Err(io::Error::from_raw_os_error(status as i32)); + } + let end = buffer.iter().position(|value| *value == 0).unwrap_or(buffer.len()); + let guid = String::from_utf16(&buffer[..end]).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + if guid.trim().is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Windows MachineGuid is empty", + )); + } + Ok(guid) } impl RuntimeNativeHostIdentity { diff --git a/crates/gpapi/src/os_profile/profile.rs b/crates/gpapi/src/os_profile/profile.rs index 9086928..88228a3 100644 --- a/crates/gpapi/src/os_profile/profile.rs +++ b/crates/gpapi/src/os_profile/profile.rs @@ -124,8 +124,7 @@ impl OsProfile { self.runtime_os == self.client_os } - /// Default software version string for the target OS, matching the - /// official client values. + /// Software version for the target OS profile. pub fn software_version(&self) -> &str { &self.software_version } diff --git a/crates/gpapi/src/os_profile/tests.rs b/crates/gpapi/src/os_profile/tests.rs index 6d9bb36..7a5a163 100644 --- a/crates/gpapi/src/os_profile/tests.rs +++ b/crates/gpapi/src/os_profile/tests.rs @@ -18,14 +18,14 @@ fn negotiated_os_version_is_used_in_profile_and_user_agent() { } #[test] -fn csc_support_defaults_match_official_profiles() { +fn csc_support_defaults_match_platform_profiles() { assert!(!ClientOs::Linux.default_csc_support()); assert!(ClientOs::Mac.default_csc_support()); assert!(ClientOs::Windows.default_csc_support()); } #[test] -fn prelogin_param_location_matches_official_profiles() { +fn prelogin_param_location_matches_platform_profiles() { assert_eq!( OsProfileBuilder::new(ClientOs::Linux) .build(test_snapshot()) @@ -91,7 +91,7 @@ fn embedded_gateway_default_browser_is_zero_for_all() { } #[test] -fn external_default_browser_values_match_official_profiles() { +fn external_default_browser_values_match_platform_profiles() { assert_eq!( OsProfileBuilder::new(ClientOs::Linux) .build(test_snapshot()) @@ -132,7 +132,7 @@ fn external_default_browser_values_match_official_profiles() { } #[test] -fn saml_password_matches_official_profiles() { +fn saml_password_matches_platform_profiles() { assert_eq!( OsProfileBuilder::new(ClientOs::Linux) .build(test_snapshot()) @@ -173,7 +173,7 @@ fn gateway_server_uses_resolved_ipv4_for_all() { } #[test] -fn kerberos_support_in_query_matches_official_profiles() { +fn kerberos_support_in_query_matches_platform_profiles() { assert!( !OsProfileBuilder::new(ClientOs::Linux) .build(test_snapshot()) @@ -192,7 +192,7 @@ fn kerberos_support_in_query_matches_official_profiles() { } #[test] -fn os_vendor_matches_official_profiles() { +fn os_vendor_matches_platform_profiles() { assert_eq!( OsProfileBuilder::new(ClientOs::Linux) .build(test_snapshot()) diff --git a/crates/gpapi/src/portal/config.rs b/crates/gpapi/src/portal/config.rs index e6baa6e..0efef57 100644 --- a/crates/gpapi/src/portal/config.rs +++ b/crates/gpapi/src/portal/config.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use anyhow::bail; -use log::{debug, info, warn}; +use log::{info, warn}; use reqwest::{Client, StatusCode}; use serde::Serialize; use specta::Type; @@ -232,7 +232,6 @@ pub async fn retrieve_config( bail!(PortalError::ConfigError("Empty portal config response".to_string())) } - debug!("Portal config response received: {} bytes", res_xml.len()); let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?; if csc::is_config_criteria(&root) { @@ -247,7 +246,6 @@ pub async fn retrieve_config( _ = cancellation.cancelled() => bail!("Portal configuration cancelled"), result = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params) => result?, }; - debug!("Portal CSC config response received: {} bytes", csc_xml.len()); let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?; return parse_portal_policy(&server, cred, root, cancellation).await; } diff --git a/crates/gpapi/src/portal/prelogin.rs b/crates/gpapi/src/portal/prelogin.rs index 241f577..3f61c3e 100644 --- a/crates/gpapi/src/portal/prelogin.rs +++ b/crates/gpapi/src/portal/prelogin.rs @@ -1,5 +1,5 @@ use anyhow::{anyhow, bail}; -use log::{debug, info, warn}; +use log::{info, warn}; use reqwest::{Client, StatusCode}; use serde::Serialize; use specta::Type; @@ -174,10 +174,8 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio Err(anyhow!(PortalError::PreloginError(err.reason))) })?; - debug!("Prelogin response XML: {}", res_xml); - let prelogin = parse_prelogin_response(&res_xml, is_gateway).map_err(|err| { - warn!("Parse response error, response: {}", res_xml); + warn!("Failed to parse prelogin response: {err}"); PortalError::PreloginError(err.to_string()) })?; diff --git a/crates/gpapi/src/session/transport/mod.rs b/crates/gpapi/src/session/transport/mod.rs index 67c23ae..7baeafd 100644 --- a/crates/gpapi/src/session/transport/mod.rs +++ b/crates/gpapi/src/session/transport/mod.rs @@ -164,6 +164,7 @@ async fn post( crate::utils::request::ResponseBodyError::Transport(error) => GatewayRequestError::Transport(error), crate::utils::request::ResponseBodyError::TooLarge => GatewayRequestError::ResponseTooLarge, })?; + crate::utils::log_response_xml(&format!("/ssl-vpn/{endpoint}"), status, &body); parse_response(&body) } diff --git a/crates/gpapi/src/utils/mod.rs b/crates/gpapi/src/utils/mod.rs index c33a57d..9f41643 100644 --- a/crates/gpapi/src/utils/mod.rs +++ b/crates/gpapi/src/utils/mod.rs @@ -13,6 +13,8 @@ mod identity_encoding; #[cfg(feature = "desktop")] pub mod lock_file; pub mod redact; +mod response_log; +pub(crate) use response_log::log_response_xml; pub mod request; #[cfg(feature = "tauri")] pub mod window; @@ -53,11 +55,10 @@ pub fn remove_url_scheme(s: &str) -> String { } #[derive(Error, Debug)] -#[error("GP response error: reason={reason}, status={status}, body={body}")] +#[error("GP response error: reason={reason}, status={status}")] pub struct GpError { pub status: StatusCode, pub reason: String, - body: String, #[source] source: Option, } @@ -79,16 +80,20 @@ pub async fn parse_gp_response(res: Response) -> anyhow::Result return Err(parse_gp_error(res).await); } - res.text().await.map_err(|err| { + let path = log::log_enabled!(log::Level::Debug).then(|| res.url().path().to_owned()); + let body = res.text().await.map_err(|err| { warn!("Failed to read response: {}", err); GpError { status, reason: "failed to read response".to_string(), - body: "".to_string(), source: Some(err), } - }) + })?; + if let Some(path) = path { + log_response_xml(&path, status, body.as_bytes()); + } + Ok(body) } async fn parse_gp_error(res: Response) -> GpError { @@ -99,15 +104,16 @@ async fn parse_gp_error(res: Response) -> GpError { .map_or_else(|| "", |v| v.to_str().unwrap_or("")) .to_string(); - let (body, source) = match res.text().await { - Ok(body) => (if body.is_empty() { "".to_string() } else { body }, None), - Err(error) => ("".to_string(), Some(error)), + let path = log::log_enabled!(log::Level::Debug).then(|| res.url().path().to_owned()); + let source = match res.text().await { + Ok(body) => { + if let Some(path) = path { + log_response_xml(&path, status, body.as_bytes()); + } + None + } + Err(error) => Some(error), }; - GpError { - status, - reason, - body, - source, - } + GpError { status, reason, source } } diff --git a/crates/gpapi/src/utils/response_log.rs b/crates/gpapi/src/utils/response_log.rs new file mode 100644 index 0000000..a48d1c9 --- /dev/null +++ b/crates/gpapi/src/utils/response_log.rs @@ -0,0 +1,221 @@ +use reqwest::StatusCode; +use xmltree::{Element, EmitterConfig, XMLNode}; + +const REDACTED: &str = "[redacted]"; +const MAX_XML_BYTES: usize = 1024 * 1024; + +pub(crate) fn log_response_xml(path: &str, status: StatusCode, body: &[u8]) { + if !log::log_enabled!(log::Level::Debug) { + return; + } + // Redirect paths can themselves contain authentication tokens. + let endpoint = match path { + "/global-protect/prelogin.esp" + | "/ssl-vpn/prelogin.esp" + | "/global-protect/getconfig.esp" + | "/global-protect/getconfig_csc.esp" + | "/ssl-vpn/login.esp" + | "/ssl-vpn/getconfig.esp" + | "/ssl-vpn/agentmessage.esp" + | "/ssl-vpn/hipreportcheck.esp" + | "/ssl-vpn/hipreport.esp" + | "/ssl-vpn/logout.esp" => path, + _ => "[response endpoint]", + }; + // Individual XML lines remain readable in macOS unified logs with limited record sizes. + for line in redact_xml(body).lines() { + log::debug!("{endpoint} response XML (HTTP {}): {line}", status.as_u16()); + } +} + +fn redact_xml(body: &[u8]) -> String { + if body.len() > MAX_XML_BYTES { + return "[XML omitted: exceeds 1 MiB]".into(); + } + let Ok(text) = std::str::from_utf8(body) else { + return "[XML omitted: invalid UTF-8]".into(); + }; + if text.to_ascii_lowercase().contains(" Some(element), + _ => None, + }); + let Some(mut root) = roots.next() else { + return "[XML omitted: no document element]".into(); + }; + if roots.next().is_some() || root.name.eq_ignore_ascii_case("html") { + return "[XML omitted: unsupported response document]".into(); + } + redact_element(&mut root); + let mut output = Vec::new(); + if root + .write_with_config( + &mut output, + EmitterConfig::new() + .perform_indent(true) + .write_document_declaration(false), + ) + .is_err() + { + return "[XML omitted: serialization failed]".into(); + } + String::from_utf8(output).unwrap_or_else(|_| "[XML omitted: serialization failed]".into()) +} + +fn sensitive_name(name: &str) -> bool { + let name: String = name + .chars() + .filter(char::is_ascii_alphanumeric) + .map(|c| c.to_ascii_lowercase()) + .collect(); + if name.ends_with("label") { + return false; + } + name.contains("cookie") + || name.contains("token") + || name.contains("password") + || name.contains("passphrase") + || name.contains("secret") + || name.starts_with("ekey") + || matches!( + name.as_str(), + "argument" + | "samlrequest" + | "samlresponse" + | "samlrequestid" + | "assertion" + | "encryptedassertion" + | "authnrequest" + | "challenge" + | "privatekey" + | "encryptionkey" + | "enckey" + | "enchskey" + | "tunnelopaque" + | "nonce" + | "user" + | "username" + | "ccusername" + | "credential" + ) +} + +fn redact_element(element: &mut Element) { + let named_secret = matches!(element.name.as_str(), "field" | "param" | "property" | "setting") + && ["name", "key"] + .iter() + .any(|name| element.attributes.get(*name).is_some_and(|value| sensitive_name(value))); + let secret = sensitive_name(&element.name) || named_secret; + for (name, value) in &mut element.attributes { + if sensitive_name(name) || (secret && !(named_secret && matches!(name.as_str(), "name" | "key"))) { + *value = REDACTED.into(); + } else { + *value = redact_url(value); + } + } + if secret { + element.children = vec![XMLNode::Text(REDACTED.into())]; + return; + } + element + .children + .retain(|node| matches!(node, XMLNode::Element(_) | XMLNode::Text(_) | XMLNode::CData(_))); + for node in &mut element.children { + match node { + XMLNode::Element(child) => redact_element(child), + XMLNode::Text(value) | XMLNode::CData(value) => *value = redact_url(value), + _ => {} + } + } +} + +fn redact_url(value: &str) -> String { + let Ok(mut url) = url::Url::parse(value) else { + return value.into(); + }; + if !matches!(url.scheme(), "http" | "https") { + return value.into(); + } + if !url.username().is_empty() { + let _ = url.set_username(REDACTED); + } + if url.password().is_some() { + let _ = url.set_password(Some(REDACTED)); + } + if url.query().is_some() { + let pairs: Vec<_> = url + .query_pairs() + .map(|(name, _)| (name.into_owned(), REDACTED)) + .collect(); + url.query_pairs_mut().clear().extend_pairs(pairs); + } + if url.fragment().is_some() { + url.set_fragment(Some(REDACTED)); + } + url.to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn preserves_policy_checks_and_redacts_authentication_material() { + let input = include_str!("../../tests/fixtures/portal-response.xml"); + let xml = redact_xml(input.as_bytes()); + let root = Element::parse(xml.as_bytes()).unwrap(); + assert!(xml.contains("custom-checks") && xml.contains("HipID") && xml.contains("NV Domain")); + assert!(xml.contains("Corp.Example.test")); + assert!(xml.contains("com.1password.1password") && xml.contains("Version")); + for secret in [ + "fixture-user-cookie", + "fixture-prelogon-cookie", + "fixture-csc-cookie", + "fixture-username", + "fixture-saml", + "fixture-attribute-token", + "fixture-property-password", + "fixture-cookie-name", + "fixture-query-token", + "fixture-url-password", + "fixture-comment", + "fixture-pi", + ] { + assert!(!xml.contains(secret), "secret retained: {secret}"); + } + assert_eq!(root.name, "policy"); + } + + #[test] + fn redacts_positional_login_arguments_and_session_keys() { + let xml = redact_xml(br#"fixture-auth-cookiefixture-user256fixture-key-c2sfixture-key-s2cfixture-hs-keyfixture-private-keyfixture-saml-responsefixture-opaque1400"#); + assert!(!xml.contains("fixture-")); + assert!(xml.contains("1400")); + Element::parse(xml.as_bytes()).unwrap(); + } + + #[test] + fn omits_unparseable_html_dtd_and_oversized_bodies_without_echoing_them() { + for body in [ + b"not XML fixture-secret".as_slice(), + b"fixture-secret", + b"fixture-secret", + b"]>&secret;", + b"fixture-secret", + b"\xfffixture-secret", + ] { + let xml = redact_xml(body); + assert!(xml.starts_with("[XML omitted:")); + assert!(!xml.contains("fixture-secret")); + } + assert_eq!( + redact_xml(&vec![b'x'; MAX_XML_BYTES + 1]), + "[XML omitted: exceeds 1 MiB]" + ); + } +} diff --git a/crates/gpapi/tests/fixtures/portal-response.xml b/crates/gpapi/tests/fixtures/portal-response.xml new file mode 100644 index 0000000..b2f16f3 --- /dev/null +++ b/crates/gpapi/tests/fixtures/portal-response.xml @@ -0,0 +1,23 @@ + + + + + fixture-user-cookie + + fixture-csc-cookie + fixture-username + fixture-saml + + + + + + 3600 + yes + + HipIDVersion + DomainNV Domain + + + Corp.Example.test + diff --git a/crates/gpapi/tests/response_logging.rs b/crates/gpapi/tests/response_logging.rs new file mode 100644 index 0000000..130db0d --- /dev/null +++ b/crates/gpapi/tests/response_logging.rs @@ -0,0 +1,123 @@ +use std::sync::Mutex; + +use gpapi::utils::parse_gp_response; +use log::{LevelFilter, Log, Metadata, Record}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpListener, +}; + +struct Capture(Mutex>); +static LOGS: Capture = Capture(Mutex::new(Vec::new())); +impl Log for Capture { + fn enabled(&self, _: &Metadata<'_>) -> bool { + true + } + fn log(&self, record: &Record<'_>) { + if record.target() == "gpapi::utils::response_log" { + self.0.lock().unwrap().push(record.args().to_string()); + } + } + fn flush(&self) {} +} + +async fn response(path: &str, status: &str, body: &str) -> reqwest::Response { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let data = format!( + "HTTP/1.1 {status}\r\nContent-Type: application/xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0; 4096]; + socket.read(&mut request).await.unwrap(); + socket.write_all(data.as_bytes()).await.unwrap(); + }); + reqwest::Client::builder() + .no_proxy() + .build() + .unwrap() + .get(format!("http://{address}{path}")) + .send() + .await + .unwrap() +} + +#[tokio::test] +async fn logs_redacted_xml_at_debug_without_changing_responses_or_exposing_error_bodies() { + rustls::crypto::ring::default_provider().install_default().unwrap(); + log::set_logger(&LOGS).unwrap(); + log::set_max_level(LevelFilter::Debug); + let portal = include_str!("fixtures/portal-response.xml"); + for path in [ + "/global-protect/getconfig.esp", + "/global-protect/getconfig_csc.esp", + "/global-protect/prelogin.esp", + "/ssl-vpn/login.esp", + ] { + let result = parse_gp_response(response(path, "200 OK", portal).await).await.unwrap(); + assert_eq!(result, portal); + } + let logs = LOGS.0.lock().unwrap().join("\n"); + assert!(logs.contains("getconfig.esp response XML")); + assert!(logs.contains("getconfig_csc.esp response XML")); + assert!(logs.contains("prelogin.esp response XML")); + assert!(logs.contains("login.esp response XML")); + assert!(logs.contains("custom-checks") && logs.contains("HipID")); + for secret in [ + "fixture-user-cookie", + "fixture-prelogon-cookie", + "fixture-csc-cookie", + "fixture-username", + "fixture-saml", + "fixture-attribute-token", + "fixture-property-password", + "fixture-cookie-name", + "fixture-query-token", + "fixture-url-password", + "fixture-comment", + "fixture-pi", + ] { + assert!(!logs.contains(secret), "logged secret: {secret}"); + } + + let error = parse_gp_response(response("/global-protect/getconfig.esp", "403 Forbidden", portal).await) + .await + .unwrap_err(); + assert_eq!(error.status, reqwest::StatusCode::FORBIDDEN); + assert!(!format!("{error:?} {error}").contains("fixture-")); + assert!(LOGS.0.lock().unwrap().iter().any(|line| line.contains("HTTP 403"))); + + let error = parse_gp_response( + response( + "/global-protect/getconfig.esp", + "500 Internal Server Error", + "fixture-error-secret", + ) + .await, + ) + .await + .unwrap_err(); + assert!(!format!("{error:?} {error}").contains("fixture-error-secret")); + assert!(!LOGS.0.lock().unwrap().join("\n").contains("fixture-error-secret")); + + LOGS.0.lock().unwrap().clear(); + let body = "fixture-login-cookie"; + parse_gp_response(response("/redirect/fixture-path-token?token=fixture-query-token", "200 OK", body).await) + .await + .unwrap(); + let logs = LOGS.0.lock().unwrap().join("\n"); + assert!(logs.contains("[response endpoint]")); + assert!(!logs.contains("fixture-")); + + LOGS.0.lock().unwrap().clear(); + log::set_max_level(LevelFilter::Info); + assert_eq!( + parse_gp_response(response("/global-protect/getconfig.esp", "200 OK", portal).await) + .await + .unwrap(), + portal + ); + assert!(LOGS.0.lock().unwrap().is_empty()); +} diff --git a/crates/gphip/Cargo.toml b/crates/gphip/Cargo.toml index fd6ea8c..fa7419f 100644 --- a/crates/gphip/Cargo.toml +++ b/crates/gphip/Cargo.toml @@ -19,3 +19,7 @@ xmltree.workspace = true [target.'cfg(unix)'.dependencies] uzers.workspace = true + +[target.'cfg(windows)'.dependencies] +windows = { version = "0.62", features = ["Win32_Networking_ActiveDirectory", "Win32_System_SystemInformation"] } +log.workspace = true diff --git a/crates/gphip/examples/windows_preview.rs b/crates/gphip/examples/windows_preview.rs new file mode 100644 index 0000000..6955b5f --- /dev/null +++ b/crates/gphip/examples/windows_preview.rs @@ -0,0 +1,12 @@ +//! Generate native Windows posture on Windows, or a Windows emulation preview elsewhere. +use gpapi::os_profile::{ClientOs, OsProfile}; +use gphip::{ReportContext, ReportInput}; + +fn main() -> anyhow::Result<()> { + let input = ReportInput { + profile: gpapi::os_profile::desktop::collect_profile(OsProfile::builder(ClientOs::Windows), None), + context: ReportContext::Preview, + }; + println!("{}", gphip::generate_report(&input)?); + Ok(()) +} diff --git a/crates/gphip/src/domain_macos.rs b/crates/gphip/src/domain_macos.rs new file mode 100644 index 0000000..f99b49c --- /dev/null +++ b/crates/gphip/src/domain_macos.rs @@ -0,0 +1,53 @@ +//! Native macOS Active Directory domain collection. +use gpapi::process::collection::CollectorCommands; +use std::{io, path::Path}; + +pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result { + let Some(output) = commands.run_executable(Path::new("/usr/sbin/dsconfigad"), &["-show"])? else { + return Ok(String::new()); + }; + let text = String::from_utf8(output.stdout).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + // A nonzero exit status does not invalidate a reported domain. + Ok(parse_domain(&text)) +} + +fn parse_domain(output: &str) -> String { + output + .lines() + .find_map(|line| { + let (label, value) = line.split_once('=')?; + (label.trim() == "Active Directory Domain").then(|| value.trim().to_owned()) + }) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_ad_domain_without_using_other_domain_fields() { + assert_eq!( + parse_domain( + "Forest = forest.test\nActive Directory Domain = Corp.Example.test \t\r\nComputer Account = HOST$\n" + ), + "Corp.Example.test" + ); + assert_eq!( + parse_domain("Active Directory Domain = first.test\nActive Directory Domain = second.test\n"), + "first.test" + ); + } + + #[test] + fn unbound_or_empty_domain_stays_empty() { + for output in [ + "", + "Not bound to Active Directory\n", + "Forest = forest.test\n", + "Active Directory Domain = \t\n", + ] { + assert_eq!(parse_domain(output), ""); + } + } +} diff --git a/crates/gphip/src/domain_unix.rs b/crates/gphip/src/domain_unix.rs new file mode 100644 index 0000000..90ce326 --- /dev/null +++ b/crates/gphip/src/domain_unix.rs @@ -0,0 +1,120 @@ +//! Native Linux and BSD computer-domain collection. +use std::io; + +#[cfg(unix)] +use gpapi::process::collection::CollectorCommands; + +#[cfg(target_os = "linux")] +pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result { + linux_domain(|program, args| read(commands, program, args)) +} + +#[cfg(target_os = "freebsd")] +pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result { + read(commands, "hostname", &["-d"]) +} + +#[cfg(target_os = "openbsd")] +pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result { + read(commands, "hostname", &[]).map(|hostname| hostname_domain(&hostname)) +} + +#[cfg(unix)] +fn read(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result { + let Some(output) = commands.run(program, args)? else { + return Ok(String::new()); + }; + let text = String::from_utf8(output.stdout).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + // A nonzero exit status does not invalidate a reported domain. + Ok(first_line(&text)) +} + +#[cfg(any(target_os = "linux", test))] +fn linux_domain(mut read: impl FnMut(&str, &[&str]) -> io::Result) -> io::Result { + let realm = read("realm", &["list", "--name-only"])?; + if !realm.is_empty() { + return Ok(realm); + } + read("dnsdomainname", &[]) +} + +fn first_line(output: &str) -> String { + output.lines().next().unwrap_or_default().trim().to_owned() +} + +#[cfg(any(target_os = "openbsd", test))] +fn hostname_domain(hostname: &str) -> String { + hostname + .split_once('.') + .map(|(_, domain)| domain) + .unwrap_or_default() + .to_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(unix)] + #[test] + fn uses_first_stdout_line_even_with_nonzero_exit() { + let budget = gpapi::collection::CollectionBudget::new(std::time::Duration::from_secs(5)); + let commands = CollectorCommands::new(&budget); + let domain = read( + &commands, + "sh", + &["-c", "printf ' Corp.Example.test \\nsecond.test\\n'; exit 7"], + ) + .unwrap(); + assert_eq!(domain, "Corp.Example.test"); + } + + #[test] + fn linux_prefers_realm_and_only_queries_dns_when_empty() { + let realm = linux_domain(|program, args| { + assert_eq!(program, "realm"); + assert_eq!(args, ["list", "--name-only"]); + Ok("Corp.Example.test".into()) + }) + .unwrap(); + assert_eq!(realm, "Corp.Example.test"); + + let mut calls = Vec::new(); + let dns = linux_domain(|program, _| { + calls.push(program.to_string()); + if program == "realm" { + Ok(String::new()) + } else { + Ok("dns.example.test".into()) + } + }) + .unwrap(); + assert_eq!(calls, ["realm", "dnsdomainname"]); + assert_eq!(dns, "dns.example.test"); + assert_eq!(linux_domain(|_, _| Ok(String::new())).unwrap(), ""); + } + + #[test] + fn interrupted_collection_does_not_continue_to_dns() { + let result = linux_domain(|program, _| { + assert_eq!(program, "realm"); + Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled")) + }); + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::Interrupted); + } + + #[test] + fn reads_only_first_line_and_preserves_domain_case() { + assert_eq!(first_line(" Corp.Example.test \r\nsecond.test\n"), "Corp.Example.test"); + assert_eq!(first_line("\nsecond.test\n"), ""); + assert_eq!(first_line(""), ""); + } + + #[test] + fn openbsd_uses_hostname_suffix_without_inventing_a_domain() { + assert_eq!(hostname_domain("host.Corp.Example.test"), "Corp.Example.test"); + assert_eq!(hostname_domain("host"), ""); + assert_eq!(hostname_domain("host."), ""); + assert_eq!(hostname_domain(""), ""); + } +} diff --git a/crates/gphip/src/lib.rs b/crates/gphip/src/lib.rs index bfec31e..2cac6f4 100644 --- a/crates/gphip/src/lib.rs +++ b/crates/gphip/src/lib.rs @@ -9,11 +9,20 @@ use gpapi::collection::{CollectionBudget, CollectionControl}; use gpapi::process::collection::CollectorCommands; use xmltree::Element; +#[cfg(target_os = "macos")] +mod domain_macos; +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))] +mod domain_unix; #[cfg(target_os = "macos")] mod sentinel_macos; #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] mod sentinel_unix; +#[cfg(windows)] +mod windows; +#[cfg(any(windows, test))] +mod windows_report; + pub const MAX_EDITED_REPORT_BYTES: usize = 48 * 1024; /// Validate an edited report before it is stored or used as a submission body. @@ -98,9 +107,9 @@ pub fn refresh_edited_report_with_control( control.check()?; let mut edited = validate_edited_report(edited_xml)?; let cookie_params = cookie_params(input); - let identity = HostInfoCollector::new(&input.profile, input, &cookie_params).collect_identity(); + let identity = HostInfoCollector::new(&input.profile, input, &cookie_params).collect_identity(control)?; control.check()?; - let domain = format!("{}.internal", identity.domain); + let domain = &identity.domain; let generate_time = get_current_time_components().0; for (name, value) in [ ("md5-sum", input.context.md5()), @@ -201,6 +210,27 @@ impl ReportContext { } } +/// Return a computer domain only for native profiles with a platform-specific source. +fn native_domain(profile: &OsProfile, control: &dyn CollectionControl) -> io::Result> { + control.check()?; + if !profile.is_native() { + return Ok(None); + } + #[cfg(windows)] + if profile.client_os() == ClientOs::Windows { + return windows::domain().map(Some); + } + #[cfg(target_os = "macos")] + if profile.client_os() == ClientOs::Mac { + return domain_macos::collect(&CollectorCommands::new(control)).map(Some); + } + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + if profile.client_os() == ClientOs::Linux { + return domain_unix::collect(&CollectorCommands::new(control)).map(Some); + } + Ok(None) +} + /// Inputs collected by the caller for one HIP report. pub struct ReportInput { pub profile: OsProfile, @@ -214,14 +244,18 @@ pub fn generate_report(input: &ReportInput) -> anyhow::Result { } /// Identity-only maintenance report. This deliberately does not enumerate the -/// machine or execute posture collectors; addresses come from the session owner. +/// interfaces or execute posture collectors; addresses come from the session owner. +/// Native profiles read the computer domain, consistent with generated and refreshed reports. pub fn generate_identity_report(input: &ReportInput) -> anyhow::Result { let params = cookie_params(input); + let budget = CollectionBudget::new(Duration::from_secs(60)); + let domain = + native_domain(&input.profile, &budget)?.unwrap_or_else(|| params.get("domain").cloned().unwrap_or_default()); let mut report = Element::new("hip-report"); for (name, value) in [ ("md5-sum", input.context.md5()), ("user-name", report_user_name(input, ¶ms)), - ("domain", params.get("domain").map(String::as_str).unwrap_or_default()), + ("domain", domain.as_str()), ("host-name", input.profile.computer()), ("host-id", input.profile.host_id()), ("ip-address", input.context.client_ip().unwrap_or_default()), @@ -338,6 +372,7 @@ struct HostInfo { clamav: Option, sentinel: Option, ufw: Option, + windows_categories: Option, } impl HostInfo { @@ -425,16 +460,6 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> { } } - /// Domain belongs to the runtime user/session, not the simulated OS, so - /// it is sourced from the auth cookie when available. - fn get_domain(&self) -> String { - self - .cookie_params - .get("domain") - .map(|s| s.to_string()) - .unwrap_or_default() - } - /// Collect network interface information with fallback fn collect_network_interface(&self) -> NetworkInterface { match netdev::get_default_interface() { @@ -452,28 +477,27 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> { } } - /// Single entry point for collecting host info — dispatches per-OS - /// behavior via `OsProfile` methods rather than `#[cfg(target_os)]`. - fn collect_identity(&self) -> HostInfo { + fn collect_identity(&self, control: &dyn CollectionControl) -> io::Result { let runtime_iface = self.collect_network_interface(); let primary = self.adapt_primary_interface(&runtime_iface); let mut interfaces = vec![primary.clone()]; interfaces.extend(self.extra_interfaces(&primary)); - HostInfo { + Ok(HostInfo { os_vendor: self.profile.os_vendor().to_string(), os_version: self.profile.os_version().to_string(), host_id: self.profile.host_id().to_string(), host_name: self.profile.computer().to_string(), software_version: self.profile.software_version().to_string(), - domain: self.domain_for_profile(), + domain: self.domain_for_profile(control)?, network_interfaces: interfaces, defender: None, clamav: None, sentinel: None, ufw: None, - } + windows_categories: None, + }) } /// Build the primary network interface with OS-appropriate naming and @@ -496,9 +520,12 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> { } } - /// Additional interfaces appended after the primary. Only Windows - /// emits the software loopback interface in HIP reports. + /// Native Windows enumerates loopback adapters; Windows emulation retains its synthetic interface. fn extra_interfaces(&self, primary: &NetworkInterface) -> Vec { + #[cfg(windows)] + if self.profile.client_os() == ClientOs::Windows && self.profile.is_native() { + return windows::loopback_interfaces(); + } match self.profile.client_os() { ClientOs::Windows => vec![NetworkInterface { name: derive_windows_network_name(self.profile.host_id(), primary), @@ -511,20 +538,29 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> { } } - /// Linux HIP reports omit the domain field; macOS/Windows include it - /// from the auth cookie. - fn domain_for_profile(&self) -> String { - match self.profile.client_os() { - ClientOs::Linux => String::new(), - ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => self.get_domain(), + fn domain_for_profile(&self, control: &dyn CollectionControl) -> io::Result { + if let Some(domain) = native_domain(self.profile, control)? { + return Ok(domain); } + let domain = match self.profile.client_os() { + ClientOs::Linux => "", + ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => { + self.cookie_params.get("domain").map(String::as_str).unwrap_or_default() + } + }; + Ok(format!("{domain}.internal")) } fn collect(&self, control: &dyn CollectionControl) -> io::Result { control.check()?; - let mut info = self.collect_identity(); + let mut info = self.collect_identity(control)?; control.check()?; let commands = CollectorCommands::new(control); + #[cfg(windows)] + if self.profile.client_os() == ClientOs::Windows && self.profile.is_native() { + info.windows_categories = Some(windows::collect(&commands, control)?.render()?); + } + if self.profile.client_os() == ClientOs::Linux && self.profile.is_native() { info.defender = detect_microsoft_defender(&commands)?; info.clamav = detect_clamav(&commands)?; @@ -671,16 +707,20 @@ fn placeholder_interface_for(profile: &OsProfile, runtime: &NetworkInterface) -> } } -/// MAC address formatting per target OS. Windows uses hyphen separators; -/// Linux and macOS preserve the colon-separated form returned by the -/// platform. +/// Native Windows uses uppercase hex and hyphens. Windows emulation retains its +/// existing casing; other profiles preserve the platform's MAC representation. fn format_mac_for(profile: &OsProfile, mac: Option) -> Option { match profile.client_os() { - ClientOs::Windows => mac.map(|m| m.replace(':', "-")), + ClientOs::Windows if profile.is_native() => mac.map(format_native_windows_mac), + ClientOs::Windows => mac.map(|value| value.replace(':', "-")), ClientOs::Linux | ClientOs::Mac | ClientOs::Ios => mac, } } +fn format_native_windows_mac(mac: String) -> String { + mac.replace(':', "-").to_ascii_uppercase() +} + // ============================================================================ // Utility Functions // ============================================================================ @@ -796,13 +836,39 @@ mod tests { } } + #[test] + fn native_windows_mac_casing_does_not_change_emulation_or_other_platforms() { + for (runtime_os, client_os, expected) in [ + (ClientOs::Windows, ClientOs::Windows, "AA-BB-CC-DD-EE-FF"), + (ClientOs::Mac, ClientOs::Windows, "aa-bb-cc-dd-ee-ff"), + (ClientOs::Linux, ClientOs::Windows, "aa-bb-cc-dd-ee-ff"), + (ClientOs::Mac, ClientOs::Mac, "aa:bb:cc:dd:ee:ff"), + (ClientOs::Linux, ClientOs::Linux, "aa:bb:cc:dd:ee:ff"), + ] { + let profile = OsProfileBuilder::new(client_os).build(gpapi::os_profile::HostSnapshot { + runtime_os, + identity: gpapi::os_profile::HostIdentity::application("host".into(), "id".into()), + os_version: "OS".into(), + software_version: "version".into(), + }); + assert_eq!( + format_mac_for(&profile, Some("aa:bb:cc:dd:ee:ff".into())).as_deref(), + Some(expected) + ); + assert_eq!(format_mac_for(&profile, Some(String::new())).as_deref(), Some("")); + assert_eq!(format_mac_for(&profile, None), None); + } + } + #[test] fn host_info_os_vendor_is_linux_for_linux_profile() { let input = make_input(make_profile(ClientOs::Linux)); let profile = make_profile(ClientOs::Linux); let cookie_params: HashMap = HashMap::new(); - let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity(); + let info = HostInfoCollector::new(&profile, &input, &cookie_params) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); assert_eq!(info.os_vendor, "Linux"); } @@ -813,7 +879,9 @@ mod tests { let profile = make_profile(ClientOs::Mac); let cookie_params: HashMap = HashMap::new(); - let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity(); + let info = HostInfoCollector::new(&profile, &input, &cookie_params) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); assert_eq!(info.os_vendor, "Apple"); } @@ -824,7 +892,9 @@ mod tests { let profile = make_profile(ClientOs::Windows); let cookie_params: HashMap = HashMap::new(); - let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity(); + let info = HostInfoCollector::new(&profile, &input, &cookie_params) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); assert_eq!(info.os_vendor, "Microsoft"); } @@ -835,7 +905,9 @@ mod tests { let profile = make_profile(ClientOs::Linux); let cookie_params: HashMap = HashMap::new(); - let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity(); + let info = HostInfoCollector::new(&profile, &input, &cookie_params) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); assert_eq!(info.host_id, profile.host_id()); } @@ -849,7 +921,9 @@ mod tests { let profile = make_profile(client_os); let cookie_params: HashMap = HashMap::new(); - let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect_identity(); + let info = HostInfoCollector::new(&profile, &input, &cookie_params) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); assert_eq!(info.host_id, profile.host_id()); } @@ -870,11 +944,206 @@ mod tests { validate_edited_report(&report).unwrap(); } + #[test] + fn emulated_windows_uses_v4_categories_and_preserves_template_posture() { + use gpapi::os_profile::HostSnapshot; + let identity = gpapi::os_profile::desktop::identity_from_parts( + "emulated-device".into(), + "emulated-id".into(), + "serial".into(), + "00:11:22:33:44:55".into(), + ); + let profile = OsProfileBuilder::new(ClientOs::Windows).build(HostSnapshot { + runtime_os: ClientOs::Mac, + identity, + os_version: "macOS".into(), + software_version: "15.0".into(), + }); + assert!(!profile.is_native()); + let mut input = make_input(profile); + input.context = ReportContext::Connected { + cookie: "domain=emulated-domain".into(), + client_ip: None, + client_ipv6: None, + md5: "test-digest".into(), + }; + let report = generate_report(&input).unwrap(); + let root = validate_edited_report(&report).unwrap(); + assert_eq!( + unique_child(&root, "domain").unwrap().get_text().unwrap(), + "emulated-domain.internal" + ); + assert!(report.contains("emulated-domain.internal")); + let identity = Element::parse(generate_identity_report(&input).unwrap().as_bytes()).unwrap(); + assert_eq!( + unique_child(&identity, "domain").unwrap().get_text().unwrap(), + "emulated-domain" + ); + let categories = unique_child(&root, "categories").unwrap(); + let names = categories + .children + .iter() + .filter_map(xmltree::XMLNode::as_element) + .filter_map(|entry| entry.attributes.get("name").map(String::as_str)) + .collect::>(); + assert_eq!( + names, + [ + "host-info", + "anti-malware", + "disk-backup", + "disk-encryption", + "firewall", + "patch-management", + "data-loss-prevention" + ] + ); + assert!(report.contains("McAfee VirusScan Enterprise")); + assert!(report.contains("McAfee ePolicy Orchestrator Agent")); + assert_eq!(report.matches("prodType=\"3\"").count(), 2); + assert!(report.contains("C:\\")); + assert!(report.contains("encrypted")); + assert!(report.contains("")); + } + + #[test] + fn emulated_unix_domains_keep_existing_cookie_and_suffix_behavior() { + for client_os in [ClientOs::Mac, ClientOs::Linux] { + let expected_domain = if client_os == ClientOs::Linux { + ".internal" + } else { + "emulated-domain.internal" + }; + let profile = OsProfileBuilder::new(client_os).build(gpapi::os_profile::HostSnapshot { + runtime_os: ClientOs::Windows, + identity: gpapi::os_profile::HostIdentity::from_parts( + "host".into(), + "id".into(), + "serial".into(), + "00:11:22:33:44:55".into(), + ), + os_version: "Windows".into(), + software_version: "11".into(), + }); + assert!(!profile.is_native()); + let mut input = make_input(profile); + input.context = ReportContext::Connected { + cookie: "domain=emulated-domain".into(), + client_ip: None, + client_ipv6: None, + md5: "test-digest".into(), + }; + let xml = generate_report(&input).unwrap(); + let generated = validate_edited_report(&xml).unwrap(); + let refreshed = validate_edited_report(&refresh_edited_report(&xml, &input).unwrap()).unwrap(); + for report in [generated, refreshed] { + assert_eq!( + unique_child(&report, "domain").unwrap().get_text().unwrap(), + expected_domain + ); + assert_eq!( + unique_child(host_info(&report).unwrap(), "domain") + .unwrap() + .get_text() + .unwrap(), + expected_domain + ); + } + let identity = Element::parse(generate_identity_report(&input).unwrap().as_bytes()).unwrap(); + assert_eq!( + unique_child(&identity, "domain").unwrap().get_text().unwrap(), + "emulated-domain" + ); + } + } + + #[test] + fn native_domain_is_shared_by_generated_edited_and_identity_reports() { + let client_os = if cfg!(windows) { + ClientOs::Windows + } else if cfg!(target_os = "macos") { + ClientOs::Mac + } else { + ClientOs::Linux + }; + let profile = OsProfileBuilder::new(client_os).build(gpapi::os_profile::HostSnapshot { + runtime_os: client_os, + identity: gpapi::os_profile::HostIdentity::from_parts( + "host".into(), + "id".into(), + "serial".into(), + "00:11:22:33:44:55".into(), + ), + os_version: "Windows".into(), + software_version: "11".into(), + }); + let mut input = make_input(profile); + input.context = ReportContext::Connected { + cookie: "domain=auth-cookie-must-not-be-used.invalid".into(), + client_ip: None, + client_ipv6: None, + md5: "test-digest".into(), + }; + let expected = native_domain(&input.profile, &CollectionBudget::new(Duration::from_secs(10))) + .unwrap() + .unwrap(); + let params = cookie_params(&input); + let mut host_info = HostInfoCollector::new(&input.profile, &input, ¶ms) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); + // Render the identity path without executing the product collectors. + if client_os == ClientOs::Windows { + host_info.windows_categories = Some(windows_report::WindowsReport::default().render().unwrap()); + } + let (generate_time, day, month, year) = get_current_time_components(); + let xml = HipReportTemplate { + client_version: input.profile.client_version(), + generate_time, + day, + month, + year, + user_name: "test-user", + host_info, + md5: "test-digest", + } + .render() + .unwrap(); + let generated = validate_edited_report(&xml).unwrap(); + let mut stale = generated.clone(); + set_field(&mut stale, "domain", "stale.internal").unwrap(); + set_field(host_info_mut(&mut stale).unwrap(), "domain", "stale.internal").unwrap(); + let refreshed = refresh_edited_report(&write_xml(&stale).unwrap(), &input).unwrap(); + let refreshed = validate_edited_report(&refreshed).unwrap(); + let identity = Element::parse(generate_identity_report(&input).unwrap().as_bytes()).unwrap(); + for report in [&generated, &refreshed, &identity] { + assert_eq!( + unique_child(report, "domain") + .unwrap() + .get_text() + .unwrap_or_default() + .as_ref(), + expected + ); + } + for mut report in [generated, refreshed] { + assert_eq!( + unique_child(host_info_mut(&mut report).unwrap(), "domain") + .unwrap() + .get_text() + .unwrap_or_default() + .as_ref(), + expected + ); + } + } + #[test] fn mac_report_renders_detected_sentinel_products() { let input = make_input(make_profile(ClientOs::Mac)); let cookie_params = HashMap::new(); - let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect_identity(); + let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); host_info.sentinel = Some(SentinelInfo { version: "25.3.4.8365".to_string(), real_time_protection: true, @@ -905,7 +1174,9 @@ mod tests { fn linux_report_renders_detected_sentinel_antimalware() { let input = make_input(make_profile(ClientOs::Linux)); let cookie_params = HashMap::new(); - let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params).collect_identity(); + let mut host_info = HostInfoCollector::new(&input.profile, &input, &cookie_params) + .collect_identity(&CollectionBudget::new(Duration::from_secs(10))) + .unwrap(); host_info.sentinel = Some(SentinelInfo { version: "25.2.2.14".to_string(), real_time_protection: true, diff --git a/crates/gphip/src/windows.rs b/crates/gphip/src/windows.rs new file mode 100644 index 0000000..e53649f --- /dev/null +++ b/crates/gphip/src/windows.rs @@ -0,0 +1,96 @@ +//! Public JSON adapter and native Windows host identity. +use super::windows_report::WindowsReport; +use gpapi::{collection::CollectionControl, process::collection::CollectorCommands}; +use std::io; + +pub(super) fn collect(commands: &CollectorCommands<'_>, control: &dyn CollectionControl) -> io::Result { + let executable = std::env::current_exe()?; + let helper = executable + .parent() + .ok_or_else(|| io::Error::other("Application directory is unavailable"))? + .join("gp-posture.exe"); + let output = commands + .run_executable(&helper, &[])? + .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Windows posture helper is not installed"))?; + if !output.status.success() { + return Err(io::Error::other("Windows posture collection failed")); + } + let report: WindowsReport = serde_json::from_slice(&output.stdout).map_err(io::Error::other)?; + for category in &report.unavailable { + log::warn!("Windows HIP data unavailable: {category}"); + } + control.check()?; + Ok(report) +} + +/// Windows supplies the loopback adapter's real ID through GetAdaptersAddresses (via netdev). +pub(super) fn loopback_interfaces() -> Vec { + netdev::get_interfaces() + .into_iter() + .filter(|interface| interface.is_loopback()) + .map(|interface| { + super::NetworkInterface::new(interface.name.clone(), interface.description.unwrap_or(interface.name)) + .with_mac(Some( + interface + .mac_addr + .map(|mac| super::format_native_windows_mac(mac.address())) + .unwrap_or_default(), + )) + .with_ipv4(interface.ipv4.first().map(|ip| ip.addr().to_string())) + .with_ipv6(interface.ipv6.first().map(|ip| ip.addr().to_string())) + }) + .collect() +} + +/// Primary DNS domain, or physical DNS domain if the primary query fails. +pub(super) fn domain() -> io::Result { + use windows::Win32::{ + Networking::ActiveDirectory::{ + DSROLE_PRIMARY_DOMAIN_INFO_BASIC, DsRoleFreeMemory, DsRoleGetPrimaryDomainInformation, + DsRolePrimaryDomainInfoBasic, + }, + System::SystemInformation::{ComputerNamePhysicalDnsDomain, GetComputerNameExW}, + }; + use windows::core::PWSTR; + + let mut buffer = std::ptr::null_mut(); + // SAFETY: a null server selects this computer; Windows allocates and owns the returned structure. + let status = unsafe { DsRoleGetPrimaryDomainInformation(None, DsRolePrimaryDomainInfoBasic, &mut buffer) }; + if status == 0 && !buffer.is_null() { + // SAFETY: the requested information level returns this structure. Copy the string before freeing its allocation. + let result = unsafe { copy_domain_name((*buffer.cast::()).DomainNameDns) }; + unsafe { DsRoleFreeMemory(buffer.cast()) }; + return result; + } + + let mut name = [0u16; 257]; + let mut size = name.len() as u32; + // SAFETY: the writable UTF-16 buffer and its character count remain valid for the call. + unsafe { GetComputerNameExW(ComputerNamePhysicalDnsDomain, Some(PWSTR(name.as_mut_ptr())), &mut size) } + .map_err(io::Error::other)?; + String::from_utf16(&name[..size as usize]).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error)) +} + +// SAFETY: a non-null name must point to a live NUL-terminated UTF-16 string. +unsafe fn copy_domain_name(name: windows::core::PWSTR) -> io::Result { + if name.is_null() { + // A successful primary-domain query with no DNS name is an empty domain, including workgroup hosts. + return Ok(String::new()); + } + unsafe { name.to_string() }.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error)) +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::core::PWSTR; + #[test] + fn primary_domain_preserves_dns_name_and_empty_workgroup_domain() { + let mut name: Vec = "Lab.Example.test\0".encode_utf16().collect(); + assert_eq!( + unsafe { copy_domain_name(PWSTR(name.as_mut_ptr())) }.unwrap(), + "Lab.Example.test" + ); + assert_eq!(unsafe { copy_domain_name(PWSTR::null()) }.unwrap(), ""); + } +} diff --git a/crates/gphip/src/windows_report.rs b/crates/gphip/src/windows_report.rs new file mode 100644 index 0000000..ee71d85 --- /dev/null +++ b/crates/gphip/src/windows_report.rs @@ -0,0 +1,298 @@ +//! Windows posture facts and their HIP v4 representation. +use serde::Deserialize; +use xmltree::{Element, XMLNode}; + +#[derive(Default, Deserialize)] +#[serde(default)] +pub(super) struct WindowsReport { + pub anti_malware: Vec, + pub disk_backup: Vec, + pub disk_encryption: Vec, + pub firewall: Vec, + pub patch_management: Vec, + pub missing_patches: Option>, + pub unavailable: Vec, +} + +#[derive(Default, Deserialize)] +#[serde(default)] +pub(super) struct Product { + pub name: String, + pub vendor: String, + pub version: String, +} + +#[derive(Default, Deserialize)] +#[serde(default)] +pub(super) struct AntiMalware { + pub product: Product, + pub enabled: Option, + pub definition_version: Option, + pub engine_version: Option, + pub definition_date: Option, + pub last_scan: Option, +} + +#[derive(Default, Deserialize)] +#[serde(default)] +pub(super) struct Backup { + pub product: Product, + pub last_backup: Option, +} + +#[derive(Default, Deserialize)] +#[serde(default)] +pub(super) struct Encryption { + pub product: Product, + pub drives: Vec, +} + +#[derive(Deserialize)] +pub(super) struct Drive { + pub name: String, + pub conversion_status: Option, +} + +#[derive(Default, Deserialize)] +#[serde(default)] +pub(super) struct ProductState { + pub product: Product, + pub enabled: Option, +} + +#[derive(Default, Deserialize)] +#[serde(default)] +pub(super) struct MissingPatch { + pub title: String, + pub description: String, + pub kb: String, + pub category: String, + pub vendor: String, + pub msrc_severity: Option, +} + +impl MissingPatch { + fn severity(&self) -> i32 { + match self.msrc_severity.as_deref().map(str::to_ascii_lowercase).as_deref() { + Some("critical") => 3, + Some("important") => 2, + Some("moderate") => 1, + Some("low") => 0, + _ => -1, + } + } +} + +impl WindowsReport { + pub fn render(&self) -> std::io::Result { + let mut categories = Vec::new(); + categories.push(category( + "anti-malware", + self.anti_malware.iter().map(|item| { + let mut info = product(&item.product); + let prod = info.get_mut_child("Prod").unwrap(); + prod.attributes.insert("prodType".into(), "3".into()); + prod.attributes.insert("osType".into(), "1".into()); + for (name, value) in [("defver", &item.definition_version), ("engver", &item.engine_version)] { + if let Some(value) = value { + prod.attributes.insert(name.into(), value.clone()); + } + } + if let Some(date) = item + .definition_date + .as_deref() + .and_then(|date| chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()) + { + use chrono::Datelike; + for (name, value) in [ + ("dateyear", date.year().to_string()), + ("datemon", date.month().to_string()), + ("dateday", date.day().to_string()), + ] { + prod.attributes.insert(name.into(), value); + } + } + field(&mut info, "real-time-protection", yes_no(item.enabled)); + field( + &mut info, + "last-full-scan-time", + item.last_scan.as_deref().unwrap_or("n/a"), + ); + info + }), + )); + categories.push(category( + "disk-backup", + self.disk_backup.iter().map(|item| { + let mut info = product(&item.product); + field( + &mut info, + "last-backup-time", + item.last_backup.as_deref().unwrap_or("n/a"), + ); + info + }), + )); + categories.push(category( + "disk-encryption", + self.disk_encryption.iter().map(|item| { + let mut info = product(&item.product); + let mut drives = Element::new("drives"); + for drive in &item.drives { + let mut entry = Element::new("entry"); + field(&mut entry, "drive-name", &drive.name); + field( + &mut entry, + "enc-state", + match drive.conversion_status { + Some(0) => "unencrypted", + Some(1) => "encrypted", + _ => "n/a", + }, + ); + drives.children.push(XMLNode::Element(entry)); + } + info.children.push(XMLNode::Element(drives)); + info + }), + )); + categories.push(category("firewall", self.firewall.iter().map(state))); + let mut patches = category("patch-management", self.patch_management.iter().map(state)); + // A failed search is not evidence that the machine has no missing updates. + if let Some(missing) = &self.missing_patches { + let mut list = Element::new("missing-patches"); + for patch in missing { + let mut entry = Element::new("entry"); + field(&mut entry, "title", &patch.title); + field(&mut entry, "description", &patch.description); + field(&mut entry, "product", ""); + field(&mut entry, "vendor", &patch.vendor); + field(&mut entry, "info-url", ""); + field(&mut entry, "kb-article-id", &patch.kb); + field(&mut entry, "security-bulletin-id", ""); + field(&mut entry, "severity", &patch.severity().to_string()); + field(&mut entry, "category", &patch.category); + field(&mut entry, "is-installed", "no"); + list.children.push(XMLNode::Element(entry)); + } + patches.children.push(XMLNode::Element(list)); + } + categories.push(patches); + let mut output = Vec::new(); + for category in categories { + category + .write_with_config( + &mut output, + xmltree::EmitterConfig::new().write_document_declaration(false), + ) + .map_err(std::io::Error::other)?; + } + String::from_utf8(output).map_err(std::io::Error::other) + } +} + +fn yes_no(enabled: Option) -> &'static str { + match enabled { + Some(true) => "yes", + Some(false) => "no", + None => "n/a", + } +} + +fn field(parent: &mut Element, name: &str, value: &str) { + let mut child = Element::new(name); + child.children.push(XMLNode::Text(value.into())); + parent.children.push(XMLNode::Element(child)); +} + +fn product(product: &Product) -> Element { + let mut info = Element::new("ProductInfo"); + let mut prod = Element::new("Prod"); + for (name, value) in [ + ("name", &product.name), + ("vendor", &product.vendor), + ("version", &product.version), + ] { + if !value.is_empty() { + prod.attributes.insert(name.into(), value.clone()); + } + } + info.children.push(XMLNode::Element(prod)); + info +} + +fn state(item: &ProductState) -> Element { + let mut info = product(&item.product); + field(&mut info, "is-enabled", yes_no(item.enabled)); + info +} + +fn category(name: &str, products: impl Iterator) -> Element { + let mut category = Element::new("entry"); + category.attributes.insert("name".into(), name.into()); + let mut list = Element::new("list"); + for product in products { + let mut entry = Element::new("entry"); + entry.children.push(XMLNode::Element(product)); + list.children.push(XMLNode::Element(entry)); + } + category.children.push(XMLNode::Element(list)); + category +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn real_posture_preserves_unavailable_values_and_escapes_product_text() { + let report: WindowsReport = serde_json::from_str( + r#"{ + "anti_malware":[{"product":{"name":"Agent & Endpoint","version":"25.1"},"enabled":true}], + "disk_encryption":[{"product":{"name":"BitLocker"},"drives":[{"name":"C:\\","conversion_status":0}]}], + "missing_patches":null + }"#, + ) + .unwrap(); + let xml = report.render().unwrap(); + let root = Element::parse(format!("{xml}").as_bytes()).unwrap(); + assert_eq!(root.children.len(), 5); + assert!(xml.contains("Agent & Endpoint")); + assert!(xml.contains("unencrypted")); + assert!(xml.contains("n/a")); + assert!(!xml.contains("missing-patches")); + assert!(!xml.contains("McAfee")); + } + + #[test] + fn missing_patch_severity_is_unknown_without_an_observed_msrc_rating() { + for category in ["driver", "update", "security_update", "critical_update"] { + let mut patch = MissingPatch { + category: category.into(), + ..Default::default() + }; + assert_eq!(patch.severity(), -1); + patch.msrc_severity = Some("Critical".into()); + assert_eq!(patch.severity(), 3); + patch.msrc_severity = Some("Unrecognized".into()); + assert_eq!(patch.severity(), -1); + } + } + + #[test] + fn successful_update_search_distinguishes_empty_and_missing_updates() { + let mut report = WindowsReport { + missing_patches: Some(vec![]), + ..Default::default() + }; + assert!(report.render().unwrap().contains("")); + report.missing_patches = Some(vec![MissingPatch { + title: "Security update".into(), + kb: "123".into(), + ..Default::default() + }]); + let xml = report.render().unwrap(); + assert!(xml.contains("123")); + assert!(xml.contains("no")); + } +} diff --git a/crates/gphip/templates/hip_report.xml b/crates/gphip/templates/hip_report.xml index 795f546..c625a70 100644 --- a/crates/gphip/templates/hip_report.xml +++ b/crates/gphip/templates/hip_report.xml @@ -2,7 +2,7 @@ {{ md5 }} {{ user_name }} - {{ host_info.domain }}.internal + {{ host_info.domain }} {{ host_info.host_name }} {{ host_info.host_id }} {{ host_info.default_ipv4() }} @@ -14,7 +14,7 @@ {{ client_version }} {{ host_info.os_version }} {{ host_info.os_vendor }} - {{ host_info.domain }}.internal + {{ host_info.domain }} {{ host_info.host_name }} {{ host_info.host_id }} @@ -39,103 +39,11 @@ {% if host_info.os_vendor == "Microsoft" -%} - - - - - - - yes - {{ generate_time }} - - - - - - - no - n/a - - - - - - - - - - - yes - {{ generate_time }} - - - - - - - no - n/a - - - - - - - - - - - n/a - - - - - - - - - - - - - C:\\ - full - - - - - - - - - - - - - yes - - - - - - - - - - - yes - - - - - - - yes - - - - - + {% if let Some(categories) = &host_info.windows_categories -%} + {{ categories|safe }} + {% else -%} + {% include "windows_emulation.xml" %} + {% endif -%} {% elif host_info.os_vendor == "Apple" -%} diff --git a/crates/gphip/templates/windows_emulation.xml b/crates/gphip/templates/windows_emulation.xml new file mode 100644 index 0000000..dfa0827 --- /dev/null +++ b/crates/gphip/templates/windows_emulation.xml @@ -0,0 +1,77 @@ + + + + + + + yes + {{ generate_time }} + + + + + + + no + n/a + + + + + + + + + + + n/a + + + + + + + + + + + + + C:\ + encrypted + + + + + + + + + + + + + yes + + + + + + + + + + + yes + + + + + + + yes + + + + + diff --git a/packaging/windows/machine-install.ps1 b/packaging/windows/machine-install.ps1 index 058bce7..cee5a99 100644 --- a/packaging/windows/machine-install.ps1 +++ b/packaging/windows/machine-install.ps1 @@ -227,7 +227,7 @@ try { if ($source -eq $destination -or $source.StartsWith($destination + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Install from an extracted package outside the application folder.' } - foreach ($name in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'libopenconnect-5.dll', 'wintun.dll', 'build-info.json')) { + foreach ($name in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'gp-posture.exe', 'libopenconnect-5.dll', 'wintun.dll', 'build-info.json')) { if (!(Test-Path -LiteralPath (Join-Path $source $name) -PathType Leaf)) { throw "Missing Windows package file: $name" } } $info = Get-Content -LiteralPath (Join-Path $source 'build-info.json') -Raw | ConvertFrom-Json @@ -249,7 +249,7 @@ try { $payload = @(Get-ChildItem -LiteralPath $source -Force | Where-Object { ($_.PSIsContainer -and $_.Name -eq 'licenses') -or (!$_.PSIsContainer -and ($_.Extension -eq '.dll' -or - $_.Name -in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'uninstall.exe', 'build-info.json'))) + $_.Name -in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'gp-posture.exe', 'uninstall.exe', 'build-info.json'))) }) foreach ($item in $payload) { $items = @($item)