feat(hip): manage reports and script execution

This commit is contained in:
Kevin Yue committed 2026-09-29 11:43:54 +08:00
1 parent 24d935ea61
commit 739cf7234b
54 files changed
+3122 -967

No files matched your search

+7
View File
@@ -9,6 +9,8 @@ use std::{
))]
use crate::constants::GP_DOWNLOADED_GUI_BINARY;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use crate::constants::GP_HIP_SCRIPT_INSTALLER_BINARY;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use crate::constants::GP_VPNC_SCRIPT_INSTALLER_BINARY;
use crate::constants::{GP_AUTH_BINARY, GP_CLIENT_BINARY, GP_GUI_BINARY, GP_GUI_HELPER_BINARY, GP_SERVICE_BINARY};
@@ -29,6 +31,11 @@ pub fn gp_vpnc_script_installer() -> PathBuf {
)
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
pub fn gp_hip_script_installer() -> PathBuf {
PathBuf::from(GP_HIP_SCRIPT_INSTALLER_BINARY)
}
pub fn gpauth() -> PathBuf {
resolve("GP_AUTH_BINARY", "gpauth", GP_AUTH_BINARY)
}
+5
View File
@@ -6,6 +6,10 @@ pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
#[cfg(target_os = "linux")]
pub const GP_VPNC_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-vpnc-script-installer";
#[cfg(target_os = "linux")]
pub const GP_HIP_SCRIPT_INSTALLER_BINARY: &str = "/usr/libexec/gpclient/gp-hip-script-installer";
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
pub const GP_HIP_SCRIPT_INSTALLER_BINARY: &str = "/usr/local/libexec/gpclient/gp-hip-script-installer";
#[cfg(target_os = "linux")]
pub const INSTALLED_VPNC_SCRIPT: &str = "/var/lib/gpclient/scripts/vpnc-script";
#[cfg(target_os = "linux")]
pub const INSTALLED_VPNC_SCRIPT_METADATA: &str = "/var/lib/gpclient/scripts/vpnc-script.metadata";
@@ -16,6 +20,7 @@ pub const INSTALLED_VPNC_SCRIPT: &str = "/var/db/gpclient/scripts/vpnc-script";
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
pub const INSTALLED_VPNC_SCRIPT_METADATA: &str = "/var/db/gpclient/scripts/vpnc-script.metadata";
pub const MAX_VPNC_SCRIPT_SIZE: usize = 1024 * 1024;
pub const MAX_HIP_SCRIPT_SIZE: usize = 1024 * 1024;
// Release binaries - macOS (Apple Silicon Homebrew)
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
-96
View File
@@ -1,96 +0,0 @@
use std::process::Stdio;
use anyhow::bail;
use tokio::process::Command;
pub struct HipLauncher<'a> {
program: &'a str,
cookie: Option<&'a str>,
client_ip: Option<&'a str>,
md5: Option<&'a str>,
client_os: Option<&'a str>,
client_version: Option<&'a str>,
}
impl<'a> HipLauncher<'a> {
pub fn new(program: &'a str) -> Self {
Self {
program,
cookie: None,
client_ip: None,
md5: None,
client_os: None,
client_version: None,
}
}
pub fn cookie(mut self, cookie: &'a str) -> Self {
self.cookie = Some(cookie);
self
}
pub fn client_ip(mut self, client_ip: &'a str) -> Self {
self.client_ip = Some(client_ip);
self
}
pub fn md5(mut self, md5: &'a str) -> Self {
self.md5 = Some(md5);
self
}
pub fn client_os(mut self, client_os: &'a str) -> Self {
self.client_os = Some(client_os);
self
}
pub fn client_version(mut self, client_version: Option<&'a str>) -> Self {
self.client_version = client_version;
self
}
pub async fn launch(&self) -> anyhow::Result<String> {
let mut cmd = Command::new(self.program);
if let Some(cookie) = self.cookie {
cmd.arg("--cookie").arg(cookie);
}
if let Some(client_ip) = self.client_ip {
cmd.arg("--client-ip").arg(client_ip);
}
if let Some(md5) = self.md5 {
cmd.arg("--md5").arg(md5);
}
if let Some(client_os) = self.client_os {
cmd.arg("--client-os").arg(client_os);
}
if let Some(client_version) = self.client_version {
cmd.env("APP_VERSION", client_version);
}
let child = cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn();
let child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", self.program, err),
};
let output = child.wait_with_output().await?;
if let Some(exit_status) = output.status.code() {
if exit_status != 0 {
bail!("HIP report generation failed with exit code {}", exit_status);
}
let report = String::from_utf8(output.stdout)?;
Ok(report)
} else {
bail!("HIP report generation failed");
}
}
}
-1
View File
@@ -6,6 +6,5 @@ pub use command_traits::CommandExt;
pub mod auth_launcher;
pub mod gui_launcher;
pub mod hip_launcher;
pub mod service_launcher;
pub mod users;
+47
View File
@@ -0,0 +1,47 @@
use serde::{Deserialize, Serialize};
use specta::Type;
/// The GUI's choice of HIP report source. gpservice resolves execution details.
#[derive(Clone, Debug, Default, Deserialize, Serialize, Type, PartialEq, Eq)]
#[serde(tag = "source", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum HipSource {
#[default]
Disabled,
Generated,
Edited {
report_id: String,
},
UserScript {
path: String,
},
ApprovedRootScript {
approval_id: String,
},
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Type, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum HipApprovalStatus {
Valid,
Revoked,
Corrupt,
OtherUser,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn source_round_trips_without_execution_uid_or_wrapper() {
let source = HipSource::ApprovedRootScript {
approval_id: "approved-1".into(),
};
let json = serde_json::to_value(&source).unwrap();
assert_eq!(
json,
serde_json::json!({ "source": "approvedRootScript", "approvalId": "approved-1" })
);
assert_eq!(serde_json::from_value::<HipSource>(json).unwrap(), source);
}
}
+1
View File
@@ -1,4 +1,5 @@
pub mod event;
pub mod hip;
pub mod request;
pub mod transport;
pub mod vpn_env;
+35 -32
View File
@@ -9,10 +9,32 @@ use crate::{
os_profile::{ClientOs, OsProfile},
};
use super::vpn_state::ConnectInfo;
use super::{hip::HipSource, vpn_state::ConnectInfo};
pub const MAX_CLIENT_IDENTITY_DATA: usize = 32 * 1024;
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreEditedHipReportChunkRequest {
pub upload_id: Option<String>,
pub offset: usize,
pub xml: String,
pub complete: bool,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PreviewHipReportRequest {
pub source: HipSource,
pub client_os: ClientOs,
pub client_version: String,
pub host_id: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ReadHipPreviewChunkRequest {
pub preview_id: String,
pub offset: usize,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct LaunchGuiRequest {
user: String,
@@ -50,9 +72,7 @@ pub struct ConnectArgs {
sslkey_data: Option<String>,
key_password: Option<String>,
hip: bool,
csd_uid: u32,
csd_wrapper: Option<String>,
hip_source: HipSource,
reconnect_timeout: u32,
mtu: u32,
@@ -80,9 +100,7 @@ impl ConnectArgs {
certificate_data: None,
sslkey_data: None,
key_password: None,
hip: false,
csd_uid: 0,
csd_wrapper: None,
hip_source: HipSource::Disabled,
reconnect_timeout: 300,
mtu: 0,
disable_ipv6: false,
@@ -154,16 +172,8 @@ impl ConnectArgs {
self.key_password.clone()
}
pub fn hip(&self) -> bool {
self.hip
}
pub fn csd_uid(&self) -> u32 {
self.csd_uid
}
pub fn csd_wrapper(&self) -> Option<String> {
self.csd_wrapper.clone()
pub fn hip_source(&self) -> &HipSource {
&self.hip_source
}
pub fn reconnect_timeout(&self) -> u32 {
@@ -212,9 +222,7 @@ impl fmt::Debug for ConnectArgs {
"client_auth_data",
&(self.certificate_data.is_some() || self.sslkey_data.is_some()),
)
.field("hip", &self.hip)
.field("csd_uid", &self.csd_uid)
.field("csd_wrapper", &self.csd_wrapper)
.field("hip_source", &self.hip_source)
.field("reconnect_timeout", &self.reconnect_timeout)
.field("mtu", &self.mtu)
.field("disable_ipv6", &self.disable_ipv6)
@@ -252,18 +260,8 @@ impl ConnectRequest {
self
}
pub fn with_hip(mut self, hip: bool) -> Self {
self.args.hip = hip;
self
}
pub fn with_csd_uid(mut self, csd_uid: u32) -> Self {
self.args.csd_uid = csd_uid;
self
}
pub fn with_csd_wrapper<T: Into<Option<String>>>(mut self, csd_wrapper: T) -> Self {
self.args.csd_wrapper = csd_wrapper.into();
pub fn with_hip_source(mut self, hip_source: HipSource) -> Self {
self.args.hip_source = hip_source;
self
}
@@ -371,6 +369,11 @@ pub struct UpdateLogLevelRequest(pub String);
pub enum WsRequest {
Connect(Box<ConnectRequest>),
Disconnect(DisconnectRequest),
StoreEditedHipReportChunk(StoreEditedHipReportChunkRequest),
PreviewHipReport(PreviewHipReportRequest),
GetHipApprovalStatus { approval_id: String },
ReadHipPreviewChunk(ReadHipPreviewChunkRequest),
GetLastSubmittedHipReport,
UpdateLogLevel(UpdateLogLevelRequest),
RestartGui,
UpdateGui(UpdateGuiRequest),
@@ -22,6 +22,7 @@ pub enum TransportError {
#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
pub enum HandshakeRejection {
VersionMismatch { client: String, service: String },
HipProtocolMismatch { client: u16, service: u16 },
ServiceRestarted { service_instance_id: Uuid },
ReconnectSuperseded,
Unauthorized,
@@ -7,6 +7,8 @@ use super::{HandshakeRejection, MAX_PRELUDE, MAX_PRODUCT_VERSION, TransportError
#[serde(deny_unknown_fields)]
pub struct ClientPrelude {
pub product_version: String,
#[serde(default)]
pub hip_protocol_version: u16,
pub service_instance_id: Uuid,
pub session_id: Uuid,
}
@@ -71,9 +73,16 @@ mod tests {
r#"{{"product_version":"2.6.4","service_instance_id":"{instance}","session_id":"{session}","extra":true}}"#
);
assert!(ClientPrelude::decode(unknown.as_bytes()).is_err());
let legacy =
format!(r#"{{"product_version":"2.6.4","service_instance_id":"{instance}","session_id":"{session}"}}"#);
assert_eq!(
ClientPrelude::decode(legacy.as_bytes()).unwrap().hip_protocol_version,
0
);
assert!(
ClientPrelude {
product_version: String::new(),
hip_protocol_version: super::super::HIP_PROTOCOL_VERSION,
service_instance_id: instance,
session_id: session,
}
@@ -1,6 +1,7 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::service::hip::HipApprovalStatus;
use crate::service::{event::WsEvent, request::WsRequest, vpn_env::VpnEnv, vpnc_script::VpncScriptMetadata};
use super::{MAX_PLAINTEXT, MAX_SERVICE_MESSAGE, ServiceErrorCode, TransportError};
@@ -39,6 +40,20 @@ pub enum ServerMessage {
#[serde(tag = "type", content = "data", rename_all = "camelCase", deny_unknown_fields)]
pub enum ServiceResult {
Accepted,
StoredHipReport {
report_id: String,
},
HipUploadProgress {
upload_id: String,
},
HipPreviewChunk {
preview_id: String,
offset: usize,
xml: String,
complete: bool,
},
HipApprovalStatus(HipApprovalStatus),
NoSubmittedHipReport,
VpncScriptMetadata(Option<VpncScriptMetadata>),
Rejected(ServiceRejection),
}
@@ -13,6 +13,7 @@ pub use noise::{NoiseInitiator, NoiseResponder, NoiseTransport};
pub const MAX_CREDENTIAL_FRAME: usize = 512;
pub const MAX_PRELUDE: usize = 256;
pub const MAX_PRODUCT_VERSION: usize = 64;
pub const HIP_PROTOCOL_VERSION: u16 = 1;
pub const MAX_PLAINTEXT: usize = 60 * 1024;
pub const MAX_WS_MESSAGE: usize = u16::MAX as usize;
pub const MAX_SERVICE_MESSAGE: usize = 256;
-3
View File
@@ -24,9 +24,6 @@ pub struct VpnEnv {
/// The default VPN script path
pub vpnc_script: Option<String>,
/// The default CSD wrapper script path
pub csd_wrapper: Option<String>,
/// The gpauth executable path
/// Used by the client to launch gpauth for authentication
pub auth_executable: String,
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "gphip"
rust-version.workspace = true
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
gpapi = { path = "../gpapi" }
anyhow.workspace = true
askama.workspace = true
chrono.workspace = true
log.workspace = true
netdev.workspace = true
serde.workspace = true
serde_json.workspace = true
serde_urlencoded.workspace = true
uuid = { workspace = true, features = ["v5"] }
uzers.workspace = true
xmltree.workspace = true
+928
View File
@@ -0,0 +1,928 @@
use anyhow::{bail, ensure};
use askama::Template;
use gpapi::os_profile::{ClientOs, OsProfile};
use log::debug;
use serde::Deserialize;
use std::collections::HashMap;
use std::process::Command;
use xmltree::Element;
pub const MAX_EDITED_REPORT_BYTES: usize = 48 * 1024;
/// Validate an edited report before it is stored or used as a submission body.
/// The parser receives UTF-8 text and never resolves external resources.
pub fn validate_edited_report(xml: &str) -> anyhow::Result<Element> {
ensure!(xml.len() <= MAX_EDITED_REPORT_BYTES, "HIP report exceeds 48 KiB");
let lower = xml.to_ascii_lowercase();
ensure!(
!lower.contains("<!doctype") && !lower.contains("<!entity"),
"HIP report must not contain a DTD or entity declaration"
);
if let Some(declaration) = lower.strip_prefix("<?xml").and_then(|rest| rest.split_once("?>")) {
let declaration = declaration.0;
if declaration.contains("encoding") {
ensure!(
declaration.contains("utf-8") || declaration.contains("utf8"),
"HIP report must use UTF-8 encoding"
);
}
}
let root = Element::parse(xml.as_bytes())?;
ensure!(root.name == "hip-report", "HIP report root must be <hip-report>");
for name in [
"md5-sum",
"user-name",
"domain",
"host-name",
"host-id",
"ip-address",
"ipv6-address",
"generate-time",
"hip-report-version",
] {
unique_child(&root, name)?;
}
let categories = unique_child(&root, "categories")?;
let mut host_info_entries = categories
.children
.iter()
.filter_map(xmltree::XMLNode::as_element)
.filter(|entry| entry.name == "entry" && entry.attributes.get("name").is_some_and(|name| name == "host-info"));
let host_info = host_info_entries
.next()
.ok_or_else(|| anyhow::anyhow!("HIP report is missing host-info"))?;
ensure!(
host_info_entries.next().is_none(),
"HIP report has duplicate host-info entries"
);
for name in ["client-version", "os", "os-vendor", "domain", "host-name", "host-id"] {
unique_child(host_info, name)?;
}
Ok(root)
}
fn unique_child<'a>(parent: &'a Element, name: &str) -> anyhow::Result<&'a Element> {
let mut matches = parent
.children
.iter()
.filter_map(xmltree::XMLNode::as_element)
.filter(|child| child.name == name);
let child = matches
.next()
.ok_or_else(|| anyhow::anyhow!("HIP report is missing <{name}>"))?;
if matches.next().is_some() {
bail!("HIP report has duplicate <{name}> elements");
}
Ok(child)
}
const CURRENT_TOP_LEVEL_FIELDS: &[&str] = &[
"md5-sum",
"user-name",
"domain",
"host-name",
"host-id",
"ip-address",
"ipv6-address",
"generate-time",
];
const CURRENT_HOST_INFO_FIELDS: &[&str] = &["client-version", "os", "os-vendor", "domain", "host-name", "host-id"];
/// Refresh only session and current-host fields in a saved HIP report.
/// User-edited categories, products, and network-interface entries remain intact.
pub fn refresh_edited_report(edited_xml: &str, input: &ReportInput) -> anyhow::Result<String> {
let mut edited = validate_edited_report(edited_xml)?;
let current = validate_edited_report(&generate_report(input)?)?;
for field in CURRENT_TOP_LEVEL_FIELDS {
copy_field(&mut edited, &current, field)?;
}
let edited_host = host_info_mut(&mut edited)?;
let current_host = host_info(&current)?;
for field in CURRENT_HOST_INFO_FIELDS {
copy_field(edited_host, current_host, field)?;
}
let refreshed = write_xml(&edited)?;
validate_edited_report(&refreshed)?;
Ok(refreshed)
}
fn copy_field(target: &mut Element, source: &Element, name: &str) -> anyhow::Result<()> {
let value = unique_child(source, name)?.children.clone();
let field = target
.get_mut_child(name)
.ok_or_else(|| anyhow::anyhow!("HIP report is missing <{name}>"))?;
field.children = value;
Ok(())
}
fn host_info(root: &Element) -> anyhow::Result<&Element> {
unique_child(root, "categories")?
.children
.iter()
.filter_map(xmltree::XMLNode::as_element)
.find(|entry| entry.name == "entry" && entry.attributes.get("name").is_some_and(|name| name == "host-info"))
.ok_or_else(|| anyhow::anyhow!("HIP report is missing host-info"))
}
fn host_info_mut(root: &mut Element) -> anyhow::Result<&mut Element> {
root
.get_mut_child("categories")
.ok_or_else(|| anyhow::anyhow!("HIP report is missing <categories>"))?
.children
.iter_mut()
.filter_map(xmltree::XMLNode::as_mut_element)
.find(|entry| entry.name == "entry" && entry.attributes.get("name").is_some_and(|name| name == "host-info"))
.ok_or_else(|| anyhow::anyhow!("HIP report is missing host-info"))
}
/// Session values for an actual submission, or an explicit pre-connection preview.
pub enum ReportContext {
Connected {
cookie: String,
client_ip: Option<String>,
client_ipv6: Option<String>,
md5: String,
},
Preview,
}
impl ReportContext {
fn cookie(&self) -> &str {
match self {
Self::Connected { cookie, .. } => cookie,
Self::Preview => "",
}
}
fn md5(&self) -> &str {
match self {
Self::Connected { md5, .. } => md5,
Self::Preview => "[available after connection]",
}
}
fn client_ip(&self) -> Option<&str> {
match self {
Self::Connected { client_ip, .. } => client_ip.as_deref(),
Self::Preview => None,
}
}
fn client_ipv6(&self) -> Option<&str> {
match self {
Self::Connected { client_ipv6, .. } => client_ipv6.as_deref(),
Self::Preview => None,
}
}
}
/// Inputs collected by the caller for one HIP report.
pub struct ReportInput {
pub profile: OsProfile,
pub context: ReportContext,
}
/// Generate the same XML report used by `gpclient hip`.
pub fn generate_report(input: &ReportInput) -> anyhow::Result<String> {
let cookie_params: HashMap<String, String> = serde_urlencoded::from_str(input.context.cookie()).unwrap_or_default();
let (generate_time, day, month, year) = get_current_time_components();
let user_name = match input.context {
ReportContext::Preview => "[available after connection]",
ReportContext::Connected { .. } => cookie_params.get("user").map(String::as_str).unwrap_or(""),
};
let host_info = HostInfoCollector::new(&input.profile, input, &cookie_params).collect();
let template = HipReportTemplate {
client_version: input.profile.client_version(),
generate_time,
day,
month,
year,
user_name,
host_info,
md5: input.context.md5(),
};
format_xml(&template.render()?)
}
#[derive(Template)]
#[template(path = "hip_report.xml")]
struct HipReportTemplate<'a> {
client_version: &'a str,
generate_time: String,
day: String,
month: String,
year: String,
user_name: &'a str,
host_info: HostInfo,
md5: &'a str,
}
#[derive(Debug, Clone, Deserialize)]
struct DefenderInfo {
#[serde(rename = "appVersion")]
app_version: String,
#[serde(rename = "engineVersion")]
engine_version: String,
#[serde(rename = "definitionsVersion")]
definitions_version: String,
#[serde(rename = "realTimeProtectionEnabled")]
real_time_protection_enabled: RealTimeProtection,
}
#[derive(Debug, Clone, Deserialize)]
struct RealTimeProtection {
value: bool,
}
#[derive(Debug, Clone)]
struct UfwInfo {
version: String,
is_enabled: bool,
}
#[derive(Debug, Clone)]
struct ClamAvInfo {
version: String,
definitions_version: Option<String>,
real_time_protection: bool,
}
/// Host information for HIP reporting
struct HostInfo {
/// Common for all OSes, e.g., "Apple", "Microsoft", "Linux"
os_vendor: String,
/// Common for all OSes, e.g., "Linux Ubuntu 20.04", "Apple Mac OS X 10.15.7", etc.
os_version: String,
/// Per-OS machine identifier (UUID for Linux/Windows, MAC for macOS)
host_id: String,
/// Common for all OSes
host_name: String,
/// Only for macOS and Windows, e.g., "10.15.7", "10.0.19044.2130"
software_version: String,
domain: String,
network_interfaces: Vec<NetworkInterface>,
defender: Option<DefenderInfo>,
clamav: Option<ClamAvInfo>,
ufw: Option<UfwInfo>,
}
impl HostInfo {
/// Get the first available IPv4 address from network interfaces
pub fn default_ipv4(&self) -> &str {
self
.network_interfaces
.first()
.and_then(|iface| iface.ipv4.as_deref())
.unwrap_or_default()
}
/// Get the first available IPv6 address from network interfaces
pub fn default_ipv6(&self) -> &str {
self
.network_interfaces
.first()
.and_then(|iface| iface.ipv6.as_deref())
.unwrap_or_default()
}
}
/// Network interface information
#[derive(Clone)]
struct NetworkInterface {
name: String,
description: String,
mac_address: Option<String>,
ipv4: Option<String>,
ipv6: Option<String>,
}
impl NetworkInterface {
/// Create a new network interface with basic information
fn new(name: String, description: String) -> Self {
Self {
name,
description,
mac_address: None,
ipv4: None,
ipv6: None,
}
}
/// Set MAC address
fn with_mac(mut self, mac: Option<String>) -> Self {
self.mac_address = mac;
self
}
/// Set IPv4 address
fn with_ipv4(mut self, ipv4: Option<String>) -> Self {
self.ipv4 = ipv4;
self
}
/// Set IPv6 address
fn with_ipv6(mut self, ipv6: Option<String>) -> Self {
self.ipv6 = ipv6;
self
}
}
// ============================================================================
// Host Information Collector
// ============================================================================
/// Helper struct for collecting host information.
///
/// Identity values (vendor, host_id, computer name, software version) come
/// from the configured `OsProfile`, while runtime state (network interfaces,
/// IP addresses) is enumerated here from the underlying machine.
struct HostInfoCollector<'p, 'a> {
profile: &'p OsProfile,
input: &'a ReportInput,
cookie_params: &'a HashMap<String, String>,
}
impl<'p, 'a> HostInfoCollector<'p, 'a> {
fn new(profile: &'p OsProfile, input: &'a ReportInput, cookie_params: &'a HashMap<String, String>) -> Self {
Self {
profile,
input,
cookie_params,
}
}
/// 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() {
Ok(iface) => NetworkInterface::new(
iface.name.clone(),
iface.description.unwrap_or_else(|| iface.name.clone()),
)
.with_mac(iface.mac_addr.map(|mac| mac.address()))
.with_ipv4(iface.ipv4.first().map(|ip| ip.addr().to_string()))
.with_ipv6(iface.ipv6.first().map(|ip| ip.addr().to_string())),
Err(_) => NetworkInterface::new("unknown".to_string(), "unknown".to_string())
.with_ipv4(self.input.context.client_ip().map(str::to_string))
.with_ipv6(self.input.context.client_ipv6().map(str::to_string)),
}
}
/// Single entry point for collecting host info — dispatches per-OS
/// behavior via `OsProfile` methods rather than `#[cfg(target_os)]`.
fn collect(&self) -> 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 {
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(),
network_interfaces: interfaces,
defender: self.defender_for_profile(),
clamav: self.clamav_for_profile(),
ufw: self.ufw_for_profile(),
}
}
/// Build the primary network interface with OS-appropriate naming and
/// MAC formatting. When emulating a different OS, the runtime interface
/// name/description are replaced with the canonical placeholder for the
/// target OS.
fn adapt_primary_interface(&self, runtime: &NetworkInterface) -> NetworkInterface {
let (name, description) = if self.profile.is_native() {
(runtime.name.clone(), runtime.description.clone())
} else {
placeholder_interface_for(self.profile, runtime)
};
NetworkInterface {
name,
description,
mac_address: format_mac_for(self.profile, runtime.mac_address.clone()),
ipv4: runtime.ipv4.clone(),
ipv6: runtime.ipv6.clone(),
}
}
/// Additional interfaces appended after the primary. Only Windows
/// emits the software loopback interface in HIP reports.
fn extra_interfaces(&self, primary: &NetworkInterface) -> Vec<NetworkInterface> {
match self.profile.client_os() {
ClientOs::Windows => vec![NetworkInterface {
name: derive_windows_network_name(self.profile.host_id(), primary),
description: "Software Loopback Interface 1".to_string(),
mac_address: Some(String::new()),
ipv4: Some("127.0.0.1".to_string()),
ipv6: Some("::1".to_string()),
}],
ClientOs::Linux | ClientOs::Mac => vec![],
}
}
/// 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 => self.get_domain(),
}
}
fn defender_for_profile(&self) -> Option<DefenderInfo> {
match self.profile.client_os() {
ClientOs::Linux => detect_microsoft_defender_blocking(),
ClientOs::Mac | ClientOs::Windows => None,
}
}
fn clamav_for_profile(&self) -> Option<ClamAvInfo> {
match self.profile.client_os() {
ClientOs::Linux => detect_clamav(),
ClientOs::Mac | ClientOs::Windows => None,
}
}
fn ufw_for_profile(&self) -> Option<UfwInfo> {
match self.profile.client_os() {
ClientOs::Linux => detect_ufw(),
ClientOs::Mac | ClientOs::Windows => None,
}
}
}
fn detect_clamav() -> Option<ClamAvInfo> {
let version_out = Command::new("clamscan").arg("--version").output().ok()?;
if !version_out.status.success() {
debug!("clamscan not found or failed");
return None;
}
let version_str = String::from_utf8(version_out.stdout).ok()?;
let (version, definitions_version) = parse_clamav_version(&version_str)?;
let rtp_out = Command::new("systemctl")
.args(["is-active", "clamav-onaccess.service"])
.output()
.ok()?;
let real_time_protection = rtp_out.status.success();
Some(ClamAvInfo {
version,
definitions_version,
real_time_protection,
})
}
fn detect_ufw() -> Option<UfwInfo> {
let version_out = Command::new("ufw").arg("version").output().ok()?;
if !version_out.status.success() {
debug!("ufw not found or failed");
return None;
}
let version_str = String::from_utf8(version_out.stdout).ok()?;
let version = parse_ufw_version(&version_str)?;
let is_root = uzers::get_effective_uid() == 0;
let status_out = ufw_status_command(is_root).output().ok()?;
if !status_out.status.success() {
if is_root {
log::warn!("ufw status failed while running as root");
} else {
log::warn!("sudo -n ufw status failed. You may need to configure sudoers to allow execution without a password.");
}
return None;
}
let status_str = String::from_utf8(status_out.stdout).ok()?;
let is_enabled = parse_ufw_status(&status_str)?;
Some(UfwInfo { version, is_enabled })
}
fn ufw_status_command(is_root: bool) -> Command {
let mut command = if is_root {
Command::new("ufw")
} else {
let mut command = Command::new("sudo");
command.args(["-n", "ufw"]);
command
};
command.arg("status").env("LC_ALL", "C");
command
}
fn parse_clamav_version(output: &str) -> Option<(String, Option<String>)> {
let mut output_parts = output.split_whitespace();
if output_parts.next()? != "ClamAV" {
return None;
}
let mut version_parts = output_parts.next()?.split('/');
let version = version_parts.next()?;
if version.is_empty() {
return None;
}
let definitions_version = version_parts
.next()
.filter(|definitions_version| !definitions_version.is_empty())
.map(str::to_string);
Some((version.to_string(), definitions_version))
}
fn parse_ufw_version(output: &str) -> Option<String> {
let mut output_parts = output.split_whitespace();
if output_parts.next()? != "ufw" {
return None;
}
output_parts.next().map(str::to_string)
}
fn parse_ufw_status(output: &str) -> Option<bool> {
let status = output
.lines()
.find_map(|line| line.trim().strip_prefix("Status:"))?
.trim();
match status {
"active" => Some(true),
"inactive" => Some(false),
_ => None,
}
}
fn detect_microsoft_defender_blocking() -> Option<DefenderInfo> {
let output = Command::new("mdatp")
.arg("health")
.arg("--output")
.arg("json")
.output()
.ok()?;
if !output.status.success() {
debug!("mdatp health command failed");
return None;
}
let json = String::from_utf8(output.stdout).ok()?;
let defender = parse_defender_info(&json)?;
debug!("Detected Microsoft Defender: {:?}", defender);
Some(defender)
}
fn parse_defender_info(json: &str) -> Option<DefenderInfo> {
serde_json::from_str(json).ok()
}
// ============================================================================
// Per-OS interface helpers (selected via OsProfile, not cfg)
// ============================================================================
/// Canonical interface name/description for the target OS when the runtime
/// is a different OS (i.e. emulation).
fn placeholder_interface_for(profile: &OsProfile, runtime: &NetworkInterface) -> (String, String) {
match profile.client_os() {
ClientOs::Linux => ("enp1s0f0".to_string(), "enp1s0f0".to_string()),
ClientOs::Mac => ("en0".to_string(), "en0".to_string()),
ClientOs::Windows => (
derive_windows_network_name(profile.host_id(), runtime),
"PANGP Virtual Ethernet Adapter Secure".to_string(),
),
}
}
/// MAC address formatting per target OS. Windows uses hyphen separators;
/// Linux and macOS preserve the colon-separated form returned by the
/// platform.
fn format_mac_for(profile: &OsProfile, mac: Option<String>) -> Option<String> {
match profile.client_os() {
ClientOs::Windows => mac.map(|m| m.replace(':', "-")),
ClientOs::Linux | ClientOs::Mac => mac,
}
}
// ============================================================================
// Utility Functions
// ============================================================================
/// Get current time components for HIP report
fn get_current_time_components() -> (String, String, String, String) {
let now = chrono::Local::now();
(
now.format("%m/%d/%Y %H:%M:%S").to_string(),
now.format("%d").to_string(),
now.format("%m").to_string(),
now.format("%Y").to_string(),
)
}
/// Format XML string with proper indentation
fn format_xml(xml_str: &str) -> anyhow::Result<String> {
let xml = Element::parse(xml_str.as_bytes())?;
write_xml(&xml)
}
fn write_xml(xml: &Element) -> anyhow::Result<String> {
let config = xmltree::EmitterConfig::new().perform_indent(true);
let mut xml_buf = Vec::new();
xml.write_with_config(&mut xml_buf, config)?;
Ok(String::from_utf8(xml_buf)?)
}
fn derive_windows_network_name(host_id: &str, iface: &NetworkInterface) -> String {
let seed = format!(
"{}-{}-{}",
host_id,
iface.mac_address.as_deref().unwrap_or("00:00:00:00:00:00"),
iface.name
);
format!(
"{{{}}}",
uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_DNS, seed.as_bytes())
.to_string()
.to_uppercase()
)
}
#[cfg(test)]
mod tests {
use super::*;
use gpapi::os_profile::OsProfileBuilder;
use std::ffi::OsStr;
fn make_input(profile: OsProfile) -> ReportInput {
ReportInput {
profile,
context: ReportContext::Connected {
cookie: String::new(),
client_ip: None,
client_ipv6: None,
md5: "deadbeef".to_string(),
},
}
}
fn make_profile(client_os: ClientOs) -> OsProfile {
OsProfileBuilder::new(client_os).build()
}
#[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();
assert_eq!(info.os_vendor, "Linux");
}
#[test]
fn host_info_os_vendor_is_apple_for_mac_profile() {
let input = make_input(make_profile(ClientOs::Mac));
let profile = make_profile(ClientOs::Mac);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
assert_eq!(info.os_vendor, "Apple");
}
#[test]
fn host_info_os_vendor_is_microsoft_for_windows_profile() {
let input = make_input(make_profile(ClientOs::Windows));
let profile = make_profile(ClientOs::Windows);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
assert_eq!(info.os_vendor, "Microsoft");
}
#[test]
fn host_info_host_id_comes_from_os_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();
assert_eq!(info.host_id, profile.host_id());
}
#[test]
fn host_info_host_id_independent_of_runtime_for_each_os() {
// host_id should reflect the OsProfile's machine identity for every
// simulated OS, regardless of the runtime platform.
for client_os in [ClientOs::Linux, ClientOs::Mac, ClientOs::Windows] {
let input = make_input(make_profile(client_os));
let profile = make_profile(client_os);
let cookie_params: HashMap<String, String> = HashMap::new();
let info = HostInfoCollector::new(&profile, &input, &cookie_params).collect();
assert_eq!(info.host_id, profile.host_id());
}
}
#[test]
fn generated_report_contains_supplied_session_fields() {
let mut input = make_input(make_profile(ClientOs::Linux));
input.context = ReportContext::Connected {
cookie: "user=test-user&domain=test-domain".to_string(),
client_ip: None,
client_ipv6: None,
md5: "test-digest".to_string(),
};
let report = generate_report(&input).unwrap();
assert!(report.contains("test-user"));
assert!(report.contains("test-digest"));
validate_edited_report(&report).unwrap();
}
#[test]
fn preview_uses_explicit_pending_digest() {
let input = ReportInput {
profile: make_profile(ClientOs::Mac),
context: ReportContext::Preview,
};
let report = generate_report(&input).unwrap();
assert!(report.contains("[available after connection]"));
validate_edited_report(&report).unwrap();
}
#[test]
fn rejects_malformed_and_unsafe_edited_reports() {
assert!(validate_edited_report("<other/>").is_err());
assert!(validate_edited_report("<!DOCTYPE hip-report [<!ENTITY x 'value'>]><hip-report/>").is_err());
assert!(validate_edited_report(&"x".repeat(MAX_EDITED_REPORT_BYTES + 1)).is_err());
let valid = generate_report(&make_input(make_profile(ClientOs::Mac))).unwrap();
assert!(validate_edited_report(&valid.replace("<md5-sum>", "<wrong-field>")).is_err());
}
#[test]
fn refreshes_exact_current_fields_and_preserves_user_categories() {
let mut input = make_input(make_profile(ClientOs::Mac));
input.context = ReportContext::Connected {
cookie: "user=current-user&domain=current-domain".to_string(),
client_ip: Some("192.0.2.4".to_string()),
client_ipv6: None,
md5: "current-digest".to_string(),
};
let current = validate_edited_report(&generate_report(&input).unwrap()).unwrap();
let mut saved = current.clone();
for field in CURRENT_TOP_LEVEL_FIELDS {
saved.get_mut_child(*field).unwrap().children = vec![xmltree::XMLNode::Text("stale".into())];
}
let saved_host = host_info_mut(&mut saved).unwrap();
for field in CURRENT_HOST_INFO_FIELDS {
saved_host.get_mut_child(*field).unwrap().children = vec![xmltree::XMLNode::Text("stale".into())];
}
let nested = Element::parse(
r#"<network-interface><entry name="manual"><ip-address><entry name="203.0.113.17"/></ip-address></entry></network-interface>"#.as_bytes(),
)
.unwrap();
saved_host.get_mut_child("network-interface").unwrap().children = nested.children;
let custom_category = Element::parse(
r#"<entry name="custom-category"><list><entry><ProductInfo><Prod name="Sentinel"/></ProductInfo></entry></list></entry>"#.as_bytes(),
)
.unwrap();
saved
.get_mut_child("categories")
.unwrap()
.children
.push(xmltree::XMLNode::Element(custom_category));
let refreshed_xml = refresh_edited_report(&write_xml(&saved).unwrap(), &input).unwrap();
let refreshed = validate_edited_report(&refreshed_xml).unwrap();
for field in CURRENT_TOP_LEVEL_FIELDS {
assert_eq!(
unique_child(&refreshed, field).unwrap().get_text(),
unique_child(&current, field).unwrap().get_text()
);
}
let refreshed_host = host_info(&refreshed).unwrap();
let current_host = host_info(&current).unwrap();
for field in CURRENT_HOST_INFO_FIELDS {
assert_eq!(
unique_child(refreshed_host, field).unwrap().get_text(),
unique_child(current_host, field).unwrap().get_text()
);
}
assert!(refreshed_xml.contains("203.0.113.17"));
assert!(refreshed_xml.contains("name=\"Sentinel\""));
assert!(refreshed_xml.contains("name=\"custom-category\""));
assert!(!refreshed_xml.contains(">stale<"));
}
#[test]
fn refresh_rejects_missing_required_host_field() {
let input = make_input(make_profile(ClientOs::Mac));
let mut saved = validate_edited_report(&generate_report(&input).unwrap()).unwrap();
let host = host_info_mut(&mut saved).unwrap();
host
.children
.retain(|node| !matches!(node, xmltree::XMLNode::Element(element) if element.name == "os"));
assert!(refresh_edited_report(&write_xml(&saved).unwrap(), &input).is_err());
}
#[test]
fn parses_microsoft_defender_health_json() {
let defender = parse_defender_info(
r#"{
"appVersion": "101.25042.0000",
"engineVersion": "1.1.25040.2",
"definitionsVersion": "1.429.201.0",
"realTimeProtectionEnabled": { "value": true }
}"#,
)
.expect("defender health json should parse");
assert_eq!(defender.app_version, "101.25042.0000");
assert_eq!(defender.engine_version, "1.1.25040.2");
assert_eq!(defender.definitions_version, "1.429.201.0");
assert!(defender.real_time_protection_enabled.value);
}
#[test]
fn rejects_invalid_microsoft_defender_health_json() {
assert!(parse_defender_info("{}").is_none());
}
#[test]
fn parses_clamav_version() {
let version =
parse_clamav_version("ClamAV 1.4.3/27562/Sun Aug 31 10:23:42 2026").expect("ClamAV version should parse");
assert_eq!(version, ("1.4.3".to_string(), Some("27562".to_string())));
}
#[test]
fn parses_clamav_version_without_definitions_version() {
assert_eq!(parse_clamav_version("ClamAV 1.4.3"), Some(("1.4.3".to_string(), None)));
}
#[test]
fn parses_ufw_version() {
assert_eq!(parse_ufw_version("ufw 0.36.2\n"), Some("0.36.2".to_string()));
assert_eq!(parse_ufw_version("unexpected output\n"), None);
}
#[test]
fn parses_ufw_status() {
assert_eq!(parse_ufw_status("Status: active\n"), Some(true));
assert_eq!(parse_ufw_status("Status: inactive\n"), Some(false));
assert_eq!(parse_ufw_status("Status: unknown\n"), None);
}
#[test]
fn runs_ufw_status_directly_as_root() {
let command = ufw_status_command(true);
assert_eq!(command.get_program(), OsStr::new("ufw"));
assert!(command.get_args().eq(["status"].into_iter().map(OsStr::new)));
}
#[test]
fn runs_ufw_status_through_non_interactive_sudo_as_non_root() {
let command = ufw_status_command(false);
assert_eq!(command.get_program(), OsStr::new("sudo"));
assert!(
command
.get_args()
.eq(["-n", "ufw", "status"].into_iter().map(OsStr::new))
);
}
}
+305
View File
@@ -0,0 +1,305 @@
<?xml version="1.0" encoding="UTF-8"?>
<hip-report name="hip-report">
<md5-sum>{{ md5 }}</md5-sum>
<user-name>{{ user_name }}</user-name>
<domain>{{ host_info.domain }}.internal</domain>
<host-name>{{ host_info.host_name }}</host-name>
<host-id>{{ host_info.host_id }}</host-id>
<ip-address>{{ host_info.default_ipv4() }}</ip-address>
<ipv6-address>{{ host_info.default_ipv6() }}</ipv6-address>
<generate-time>{{ generate_time }}</generate-time>
<hip-report-version>4</hip-report-version>
<categories>
<entry name="host-info">
<client-version>{{ client_version }}</client-version>
<os>{{ host_info.os_version }}</os>
<os-vendor>{{ host_info.os_vendor }}</os-vendor>
<domain>{{ host_info.domain }}.internal</domain>
<host-name>{{ host_info.host_name }}</host-name>
<host-id>{{ host_info.host_id }}</host-id>
<network-interface>
{% for iface in host_info.network_interfaces.iter() -%}
<entry name="{{ iface.name }}">
<description>{{ iface.description }}</description>
{% if let Some(mac) = iface.mac_address -%}
<mac-address>{{ mac }}</mac-address>
{% endif -%}
{% if let Some(ipv4) = iface.ipv4 -%}
<ip-address>
<entry name="{{ ipv4 }}"/>
</ip-address>
{% endif -%}
{% if let Some(ipv6) = iface.ipv6 -%}
<ipv6-address>
<entry name="{{ ipv6 }}"/>
</ipv6-address>
{% endif -%}
</entry>
{% endfor -%}
</network-interface>
</entry>
{% if host_info.os_vendor == "Microsoft" -%}
<entry name="antivirus">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="1" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="1" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>no</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="anti-spyware">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="2" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="2" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>no</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-backup">
<list>
<entry>
<ProductInfo>
<Prod name="Windows Backup and Restore" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<last-backup-time>n/a</last-backup-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod name="Windows Drive Encryption" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<drives>
<entry>
<drive-name>C:\\</drive-name>
<enc-state>full</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
<entry>
<ProductInfo>
<Prod name="Microsoft Windows Firewall" version="10.0.22621.4830" vendor="Microsoft Corp.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee ePolicy Orchestrator Agent" version="5.0.5.658" vendor="McAfee, Inc.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Microsoft Windows Update Agent" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches/>
</entry>
{% elif host_info.os_vendor == "Apple" -%}
<entry name="anti-malware">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Xprotect" version="2167" defver="235000000000000" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Gatekeeper" version="{{ host_info.software_version }}" defver="" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-backup">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Time Machine" version="1.3"/>
<last-backup-time>n/a</last-backup-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="FileVault" version="{{ host_info.software_version }}"/>
<drives>
<entry>
<drive-name>Macintosh HD</drive-name>
<enc-state>encrypted</enc-state>
</entry>
<entry>
<drive-name>Data</drive-name>
<enc-state>encrypted</enc-state>
</entry>
<entry>
<drive-name>All</drive-name>
<enc-state>encrypted</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Mac OS X Builtin Firewall" version="{{ host_info.software_version }}"/>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod vendor="OpenBSD" name="Packet Filter" version="{{ host_info.software_version }}"/>
<is-enabled>no</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Software Update" version="3.0"/>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches>
</missing-patches>
</entry>
{% elif host_info.os_vendor == "Linux" -%}
<entry name="anti-malware">
<list>
{% if let Some(defender) = &host_info.defender %}
<entry>
<ProductInfo>
<Prod name="Microsoft Defender ATP" version="{{ defender.app_version }}" defver="{{ defender.definitions_version }}" prodType="3" engver="{{ defender.engine_version }}" osType="1" vendor="Microsoft Corporation" dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>{% if defender.real_time_protection_enabled.value %}yes{% else %}no{% endif %}</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
{% endif -%}
{% if let Some(clamav) = &host_info.clamav %}
<entry>
<ProductInfo>
<Prod vendor="Cisco Systems, Inc." name="ClamAV" version="{{ clamav.version }}"{% if let Some(definitions_version) = &clamav.definitions_version %} defver="{{ definitions_version }}"{% endif %} engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="1"/>
<real-time-protection>{% if clamav.real_time_protection %}yes{% else %}no{% endif %}</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
{% endif -%}
</list>
</entry>
<entry name="disk-backup">
<list/>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod name="cryptsetup" version="2.3.3" vendor="GitLab Inc.">
</Prod>
<drives>
<entry>
<drive-name>/</drive-name>
<enc-state>encrypted</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
{% if let Some(ufw) = &host_info.ufw %}
<entry>
<ProductInfo>
<Prod vendor="Canonical Ltd." name="UFW" version="{{ ufw.version }}"/>
<is-enabled>{% if ufw.is_enabled %}yes{% else %}no{% endif %}</is-enabled>
</ProductInfo>
</entry>
{% endif -%}
<entry>
<ProductInfo>
<Prod name="IPTables" version="1.8.4" vendor="IPTables">
</Prod>
<is-enabled>no</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="nftables" version="0.9.3" vendor="The Netfilter Project">
</Prod>
<is-enabled>n/a</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod name="Dandified Yum" version="4.2.23" vendor="Red Hat, Inc.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches/>
</entry>
{% endif -%}
<entry name="data-loss-prevention">
<list/>
</entry>
</categories>
</hip-report>
+13
View File
@@ -7,6 +7,7 @@ use std::ffi::{c_char, c_int, c_long, c_void};
#[derive(Debug)]
pub(crate) struct ConnectOptions {
pub user_data: *mut c_void,
pub on_hip_report_submitted: Option<extern "C" fn(*mut c_void, *const c_char, usize)>,
pub server: *const c_char,
pub cookie: *const c_char,
@@ -85,6 +86,18 @@ pub(crate) fn connect(options: &ConnectOptions) -> i32 {
unsafe { vpn_connect(options, on_vpn_connected) }
}
#[unsafe(no_mangle)]
pub(crate) extern "C" fn on_hip_report_submitted(vpn: *mut c_void, report: *const c_char, length: usize) {
let vpn = unsafe { &*(vpn as *const Vpn) };
if report.is_null() || length > 1024 * 1024 {
return;
}
let bytes = unsafe { std::slice::from_raw_parts(report.cast::<u8>(), length) };
if let Ok(report) = std::str::from_utf8(bytes) {
vpn.on_hip_report_submitted(report);
}
}
#[unsafe(no_mangle)]
extern "C" fn on_vpn_connected(pipe_fd: i32, session_info: *const VpnSessionInfoRaw, vpn: *mut c_void) {
let vpn = unsafe { &*(vpn as *const Vpn) };
+2
View File
@@ -105,6 +105,8 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
}
context.vpninfo = vpninfo;
openconnect_set_gp_hip_report_callback(vpninfo, options->user_data,
options->on_hip_report_submitted);
context.command_fd = openconnect_setup_cmd_pipe(vpninfo);
if (context.command_fd < 0) {
ERROR("openconnect_setup_cmd_pipe failed");
+3
View File
@@ -16,9 +16,12 @@ typedef struct vpn_session_info {
typedef void (*vpn_connected_callback)(int cmd_pipe_fd,
const vpn_session_info *session_info,
void *user_data);
typedef void (*vpn_hip_report_callback)(void *user_data, const char *report,
size_t length);
typedef struct vpn_options {
void *user_data;
vpn_hip_report_callback on_hip_report_submitted;
const char *server;
const char *cookie;
+37
View File
@@ -10,6 +10,7 @@ use crate::ffi;
use crate::vpn_utils::{check_executable, find_csd_wrapper, find_vpnc_script};
type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce(VpnSessionInfo) + 'static + Send + Sync>>>>;
type OnHipReportCallback = RwLock<Option<Arc<dyn Fn(&str) + Send + Sync>>>;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct VpnSessionInfo {
@@ -130,6 +131,7 @@ pub struct Vpn {
no_xmlpost: bool,
callback: OnConnectedCallback,
hip_report_callback: OnHipReportCallback,
}
impl Vpn {
@@ -144,6 +146,19 @@ impl Vpn {
ffi::connect(&options)
}
/// Receives a borrowed report after the gateway accepts its HIP submission.
/// The callback must copy the XML if it needs to retain it.
pub fn set_hip_report_callback(&self, callback: impl Fn(&str) + Send + Sync + 'static) {
*self.hip_report_callback.write().unwrap() = Some(Arc::new(callback));
}
pub(crate) fn on_hip_report_submitted(&self, report: &str) {
let callback = self.hip_report_callback.read().unwrap().clone();
if let Some(callback) = callback {
callback(report);
}
}
pub(crate) fn on_connected(&self, pipe_fd: i32, session_info: VpnSessionInfo) {
info!("Connected to VPN, pipe_fd: {}", pipe_fd);
@@ -169,6 +184,7 @@ impl Vpn {
fn build_connect_options(&self) -> ffi::ConnectOptions {
ffi::ConnectOptions {
user_data: self as *const _ as *mut _,
on_hip_report_submitted: Some(ffi::on_hip_report_submitted),
server: self.server.as_ptr(),
cookie: self.cookie.as_ptr(),
@@ -480,6 +496,7 @@ impl VpnBuilder {
no_xmlpost: self.no_xmlpost,
callback: Default::default(),
hip_report_callback: Default::default(),
})
}
@@ -603,6 +620,7 @@ mod tests {
dpd_interval: 0,
no_xmlpost: false,
callback: Default::default(),
hip_report_callback: Default::default(),
};
let options = vpn.build_connect_options();
@@ -611,6 +629,25 @@ mod tests {
assert_eq!(host_id, "profile-host-id");
}
#[test]
fn hip_report_callback_copies_only_bounded_utf8() {
let vpn = Vpn::builder("vpn.example.com", "cookie")
.script_path("/bin/sh".to_string())
.build()
.unwrap();
let reports = Arc::new(Mutex::new(Vec::new()));
let received = Arc::clone(&reports);
vpn.set_hip_report_callback(move |report| received.lock().unwrap().push(report.to_owned()));
let options = vpn.build_connect_options();
let callback = options.on_hip_report_submitted.unwrap();
callback(options.user_data, b"<report/>".as_ptr().cast(), 9);
callback(options.user_data, b"\xff".as_ptr().cast(), 1);
callback(options.user_data, b"x".as_ptr().cast(), 1024 * 1024 + 1);
assert_eq!(*reports.lock().unwrap(), ["<report/>"]);
}
#[test]
fn disconnect_before_connect_is_retained_without_contacting_server() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();