mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 06:26:14 -05:00
release: prepare GP Connect 3.5.0 with Windows support
This commit is contained in:
172 files changed
+9629
-1171
No files matched your search
@@ -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<String> {
|
||||
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), "");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String> {
|
||||
linux_domain(|program, args| read(commands, program, args))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "freebsd")]
|
||||
pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result<String> {
|
||||
read(commands, "hostname", &["-d"])
|
||||
}
|
||||
|
||||
#[cfg(target_os = "openbsd")]
|
||||
pub(super) fn collect(commands: &CollectorCommands<'_>) -> io::Result<String> {
|
||||
read(commands, "hostname", &[]).map(|hostname| hostname_domain(&hostname))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn read(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result<String> {
|
||||
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<String>) -> io::Result<String> {
|
||||
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(""), "");
|
||||
}
|
||||
}
|
||||
+340
-44
@@ -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<Option<String>> {
|
||||
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,17 @@ pub fn generate_report(input: &ReportInput) -> anyhow::Result<String> {
|
||||
}
|
||||
|
||||
/// Identity-only maintenance report. This deliberately does not enumerate the
|
||||
/// machine or execute posture collectors; addresses come from the session owner.
|
||||
pub fn generate_identity_report(input: &ReportInput) -> anyhow::Result<String> {
|
||||
/// 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, control: &dyn CollectionControl) -> anyhow::Result<String> {
|
||||
let params = cookie_params(input);
|
||||
let domain =
|
||||
native_domain(&input.profile, control)?.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()),
|
||||
@@ -241,10 +274,18 @@ pub fn generate_identity_report(input: &ReportInput) -> anyhow::Result<String> {
|
||||
}
|
||||
|
||||
pub fn generate_report_with_control(input: &ReportInput, control: &dyn CollectionControl) -> anyhow::Result<String> {
|
||||
Ok(generate_report_details(input, control)?.xml)
|
||||
}
|
||||
|
||||
pub fn generate_report_details(
|
||||
input: &ReportInput,
|
||||
control: &dyn CollectionControl,
|
||||
) -> anyhow::Result<gpapi::hip::HipReport> {
|
||||
control.check()?;
|
||||
let cookie_params = cookie_params(input);
|
||||
let (generate_time, day, month, year) = get_current_time_components();
|
||||
let host_info = HostInfoCollector::new(&input.profile, input, &cookie_params).collect(control)?;
|
||||
let windows_updates = host_info.windows_updates.clone();
|
||||
let template = HipReportTemplate {
|
||||
client_version: input.profile.client_version(),
|
||||
generate_time,
|
||||
@@ -255,9 +296,9 @@ pub fn generate_report_with_control(input: &ReportInput, control: &dyn Collectio
|
||||
host_info,
|
||||
md5: input.context.md5(),
|
||||
};
|
||||
let report = format_xml(&template.render()?)?;
|
||||
let xml = format_xml(&template.render()?)?;
|
||||
control.check()?;
|
||||
Ok(report)
|
||||
Ok(gpapi::hip::HipReport { xml, windows_updates })
|
||||
}
|
||||
|
||||
fn cookie_params(input: &ReportInput) -> HashMap<String, String> {
|
||||
@@ -338,6 +379,8 @@ struct HostInfo {
|
||||
clamav: Option<ClamAvInfo>,
|
||||
sentinel: Option<SentinelInfo>,
|
||||
ufw: Option<UfwInfo>,
|
||||
windows_categories: Option<String>,
|
||||
windows_updates: Option<gpapi::hip::WindowsUpdateStatus>,
|
||||
}
|
||||
|
||||
impl HostInfo {
|
||||
@@ -425,16 +468,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 +485,28 @@ 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<HostInfo> {
|
||||
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,
|
||||
windows_updates: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Build the primary network interface with OS-appropriate naming and
|
||||
@@ -496,9 +529,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<NetworkInterface> {
|
||||
#[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 +547,31 @@ 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<String> {
|
||||
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<HostInfo> {
|
||||
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() {
|
||||
let report = windows::collect(&commands, control)?;
|
||||
info.windows_updates = Some(report.update_status());
|
||||
info.windows_categories = Some(report.render()?);
|
||||
}
|
||||
|
||||
if self.profile.client_os() == ClientOs::Linux && self.profile.is_native() {
|
||||
info.defender = detect_microsoft_defender(&commands)?;
|
||||
info.clamav = detect_clamav(&commands)?;
|
||||
@@ -570,11 +617,14 @@ fn detect_ufw(commands: &CollectorCommands<'_>) -> io::Result<Option<UfwInfo>> {
|
||||
let Some(ufw) = commands.resolve("ufw") else {
|
||||
return Ok(None);
|
||||
};
|
||||
#[cfg(unix)]
|
||||
let output = if uzers::get_effective_uid() == 0 {
|
||||
commands.run_path(&ufw, &["status"])?
|
||||
} else {
|
||||
commands.run("sudo", &["-n", &ufw.to_string_lossy(), "status"])?
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let output = commands.run_path(&ufw, &["status"])?;
|
||||
let Some(output) = output.filter(|output| output.status.success()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -668,16 +718,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<String>) -> Option<String> {
|
||||
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
|
||||
// ============================================================================
|
||||
@@ -756,6 +810,17 @@ mod tests {
|
||||
gpapi::os_profile::desktop::collect_profile(OsProfileBuilder::new(client_os), None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_identity_report_stops_before_domain_collection() {
|
||||
let input = make_input(make_profile(ClientOs::Linux));
|
||||
let cancelled = || Err(io::Error::from(io::ErrorKind::Interrupted));
|
||||
let error = generate_identity_report(&input, &cancelled).unwrap_err();
|
||||
assert_eq!(
|
||||
error.downcast_ref::<io::Error>().unwrap().kind(),
|
||||
io::ErrorKind::Interrupted
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_report_contains_session_identity_without_posture() {
|
||||
for os in [ClientOs::Linux, ClientOs::Mac, ClientOs::Windows] {
|
||||
@@ -766,7 +831,7 @@ mod tests {
|
||||
client_ipv6: Some("2001:db8::7".into()),
|
||||
md5: "identity-token".into(),
|
||||
};
|
||||
let xml = generate_identity_report(&input).unwrap();
|
||||
let xml = generate_identity_report(&input, &|| Ok(())).unwrap();
|
||||
let root = Element::parse(xml.as_bytes()).unwrap();
|
||||
assert_eq!(
|
||||
unique_child(&root, "user-name").unwrap().get_text().unwrap(),
|
||||
@@ -793,13 +858,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<String, String> = 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");
|
||||
}
|
||||
@@ -810,7 +901,9 @@ mod tests {
|
||||
let profile = make_profile(ClientOs::Mac);
|
||||
let cookie_params: HashMap<String, String> = 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");
|
||||
}
|
||||
@@ -821,7 +914,9 @@ mod tests {
|
||||
let profile = make_profile(ClientOs::Windows);
|
||||
let cookie_params: HashMap<String, String> = 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");
|
||||
}
|
||||
@@ -832,7 +927,9 @@ mod tests {
|
||||
let profile = make_profile(ClientOs::Linux);
|
||||
let cookie_params: HashMap<String, String> = 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());
|
||||
}
|
||||
@@ -846,7 +943,9 @@ mod tests {
|
||||
let profile = make_profile(client_os);
|
||||
let cookie_params: HashMap<String, String> = 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());
|
||||
}
|
||||
@@ -867,11 +966,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("<domain>emulated-domain.internal</domain>"));
|
||||
let identity = Element::parse(generate_identity_report(&input, &|| Ok(())).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::<Vec<_>>();
|
||||
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("<drive-name>C:\\</drive-name>"));
|
||||
assert!(report.contains("<enc-state>encrypted</enc-state>"));
|
||||
assert!(report.contains("<missing-patches />"));
|
||||
}
|
||||
|
||||
#[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, &|| Ok(())).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, &|| Ok(())).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,
|
||||
@@ -902,7 +1196,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,
|
||||
|
||||
@@ -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<WindowsReport> {
|
||||
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<super::NetworkInterface> {
|
||||
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<String> {
|
||||
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::<DSROLE_PRIMARY_DOMAIN_INFO_BASIC>()).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<String> {
|
||||
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<u16> = "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(), "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
//! 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<AntiMalware>,
|
||||
pub disk_backup: Vec<Backup>,
|
||||
pub disk_encryption: Vec<Encryption>,
|
||||
pub firewall: Vec<ProductState>,
|
||||
pub patch_management: Vec<ProductState>,
|
||||
pub missing_patches: Option<Vec<MissingPatch>>,
|
||||
pub patches_checked_at: Option<u64>,
|
||||
pub unavailable: Vec<String>,
|
||||
}
|
||||
|
||||
#[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<bool>,
|
||||
pub definition_version: Option<String>,
|
||||
pub engine_version: Option<String>,
|
||||
pub definition_date: Option<String>,
|
||||
pub last_scan: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub(super) struct Backup {
|
||||
pub product: Product,
|
||||
pub last_backup: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub(super) struct Encryption {
|
||||
pub product: Product,
|
||||
pub drives: Vec<Drive>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct Drive {
|
||||
pub name: String,
|
||||
pub conversion_status: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub(super) struct ProductState {
|
||||
pub product: Product,
|
||||
pub enabled: Option<bool>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
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(super) fn update_status(&self) -> gpapi::hip::WindowsUpdateStatus {
|
||||
let mut status = gpapi::hip::WindowsUpdateStatus::default();
|
||||
if self.missing_patches.is_some() {
|
||||
status.checked_at = self.patches_checked_at;
|
||||
} else {
|
||||
status.omitted_snapshot_at = self.patches_checked_at;
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
pub fn render(&self) -> std::io::Result<String> {
|
||||
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<bool>) -> &'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<Item = Element>) -> 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 omitted_snapshot_can_be_refreshed_without_claiming_patch_details() {
|
||||
let mut report = WindowsReport::default();
|
||||
assert_eq!(report.update_status().refresh_cursor(), None);
|
||||
report.patches_checked_at = Some(123);
|
||||
let status = report.update_status();
|
||||
assert_eq!(status.checked_at, None);
|
||||
assert_eq!(status.refresh_cursor(), Some(123));
|
||||
assert!(!report.render().unwrap().contains("missing-patches"));
|
||||
report.missing_patches = Some(Vec::new());
|
||||
assert_eq!(report.update_status().checked_at, Some(123));
|
||||
assert_eq!(report.update_status().refresh_cursor(), Some(123));
|
||||
}
|
||||
|
||||
#[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!("<categories>{xml}</categories>").as_bytes()).unwrap();
|
||||
assert_eq!(root.children.len(), 5);
|
||||
assert!(xml.contains("Agent & Endpoint"));
|
||||
assert!(xml.contains("<enc-state>unencrypted</enc-state>"));
|
||||
assert!(xml.contains("<last-full-scan-time>n/a</last-full-scan-time>"));
|
||||
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("<missing-patches />"));
|
||||
report.missing_patches = Some(vec![MissingPatch {
|
||||
title: "Security update".into(),
|
||||
kb: "123".into(),
|
||||
..Default::default()
|
||||
}]);
|
||||
let xml = report.render().unwrap();
|
||||
assert!(xml.contains("<kb-article-id>123</kb-article-id>"));
|
||||
assert!(xml.contains("<is-installed>no</is-installed>"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user