From 739cf7234be73547a0ff4204453e01d6605c04e8 Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Tue, 29 Sep 2026 11:43:54 +0800 Subject: [PATCH] feat(hip): manage reports and script execution --- Cargo.lock | 27 +- Makefile | 6 + apps/gpclient/Cargo.toml | 7 +- apps/gpclient/src/connect/gateway.rs | 21 +- apps/gpclient/src/hip.rs | 738 +------------- apps/gpgui-helper/src-tauri/src/updater.rs | 6 +- apps/gpservice/Cargo.toml | 4 +- apps/gpservice/src/bin/gp-hip-runner.rs | 137 +++ .../src/bin/gp-hip-script-installer/main.rs | 10 + .../privileged_unix.rs | 56 ++ .../gp-hip-script-installer/unsupported.rs | 4 + apps/gpservice/src/cli.rs | 9 +- apps/gpservice/src/credential_lease.rs | 8 +- apps/gpservice/src/dev_bootstrap.rs | 4 +- apps/gpservice/src/hip_approval.rs | 400 ++++++++ apps/gpservice/src/hip_preview.rs | 275 ++++++ apps/gpservice/src/hip_runner_state.rs | 59 ++ apps/gpservice/src/hip_source.rs | 291 ++++++ apps/gpservice/src/lib.rs | 3 + apps/gpservice/src/macos_broker.rs | 2 +- apps/gpservice/src/main.rs | 2 + apps/gpservice/src/request_dispatcher.rs | 53 +- apps/gpservice/src/runtime_user/default.rs | 4 +- apps/gpservice/src/runtime_user/mod.rs | 2 +- .../src/runtime_user/privileged_unix.rs | 12 +- apps/gpservice/src/session_registry.rs | 278 +++++- apps/gpservice/src/vpn_task.rs | 165 +++- apps/gpservice/src/ws_connection.rs | 205 +++- apps/gpservice/src/ws_server.rs | 7 +- crates/common/src/binary_paths.rs | 7 + crates/common/src/constants.rs | 5 + crates/gpapi/src/process/hip_launcher.rs | 96 -- crates/gpapi/src/process/mod.rs | 1 - crates/gpapi/src/service/hip.rs | 47 + crates/gpapi/src/service/mod.rs | 1 + crates/gpapi/src/service/request.rs | 67 +- crates/gpapi/src/service/transport/error.rs | 1 + .../gpapi/src/service/transport/handshake.rs | 9 + crates/gpapi/src/service/transport/message.rs | 15 + crates/gpapi/src/service/transport/mod.rs | 1 + crates/gpapi/src/service/vpn_env.rs | 3 - crates/gphip/Cargo.toml | 20 + crates/gphip/src/lib.rs | 928 ++++++++++++++++++ .../gphip}/templates/hip_report.xml | 0 crates/openconnect/deps/openconnect | 2 +- crates/openconnect/src/ffi/mod.rs | 13 + crates/openconnect/src/ffi/vpn.c | 2 + crates/openconnect/src/ffi/vpn.h | 3 + crates/openconnect/src/vpn.rs | 37 + packaging/binary/Makefile.in | 4 + packaging/bsd/com.yuezk.gpgui.policy | 11 + .../files/usr/libexec/gpclient/hipreport.sh | 8 +- .../polkit-1/actions/com.yuezk.gpgui.policy | 11 + .../rpm/globalprotect-openconnect.spec.in | 2 + 54 files changed, 3122 insertions(+), 967 deletions(-) create mode 100644 apps/gpservice/src/bin/gp-hip-runner.rs create mode 100644 apps/gpservice/src/bin/gp-hip-script-installer/main.rs create mode 100644 apps/gpservice/src/bin/gp-hip-script-installer/privileged_unix.rs create mode 100644 apps/gpservice/src/bin/gp-hip-script-installer/unsupported.rs create mode 100644 apps/gpservice/src/hip_approval.rs create mode 100644 apps/gpservice/src/hip_preview.rs create mode 100644 apps/gpservice/src/hip_runner_state.rs create mode 100644 apps/gpservice/src/hip_source.rs delete mode 100644 crates/gpapi/src/process/hip_launcher.rs create mode 100644 crates/gpapi/src/service/hip.rs create mode 100644 crates/gphip/Cargo.toml create mode 100644 crates/gphip/src/lib.rs rename {apps/gpclient => crates/gphip}/templates/hip_report.xml (100%) diff --git a/Cargo.lock b/Cargo.lock index f245a2f..4eb13a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1905,29 +1905,24 @@ name = "gpclient" version = "2.6.5" dependencies = [ "anyhow", - "askama", - "chrono", "clap", "common", "compile-time", "directories", "env_logger", "gpapi", + "gphip", "inquire", "log", - "netdev", "openconnect", "reqwest", "serde", "serde_json", - "serde_urlencoded", "sysinfo", "tempfile", "tokio", - "uuid", "uzers", "whoami", - "xmltree", ] [[package]] @@ -1951,18 +1946,38 @@ dependencies = [ "zeroize", ] +[[package]] +name = "gphip" +version = "2.6.5" +dependencies = [ + "anyhow", + "askama", + "chrono", + "gpapi", + "log", + "netdev", + "serde", + "serde_json", + "serde_urlencoded", + "uuid", + "uzers", + "xmltree", +] + [[package]] name = "gpservice" version = "2.6.5" dependencies = [ "anyhow", "axum", + "base64 0.22.1", "clap", "common", "compile-time", "env_logger", "futures", "gpapi", + "gphip", "log", "nix 0.31.3", "openconnect", diff --git a/Makefile b/Makefile index 03fc99b..9df5f6e 100644 --- a/Makefile +++ b/Makefile @@ -145,6 +145,8 @@ install: install -Dm755 target/release/gpclient $(DESTDIR)/usr/bin/gpclient install -Dm755 target/release/gpauth $(DESTDIR)/usr/bin/gpauth install -Dm755 target/release/gpservice $(DESTDIR)/usr/bin/gpservice + install -Dm755 target/release/gp-hip-runner $(DESTDIR)/usr/libexec/gpclient/gp-hip-runner + install -Dm755 target/release/gp-hip-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer install -Dm755 target/release/gp-vpnc-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-vpnc-script-installer # Install the GUI components if BUILD_GUI_HELPER is set to 1 @@ -194,6 +196,8 @@ install-bsd: fi install -d $(DESTDIR)$(PREFIX)/libexec/gpclient + install -m 755 target/release/gp-hip-runner $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-hip-runner + install -m 755 target/release/gp-hip-script-installer $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-hip-script-installer install -m 755 target/release/gp-vpnc-script-installer $(DESTDIR)$(PREFIX)/libexec/gpclient/gp-vpnc-script-installer install -m 755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)$(PREFIX)/libexec/gpclient/vpnc-script install -m 755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)$(PREFIX)/libexec/gpclient/hipreport.sh @@ -296,6 +300,8 @@ uninstall: rm -f $(DESTDIR)/usr/bin/gpclient rm -f $(DESTDIR)/usr/bin/gpauth rm -f $(DESTDIR)/usr/bin/gpservice + rm -f $(DESTDIR)/usr/libexec/gpclient/gp-hip-runner + rm -f $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer rm -f $(DESTDIR)/usr/bin/gpgui-helper rm -f $(DESTDIR)/usr/bin/gpgui diff --git a/apps/gpclient/Cargo.toml b/apps/gpclient/Cargo.toml index 2f30f52..86fc448 100644 --- a/apps/gpclient/Cargo.toml +++ b/apps/gpclient/Cargo.toml @@ -9,11 +9,10 @@ license.workspace = true [dependencies] common = { path = "../../crates/common" } gpapi = { path = "../../crates/gpapi", features = ["clap"] } +gphip = { path = "../../crates/gphip" } openconnect = { path = "../../crates/openconnect" } anyhow.workspace = true -askama.workspace = true -chrono.workspace = true clap.workspace = true env_logger.workspace = true inquire = "0.9" @@ -22,15 +21,11 @@ tokio = { workspace = true, features = ["rt-multi-thread"] } sysinfo.workspace = true serde.workspace = true serde_json.workspace = true -serde_urlencoded.workspace = true whoami.workspace = true tempfile.workspace = true reqwest.workspace = true directories.workspace = true compile-time.workspace = true -netdev.workspace = true -xmltree.workspace = true -uuid = { workspace = true, features = ["v5"] } uzers.workspace = true [features] diff --git a/apps/gpclient/src/connect/gateway.rs b/apps/gpclient/src/connect/gateway.rs index ad36b42..f1d5857 100644 --- a/apps/gpclient/src/connect/gateway.rs +++ b/apps/gpclient/src/connect/gateway.rs @@ -15,7 +15,7 @@ use gpapi::{ gp_params::GpParams, os_profile::OsProfile, portal::prelogin, - process::users::{get_non_root_user, get_user_by_name}, + process::users::get_user_by_name, utils::shutdown_signal, }; use inquire::Text; @@ -499,7 +499,7 @@ fn get_uid(user: &Option) -> anyhow::Result { if let Some(user) = user { get_user_by_name(user).map(|user| user.uid()) } else { - get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid())) + Ok(uzers::get_effective_uid()) } } @@ -516,6 +516,23 @@ fn apply_os_profile(builder: VpnBuilder, profile: &OsProfile) -> VpnBuilder { mod tests { use super::*; + #[test] + fn hip_script_defaults_to_process_effective_uid() { + assert_eq!(get_uid(&None).unwrap(), uzers::get_effective_uid()); + } + + #[test] + fn explicit_hip_user_must_exist() { + assert!(get_uid(&Some("gpclient-nonexistent-hip-user".to_string())).is_err()); + } + + #[test] + fn explicit_hip_user_resolves_to_the_selected_account() { + let current = uzers::get_user_by_uid(uzers::get_effective_uid()).unwrap(); + let name = current.name().to_string_lossy().into_owned(); + assert_eq!(get_uid(&Some(name)).unwrap(), current.uid()); + } + #[test] fn openconnect_success_is_not_a_gateway_failure() { assert!(classify_openconnect_result(0, false, false).is_ok()); diff --git a/apps/gpclient/src/hip.rs b/apps/gpclient/src/hip.rs index 286d571..f978638 100644 --- a/apps/gpclient/src/hip.rs +++ b/apps/gpclient/src/hip.rs @@ -1,137 +1,9 @@ -use askama::Template; use clap::Args; use gpapi::{ clap::args::Os, - os_profile::{ClientOs, OsProfile, OsProfileBuilder}, + os_profile::{ClientOs, OsProfileBuilder}, }; -use log::debug; -use serde::Deserialize; -use std::collections::HashMap; -use std::process::Command; -use xmltree::Element; - -#[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, - 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, - defender: Option, - clamav: Option, - ufw: Option, -} - -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, - ipv4: Option, - ipv6: Option, -} - -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) -> Self { - self.mac_address = mac; - self - } - - /// Set IPv4 address - fn with_ipv4(mut self, ipv4: Option) -> Self { - self.ipv4 = ipv4; - self - } - - /// Set IPv6 address - fn with_ipv6(mut self, ipv6: Option) -> Self { - self.ipv6 = ipv6; - self - } -} +use gphip::{ReportContext, ReportInput, generate_report}; #[derive(Args)] pub(crate) struct HipArgs { @@ -162,603 +34,29 @@ pub(crate) struct HipArgs { pub(crate) struct HipHandler<'a> { args: &'a HipArgs, - profile: OsProfile, } impl<'a> HipHandler<'a> { pub(crate) fn new(args: &'a HipArgs) -> Self { - let profile = build_os_profile(args); - Self { args, profile } + Self { args } } pub(crate) async fn handle(&self) -> anyhow::Result<()> { - let cookie_params = self.parse_cookie(); - let report = self.generate_hip_report(&cookie_params)?; - - debug!("Generated HIP report:\n{}", report); - println!("{}", report); - + let client_os = ClientOs::from(self.args.client_os); + let mut builder = OsProfileBuilder::new(client_os).client_version(self.args.client_version.clone()); + if let Some(host_id) = self.args.host_id.as_deref() { + builder = builder.host_id_override(host_id); + } + let input = ReportInput { + profile: builder.build(), + context: ReportContext::Connected { + cookie: self.args.cookie.clone(), + client_ip: self.args.client_ip.clone(), + client_ipv6: self.args.client_ipv6.clone(), + md5: self.args.md5.clone(), + }, + }; + println!("{}", generate_report(&input)?); Ok(()) } - - fn parse_cookie(&self) -> HashMap { - // Parse URL-encoded cookie string using serde_urlencoded - serde_urlencoded::from_str(&self.args.cookie).unwrap_or_default() - } - - /// Generate the complete HIP report XML - fn generate_hip_report(&self, cookie_params: &HashMap) -> anyhow::Result { - let (generate_time, day, month, year) = get_current_time_components(); - let user_name = cookie_params.get("user").map(|s| s.as_str()).unwrap_or(""); - let host_info = self.collect_host_info(cookie_params); - - let template = HipReportTemplate { - client_version: &self.args.client_version, - generate_time, - day, - month, - year, - user_name, - host_info, - md5: &self.args.md5, - }; - - let report = template.render()?; - format_xml(&report) - } - - /// Collect host information using the configured OsProfile. - fn collect_host_info(&self, cookie_params: &'a HashMap) -> HostInfo { - HostInfoCollector::new(&self.profile, self.args, cookie_params).collect() - } -} - -/// Construct an `OsProfile` from CLI args, falling back to per-OS defaults -/// for any value not supplied on the command line. -fn build_os_profile(args: &HipArgs) -> OsProfile { - let client_os = ClientOs::from(args.client_os); - let mut builder = OsProfileBuilder::new(client_os).client_version(args.client_version.clone()); - if let Some(host_id) = args.host_id.as_deref() { - debug!("HIP host-id override supplied: {}", host_id); - builder = builder.host_id_override(host_id); - } - let profile = builder.build(); - debug!( - "HIP OS profile host-id: runtime={}, projected={}, client_os={}", - profile.host_identity().host_id(), - profile.host_id(), - client_os.as_str() - ); - profile -} - -// ============================================================================ -// 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, - args: &'a HipArgs, - cookie_params: &'a HashMap, -} - -impl<'p, 'a> HostInfoCollector<'p, 'a> { - fn new(profile: &'p OsProfile, args: &'a HipArgs, cookie_params: &'a HashMap) -> Self { - Self { - profile, - args, - 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.args.client_ip.clone()) - .with_ipv6(self.args.client_ipv6.clone()), - } - } - - /// 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 { - 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 { - match self.profile.client_os() { - ClientOs::Linux => detect_microsoft_defender_blocking(), - ClientOs::Mac | ClientOs::Windows => None, - } - } - - fn clamav_for_profile(&self) -> Option { - match self.profile.client_os() { - ClientOs::Linux => detect_clamav(), - ClientOs::Mac | ClientOs::Windows => None, - } - } - - fn ufw_for_profile(&self) -> Option { - match self.profile.client_os() { - ClientOs::Linux => detect_ufw(), - ClientOs::Mac | ClientOs::Windows => None, - } - } -} - -fn detect_clamav() -> Option { - 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 { - 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)> { - 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 { - 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 { - 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 { - 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 { - 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) -> Option { - 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 { - let xml = Element::parse(xml_str.as_bytes())?; - - 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::runtime_client_os; - use std::ffi::OsStr; - - fn make_hip_args(client_os: Os) -> HipArgs { - HipArgs { - client_version: "6.2.4-49".to_string(), - client_os, - os_version: Some("test-os-version".to_string()), - host_id: None, - 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 args = make_hip_args(Os::Linux); - let profile = make_profile(ClientOs::Linux); - let cookie_params: HashMap = HashMap::new(); - - let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect(); - - assert_eq!(info.os_vendor, "Linux"); - } - - #[test] - fn host_info_os_vendor_is_apple_for_mac_profile() { - let args = make_hip_args(Os::Mac); - let profile = make_profile(ClientOs::Mac); - let cookie_params: HashMap = HashMap::new(); - - let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect(); - - assert_eq!(info.os_vendor, "Apple"); - } - - #[test] - fn host_info_os_vendor_is_microsoft_for_windows_profile() { - let args = make_hip_args(Os::Windows); - let profile = make_profile(ClientOs::Windows); - let cookie_params: HashMap = HashMap::new(); - - let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect(); - - assert_eq!(info.os_vendor, "Microsoft"); - } - - #[test] - fn host_info_host_id_comes_from_os_profile() { - let args = make_hip_args(Os::Linux); - let profile = make_profile(ClientOs::Linux); - let cookie_params: HashMap = HashMap::new(); - - let info = HostInfoCollector::new(&profile, &args, &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, os_arg) in [ - (ClientOs::Linux, Os::Linux), - (ClientOs::Mac, Os::Mac), - (ClientOs::Windows, Os::Windows), - ] { - let args = make_hip_args(os_arg); - let profile = make_profile(client_os); - let cookie_params: HashMap = HashMap::new(); - - let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect(); - - assert_eq!(info.host_id, profile.host_id()); - } - } - - #[test] - fn hip_os_version_argument_is_ignored() { - let args = make_hip_args(Os::Linux); - let profile = build_os_profile(&args); - let cookie_params: HashMap = HashMap::new(); - - let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect(); - - assert_eq!(info.os_version, profile.os_version()); - assert_ne!(info.os_version, "test-os-version"); - } - - #[test] - fn host_id_argument_sets_profile_runtime_identity() { - let mut args = make_hip_args(Os::default()); - args.host_id = Some("auth-host-id".to_string()); - - let profile = build_os_profile(&args); - - assert_eq!(profile.client_os(), runtime_client_os()); - assert_eq!(profile.host_identity().host_id(), "auth-host-id"); - } - - #[test] - fn host_info_uses_host_id_argument_for_native_profile() { - let mut args = make_hip_args(Os::default()); - args.host_id = Some("auth-host-id".to_string()); - let profile = build_os_profile(&args); - let cookie_params: HashMap = HashMap::new(); - - let info = HostInfoCollector::new(&profile, &args, &cookie_params).collect(); - - assert_eq!(profile.host_identity().host_id(), "auth-host-id"); - assert_eq!(info.host_id, profile.host_id()); - } - - #[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)) - ); - } } diff --git a/apps/gpgui-helper/src-tauri/src/updater.rs b/apps/gpgui-helper/src-tauri/src/updater.rs index bb85b68..7f16ff4 100644 --- a/apps/gpgui-helper/src-tauri/src/updater.rs +++ b/apps/gpgui-helper/src-tauri/src/updater.rs @@ -246,9 +246,7 @@ async fn run_installer_connection( rejection.code(), rejection.message() )), - ServiceResult::VpncScriptMetadata(_) => { - Err(anyhow::anyhow!("Service sent an unexpected VPNC script metadata reply")) - } + _ => Err(anyhow::anyhow!("Service sent an unexpected GUI installation reply")), }; let _ = command.reply.send(result); } @@ -301,6 +299,7 @@ async fn connect_installer_at( let (mut socket, _) = connect_async_with_config(endpoint, Some(config), false).await?; let prelude = ClientPrelude { product_version: credential.product_version().to_owned(), + hip_protocol_version: gpapi::service::transport::HIP_PROTOCOL_VERSION, service_instance_id: credential.service_instance_id(), session_id: credential.session_id(), }; @@ -633,7 +632,6 @@ mod tests { snapshot: VpnEnv { vpn_state: VpnState::Disconnected, vpnc_script: None, - csd_wrapper: None, auth_executable: String::new(), host_info: HostInfo { host_identity: HostIdentity::collect(), diff --git a/apps/gpservice/Cargo.toml b/apps/gpservice/Cargo.toml index dd2b1f2..4158522 100644 --- a/apps/gpservice/Cargo.toml +++ b/apps/gpservice/Cargo.toml @@ -7,6 +7,9 @@ license.workspace = true [dependencies] common = { path = "../../crates/common" } gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] } +gphip = { path = "../../crates/gphip" } +base64.workspace = true +sha256.workspace = true openconnect = { path = "../../crates/openconnect" } clap.workspace = true anyhow.workspace = true @@ -31,4 +34,3 @@ nix = { version = "0.31", features = ["fs", "socket", "user"] } [dev-dependencies] tokio-tungstenite = "0.29" -sha256.workspace = true diff --git a/apps/gpservice/src/bin/gp-hip-runner.rs b/apps/gpservice/src/bin/gp-hip-runner.rs new file mode 100644 index 0000000..77cec1e --- /dev/null +++ b/apps/gpservice/src/bin/gp-hip-runner.rs @@ -0,0 +1,137 @@ +use std::{ + env, fs, + io::{self, Write}, +}; + +use anyhow::{Context, ensure}; +use clap::Parser; +use gpapi::{ + clap::args::Os, + os_profile::{ClientOs, OsProfileBuilder}, +}; +use gphip::{ReportContext, ReportInput, generate_report, refresh_edited_report}; +use gpservice::hip_runner_state::{MAX_STATE_BYTES, RunnerReport, STATE_NAME, validate_root_owned_path}; + +#[derive(Parser)] +struct Args { + #[arg(long)] + client_version: String, + #[arg(long, value_enum)] + client_os: Os, + #[arg(long)] + os_version: Option, + #[arg(long)] + host_id: Option, + #[arg(long)] + cookie: Option, + #[arg(long)] + client_ip: Option, + #[arg(long)] + client_ipv6: Option, + #[arg(long)] + md5: Option, + #[arg(long)] + preview: bool, +} + +fn main() { + if let Err(err) = run() { + eprintln!("HIP report generation failed: {err:#}"); + std::process::exit(1); + } +} + +fn run() -> anyhow::Result<()> { + let args = Args::parse(); + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + let original_args: Vec<_> = env::args_os().skip(1).collect(); + let executable = env::current_exe().context("Cannot locate HIP runner")?; + validate_root_owned_path(&executable, true)?; + let state = executable + .parent() + .context("HIP runner has no parent")? + .join(STATE_NAME); + let metadata = fs::symlink_metadata(&state).context("Cannot inspect HIP report state")?; + ensure!( + metadata.is_file() && !metadata.file_type().is_symlink(), + "Invalid HIP report state" + ); + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + ensure!( + metadata.uid() == 0 && metadata.permissions().mode() & 0o077 == 0, + "HIP report state is not private" + ); + ensure!( + metadata.len() <= MAX_STATE_BYTES as u64, + "HIP report state is too large" + ); + let bytes = fs::read(&state).context("Cannot read HIP report state")?; + ensure!(bytes.len() <= MAX_STATE_BYTES, "HIP report state is too large"); + let report: RunnerReport = serde_json::from_slice(&bytes).context("Invalid HIP report state")?; + + // This binary is single-threaded. Clear the VPN and desktop environment + // before host collectors invoke any external system utilities. + for (key, _) in env::vars_os() { + unsafe { env::remove_var(key) }; + } + unsafe { + env::set_var("PATH", "/usr/bin:/bin:/usr/sbin:/sbin"); + env::set_var("LC_ALL", "C"); + env::set_var( + "HOME", + if cfg!(target_os = "macos") { + "/var/root" + } else { + "/root" + }, + ); + } + + let report = match report { + RunnerReport::ApprovedRootScript { approval_id, owner_uid } => { + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + { + let approved = gpservice::hip_approval::resolve(&approval_id, owner_uid)?; + let script_args = original_args.into_iter().filter(|arg| arg != "--preview"); + let status = std::process::Command::new(approved.path) + .args(script_args) + .status() + .context("Approved HIP script did not start")?; + ensure!(status.success(), "Approved HIP script failed"); + return Ok(()); + } + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))] + { + let _ = (approval_id, owner_uid); + anyhow::bail!("Root HIP script approvals are unavailable on this platform"); + } + } + report => report, + }; + + let mut builder = OsProfileBuilder::new(ClientOs::from(args.client_os)).client_version(args.client_version); + if let Some(host_id) = args.host_id { + builder = builder.host_id_override(host_id); + } + let context = if args.preview { + ReportContext::Preview + } else { + ReportContext::Connected { + cookie: args.cookie.context("Missing HIP cookie")?, + client_ip: args.client_ip, + client_ipv6: args.client_ipv6, + md5: args.md5.context("Missing HIP digest")?, + } + }; + let input = ReportInput { + profile: builder.build(), + context, + }; + let xml = match report { + RunnerReport::Generated => generate_report(&input)?, + RunnerReport::Edited { xml } => refresh_edited_report(&xml, &input)?, + RunnerReport::ApprovedRootScript { .. } => unreachable!("approved script returned before report generation"), + }; + io::stdout().write_all(xml.as_bytes())?; + Ok(()) +} diff --git a/apps/gpservice/src/bin/gp-hip-script-installer/main.rs b/apps/gpservice/src/bin/gp-hip-script-installer/main.rs new file mode 100644 index 0000000..87ca689 --- /dev/null +++ b/apps/gpservice/src/bin/gp-hip-script-installer/main.rs @@ -0,0 +1,10 @@ +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +#[path = "privileged_unix.rs"] +mod platform; +#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))] +#[path = "unsupported.rs"] +mod platform; + +fn main() { + platform::run(); +} diff --git a/apps/gpservice/src/bin/gp-hip-script-installer/privileged_unix.rs b/apps/gpservice/src/bin/gp-hip-script-installer/privileged_unix.rs new file mode 100644 index 0000000..81c9963 --- /dev/null +++ b/apps/gpservice/src/bin/gp-hip-script-installer/privileged_unix.rs @@ -0,0 +1,56 @@ +use std::io::Read; + +use anyhow::{Context, ensure}; +use clap::{Parser, Subcommand}; +use gpservice::hip_approval::{self, InstallRequest}; +use nix::unistd::Uid; + +const MAX_INSTALL_REQUEST_SIZE: u64 = 2 * 1024 * 1024; + +#[derive(Parser)] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + Install, + Revoke { approval_id: String }, +} + +fn try_run() -> anyhow::Result<()> { + ensure!(Uid::effective().is_root(), "HIP script installer must run as root"); + let approving_uid = std::env::var("PKEXEC_UID") + .context("HIP script installer requires pkexec authorization")? + .parse::() + .context("Invalid pkexec user identity")?; + ensure!(approving_uid != 0, "HIP script installer requires a desktop user"); + + match Cli::parse().command { + Command::Install => { + let mut input = Vec::new(); + std::io::stdin() + .lock() + .take(MAX_INSTALL_REQUEST_SIZE + 1) + .read_to_end(&mut input)?; + ensure!( + input.len() as u64 <= MAX_INSTALL_REQUEST_SIZE, + "HIP install request is too large" + ); + let request: InstallRequest = serde_json::from_slice(&input).context("Invalid HIP install request")?; + let info = hip_approval::install(request, approving_uid)?; + serde_json::to_writer(std::io::stdout().lock(), &info)?; + println!(); + } + Command::Revoke { approval_id } => hip_approval::revoke(&approval_id, approving_uid)?, + } + Ok(()) +} + +pub(super) fn run() { + if let Err(err) = try_run() { + eprintln!("HIP approval failed: {err:#}"); + std::process::exit(1); + } +} diff --git a/apps/gpservice/src/bin/gp-hip-script-installer/unsupported.rs b/apps/gpservice/src/bin/gp-hip-script-installer/unsupported.rs new file mode 100644 index 0000000..3d0975d --- /dev/null +++ b/apps/gpservice/src/bin/gp-hip-script-installer/unsupported.rs @@ -0,0 +1,4 @@ +pub(super) fn run() { + eprintln!("Root HIP script approvals are unavailable on this platform"); + std::process::exit(1); +} diff --git a/apps/gpservice/src/cli.rs b/apps/gpservice/src/cli.rs index dae1864..439dfab 100644 --- a/apps/gpservice/src/cli.rs +++ b/apps/gpservice/src/cli.rs @@ -100,7 +100,7 @@ impl Cli { let gui_restart_requested = Arc::new(AtomicBool::new(false)); let registry = Arc::new(SessionRegistry::new(Uuid::new_v4())); let externally_brokered = self.externally_brokered(); - let trusted_csd_uid = crate::runtime_user::trusted_csd_uid()?; + let desktop_uid = crate::runtime_user::desktop_uid(); let brokered_scripts_dir = if externally_brokered { let executable = std::env::current_exe().context("Failed to locate the gpservice executable")?; let contents_dir = executable @@ -111,7 +111,7 @@ impl Cli { } else { None }; - let (mut vpn_task, lifecycle) = VpnTask::new(vpn_state_tx, externally_brokered, trusted_csd_uid); + let (mut vpn_task, lifecycle) = VpnTask::new(vpn_state_tx, externally_brokered, Arc::clone(®istry)); let dispatcher = Arc::new(RequestDispatcher::new( lifecycle.clone(), Arc::clone(&gui_restart_requested), @@ -196,7 +196,7 @@ impl Cli { let envs = self.env_file.as_ref().map(env_utils::load_env_vars).transpose()?; let minimized = self.minimized; tokio::spawn(async move { - launch_gui(envs, registry, minimized, gui_restart_requested).await; + launch_gui(envs, registry, desktop_uid, minimized, gui_restart_requested).await; let _ = shutdown_tx.send(()).await; }); } else { @@ -366,11 +366,12 @@ mod signals { async fn launch_gui( envs: Option>, registry: Arc, + desktop_uid: Option, mut minimized: bool, restart_requested: Arc, ) { loop { - let credential = match registry.issue(env!("CARGO_PKG_VERSION")) { + let credential = match registry.issue(env!("CARGO_PKG_VERSION"), desktop_uid) { Ok(credential) => credential, Err(err) => { warn!("Failed to issue GUI credential: {err}"); diff --git a/apps/gpservice/src/credential_lease.rs b/apps/gpservice/src/credential_lease.rs index 4415783..9c7eb57 100644 --- a/apps/gpservice/src/credential_lease.rs +++ b/apps/gpservice/src/credential_lease.rs @@ -7,8 +7,12 @@ use tokio::{ use crate::session_registry::SessionRegistry; -pub(crate) async fn serve(mut stream: UnixStream, registry: Arc) -> anyhow::Result<()> { - let credential = registry.issue(env!("CARGO_PKG_VERSION"))?; +pub(crate) async fn serve( + mut stream: UnixStream, + registry: Arc, + desktop_uid: Option, +) -> anyhow::Result<()> { + let credential = registry.issue(env!("CARGO_PKG_VERSION"), desktop_uid)?; let session_id = credential.session_id(); let result = async { stream.write_all(&credential.encode_frame()?).await?; diff --git a/apps/gpservice/src/dev_bootstrap.rs b/apps/gpservice/src/dev_bootstrap.rs index dc208e1..767337d 100644 --- a/apps/gpservice/src/dev_bootstrap.rs +++ b/apps/gpservice/src/dev_bootstrap.rs @@ -54,7 +54,7 @@ impl DevBootstrap { } let registry = Arc::clone(&self.registry); tokio::spawn(async move { - if let Err(err) = credential_lease::serve(stream, registry).await { + if let Err(err) = credential_lease::serve(stream, registry, Some(self.allowed_uid)).await { warn!("Debug credential client ended: {err}"); } }); @@ -188,7 +188,7 @@ mod tests { async fn anchor_eof_revokes_issued_credential() { let registry = Arc::new(SessionRegistry::new(Uuid::new_v4())); let (service, mut client) = UnixStream::pair().unwrap(); - let task = tokio::spawn(credential_lease::serve(service, Arc::clone(®istry))); + let task = tokio::spawn(credential_lease::serve(service, Arc::clone(®istry), Some(1234))); let mut header = [0_u8; 2]; client.read_exact(&mut header).await.unwrap(); diff --git a/apps/gpservice/src/hip_approval.rs b/apps/gpservice/src/hip_approval.rs new file mode 100644 index 0000000..42ce0fc --- /dev/null +++ b/apps/gpservice/src/hip_approval.rs @@ -0,0 +1,400 @@ +use std::{ + fs::{self, File, OpenOptions}, + io::Write, + os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}, + path::{Path, PathBuf}, +}; + +use anyhow::{Context, ensure}; +use base64::{Engine, engine::general_purpose::STANDARD}; +use gpapi::service::hip::HipApprovalStatus; +use serde::{Deserialize, Serialize}; +use tempfile::Builder; +use uuid::Uuid; + +use crate::hip_runner_state::validate_root_owned_path; + +#[cfg(target_os = "linux")] +pub const APPROVAL_DIRECTORY: &str = "/var/lib/gpclient/hip-approvals"; +#[cfg(any(target_os = "freebsd", target_os = "openbsd"))] +pub const APPROVAL_DIRECTORY: &str = "/var/db/gpclient/hip-approvals"; +pub const MAX_SCRIPT_SIZE: usize = common::constants::MAX_HIP_SCRIPT_SIZE; +const MAX_METADATA_SIZE: u64 = 8 * 1024; +const METADATA_VERSION: u8 = 1; +const SCRIPT_NAME: &str = "script"; +const METADATA_NAME: &str = "metadata.json"; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InstallRequest { + pub original_path: String, + pub contents_base64: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ApprovalInfo { + pub approval_id: String, + pub owner_uid: u32, + pub sha256: String, + pub original_path: String, +} + +#[derive(Clone, Debug)] +pub struct ApprovedScript { + pub info: ApprovalInfo, + pub path: PathBuf, +} + +#[derive(Deserialize, Serialize)] +struct StoredMetadata { + version: u8, + info: ApprovalInfo, +} + +impl InstallRequest { + fn contents(&self) -> anyhow::Result> { + ensure!(self.original_path.len() <= 4096, "HIP script path is too long"); + ensure!( + Path::new(&self.original_path).is_absolute(), + "HIP script path must be absolute" + ); + ensure!( + !self.original_path.contains('\0'), + "HIP script path contains a NUL byte" + ); + ensure!( + self.contents_base64.len() <= (MAX_SCRIPT_SIZE + 2).div_ceil(3) * 4, + "HIP script exceeds 1 MiB" + ); + let contents = STANDARD + .decode(&self.contents_base64) + .context("Invalid HIP script content encoding")?; + ensure!( + !contents.is_empty() && contents.len() <= MAX_SCRIPT_SIZE, + "HIP script must be 1 MiB or smaller" + ); + Ok(contents) + } +} + +pub fn install(request: InstallRequest, approving_uid: u32) -> anyhow::Result { + ensure!(approving_uid != 0, "Root cannot approve a desktop HIP script"); + let contents = request.contents()?; + let base = Path::new(APPROVAL_DIRECTORY); + fs::create_dir_all(base).context("Cannot create HIP approval directory")?; + validate_root_owned_path(base, false)?; + fs::set_permissions(base, fs::Permissions::from_mode(0o700))?; + install_at(base, &contents, request.original_path, approving_uid, 0) +} + +pub fn resolve(approval_id: &str, desktop_uid: u32) -> anyhow::Result { + ensure!(desktop_uid != 0, "Root is not a desktop HIP approval owner"); + let base = Path::new(APPROVAL_DIRECTORY); + validate_root_owned_path(base, false)?; + resolve_at(base, approval_id, desktop_uid, 0) +} + +pub fn revoke(approval_id: &str, approving_uid: u32) -> anyhow::Result<()> { + ensure!(approving_uid != 0, "Root cannot revoke another user's HIP approval"); + let base = Path::new(APPROVAL_DIRECTORY); + validate_root_owned_path(base, false)?; + revoke_at(base, approval_id, approving_uid, 0) +} + +pub fn status(approval_id: &str, desktop_uid: u32) -> anyhow::Result { + status_at(Path::new(APPROVAL_DIRECTORY), approval_id, desktop_uid, 0) +} + +fn status_at(base: &Path, approval_id: &str, desktop_uid: u32, file_owner: u32) -> anyhow::Result { + ensure!(desktop_uid != 0, "HIP approval status requires a desktop user"); + validate_id(approval_id)?; + for path in [ + base.to_path_buf(), + base.join(approval_id), + base.join(approval_id).join(METADATA_NAME), + ] { + match fs::symlink_metadata(&path) { + Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(HipApprovalStatus::Revoked), + Err(_) => return Ok(HipApprovalStatus::Corrupt), + Ok(_) => {} + } + } + if validate_private_dir(base, file_owner).is_err() + || (file_owner == 0 && validate_root_owned_path(base, false).is_err()) + { + return Ok(HipApprovalStatus::Corrupt); + } + let info = match read_metadata_unbound_at(base, approval_id, file_owner) { + Ok(info) => info, + Err(_) => return Ok(HipApprovalStatus::Corrupt), + }; + if info.owner_uid != desktop_uid { + return Ok(HipApprovalStatus::OtherUser); + } + Ok(if resolve_at(base, approval_id, desktop_uid, file_owner).is_ok() { + HipApprovalStatus::Valid + } else { + HipApprovalStatus::Corrupt + }) +} + +fn install_at( + base: &Path, + contents: &[u8], + original_path: String, + approving_uid: u32, + file_owner: u32, +) -> anyhow::Result { + validate_private_dir(base, file_owner)?; + ensure!( + !contents.is_empty() && contents.len() <= MAX_SCRIPT_SIZE, + "HIP script must be 1 MiB or smaller" + ); + let approval_id = Uuid::new_v4().to_string(); + let info = ApprovalInfo { + approval_id: approval_id.clone(), + owner_uid: approving_uid, + sha256: sha256::digest(contents), + original_path, + }; + let staged = Builder::new().prefix(".install-").tempdir_in(base)?; + fs::set_permissions(staged.path(), fs::Permissions::from_mode(0o700))?; + validate_private_dir(staged.path(), file_owner)?; + + let script = staged.path().join(SCRIPT_NAME); + write_new(&script, contents, 0o500)?; + let metadata = staged.path().join(METADATA_NAME); + let stored = StoredMetadata { + version: METADATA_VERSION, + info: info.clone(), + }; + let encoded = serde_json::to_vec(&stored)?; + ensure!( + encoded.len() as u64 <= MAX_METADATA_SIZE, + "HIP approval metadata is too large" + ); + write_new(&metadata, &encoded, 0o600)?; + File::open(staged.path())?.sync_all()?; + + let target = base.join(&approval_id); + ensure!(!target.exists(), "HIP approval ID collision"); + fs::rename(staged.path(), &target).context("Cannot publish HIP approval")?; + File::open(base)?.sync_all()?; + Ok(info) +} + +fn resolve_at(base: &Path, approval_id: &str, desktop_uid: u32, file_owner: u32) -> anyhow::Result { + let info = read_metadata_at(base, approval_id, desktop_uid, file_owner)?; + let script = base.join(approval_id).join(SCRIPT_NAME); + validate_file(&script, file_owner, 0o500, MAX_SCRIPT_SIZE as u64)?; + let contents = fs::read(&script)?; + ensure!(!contents.is_empty(), "Approved HIP script is empty"); + ensure!( + sha256::digest(&contents) == info.sha256, + "Approved HIP script digest mismatch" + ); + Ok(ApprovedScript { info, path: script }) +} + +fn read_metadata_at(base: &Path, approval_id: &str, desktop_uid: u32, file_owner: u32) -> anyhow::Result { + let info = read_metadata_unbound_at(base, approval_id, file_owner)?; + ensure!(info.owner_uid == desktop_uid, "HIP approval belongs to another user"); + Ok(info) +} + +fn read_metadata_unbound_at(base: &Path, approval_id: &str, file_owner: u32) -> anyhow::Result { + validate_id(approval_id)?; + validate_private_dir(base, file_owner)?; + let directory = base.join(approval_id); + validate_private_dir(&directory, file_owner)?; + let metadata_path = directory.join(METADATA_NAME); + validate_file(&metadata_path, file_owner, 0o600, MAX_METADATA_SIZE)?; + let stored: StoredMetadata = serde_json::from_slice(&fs::read(metadata_path)?)?; + ensure!(stored.version == METADATA_VERSION, "Unsupported HIP approval version"); + ensure!(stored.info.approval_id == approval_id, "HIP approval ID mismatch"); + ensure!( + stored.info.sha256.len() == 64 && stored.info.sha256.bytes().all(|byte| byte.is_ascii_hexdigit()), + "Invalid HIP approval digest" + ); + + Ok(stored.info) +} + +fn revoke_at(base: &Path, approval_id: &str, approving_uid: u32, file_owner: u32) -> anyhow::Result<()> { + validate_id(approval_id)?; + let directory = base.join(approval_id); + // The GUI may retry after removal succeeds but saving its settings fails. + if let Err(err) = fs::symlink_metadata(&directory) { + if err.kind() == std::io::ErrorKind::NotFound { + return Ok(()); + } + return Err(err).context("Cannot inspect HIP approval directory"); + } + read_metadata_at(base, approval_id, approving_uid, file_owner)?; + // Renaming first makes revocation atomic for the runner. Cleanup is separate: + // a failed cleanup cannot make this approval executable again. + let revoked = base.join(format!(".revoked-{approval_id}")); + fs::rename(&directory, &revoked).context("Cannot revoke HIP approval")?; + File::open(base)?.sync_all()?; + if let Err(err) = fs::remove_dir_all(&revoked) { + log::warn!("HIP approval was revoked but its snapshot could not be removed: {err}"); + } else { + File::open(base)?.sync_all()?; + } + Ok(()) +} + +fn write_new(path: &Path, bytes: &[u8], mode: u32) -> anyhow::Result<()> { + let mut file = OpenOptions::new().write(true).create_new(true).mode(mode).open(path)?; + file.write_all(bytes)?; + file.sync_all()?; + Ok(()) +} + +fn validate_id(value: &str) -> anyhow::Result<()> { + let parsed = Uuid::parse_str(value).context("Invalid HIP approval ID")?; + ensure!(parsed.to_string() == value, "HIP approval ID must use canonical form"); + Ok(()) +} + +fn validate_private_dir(path: &Path, owner_uid: u32) -> anyhow::Result<()> { + let metadata = fs::symlink_metadata(path).with_context(|| format!("Cannot inspect {}", path.display()))?; + ensure!( + metadata.is_dir() && !metadata.file_type().is_symlink(), + "HIP approval directory is not a directory" + ); + ensure!( + metadata.uid() == owner_uid && metadata.permissions().mode() & 0o077 == 0, + "HIP approval directory {} is not private (owner {}, mode {:o})", + path.display(), + metadata.uid(), + metadata.permissions().mode() & 0o777 + ); + Ok(()) +} + +fn validate_file(path: &Path, owner_uid: u32, mode: u32, max_size: u64) -> anyhow::Result<()> { + let metadata = fs::symlink_metadata(path).with_context(|| format!("Cannot inspect {}", path.display()))?; + ensure!( + metadata.is_file() && !metadata.file_type().is_symlink(), + "HIP approval file is not regular" + ); + ensure!( + metadata.uid() == owner_uid && metadata.permissions().mode() & 0o777 == mode, + "HIP approval file has unsafe ownership or mode" + ); + ensure!(metadata.len() <= max_size, "HIP approval file is too large"); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fixture() -> (tempfile::TempDir, u32) { + let base = tempfile::tempdir().unwrap(); + fs::set_permissions(base.path(), fs::Permissions::from_mode(0o700)).unwrap(); + let owner = fs::symlink_metadata(base.path()).unwrap().uid(); + (base, owner) + } + + #[test] + fn install_request_rejects_oversized_or_relative_script() { + let request = InstallRequest { + original_path: "hip.sh".into(), + contents_base64: STANDARD.encode(b"#!/bin/sh\n"), + }; + assert!(request.contents().is_err()); + let oversized = InstallRequest { + original_path: "/home/user/hip.sh".into(), + contents_base64: STANDARD.encode(vec![b'x'; MAX_SCRIPT_SIZE + 1]), + }; + assert!(oversized.contents().is_err()); + } + + #[test] + fn approval_binds_owner_and_exact_script_digest() { + let (base, owner) = fixture(); + let info = install_at( + base.path(), + b"#!/bin/sh\necho ok\n", + "/home/user/hip.sh".into(), + 1000, + owner, + ) + .unwrap(); + let approved = resolve_at(base.path(), &info.approval_id, 1000, owner).unwrap(); + assert_eq!(approved.info.sha256, info.sha256); + assert!(resolve_at(base.path(), &info.approval_id, 1001, owner).is_err()); + fs::set_permissions(&approved.path, fs::Permissions::from_mode(0o700)).unwrap(); + fs::write(&approved.path, b"#!/bin/sh\necho changed\n").unwrap(); + fs::set_permissions(&approved.path, fs::Permissions::from_mode(0o500)).unwrap(); + assert!(resolve_at(base.path(), &info.approval_id, 1000, owner).is_err()); + } + + #[test] + fn revoked_approval_is_unavailable() { + let (base, owner) = fixture(); + let info = install_at(base.path(), b"#!/bin/sh\n", "/home/user/hip.sh".into(), 1000, owner).unwrap(); + assert!(revoke_at(base.path(), &info.approval_id, 1001, owner).is_err()); + revoke_at(base.path(), &info.approval_id, 1000, owner).unwrap(); + revoke_at(base.path(), &info.approval_id, 1000, owner).unwrap(); + assert!(resolve_at(base.path(), &info.approval_id, 1000, owner).is_err()); + } + + #[test] + fn status_distinguishes_owner_corruption_and_revocation() { + let (base, owner) = fixture(); + let info = install_at( + base.path(), + b"#!/bin/sh\necho ok\n", + "/home/user/hip.sh".into(), + 1000, + owner, + ) + .unwrap(); + assert_eq!( + status_at(base.path(), &info.approval_id, 1000, owner).unwrap(), + HipApprovalStatus::Valid + ); + assert_eq!( + status_at(base.path(), &info.approval_id, 1001, owner).unwrap(), + HipApprovalStatus::OtherUser + ); + let script = base.path().join(&info.approval_id).join(SCRIPT_NAME); + fs::set_permissions(&script, fs::Permissions::from_mode(0o700)).unwrap(); + assert_eq!( + status_at(base.path(), &info.approval_id, 1000, owner).unwrap(), + HipApprovalStatus::Corrupt + ); + fs::remove_file(base.path().join(&info.approval_id).join(METADATA_NAME)).unwrap(); + assert_eq!( + status_at(base.path(), &info.approval_id, 1000, owner).unwrap(), + HipApprovalStatus::Revoked + ); + } + + #[test] + fn revoke_succeeds_if_script_was_corrupted() { + let (base, owner) = fixture(); + let info = install_at(base.path(), b"#!/bin/sh\n", "/home/user/hip.sh".into(), 1000, owner).unwrap(); + let script = base.path().join(&info.approval_id).join(SCRIPT_NAME); + fs::set_permissions(&script, fs::Permissions::from_mode(0o700)).unwrap(); + fs::write(&script, b"changed").unwrap(); + assert!(resolve_at(base.path(), &info.approval_id, 1000, owner).is_err()); + revoke_at(base.path(), &info.approval_id, 1000, owner).unwrap(); + assert!(!base.path().join(&info.approval_id).exists()); + } + + #[test] + fn rejects_symlinked_script() { + use std::os::unix::fs::symlink; + let (base, owner) = fixture(); + let info = install_at(base.path(), b"#!/bin/sh\n", "/home/user/hip.sh".into(), 1000, owner).unwrap(); + let script = base.path().join(&info.approval_id).join(SCRIPT_NAME); + fs::remove_file(&script).unwrap(); + symlink("/bin/sh", &script).unwrap(); + assert!(resolve_at(base.path(), &info.approval_id, 1000, owner).is_err()); + } +} diff --git a/apps/gpservice/src/hip_preview.rs b/apps/gpservice/src/hip_preview.rs new file mode 100644 index 0000000..c3d6965 --- /dev/null +++ b/apps/gpservice/src/hip_preview.rs @@ -0,0 +1,275 @@ +use std::{os::unix::process::CommandExt, process::Stdio, sync::Arc, time::Duration}; + +use anyhow::{Context, bail, ensure}; +use gpapi::service::{hip::HipSource, request::PreviewHipReportRequest}; +use tokio::{io::AsyncReadExt, process::Command}; + +const MAX_PREVIEW_BYTES: u64 = 1024 * 1024; +const PREVIEW_TIMEOUT: Duration = Duration::from_secs(60); +const PREVIEW_COOKIE: &str = "user=preview&domain=preview&computer=preview"; +const PREVIEW_IP: &str = "192.0.2.1"; +const PREVIEW_MD5: &str = "00000000000000000000000000000000"; + +pub(crate) async fn generate( + request: PreviewHipReportRequest, + edited_report: Option>, + desktop_uid: Option, +) -> anyhow::Result { + ensure!(request.client_version.len() <= 64, "Invalid HIP client version"); + ensure!( + request.host_id.as_ref().is_none_or(|id| id.len() <= 256), + "Invalid HIP host ID" + ); + + let source = &request.source; + let execution = match source { + HipSource::Disabled => bail!("HIP is disabled"), + HipSource::Generated | HipSource::Edited { .. } => crate::hip_source::preview_runner(edited_report)?, + HipSource::UserScript { .. } | HipSource::ApprovedRootScript { .. } => { + crate::hip_source::resolve(source, desktop_uid, false, None)? + } + }; + let script = execution + .wrapper + .as_deref() + .context("HIP preview script is unavailable")?; + let is_runner = !matches!(source, HipSource::UserScript { .. }); + let mut command = Command::new(script); + command + .arg("--client-version") + .arg(&request.client_version) + .arg("--client-os") + .arg(request.client_os.as_str()) + .arg("--os-version") + .arg(request.client_os.default_os_version()); + if let Some(host_id) = request.host_id { + command.arg("--host-id").arg(host_id); + } + if is_runner { + command.arg("--preview"); + } + command + .arg("--cookie") + .arg(PREVIEW_COOKIE) + .arg("--client-ip") + .arg(PREVIEW_IP) + .arg("--md5") + .arg(PREVIEW_MD5) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + command.as_std_mut().process_group(0); + configure_identity(&mut command, execution.uid, &request.client_version)?; + command.kill_on_drop(true); + + let mut child = command.spawn().context("Failed to launch HIP preview")?; + let mut process_group = ProcessGroupGuard::new(child.id()); + let mut stdout = child + .stdout + .take() + .context("HIP preview has no output stream")? + .take(MAX_PREVIEW_BYTES + 1); + let output = tokio::time::timeout(PREVIEW_TIMEOUT, async { + let mut bytes = Vec::new(); + stdout.read_to_end(&mut bytes).await?; + ensure!(bytes.len() as u64 <= MAX_PREVIEW_BYTES, "HIP preview exceeds 1 MiB"); + let status = child.wait().await?; + process_group.disarm(); + ensure!(status.success(), "HIP preview generator failed"); + Ok::<_, anyhow::Error>(String::from_utf8(bytes)?) + }) + .await; + match output { + Ok(Ok(xml)) => { + if matches!( + source, + HipSource::UserScript { .. } | HipSource::ApprovedRootScript { .. } + ) { + gphip::validate_edited_report(&xml).context("Custom HIP script did not emit a valid HIP report")?; + } + Ok(xml) + } + Ok(Err(error)) => { + terminate_group(&mut child, &mut process_group).await; + Err(error) + } + Err(_) => { + terminate_group(&mut child, &mut process_group).await; + anyhow::bail!("HIP preview timed out") + } + } +} + +fn configure_identity(command: &mut Command, uid: u32, app_version: &str) -> anyhow::Result<()> { + command + .as_std_mut() + .env_clear() + .env("PATH", "/usr/bin:/bin:/usr/sbin:/sbin") + .env("LC_ALL", "C") + .env("APP_VERSION", app_version); + if uid == 0 { + command.as_std_mut().env("HOME", "/root"); + return Ok(()); + } + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + { + use nix::unistd::{Uid, User}; + let user = User::from_uid(Uid::from_raw(uid))?.context("Desktop user is unavailable")?; + command + .as_std_mut() + .env("HOME", &user.dir) + .env("USER", &user.name) + .env("LOGNAME", &user.name) + .current_dir(&user.dir); + if Uid::effective().as_raw() == uid { + return Ok(()); + } + // Match OpenConnect's CSD child: a single primary group, then the desktop UID. + unsafe { + command.as_std_mut().pre_exec(move || { + nix::unistd::setgid(user.gid).map_err(std::io::Error::from)?; + nix::unistd::setgroups(&[user.gid]).map_err(std::io::Error::from)?; + nix::unistd::setuid(Uid::from_raw(uid)).map_err(std::io::Error::from)?; + Ok(()) + }); + } + Ok(()) + } + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))] + { + bail!("Custom HIP previews are unavailable on this platform") + } +} + +struct ProcessGroupGuard(Option); + +impl ProcessGroupGuard { + fn new(pid: Option) -> Self { + Self(pid) + } + + fn kill(&mut self) { + if let Some(pid) = self.0.take() { + unsafe { nix::libc::kill(-(pid as i32), nix::libc::SIGKILL) }; + } + } + + fn disarm(&mut self) { + self.0 = None; + } +} + +impl Drop for ProcessGroupGuard { + fn drop(&mut self) { + self.kill(); + } +} + +async fn terminate_group(child: &mut tokio::process::Child, process_group: &mut ProcessGroupGuard) { + process_group.kill(); + let _ = child.start_kill(); + let _ = child.wait().await; +} + +#[cfg(all(test, any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))] +mod tests { + use super::*; + use gpapi::os_profile::ClientOs; + use std::{fs, os::unix::fs::PermissionsExt}; + + fn request(path: &std::path::Path) -> PreviewHipReportRequest { + PreviewHipReportRequest { + source: HipSource::UserScript { + path: path.to_string_lossy().into_owned(), + }, + client_os: ClientOs::Linux, + client_version: "6.3.3".into(), + host_id: Some("host-test".into()), + } + } + + fn script(path: &std::path::Path, body: &str) { + fs::write(path, format!("#!/bin/sh\n{body}\n")).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap(); + } + + #[tokio::test] + async fn user_script_preview_receives_placeholders_and_validates_output() { + let uid = nix::unistd::Uid::effective().as_raw(); + if uid == 0 { + return; + } + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("hip.sh"); + script( + &path, + r#" +test "$1" = --client-version && test "$2" = 6.3.3 || exit 2 +test "$3" = --client-os && test "$4" = Linux || exit 2 +test "$5" = --os-version || exit 2 +test "$7" = --host-id && test "$8" = host-test || exit 2 +test "$9" = --cookie && test "${10}" = 'user=preview&domain=preview&computer=preview' || exit 2 +test "${11}" = --client-ip && test "${12}" = 192.0.2.1 || exit 2 +test "${13}" = --md5 && test "${14}" = 00000000000000000000000000000000 || exit 2 +test "$#" = 14 || exit 2 +test "$APP_VERSION" = 6.3.3 || exit 2 +printf '%s' '' +"#, + ); + let xml = generate(request(&path), None, Some(uid)).await.unwrap(); + assert!(xml.starts_with("")); + + script(&path, "printf '%s' ''"); + assert!(generate(request(&path), None, Some(uid)).await.is_err()); + + script(&path, "head -c 1048577 /dev/zero"); + let err = generate(request(&path), None, Some(uid)).await.unwrap_err(); + assert!(err.to_string().contains("exceeds 1 MiB")); + } + + #[cfg(target_os = "linux")] + #[tokio::test] + async fn cancelling_preview_stops_its_process_group() { + let uid = nix::unistd::Uid::effective().as_raw(); + if uid == 0 { + return; + } + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("hip.sh"); + let pid_file = dir.path().join("pids"); + script( + &path, + &format!( + "sleep 30 & child=$!; echo \"$$ $child\" > \"{}\"; wait", + pid_file.display() + ), + ); + let preview = tokio::spawn(generate(request(&path), None, Some(uid))); + let pids = tokio::time::timeout(Duration::from_secs(3), async { + loop { + if let Ok(pids) = fs::read_to_string(&pid_file) { + break pids; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + let child_pid = pids.split_whitespace().nth(1).unwrap().parse::().unwrap(); + preview.abort(); + assert!(preview.await.unwrap_err().is_cancelled()); + tokio::time::timeout(Duration::from_secs(3), async { + loop { + let state = fs::read_to_string(format!("/proc/{child_pid}/stat")) + .ok() + .and_then(|stat| stat.rsplit_once(") ").and_then(|(_, fields)| fields.chars().next())); + if state.is_none_or(|state| state == 'Z') { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + } +} diff --git a/apps/gpservice/src/hip_runner_state.rs b/apps/gpservice/src/hip_runner_state.rs new file mode 100644 index 0000000..4300a7e --- /dev/null +++ b/apps/gpservice/src/hip_runner_state.rs @@ -0,0 +1,59 @@ +use std::{ + fs, + os::unix::fs::{MetadataExt, PermissionsExt}, + path::Path, +}; + +use anyhow::{Context, ensure}; +use serde::{Deserialize, Serialize}; + +pub const RUNNER_NAME: &str = "gp-hip-runner"; +pub const STATE_NAME: &str = "report.json"; +pub const MAX_STATE_BYTES: usize = 512 * 1024; + +#[derive(Deserialize, Serialize)] +#[serde(tag = "source", rename_all = "camelCase")] +pub enum RunnerReport { + Generated, + Edited { xml: String }, + ApprovedRootScript { approval_id: String, owner_uid: u32 }, +} + +/// Check every component because a trusted file below a writable parent can +/// be replaced before a later HIP refresh. +pub fn validate_root_owned_path(path: &Path, file: bool) -> anyhow::Result<()> { + ensure!(path.is_absolute(), "HIP runner path must be absolute"); + for component in path.ancestors().take_while(|part| part.as_os_str() != "/") { + let metadata = + fs::symlink_metadata(component).with_context(|| format!("Cannot inspect {}", component.display()))?; + ensure!(!metadata.file_type().is_symlink(), "HIP runner path contains a symlink"); + ensure!(metadata.uid() == 0, "HIP runner path is not root-owned"); + ensure!( + metadata.permissions().mode() & 0o022 == 0, + "HIP runner path is writable by another user" + ); + if component == path && file { + ensure!(metadata.is_file(), "HIP runner is not a regular file"); + ensure!( + metadata.permissions().mode() & 0o111 != 0, + "HIP runner is not executable" + ); + } else { + ensure!(metadata.is_dir(), "HIP runner parent is not a directory"); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_user_owned_runner_directory() { + let temp = tempfile::tempdir().unwrap(); + if unsafe { nix::libc::geteuid() } != 0 { + assert!(validate_root_owned_path(temp.path(), false).is_err()); + } + } +} diff --git a/apps/gpservice/src/hip_source.rs b/apps/gpservice/src/hip_source.rs new file mode 100644 index 0000000..9a882a1 --- /dev/null +++ b/apps/gpservice/src/hip_source.rs @@ -0,0 +1,291 @@ +use std::{ + fs::{self, OpenOptions}, + io::Write, + os::unix::fs::{OpenOptionsExt, PermissionsExt}, + path::{Path, PathBuf}, + sync::Arc, +}; + +use anyhow::{Context, bail, ensure}; +use gpapi::service::hip::HipSource; +use gpservice::hip_runner_state::{MAX_STATE_BYTES, RUNNER_NAME, RunnerReport, STATE_NAME, validate_root_owned_path}; +use tempfile::{Builder, TempDir}; + +pub(crate) struct HipExecution { + pub enabled: bool, + pub uid: u32, + pub wrapper: Option, + _state_dir: Option, + approval: Option<(String, u32)>, +} + +impl HipExecution { + fn disabled() -> Self { + Self { + enabled: false, + uid: 0, + wrapper: None, + _state_dir: None, + approval: None, + } + } + + fn script(uid: u32, wrapper: PathBuf, state_dir: Option) -> Self { + Self { + enabled: true, + uid, + wrapper: Some(wrapper.to_string_lossy().into_owned()), + _state_dir: state_dir, + approval: None, + } + } + + pub(crate) fn approval_id(&self) -> Option<&str> { + self.approval.as_ref().map(|(id, _)| id.as_str()) + } + + pub(crate) fn approval_is_valid(&self) -> bool { + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + if let Some((id, uid)) = &self.approval { + return gpservice::hip_approval::resolve(id, *uid).is_ok(); + } + true + } +} + +pub(crate) fn resolve( + source: &HipSource, + desktop_uid: Option, + brokered_macos: bool, + edited_report: Option>, +) -> anyhow::Result { + match source { + HipSource::Disabled => Ok(HipExecution::disabled()), + HipSource::Generated => stage_runner(RunnerReport::Generated), + HipSource::Edited { .. } => { + let xml = edited_report.context("Edited HIP report was not uploaded for this connection")?; + gphip::validate_edited_report(&xml)?; + stage_runner(RunnerReport::Edited { xml: xml.to_string() }) + } + HipSource::UserScript { path } => { + if cfg!(target_os = "macos") || brokered_macos { + bail!("Custom HIP scripts are unavailable on macOS"); + } + let uid = desktop_uid.context("HIP custom scripts require a verified desktop user")?; + ensure!(uid != 0, "HIP custom scripts require a non-root desktop user"); + let path = PathBuf::from(path); + let metadata = fs::symlink_metadata(&path).context("Failed to inspect the HIP script")?; + ensure!( + metadata.is_file() && !metadata.file_type().is_symlink() && metadata.permissions().mode() & 0o111 != 0, + "HIP custom script must be an executable regular file" + ); + Ok(HipExecution::script(uid, path, None)) + } + HipSource::ApprovedRootScript { approval_id } => { + if cfg!(target_os = "macos") || brokered_macos { + bail!("Custom HIP scripts are unavailable on macOS"); + } + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + { + let owner_uid = desktop_uid.context("Root HIP scripts require a verified desktop user")?; + gpservice::hip_approval::resolve(approval_id, owner_uid)?; + let mut execution = stage_runner(RunnerReport::ApprovedRootScript { + approval_id: approval_id.clone(), + owner_uid, + })?; + execution.approval = Some((approval_id.clone(), owner_uid)); + Ok(execution) + } + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))] + { + let _ = (approval_id, desktop_uid); + bail!("Root HIP script approvals are unavailable on this platform") + } + } + } +} + +pub(crate) fn preview_runner(edited_report: Option>) -> anyhow::Result { + let report = if let Some(xml) = edited_report { + gphip::validate_edited_report(&xml)?; + RunnerReport::Edited { xml: xml.to_string() } + } else { + RunnerReport::Generated + }; + stage_runner(report) +} + +fn stage_runner(report: RunnerReport) -> anyhow::Result { + let source = packaged_runner()?; + let base = runner_state_base(); + fs::create_dir_all(base).context("Cannot create HIP runtime directory")?; + validate_root_owned_path(base, false)?; + fs::set_permissions(base, fs::Permissions::from_mode(0o700))?; + let state_dir = Builder::new().prefix("session-").tempdir_in(base)?; + fs::set_permissions(state_dir.path(), fs::Permissions::from_mode(0o700))?; + validate_root_owned_path(state_dir.path(), false)?; + + let runner = state_dir.path().join(RUNNER_NAME); + fs::copy(&source, &runner).context("Cannot stage HIP runner")?; + fs::set_permissions(&runner, fs::Permissions::from_mode(0o500))?; + validate_root_owned_path(&runner, true)?; + verify_staged_runner(&runner)?; + + let encoded_state = serde_json::to_vec(&report)?; + ensure!( + encoded_state.len() <= MAX_STATE_BYTES, + "HIP runner state exceeds its size limit" + ); + let state = state_dir.path().join(STATE_NAME); + let mut state_file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&state)?; + state_file.write_all(&encoded_state)?; + state_file.flush()?; + Ok(HipExecution::script(0, runner, Some(state_dir))) +} + +fn runner_state_base() -> &'static Path { + #[cfg(target_os = "macos")] + { + Path::new("/private/var/db/gpclient/hip") + } + #[cfg(target_os = "linux")] + { + Path::new("/var/lib/gpclient/hip") + } + #[cfg(any(target_os = "freebsd", target_os = "openbsd"))] + { + Path::new("/var/db/gpclient/hip") + } +} + +fn packaged_runner() -> anyhow::Result { + #[cfg(target_os = "macos")] + let path = std::env::current_exe() + .context("Cannot locate HIP runner")? + .with_file_name(RUNNER_NAME); + #[cfg(target_os = "linux")] + let path = PathBuf::from("/usr/libexec/gpclient/gp-hip-runner"); + #[cfg(any(target_os = "freebsd", target_os = "openbsd"))] + let path = PathBuf::from("/usr/local/libexec/gpclient/gp-hip-runner"); + + #[cfg(not(target_os = "macos"))] + validate_root_owned_path(&path, true)?; + #[cfg(target_os = "macos")] + verify_packaged_macos_runner(&path)?; + ensure!(path.is_file(), "Bundled HIP runner is missing"); + Ok(path) +} + +#[cfg(target_os = "macos")] +fn verify_packaged_macos_runner(path: &Path) -> anyhow::Result<()> { + use std::process::Command; + let service = std::env::current_exe()?; + let app = service + .parent() + .and_then(Path::parent) + .and_then(Path::parent) + .context("gpservice is not in an app bundle")?; + ensure!( + path.parent() == service.parent(), + "HIP runner is outside the app Helpers directory" + ); + let status = Command::new("/usr/bin/codesign") + .args(["--verify", "--deep", "--strict"]) + .arg(app) + .status()?; + ensure!(status.success(), "HIP application bundle signature is invalid"); + Ok(()) +} + +#[cfg(target_os = "macos")] +fn verify_staged_runner(path: &Path) -> anyhow::Result<()> { + use std::process::Command; + let status = Command::new("/usr/bin/codesign") + .args(["--verify", "--strict"]) + .arg(path) + .status()?; + ensure!(status.success(), "Staged HIP runner signature is invalid"); + let service = std::env::current_exe()?; + ensure!( + signing_team(path)? == signing_team(&service)?, + "HIP runner and service have different signing teams" + ); + + // The staged runner has no app Frameworks directory. Reject any library + // reference that could resolve through a writable bundle or search path. + let output = Command::new("/usr/bin/otool").arg("-L").arg(path).output()?; + ensure!(output.status.success(), "Cannot inspect HIP runner libraries"); + for library in String::from_utf8(output.stdout)? + .lines() + .skip(1) + .filter_map(|line| line.trim().split_whitespace().next()) + { + ensure!( + library.starts_with("/usr/lib/") || library.starts_with("/System/Library/"), + "HIP runner loads a library outside the trusted system paths" + ); + } + Ok(()) +} + +#[cfg(target_os = "macos")] +fn signing_team(path: &Path) -> anyhow::Result { + let output = std::process::Command::new("/usr/bin/codesign") + .args(["-d", "--verbose=4"]) + .arg(path) + .output()?; + ensure!(output.status.success(), "Cannot inspect code signature"); + let details = String::from_utf8(output.stderr)?; + details + .lines() + .find_map(|line| line.strip_prefix("TeamIdentifier=")) + .filter(|team| !team.is_empty() && *team != "not set") + .map(str::to_owned) + .context("Signed HIP binary has no team identifier") +} + +#[cfg(not(target_os = "macos"))] +fn verify_staged_runner(_path: &Path) -> anyhow::Result<()> { + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn disabled_has_no_script_on_both_gui_platforms() { + for brokered_macos in [false, true] { + let execution = resolve(&HipSource::Disabled, None, brokered_macos, None).unwrap(); + assert!(!execution.enabled); + assert!(execution.wrapper.is_none()); + } + } + + #[test] + fn custom_source_cannot_choose_root_or_run_on_macos() { + let source = HipSource::UserScript { + path: "/tmp/hip.sh".into(), + }; + assert!(resolve(&source, None, false, None).is_err()); + assert!(resolve(&source, Some(0), false, None).is_err()); + assert!(resolve(&source, Some(1000), true, None).is_err()); + #[cfg(target_os = "macos")] + assert!(resolve(&source, Some(1000), false, None).is_err()); + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + #[test] + fn root_source_requires_a_bound_user_and_installed_approval() { + let source = HipSource::ApprovedRootScript { + approval_id: "00000000-0000-4000-8000-000000000000".into(), + }; + assert!(resolve(&source, None, false, None).is_err()); + assert!(resolve(&source, Some(0), false, None).is_err()); + assert!(resolve(&source, Some(1000), false, None).is_err()); + } +} diff --git a/apps/gpservice/src/lib.rs b/apps/gpservice/src/lib.rs index da1ab0e..e04c42c 100644 --- a/apps/gpservice/src/lib.rs +++ b/apps/gpservice/src/lib.rs @@ -1,2 +1,5 @@ #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +pub mod hip_approval; +pub mod hip_runner_state; +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] pub mod vpnc_script; diff --git a/apps/gpservice/src/macos_broker.rs b/apps/gpservice/src/macos_broker.rs index b1917ef..c07c467 100644 --- a/apps/gpservice/src/macos_broker.rs +++ b/apps/gpservice/src/macos_broker.rs @@ -45,7 +45,7 @@ impl CredentialServer { } let registry = Arc::clone(&self.registry); tokio::spawn(async move { - if let Err(err) = credential_lease::serve(stream, registry).await { + if let Err(err) = credential_lease::serve(stream, registry, None).await { warn!("Broker credential lease ended: {err}"); } }); diff --git a/apps/gpservice/src/main.rs b/apps/gpservice/src/main.rs index 407ad13..3ada543 100644 --- a/apps/gpservice/src/main.rs +++ b/apps/gpservice/src/main.rs @@ -6,6 +6,8 @@ mod dev_bootstrap; #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", all(test, unix)))] mod device_anchor; mod handlers; +mod hip_preview; +mod hip_source; #[cfg(target_os = "macos")] mod macos_broker; mod request_dispatcher; diff --git a/apps/gpservice/src/request_dispatcher.rs b/apps/gpservice/src/request_dispatcher.rs index f4c1268..84273f0 100644 --- a/apps/gpservice/src/request_dispatcher.rs +++ b/apps/gpservice/src/request_dispatcher.rs @@ -51,7 +51,13 @@ impl RequestDispatcher { } } - pub fn dispatch_lifecycle(&self, request: WsRequest) -> Result { + pub fn dispatch_lifecycle( + &self, + request: WsRequest, + desktop_uid: Option, + edited_report: Option>, + session_id: Option, + ) -> Result { match request { WsRequest::Connect(request) => { if let Err(message) = self.validate_connect_paths(&request) { @@ -67,7 +73,11 @@ impl RequestDispatcher { "Request could not be accepted", )); } - Err(self.lifecycle.submit_connect(*request)) + Err( + self + .lifecycle + .submit_connect(*request, desktop_uid, edited_report, session_id), + ) } WsRequest::Disconnect(_) => Err(self.lifecycle.request_disconnect()), request => Ok(request), @@ -75,7 +85,7 @@ impl RequestDispatcher { } pub async fn dispatch(&self, request: WsRequest) -> ServiceResult { - let request = match self.dispatch_lifecycle(request) { + let request = match self.dispatch_lifecycle(request, None, None, None) { Ok(request) => request, Err(result) => return result, }; @@ -121,7 +131,15 @@ impl RequestDispatcher { } ServiceResult::Accepted } - WsRequest::Connect(_) | WsRequest::Disconnect(_) => unreachable!("lifecycle request was already dispatched"), + WsRequest::Connect(_) + | WsRequest::Disconnect(_) + | WsRequest::StoreEditedHipReportChunk(_) + | WsRequest::PreviewHipReport(_) + | WsRequest::GetHipApprovalStatus { .. } + | WsRequest::ReadHipPreviewChunk(_) + | WsRequest::GetLastSubmittedHipReport => { + unreachable!("session-bound request was already dispatched") + } } } @@ -130,12 +148,14 @@ impl RequestDispatcher { return Ok(()); }; let expected_script = scripts.join("vpnc-script").to_string_lossy().into_owned(); - let expected_wrapper = scripts.join("hipreport.sh").to_string_lossy().into_owned(); if request.args().vpnc_script().as_deref() != Some(expected_script.as_str()) { return Err("macOS VPN script must be the bundled script"); } - if request.args().csd_wrapper().as_deref() != Some(expected_wrapper.as_str()) { - return Err("macOS HIP wrapper must be the bundled wrapper"); + if matches!( + request.args().hip_source(), + gpapi::service::hip::HipSource::UserScript { .. } | gpapi::service::hip::HipSource::ApprovedRootScript { .. } + ) { + return Err("macOS does not support custom HIP scripts"); } if request.args().certificate().is_some() || request.args().sslkey().is_some() { return Err("macOS client identity must be provided as protected data, not root-readable paths"); @@ -408,7 +428,6 @@ mod tests { let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]); let request = ConnectRequest::new(info, "cookie".into()) .with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string())) - .with_csd_wrapper(Some("/app/Contents/Resources/Scripts/hipreport.sh".to_string())) .with_certificate(Some("/Users/example/client.pem".to_string())); let ServiceResult::Rejected(rejection) = dispatcher.dispatch(WsRequest::Connect(Box::new(request))).await else { panic!("brokered mode accepted a root-readable identity path"); @@ -428,16 +447,24 @@ mod tests { let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into()); let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]); let bundled = ConnectRequest::new(info.clone(), "cookie".into()) - .with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string())) - .with_csd_wrapper(Some("/app/Contents/Resources/Scripts/hipreport.sh".to_string())); + .with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string())); assert_eq!(dispatcher.validate_connect_paths(&bundled), Ok(())); - let old_layout = ConnectRequest::new(info, "cookie".into()) - .with_vpnc_script(Some("/app/Contents/Helpers/vpnc-script".to_string())) - .with_csd_wrapper(Some("/app/Contents/Helpers/hipreport.sh".to_string())); + let old_layout = ConnectRequest::new(info.clone(), "cookie".into()) + .with_vpnc_script(Some("/app/Contents/Helpers/vpnc-script".to_string())); assert_eq!( dispatcher.validate_connect_paths(&old_layout), Err("macOS VPN script must be the bundled script") ); + + let custom = ConnectRequest::new(info, "cookie".into()) + .with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string())) + .with_hip_source(gpapi::service::hip::HipSource::UserScript { + path: "/tmp/hip.sh".into(), + }); + assert_eq!( + dispatcher.validate_connect_paths(&custom), + Err("macOS does not support custom HIP scripts") + ); } } diff --git a/apps/gpservice/src/runtime_user/default.rs b/apps/gpservice/src/runtime_user/default.rs index 42e7133..55f1488 100644 --- a/apps/gpservice/src/runtime_user/default.rs +++ b/apps/gpservice/src/runtime_user/default.rs @@ -1,3 +1,3 @@ -pub(crate) fn trusted_csd_uid() -> anyhow::Result> { - Ok(None) +pub(crate) fn desktop_uid() -> Option { + None } diff --git a/apps/gpservice/src/runtime_user/mod.rs b/apps/gpservice/src/runtime_user/mod.rs index 177ba34..026de51 100644 --- a/apps/gpservice/src/runtime_user/mod.rs +++ b/apps/gpservice/src/runtime_user/mod.rs @@ -5,4 +5,4 @@ mod platform; #[path = "default.rs"] mod platform; -pub(crate) use platform::trusted_csd_uid; +pub(crate) use platform::desktop_uid; diff --git a/apps/gpservice/src/runtime_user/privileged_unix.rs b/apps/gpservice/src/runtime_user/privileged_unix.rs index bd78ab1..4a4f17e 100644 --- a/apps/gpservice/src/runtime_user/privileged_unix.rs +++ b/apps/gpservice/src/runtime_user/privileged_unix.rs @@ -1,7 +1,9 @@ -pub(crate) fn trusted_csd_uid() -> anyhow::Result> { - let uid = gpapi::process::users::get_non_root_user()?.uid(); - if uid == 0 { - anyhow::bail!("The HIP script user must not be root"); +pub(crate) fn desktop_uid() -> Option { + match gpapi::process::users::get_non_root_user() { + Ok(user) => Some(user.uid()), + Err(err) => { + log::warn!("No verified desktop user is available for custom HIP scripts: {err}"); + None + } } - Ok(Some(uid)) } diff --git a/apps/gpservice/src/session_registry.rs b/apps/gpservice/src/session_registry.rs index 75bea85..8bb7c8c 100644 --- a/apps/gpservice/src/session_registry.rs +++ b/apps/gpservice/src/session_registry.rs @@ -13,9 +13,11 @@ use crate::ws_connection::ConnectionControl; const ACTIVATION_TIMEOUT: Duration = Duration::from_secs(15); const MAX_PENDING_SESSIONS: usize = 16; +const HIP_PREVIEW_CHUNK_BYTES: usize = 16 * 1024; pub struct HandshakePermit { pub session_id: Uuid, + pub desktop_uid: Option, pub observed_generation: u64, pub secret: Zeroizing<[u8; 32]>, token: Uuid, @@ -38,6 +40,13 @@ pub enum SessionError { ReconnectSuperseded, #[error("session registry is unavailable")] Unavailable, + #[error("invalid HIP report upload")] + InvalidHipUpload, +} + +pub enum HipUploadResult { + Progress(Uuid), + Stored(Uuid), } enum SessionStatus { @@ -55,6 +64,11 @@ enum SessionStatus { struct SessionRecord { secret: Zeroizing<[u8; 32]>, product_version: String, + desktop_uid: Option, + edited_hip_report: Option<(Uuid, Arc)>, + edited_hip_upload: Option<(Uuid, String)>, + hip_preview: Option<(Uuid, Arc)>, + last_successful_hip_report: Option>, status: SessionStatus, } @@ -71,7 +85,7 @@ impl SessionRegistry { } } - pub fn issue(&self, product_version: &str) -> Result, SessionError> { + pub fn issue(&self, product_version: &str, desktop_uid: Option) -> Result, SessionError> { let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?; let now = Instant::now(); sessions.retain(|_, record| { @@ -108,6 +122,11 @@ impl SessionRegistry { SessionRecord { secret: Zeroizing::new(*credential.secret()), product_version: credential.product_version().to_owned(), + desktop_uid, + edited_hip_report: None, + edited_hip_upload: None, + hip_preview: None, + last_successful_hip_report: None, status: SessionStatus::Pending { activation_deadline: Instant::now() + ACTIVATION_TIMEOUT, handshake_token: None, @@ -186,6 +205,7 @@ impl SessionRegistry { let record = sessions.get(&session_id).ok_or(SessionError::Unauthorized)?; Ok(HandshakePermit { session_id, + desktop_uid: record.desktop_uid, observed_generation, secret: Zeroizing::new(*record.secret), token, @@ -278,6 +298,122 @@ impl SessionRegistry { ) } + pub fn append_edited_hip_report_chunk( + &self, + session_id: Uuid, + upload_id: Option, + offset: usize, + chunk: String, + complete: bool, + ) -> Result { + let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?; + let record = sessions.get_mut(&session_id).ok_or(SessionError::Unauthorized)?; + if !matches!(record.status, SessionStatus::Active { .. }) { + return Err(SessionError::Unauthorized); + } + if upload_id.is_none() { + if offset != 0 { + return Err(SessionError::InvalidHipUpload); + } + record.edited_hip_upload = Some((Uuid::new_v4(), String::new())); + } + let (current_id, xml) = record + .edited_hip_upload + .as_mut() + .ok_or(SessionError::InvalidHipUpload)?; + if upload_id.is_some_and(|id| id != *current_id) || offset != xml.len() || chunk.len() > 8 * 1024 { + return Err(SessionError::InvalidHipUpload); + } + if xml.len() + chunk.len() > gphip::MAX_EDITED_REPORT_BYTES { + record.edited_hip_upload = None; + return Err(SessionError::InvalidHipUpload); + } + xml.push_str(&chunk); + if !complete { + return Ok(HipUploadResult::Progress(*current_id)); + } + if gphip::validate_edited_report(xml).is_err() { + record.edited_hip_upload = None; + return Err(SessionError::InvalidHipUpload); + } + let (_, xml) = record.edited_hip_upload.take().ok_or(SessionError::InvalidHipUpload)?; + let report_id = Uuid::new_v4(); + record.edited_hip_report = Some((report_id, Arc::from(xml))); + Ok(HipUploadResult::Stored(report_id)) + } + + pub fn edited_hip_report(&self, session_id: Uuid, report_id: Uuid) -> Result, SessionError> { + let sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?; + let record = sessions.get(&session_id).ok_or(SessionError::Unauthorized)?; + record + .edited_hip_report + .as_ref() + .filter(|(id, _)| *id == report_id) + .map(|(_, xml)| Arc::clone(xml)) + .ok_or(SessionError::Unauthorized) + } + + pub fn store_hip_preview(&self, session_id: Uuid, xml: String) -> Result { + let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?; + let record = sessions.get_mut(&session_id).ok_or(SessionError::Unauthorized)?; + if !matches!(record.status, SessionStatus::Active { .. }) { + return Err(SessionError::Unauthorized); + } + let preview_id = Uuid::new_v4(); + record.hip_preview = Some((preview_id, Arc::from(xml))); + Ok(preview_id) + } + + pub fn hip_preview_chunk( + &self, + session_id: Uuid, + preview_id: Uuid, + offset: usize, + ) -> Result<(String, bool), SessionError> { + let sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?; + let record = sessions.get(&session_id).ok_or(SessionError::Unauthorized)?; + let (_, xml) = record + .hip_preview + .as_ref() + .filter(|(id, _)| *id == preview_id) + .ok_or(SessionError::Unauthorized)?; + if offset > xml.len() || !xml.is_char_boundary(offset) { + return Err(SessionError::Unauthorized); + } + let mut end = (offset + HIP_PREVIEW_CHUNK_BYTES).min(xml.len()); + while !xml.is_char_boundary(end) { + end -= 1; + } + Ok((xml[offset..end].to_owned(), end == xml.len())) + } + + pub fn store_successful_hip_report(&self, session_id: Uuid, xml: &str) -> Result<(), SessionError> { + if xml.len() > 1024 * 1024 { + return Err(SessionError::Unavailable); + } + let mut sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?; + let record = sessions.get_mut(&session_id).ok_or(SessionError::Unauthorized)?; + if !matches!(record.status, SessionStatus::Active { .. }) { + return Err(SessionError::Unauthorized); + } + record.last_successful_hip_report = Some(Arc::from(xml)); + Ok(()) + } + + pub fn last_successful_hip_report(&self, session_id: Uuid) -> Result>, SessionError> { + let sessions = self.sessions.lock().map_err(|_| SessionError::Unavailable)?; + let record = sessions.get(&session_id).ok_or(SessionError::Unauthorized)?; + Ok(record.last_successful_hip_report.as_ref().map(Arc::clone)) + } + + pub fn clear_successful_hip_report(&self, session_id: Uuid) { + if let Ok(mut sessions) = self.sessions.lock() + && let Some(record) = sessions.get_mut(&session_id) + { + record.last_successful_hip_report = None; + } + } + pub fn disconnect_if_current(&self, session_id: Uuid, generation: u64) { let Ok(mut sessions) = self.sessions.lock() else { return; @@ -332,10 +468,144 @@ mod tests { ConnectionControl::new(Uuid::new_v4(), tx).0 } + #[test] + fn credential_retains_verified_desktop_user_across_reconnect() { + let registry = Arc::new(SessionRegistry::new(Uuid::new_v4())); + let credential = registry.issue("2.6.4", Some(1000)).unwrap(); + let first = registry + .begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4") + .unwrap(); + assert_eq!(first.desktop_uid, Some(1000)); + registry.commit_attach(&first, control()).unwrap(); + + let reconnect = registry + .begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4") + .unwrap(); + assert_eq!(reconnect.desktop_uid, Some(1000)); + } + + #[test] + fn edited_hip_report_is_session_bound_and_replaced_without_affecting_pinned_content() { + fn upload(registry: &SessionRegistry, session_id: Uuid, xml: &str) -> Uuid { + let mut upload_id = None; + let mut offset = 0; + while offset < xml.len() { + let mut end = (offset + 8 * 1024).min(xml.len()); + while !xml.is_char_boundary(end) { + end -= 1; + } + let complete = end == xml.len(); + match registry + .append_edited_hip_report_chunk(session_id, upload_id, offset, xml[offset..end].into(), complete) + .unwrap() + { + HipUploadResult::Progress(id) => upload_id = Some(id), + HipUploadResult::Stored(id) => return id, + } + offset = end; + } + panic!("upload did not complete") + } + + let registry = Arc::new(SessionRegistry::new(Uuid::new_v4())); + let first_credential = registry.issue("2.6.4", Some(1000)).unwrap(); + let second_credential = registry.issue("2.6.4", Some(1001)).unwrap(); + for credential in [&first_credential, &second_credential] { + let permit = registry + .begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4") + .unwrap(); + registry.commit_attach(&permit, control()).unwrap(); + } + + let valid = gphip::generate_report(&gphip::ReportInput { + profile: gpapi::os_profile::OsProfile::builder(gpapi::os_profile::ClientOs::Linux).build(), + context: gphip::ReportContext::Preview, + }) + .unwrap(); + let first_id = upload(®istry, first_credential.session_id(), &valid); + let pinned = registry + .edited_hip_report(first_credential.session_id(), first_id) + .unwrap(); + assert!(matches!( + registry.edited_hip_report(second_credential.session_id(), first_id), + Err(SessionError::Unauthorized) + )); + let second_id = upload(®istry, first_credential.session_id(), &valid); + assert!(matches!( + registry.edited_hip_report(first_credential.session_id(), first_id), + Err(SessionError::Unauthorized) + )); + assert_eq!( + &*registry + .edited_hip_report(first_credential.session_id(), second_id) + .unwrap(), + valid + ); + assert_eq!(&*pinned, valid); + registry.revoke(first_credential.session_id()); + assert!(matches!( + registry.edited_hip_report(first_credential.session_id(), second_id), + Err(SessionError::Unauthorized) + )); + } + + #[test] + fn submitted_report_changes_only_after_success_callback_and_is_session_bound() { + let registry = Arc::new(SessionRegistry::new(Uuid::new_v4())); + let credential = registry.issue("2.6.4", Some(1000)).unwrap(); + let permit = registry + .begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4") + .unwrap(); + registry.commit_attach(&permit, control()).unwrap(); + assert!( + registry + .last_successful_hip_report(credential.session_id()) + .unwrap() + .is_none() + ); + registry + .store_successful_hip_report(credential.session_id(), "first") + .unwrap(); + assert_eq!( + registry + .last_successful_hip_report(credential.session_id()) + .unwrap() + .as_deref(), + Some("first") + ); + let preview_id = registry + .store_hip_preview(credential.session_id(), "é".repeat(8193)) + .unwrap(); + let (first_chunk, complete) = registry + .hip_preview_chunk(credential.session_id(), preview_id, 0) + .unwrap(); + assert!(!complete); + assert!(first_chunk.len() <= HIP_PREVIEW_CHUNK_BYTES); + assert!( + registry + .hip_preview_chunk(credential.session_id(), preview_id, 1) + .is_err() + ); + assert_eq!( + registry + .last_successful_hip_report(credential.session_id()) + .unwrap() + .as_deref(), + Some("first") + ); + registry.clear_successful_hip_report(credential.session_id()); + assert!( + registry + .last_successful_hip_report(credential.session_id()) + .unwrap() + .is_none() + ); + } + #[test] fn reconnect_uses_generation_compare_and_swap() { let registry = Arc::new(SessionRegistry::new(Uuid::new_v4())); - let credential = registry.issue("2.6.4").unwrap(); + let credential = registry.issue("2.6.4", None).unwrap(); let first = registry .begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4") .unwrap(); @@ -356,7 +626,7 @@ mod tests { #[test] fn failed_initial_handshake_only_revokes_its_own_reservation() { let registry = Arc::new(SessionRegistry::new(Uuid::new_v4())); - let credential = registry.issue("2.6.4").unwrap(); + let credential = registry.issue("2.6.4", None).unwrap(); let first = registry .begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4") .unwrap(); @@ -370,7 +640,7 @@ mod tests { #[test] fn failed_reconnect_keeps_active_connection_authoritative() { let registry = Arc::new(SessionRegistry::new(Uuid::new_v4())); - let credential = registry.issue("2.6.4").unwrap(); + let credential = registry.issue("2.6.4", None).unwrap(); let first = registry .begin_handshake(credential.service_instance_id(), credential.session_id(), "2.6.4") .unwrap(); diff --git a/apps/gpservice/src/vpn_task.rs b/apps/gpservice/src/vpn_task.rs index 6a69703..30c28f8 100644 --- a/apps/gpservice/src/vpn_task.rs +++ b/apps/gpservice/src/vpn_task.rs @@ -20,6 +20,7 @@ use log::{info, warn}; use openconnect::{Vpn, VpnSessionInfo}; use tokio::sync::{Notify, mpsc, watch}; use tokio_util::sync::CancellationToken; +use uuid::Uuid; use zeroize::Zeroizing; #[derive(Clone)] @@ -29,7 +30,13 @@ pub(crate) struct LifecycleHandle { } impl LifecycleHandle { - pub fn submit_connect(&self, request: ConnectRequest) -> ServiceResult { + pub fn submit_connect( + &self, + request: ConnectRequest, + desktop_uid: Option, + edited_report: Option>, + session_id: Option, + ) -> ServiceResult { let attempt = { let mut admissions = self.admissions.lock().expect("VPN lifecycle admissions mutex poisoned"); if admissions.current.is_some() { @@ -46,7 +53,13 @@ impl LifecycleHandle { attempt }; - match self.events.try_send(LifecycleEvent::Start { attempt, request }) { + match self.events.try_send(LifecycleEvent::Start { + attempt, + request, + desktop_uid, + edited_report, + session_id, + }) { Ok(()) => ServiceResult::Accepted, Err(mpsc::error::TrySendError::Full(_)) => { self.clear_attempt(attempt); @@ -169,7 +182,8 @@ impl LifecycleHandle { #[cfg(test)] pub(crate) fn for_tests() -> Self { let (vpn_state_tx, _vpn_state_rx) = watch::channel(VpnState::Disconnected); - let (_task, lifecycle) = VpnTask::new(vpn_state_tx, false, None); + let registry = Arc::new(crate::session_registry::SessionRegistry::new(Uuid::new_v4())); + let (_task, lifecycle) = VpnTask::new(vpn_state_tx, false, registry); lifecycle } } @@ -202,18 +216,33 @@ enum AdmissionPhase { } enum LifecycleEvent { - Start { attempt: u64, request: ConnectRequest }, - Stop { attempt: u64 }, - Established { attempt: u64, session: VpnSessionInfo }, - Ended { attempt: u64 }, + Start { + attempt: u64, + request: ConnectRequest, + desktop_uid: Option, + edited_report: Option>, + session_id: Option, + }, + Stop { + attempt: u64, + }, + Established { + attempt: u64, + session: VpnSessionInfo, + }, + Ended { + attempt: u64, + }, } struct ActiveAttempt { attempt: u64, + session_id: Option, vpn: Arc, info: ConnectInfo, allow_extend_session: bool, _identity_files: Vec, + _hip_execution: crate::hip_source::HipExecution, } pub(crate) struct VpnTask { @@ -221,7 +250,7 @@ pub(crate) struct VpnTask { lifecycle: LifecycleHandle, vpn_state_tx: watch::Sender, brokered_macos: bool, - trusted_csd_uid: Option, + registry: Arc, active: Option, cancel_token: CancellationToken, } @@ -230,7 +259,7 @@ impl VpnTask { pub fn new( vpn_state_tx: watch::Sender, brokered_macos: bool, - trusted_csd_uid: Option, + registry: Arc, ) -> (Self, LifecycleHandle) { let (events_tx, events) = mpsc::channel(4); let lifecycle = LifecycleHandle { @@ -242,7 +271,7 @@ impl VpnTask { lifecycle: lifecycle.clone(), vpn_state_tx, brokered_macos, - trusted_csd_uid, + registry, active: None, cancel_token: CancellationToken::new(), }; @@ -256,6 +285,7 @@ impl VpnTask { pub async fn start(&mut self, server_cancel_token: CancellationToken) { let cancel_token = self.cancel_token.clone(); let mut shutting_down = false; + let mut approval_poll = tokio::time::interval(std::time::Duration::from_secs(1)); loop { if shutting_down { @@ -277,6 +307,14 @@ impl VpnTask { shutting_down = true; self.lifecycle.request_disconnect(); } + _ = approval_poll.tick() => { + if self.active.as_ref().is_some_and(|active| { + active._hip_execution.approval_id().is_some() && !active._hip_execution.approval_is_valid() + }) { + warn!("Active HIP script approval is no longer valid; disconnecting VPN"); + self.lifecycle.request_disconnect(); + } + } } } @@ -296,14 +334,27 @@ impl VpnTask { fn handle_event(&mut self, event: LifecycleEvent) { match event { - LifecycleEvent::Start { attempt, request } => self.start_attempt(attempt, request), + LifecycleEvent::Start { + attempt, + request, + desktop_uid, + edited_report, + session_id, + } => self.start_attempt(attempt, request, desktop_uid, edited_report, session_id), LifecycleEvent::Stop { attempt } => self.stop_attempt(attempt), LifecycleEvent::Established { attempt, session } => self.establish_attempt(attempt, session), LifecycleEvent::Ended { attempt } => self.end_attempt(attempt), } } - fn start_attempt(&mut self, attempt: u64, request: ConnectRequest) { + fn start_attempt( + &mut self, + attempt: u64, + request: ConnectRequest, + desktop_uid: Option, + edited_report: Option>, + session_id: Option, + ) { if !self.lifecycle.activate_attempt(attempt) { self.finish_attempt(attempt); return; @@ -328,8 +379,8 @@ impl VpnTask { return; } }; - let csd_uid = match resolve_csd_uid(self.trusted_csd_uid, args.csd_uid(), args.hip()) { - Ok(uid) => uid, + let hip = match crate::hip_source::resolve(args.hip_source(), desktop_uid, self.brokered_macos, edited_report) { + Ok(execution) => execution, Err(err) => { warn!("Failed to select the HIP script user: {err}"); self.finish_attempt(attempt); @@ -345,9 +396,9 @@ impl VpnTask { .certificate(identity.certificate.clone()) .sslkey(identity.sslkey.clone()) .key_password(args.key_password()) - .hip(args.hip()) - .csd_uid(csd_uid) - .csd_wrapper(args.csd_wrapper()) + .hip(hip.enabled) + .csd_uid(hip.uid) + .csd_wrapper(hip.wrapper.clone()) .reconnect_timeout(args.reconnect_timeout()) .mtu(args.mtu()) .disable_ipv6(args.disable_ipv6()) @@ -365,6 +416,15 @@ impl VpnTask { } }; + if let Some(session_id) = session_id { + let registry = Arc::clone(&self.registry); + vpn.set_hip_report_callback(move |xml| { + if let Err(error) = registry.store_successful_hip_report(session_id, xml) { + warn!("Could not retain the submitted HIP report: {error}"); + } + }); + } + if self.lifecycle.is_stop_requested(attempt) { self.finish_attempt(attempt); return; @@ -385,10 +445,12 @@ impl VpnTask { } else { self.active = Some(ActiveAttempt { attempt, + session_id, vpn: Arc::clone(&vpn), info: info.clone(), allow_extend_session, _identity_files: identity.files, + _hip_execution: hip, }); self.send_state(VpnState::Connecting(Box::new(info))); thread::spawn(move || { @@ -460,6 +522,9 @@ impl VpnTask { if self.active.as_ref().is_none_or(|active| active.attempt != attempt) { return; } + if let Some(session_id) = self.active.as_ref().and_then(|active| active.session_id) { + self.registry.clear_successful_hip_report(session_id); + } self.active = None; self.finish_attempt(attempt); } @@ -474,14 +539,6 @@ impl VpnTask { } } -fn resolve_csd_uid(trusted_uid: Option, requested_uid: u32, hip_enabled: bool) -> anyhow::Result { - let uid = trusted_uid.unwrap_or(requested_uid); - if hip_enabled && uid == 0 { - anyhow::bail!("HIP scripts must not run as root"); - } - Ok(uid) -} - struct PreparedIdentity { certificate: Option, sslkey: Option, @@ -534,11 +591,16 @@ fn write_identity_file( #[cfg(test)] mod tests { use super::*; + use crate::session_registry::SessionRegistry; + + fn registry() -> Arc { + Arc::new(SessionRegistry::new(Uuid::new_v4())) + } #[test] fn disconnect_before_start_discards_the_pending_attempt() { let (vpn_state_tx, _vpn_state_rx) = watch::channel(VpnState::Disconnected); - let (mut task, lifecycle) = VpnTask::new(vpn_state_tx, false, None); + let (mut task, lifecycle) = VpnTask::new(vpn_state_tx, false, registry()); let request = ConnectRequest::new( ConnectInfo::new( "portal.example.com".to_string(), @@ -548,7 +610,10 @@ mod tests { "cookie".to_string(), ); - assert!(matches!(lifecycle.submit_connect(request), ServiceResult::Accepted)); + assert!(matches!( + lifecycle.submit_connect(request, None, None, None), + ServiceResult::Accepted + )); assert!(matches!(lifecycle.request_disconnect(), ServiceResult::Accepted)); let start = task.events.try_recv().unwrap(); task.handle_event(start); @@ -561,7 +626,7 @@ mod tests { fn late_established_event_is_ignored_after_disconnect_is_accepted() { let (vpn_state_tx, vpn_state_rx) = watch::channel(VpnState::Disconnected); let state_rx = vpn_state_rx.clone(); - let (task, lifecycle) = VpnTask::new(vpn_state_tx, false, None); + let (task, lifecycle) = VpnTask::new(vpn_state_tx, false, registry()); let info = ConnectInfo::new( "portal.example.com".to_string(), gpapi::gateway::Gateway::new("vpn".to_string(), "vpn.example.com".to_string()), @@ -569,7 +634,10 @@ mod tests { ); let request = ConnectRequest::new(info.clone(), "cookie".to_string()); - assert!(matches!(lifecycle.submit_connect(request), ServiceResult::Accepted)); + assert!(matches!( + lifecycle.submit_connect(request, None, None, None), + ServiceResult::Accepted + )); assert!(lifecycle.activate_attempt(0)); assert!(matches!(lifecycle.request_disconnect(), ServiceResult::Accepted)); task.publish_connected(0, info, SessionInfo::default()); @@ -580,7 +648,7 @@ mod tests { #[tokio::test] async fn disconnect_waiter_completes_for_its_attempt_before_a_later_connect() { let (vpn_state_tx, _vpn_state_rx) = watch::channel(VpnState::Disconnected); - let (task, lifecycle) = VpnTask::new(vpn_state_tx, false, None); + let (task, lifecycle) = VpnTask::new(vpn_state_tx, false, registry()); let request = || { ConnectRequest::new( ConnectInfo::new( @@ -592,7 +660,10 @@ mod tests { ) }; - assert!(matches!(lifecycle.submit_connect(request()), ServiceResult::Accepted)); + assert!(matches!( + lifecycle.submit_connect(request(), None, None, None), + ServiceResult::Accepted + )); let waiter_lifecycle = lifecycle.clone(); let waiter = tokio::spawn(async move { waiter_lifecycle.disconnect_and_wait().await }); while !lifecycle.is_stop_requested(0) { @@ -600,7 +671,10 @@ mod tests { } task.finish_attempt(0); - assert!(matches!(lifecycle.submit_connect(request()), ServiceResult::Accepted)); + assert!(matches!( + lifecycle.submit_connect(request(), None, None, None), + ServiceResult::Accepted + )); assert!( tokio::time::timeout(std::time::Duration::from_secs(1), waiter) .await @@ -612,7 +686,7 @@ mod tests { #[test] fn repeated_disconnects_enqueue_one_stop_for_an_attempt() { let (vpn_state_tx, _vpn_state_rx) = watch::channel(VpnState::Disconnected); - let (mut task, lifecycle) = VpnTask::new(vpn_state_tx, false, None); + let (mut task, lifecycle) = VpnTask::new(vpn_state_tx, false, registry()); let request = ConnectRequest::new( ConnectInfo::new( "portal.example.com".to_string(), @@ -622,7 +696,10 @@ mod tests { "cookie".to_string(), ); - assert!(matches!(lifecycle.submit_connect(request), ServiceResult::Accepted)); + assert!(matches!( + lifecycle.submit_connect(request, None, None, None), + ServiceResult::Accepted + )); assert!(matches!(lifecycle.request_disconnect(), ServiceResult::Accepted)); assert!(matches!(lifecycle.request_disconnect(), ServiceResult::Accepted)); assert!(matches!(task.events.try_recv(), Ok(LifecycleEvent::Start { .. }))); @@ -633,7 +710,7 @@ mod tests { #[test] fn second_connect_is_rejected_while_an_attempt_is_admitted() { let (vpn_state_tx, _vpn_state_rx) = watch::channel(VpnState::Disconnected); - let (_task, lifecycle) = VpnTask::new(vpn_state_tx, false, None); + let (_task, lifecycle) = VpnTask::new(vpn_state_tx, false, registry()); let request = || { ConnectRequest::new( ConnectInfo::new( @@ -645,24 +722,16 @@ mod tests { ) }; - assert!(matches!(lifecycle.submit_connect(request()), ServiceResult::Accepted)); assert!(matches!( - lifecycle.submit_connect(request()), + lifecycle.submit_connect(request(), None, None, None), + ServiceResult::Accepted + )); + assert!(matches!( + lifecycle.submit_connect(request(), None, None, None), ServiceResult::Rejected(rejection) if rejection.code() == ServiceErrorCode::Busy )); } - #[test] - fn trusted_csd_uid_overrides_request_uid() { - assert_eq!(resolve_csd_uid(Some(1000), 0, true).unwrap(), 1000); - } - - #[test] - fn root_csd_uid_is_rejected_when_hip_is_enabled() { - assert!(resolve_csd_uid(None, 0, true).is_err()); - assert_eq!(resolve_csd_uid(None, 0, false).unwrap(), 0); - } - #[test] fn maps_openconnect_session_metadata_to_service_session_info() { let info = SessionInfo::from_vpn_session_fields( diff --git a/apps/gpservice/src/ws_connection.rs b/apps/gpservice/src/ws_connection.rs index a679134..e2563b3 100644 --- a/apps/gpservice/src/ws_connection.rs +++ b/apps/gpservice/src/ws_connection.rs @@ -4,8 +4,9 @@ use axum::extract::ws::{CloseFrame, Message, Utf8Bytes, WebSocket}; use futures::StreamExt; use gpapi::service::transport::{ ClientMessage, ClientPrelude, CloseReason, HandshakeRejection, NoiseResponder, NoiseTransport, ServerMessage, - ServerPrelude, ServiceResult, + ServerPrelude, ServiceErrorCode, ServiceResult, }; +use gpapi::service::{hip::HipSource, request::WsRequest}; use log::{info, warn}; use tokio::sync::{mpsc, watch}; use tokio::time::Instant; @@ -148,6 +149,7 @@ impl WsConnection { &ctx, &control, permit.session_id, + permit.desktop_uid, generation, &mut pending_requests, ).await.is_err() { @@ -215,6 +217,17 @@ async fn establish( .await?; return Err(CloseReason::VersionMismatch); } + if prelude.hip_protocol_version != gpapi::service::transport::HIP_PROTOCOL_VERSION { + send_server_prelude( + socket, + ServerPrelude::Rejected(HandshakeRejection::HipProtocolMismatch { + client: prelude.hip_protocol_version, + service: gpapi::service::transport::HIP_PROTOCOL_VERSION, + }), + ) + .await?; + return Err(CloseReason::VersionMismatch); + } let permit = match ctx.registry().begin_handshake( prelude.service_instance_id, @@ -308,6 +321,7 @@ async fn handle_client_message( ctx: &Arc, control: &ConnectionControl, session_id: Uuid, + desktop_uid: Option, generation: u64, pending_requests: &mut HashSet, ) -> Result<(), ()> { @@ -323,8 +337,192 @@ async fn handle_client_message( return Err(()); } + if let WsRequest::StoreEditedHipReportChunk(report) = request { + let upload_id = report.upload_id.as_deref().and_then(|id| Uuid::parse_str(id).ok()); + let result = if report.upload_id.is_some() && upload_id.is_none() { + ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP upload ID") + } else { + match ctx.registry().append_edited_hip_report_chunk( + session_id, + upload_id, + report.offset, + report.xml, + report.complete, + ) { + Ok(crate::session_registry::HipUploadResult::Progress(upload_id)) => ServiceResult::HipUploadProgress { + upload_id: upload_id.to_string(), + }, + Ok(crate::session_registry::HipUploadResult::Stored(report_id)) => ServiceResult::StoredHipReport { + report_id: report_id.to_string(), + }, + Err(_) => ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP report upload"), + } + }; + if control.send(ConnectionCommand::Reply { id, result }).is_err() { + pending_requests.remove(&id); + control.close(CloseReason::InternalError); + } + return Ok(()); + } + + if let WsRequest::ReadHipPreviewChunk(chunk) = request { + let result = Uuid::parse_str(&chunk.preview_id) + .ok() + .and_then(|preview_id| { + ctx + .registry() + .hip_preview_chunk(session_id, preview_id, chunk.offset) + .ok() + .map(|(xml, complete)| ServiceResult::HipPreviewChunk { + preview_id: preview_id.to_string(), + offset: chunk.offset, + xml, + complete, + }) + }) + .unwrap_or_else(|| ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "HIP preview is unavailable")); + control.send(ConnectionCommand::Reply { id, result }).map_err(|_| ())?; + return Ok(()); + } + + if let WsRequest::GetLastSubmittedHipReport = request { + let result = match ctx.registry().last_successful_hip_report(session_id) { + Ok(Some(report)) => match ctx.registry().store_hip_preview(session_id, report.to_string()) { + Ok(preview_id) => match ctx.registry().hip_preview_chunk(session_id, preview_id, 0) { + Ok((xml, complete)) => ServiceResult::HipPreviewChunk { + preview_id: preview_id.to_string(), + offset: 0, + xml, + complete, + }, + Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "Submitted HIP report is unavailable"), + }, + Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "Submitted HIP report is unavailable"), + }, + Ok(None) => ServiceResult::NoSubmittedHipReport, + Err(_) => ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Session is unavailable"), + }; + control.send(ConnectionCommand::Reply { id, result }).map_err(|_| ())?; + return Ok(()); + } + + if let WsRequest::GetHipApprovalStatus { approval_id } = request { + let result = if let Some(uid) = desktop_uid.filter(|uid| *uid != 0) { + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] + { + match gpservice::hip_approval::status(&approval_id, uid) { + Ok(status) => ServiceResult::HipApprovalStatus(status), + Err(_) => ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP approval ID"), + } + } + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))] + { + let _ = (uid, approval_id); + ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "HIP script approvals are unavailable") + } + } else { + ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Desktop user is unavailable") + }; + control.send(ConnectionCommand::Reply { id, result }).map_err(|_| ())?; + return Ok(()); + } + + if let WsRequest::PreviewHipReport(preview) = request { + let edited_report = if let HipSource::Edited { report_id } = &preview.source { + let report_id = match Uuid::parse_str(report_id) { + Ok(id) => id, + Err(_) => { + control + .send(ConnectionCommand::Reply { + id, + result: ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP report ID"), + }) + .map_err(|_| ())?; + return Ok(()); + } + }; + match ctx.registry().edited_hip_report(session_id, report_id) { + Ok(report) => Some(report), + Err(_) => { + control + .send(ConnectionCommand::Reply { + id, + result: ServiceResult::rejected( + ServiceErrorCode::InvalidRequest, + "HIP report is unavailable for this session", + ), + }) + .map_err(|_| ())?; + return Ok(()); + } + } + } else { + None + }; + let registry = Arc::clone(ctx.registry()); + let control = control.clone(); + tokio::spawn(async move { + let result = match crate::hip_preview::generate(preview, edited_report, desktop_uid).await { + Ok(xml) => match registry.store_hip_preview(session_id, xml) { + Ok(preview_id) => match registry.hip_preview_chunk(session_id, preview_id, 0) { + Ok((xml, complete)) => ServiceResult::HipPreviewChunk { + preview_id: preview_id.to_string(), + offset: 0, + xml, + complete, + }, + Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"), + }, + Err(_) => ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview is unavailable"), + }, + Err(error) => { + warn!("HIP preview failed: {error:#}"); + ServiceResult::rejected(ServiceErrorCode::Internal, "HIP preview failed") + } + }; + control.send_reply(id, result).await; + }); + return Ok(()); + } + + let edited_report = if let WsRequest::Connect(connect) = &request { + if let HipSource::Edited { report_id } = connect.args().hip_source() { + let report_id = match Uuid::parse_str(report_id) { + Ok(id) => id, + Err(_) => { + control + .send(ConnectionCommand::Reply { + id, + result: ServiceResult::rejected(ServiceErrorCode::InvalidRequest, "Invalid HIP report ID"), + }) + .map_err(|_| ())?; + return Ok(()); + } + }; + match ctx.registry().edited_hip_report(session_id, report_id) { + Ok(report) => Some(report), + Err(_) => { + control + .send(ConnectionCommand::Reply { + id, + result: ServiceResult::rejected( + ServiceErrorCode::InvalidRequest, + "HIP report is unavailable for this session", + ), + }) + .map_err(|_| ())?; + return Ok(()); + } + } + } else { + None + } + } else { + None + }; + let dispatcher = ctx.dispatcher(); - let request = match dispatcher.dispatch_lifecycle(request) { + let request = match dispatcher.dispatch_lifecycle(request, desktop_uid, edited_report, Some(session_id)) { Ok(request) => request, Err(result) => { if control.send(ConnectionCommand::Reply { id, result }).is_err() { @@ -417,7 +615,7 @@ mod tests { #[tokio::test] async fn authenticates_attaches_and_replies_to_a_request() { let registry = Arc::new(SessionRegistry::new(Uuid::new_v4())); - let credential = registry.issue(env!("CARGO_PKG_VERSION")).unwrap(); + let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap(); let dispatcher = Arc::new(RequestDispatcher::new( crate::vpn_task::LifecycleHandle::for_tests(), Arc::new(AtomicBool::new(false)), @@ -441,6 +639,7 @@ mod tests { let (mut socket, _) = connect_async(format!("ws://{address}/ws")).await.unwrap(); let prelude = ClientPrelude { product_version: env!("CARGO_PKG_VERSION").to_owned(), + hip_protocol_version: gpapi::service::transport::HIP_PROTOCOL_VERSION, service_instance_id: credential.service_instance_id(), session_id: credential.session_id(), }; diff --git a/apps/gpservice/src/ws_server.rs b/apps/gpservice/src/ws_server.rs index c32ed8c..9055264 100644 --- a/apps/gpservice/src/ws_server.rs +++ b/apps/gpservice/src/ws_server.rs @@ -12,7 +12,7 @@ use gpapi::{ utils::lock_file::LockFile, }; use log::{info, warn}; -use openconnect::{find_csd_wrapper, find_vpnc_script}; +use openconnect::find_vpnc_script; use tokio::{ net::TcpListener, sync::{Mutex, Semaphore, mpsc, oneshot, watch}, @@ -259,7 +259,6 @@ fn build_snapshot(vpn_state: VpnState) -> VpnEnv { VpnEnv { vpn_state, vpnc_script: find_vpnc_script().map(ToOwned::to_owned), - csd_wrapper: find_csd_wrapper().map(ToOwned::to_owned), auth_executable: binary_paths::gpauth().to_string_lossy().into_owned(), host_info: HostInfo { host_identity: HostIdentity::collect(), @@ -282,7 +281,7 @@ mod tests { #[tokio::test] async fn resync_snapshot_is_ordered_with_state_events() { let registry = Arc::new(SessionRegistry::new(Uuid::new_v4())); - let credential = registry.issue(env!("CARGO_PKG_VERSION")).unwrap(); + let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap(); let permit = registry .begin_handshake( credential.service_instance_id(), @@ -339,7 +338,7 @@ mod tests { #[tokio::test] async fn removed_prepared_candidate_cannot_commit_takeover() { let registry = Arc::new(SessionRegistry::new(Uuid::new_v4())); - let credential = registry.issue(env!("CARGO_PKG_VERSION")).unwrap(); + let credential = registry.issue(env!("CARGO_PKG_VERSION"), None).unwrap(); let dispatcher = Arc::new(RequestDispatcher::new( crate::vpn_task::LifecycleHandle::for_tests(), Arc::new(AtomicBool::new(false)), diff --git a/crates/common/src/binary_paths.rs b/crates/common/src/binary_paths.rs index 0611c50..94eb15a 100644 --- a/crates/common/src/binary_paths.rs +++ b/crates/common/src/binary_paths.rs @@ -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) } diff --git a/crates/common/src/constants.rs b/crates/common/src/constants.rs index 3046802..7f00c52 100644 --- a/crates/common/src/constants.rs +++ b/crates/common/src/constants.rs @@ -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"))] diff --git a/crates/gpapi/src/process/hip_launcher.rs b/crates/gpapi/src/process/hip_launcher.rs deleted file mode 100644 index 42f6336..0000000 --- a/crates/gpapi/src/process/hip_launcher.rs +++ /dev/null @@ -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 { - 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"); - } - } -} diff --git a/crates/gpapi/src/process/mod.rs b/crates/gpapi/src/process/mod.rs index 502b2f9..e45e056 100644 --- a/crates/gpapi/src/process/mod.rs +++ b/crates/gpapi/src/process/mod.rs @@ -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; diff --git a/crates/gpapi/src/service/hip.rs b/crates/gpapi/src/service/hip.rs new file mode 100644 index 0000000..58e00d4 --- /dev/null +++ b/crates/gpapi/src/service/hip.rs @@ -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::(json).unwrap(), source); + } +} diff --git a/crates/gpapi/src/service/mod.rs b/crates/gpapi/src/service/mod.rs index e5e88df..7f33a4c 100644 --- a/crates/gpapi/src/service/mod.rs +++ b/crates/gpapi/src/service/mod.rs @@ -1,4 +1,5 @@ pub mod event; +pub mod hip; pub mod request; pub mod transport; pub mod vpn_env; diff --git a/crates/gpapi/src/service/request.rs b/crates/gpapi/src/service/request.rs index 4f3d9f1..763f35a 100644 --- a/crates/gpapi/src/service/request.rs +++ b/crates/gpapi/src/service/request.rs @@ -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, + 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, +} + +#[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, key_password: Option, - hip: bool, - csd_uid: u32, - csd_wrapper: Option, + 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 { - 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>>(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), Disconnect(DisconnectRequest), + StoreEditedHipReportChunk(StoreEditedHipReportChunkRequest), + PreviewHipReport(PreviewHipReportRequest), + GetHipApprovalStatus { approval_id: String }, + ReadHipPreviewChunk(ReadHipPreviewChunkRequest), + GetLastSubmittedHipReport, UpdateLogLevel(UpdateLogLevelRequest), RestartGui, UpdateGui(UpdateGuiRequest), diff --git a/crates/gpapi/src/service/transport/error.rs b/crates/gpapi/src/service/transport/error.rs index 801d304..3bfd087 100644 --- a/crates/gpapi/src/service/transport/error.rs +++ b/crates/gpapi/src/service/transport/error.rs @@ -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, diff --git a/crates/gpapi/src/service/transport/handshake.rs b/crates/gpapi/src/service/transport/handshake.rs index 78d3a91..40dc9ba 100644 --- a/crates/gpapi/src/service/transport/handshake.rs +++ b/crates/gpapi/src/service/transport/handshake.rs @@ -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, } diff --git a/crates/gpapi/src/service/transport/message.rs b/crates/gpapi/src/service/transport/message.rs index 8efdbba..0c1092b 100644 --- a/crates/gpapi/src/service/transport/message.rs +++ b/crates/gpapi/src/service/transport/message.rs @@ -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), Rejected(ServiceRejection), } diff --git a/crates/gpapi/src/service/transport/mod.rs b/crates/gpapi/src/service/transport/mod.rs index 741448e..df7e00d 100644 --- a/crates/gpapi/src/service/transport/mod.rs +++ b/crates/gpapi/src/service/transport/mod.rs @@ -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; diff --git a/crates/gpapi/src/service/vpn_env.rs b/crates/gpapi/src/service/vpn_env.rs index 062f00c..56a14eb 100644 --- a/crates/gpapi/src/service/vpn_env.rs +++ b/crates/gpapi/src/service/vpn_env.rs @@ -24,9 +24,6 @@ pub struct VpnEnv { /// The default VPN script path pub vpnc_script: Option, - /// The default CSD wrapper script path - pub csd_wrapper: Option, - /// The gpauth executable path /// Used by the client to launch gpauth for authentication pub auth_executable: String, diff --git a/crates/gphip/Cargo.toml b/crates/gphip/Cargo.toml new file mode 100644 index 0000000..e83c07a --- /dev/null +++ b/crates/gphip/Cargo.toml @@ -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 diff --git a/crates/gphip/src/lib.rs b/crates/gphip/src/lib.rs new file mode 100644 index 0000000..79dae6f --- /dev/null +++ b/crates/gphip/src/lib.rs @@ -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 { + ensure!(xml.len() <= MAX_EDITED_REPORT_BYTES, "HIP report exceeds 48 KiB"); + let lower = xml.to_ascii_lowercase(); + ensure!( + !lower.contains("")) { + 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 "); + 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 { + 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, ¤t, field)?; + } + + let edited_host = host_info_mut(&mut edited)?; + let current_host = host_info(¤t)?; + 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 "))? + .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, + client_ipv6: Option, + 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 { + let cookie_params: HashMap = 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, + 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, + defender: Option, + clamav: Option, + ufw: Option, +} + +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, + ipv4: Option, + ipv6: Option, +} + +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) -> Self { + self.mac_address = mac; + self + } + + /// Set IPv4 address + fn with_ipv4(mut self, ipv4: Option) -> Self { + self.ipv4 = ipv4; + self + } + + /// Set IPv6 address + fn with_ipv6(mut self, ipv6: Option) -> 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, +} + +impl<'p, 'a> HostInfoCollector<'p, 'a> { + fn new(profile: &'p OsProfile, input: &'a ReportInput, cookie_params: &'a HashMap) -> 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 { + 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 { + match self.profile.client_os() { + ClientOs::Linux => detect_microsoft_defender_blocking(), + ClientOs::Mac | ClientOs::Windows => None, + } + } + + fn clamav_for_profile(&self) -> Option { + match self.profile.client_os() { + ClientOs::Linux => detect_clamav(), + ClientOs::Mac | ClientOs::Windows => None, + } + } + + fn ufw_for_profile(&self) -> Option { + match self.profile.client_os() { + ClientOs::Linux => detect_ufw(), + ClientOs::Mac | ClientOs::Windows => None, + } + } +} + +fn detect_clamav() -> Option { + 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 { + 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)> { + 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 { + 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 { + 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 { + 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 { + 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) -> Option { + 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 { + let xml = Element::parse(xml_str.as_bytes())?; + + write_xml(&xml) +} + +fn write_xml(xml: &Element) -> anyhow::Result { + 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 = 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 = 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 = 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 = 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 = 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("").is_err()); + assert!(validate_edited_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("", "")).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#""#.as_bytes(), + ) + .unwrap(); + saved_host.get_mut_child("network-interface").unwrap().children = nested.children; + let custom_category = Element::parse( + r#""#.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(¤t, field).unwrap().get_text() + ); + } + let refreshed_host = host_info(&refreshed).unwrap(); + let current_host = host_info(¤t).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)) + ); + } +} diff --git a/apps/gpclient/templates/hip_report.xml b/crates/gphip/templates/hip_report.xml similarity index 100% rename from apps/gpclient/templates/hip_report.xml rename to crates/gphip/templates/hip_report.xml diff --git a/crates/openconnect/deps/openconnect b/crates/openconnect/deps/openconnect index 7a019c0..0d69b28 160000 --- a/crates/openconnect/deps/openconnect +++ b/crates/openconnect/deps/openconnect @@ -1 +1 @@ -Subproject commit 7a019c0c04eeafce5d738957212315b5d2f4cf63 +Subproject commit 0d69b28c140b81265bd5ca31f145dae69a15a1fd diff --git a/crates/openconnect/src/ffi/mod.rs b/crates/openconnect/src/ffi/mod.rs index 51260b3..b22a4fd 100644 --- a/crates/openconnect/src/ffi/mod.rs +++ b/crates/openconnect/src/ffi/mod.rs @@ -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, 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::(), 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) }; diff --git a/crates/openconnect/src/ffi/vpn.c b/crates/openconnect/src/ffi/vpn.c index 6558eaf..63f2fa1 100644 --- a/crates/openconnect/src/ffi/vpn.c +++ b/crates/openconnect/src/ffi/vpn.c @@ -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"); diff --git a/crates/openconnect/src/ffi/vpn.h b/crates/openconnect/src/ffi/vpn.h index 7c492b3..e87ff42 100644 --- a/crates/openconnect/src/ffi/vpn.h +++ b/crates/openconnect/src/ffi/vpn.h @@ -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; diff --git a/crates/openconnect/src/vpn.rs b/crates/openconnect/src/vpn.rs index 157c735..3adb5ae 100644 --- a/crates/openconnect/src/vpn.rs +++ b/crates/openconnect/src/vpn.rs @@ -10,6 +10,7 @@ use crate::ffi; use crate::vpn_utils::{check_executable, find_csd_wrapper, find_vpnc_script}; type OnConnectedCallback = Arc>>>; +type OnHipReportCallback = RwLock>>; #[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"".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(), [""]); + } + #[test] fn disconnect_before_connect_is_retained_without_contacting_server() { let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/packaging/binary/Makefile.in b/packaging/binary/Makefile.in index 810675f..49e0e23 100644 --- a/packaging/binary/Makefile.in +++ b/packaging/binary/Makefile.in @@ -3,6 +3,8 @@ install: install -Dm755 artifacts/usr/bin/gpclient $(DESTDIR)/usr/bin/gpclient install -Dm755 artifacts/usr/bin/gpservice $(DESTDIR)/usr/bin/gpservice + install -Dm755 artifacts/usr/libexec/gpclient/gp-hip-runner $(DESTDIR)/usr/libexec/gpclient/gp-hip-runner + install -Dm755 artifacts/usr/libexec/gpclient/gp-hip-script-installer $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer install -Dm755 artifacts/usr/bin/gpauth $(DESTDIR)/usr/bin/gpauth install -Dm755 artifacts/usr/bin/gpgui-helper $(DESTDIR)/usr/bin/gpgui-helper @@ -37,6 +39,8 @@ uninstall: rm -f $(DESTDIR)/usr/bin/gpclient rm -f $(DESTDIR)/usr/bin/gpservice + rm -f $(DESTDIR)/usr/libexec/gpclient/gp-hip-runner + rm -f $(DESTDIR)/usr/libexec/gpclient/gp-hip-script-installer rm -f $(DESTDIR)/usr/bin/gpauth rm -f $(DESTDIR)/usr/bin/gpgui-helper rm -f $(DESTDIR)/usr/bin/gpgui diff --git a/packaging/bsd/com.yuezk.gpgui.policy b/packaging/bsd/com.yuezk.gpgui.policy index 6f87593..817a317 100644 --- a/packaging/bsd/com.yuezk.gpgui.policy +++ b/packaging/bsd/com.yuezk.gpgui.policy @@ -26,4 +26,15 @@ /usr/local/libexec/gpclient/gp-vpnc-script-installer true + + Approve a GP Connect HIP script to run as root + Administrator authentication is required to run a HIP script as root + + auth_admin + auth_admin + auth_admin + + /usr/local/libexec/gpclient/gp-hip-script-installer + true + diff --git a/packaging/files/usr/libexec/gpclient/hipreport.sh b/packaging/files/usr/libexec/gpclient/hipreport.sh index 11cc91e..9e66788 100755 --- a/packaging/files/usr/libexec/gpclient/hipreport.sh +++ b/packaging/files/usr/libexec/gpclient/hipreport.sh @@ -1,7 +1,6 @@ #!/bin/sh # Wrapper for gpclient hip -LOGFILE="/tmp/gpclient-hipreport.log" LINUX_GPCLIENT_BIN="/usr/bin/gpclient" ARM64_HOMEBREW_GPCLIENT_BIN="/opt/homebrew/bin/gpclient" @@ -15,11 +14,8 @@ elif [ -x "$ARM64_HOMEBREW_GPCLIENT_BIN" ]; then elif [ -x "$LOCAL_GPCLIENT_BIN" ]; then GPCLIENT_BIN="$LOCAL_GPCLIENT_BIN" else - echo "Error: gpclient binary not found." > "$LOGFILE" + echo "Error: gpclient binary not found." >&2 exit 1 fi -# Redirect the output to a file for debugging then output to stdout -HIP_REPORT_OUTPUT=$(exec 2> "$LOGFILE" "$GPCLIENT_BIN" hip -vv "$@") - -echo "$HIP_REPORT_OUTPUT" +exec "$GPCLIENT_BIN" hip "$@" diff --git a/packaging/files/usr/share/polkit-1/actions/com.yuezk.gpgui.policy b/packaging/files/usr/share/polkit-1/actions/com.yuezk.gpgui.policy index 043508b..4e8b2af 100644 --- a/packaging/files/usr/share/polkit-1/actions/com.yuezk.gpgui.policy +++ b/packaging/files/usr/share/polkit-1/actions/com.yuezk.gpgui.policy @@ -26,4 +26,15 @@ /usr/libexec/gpclient/gp-vpnc-script-installer true + + Approve a GP Connect HIP script to run as root + Administrator authentication is required to run a HIP script as root + + auth_admin + auth_admin + auth_admin + + /usr/libexec/gpclient/gp-hip-script-installer + true + diff --git a/packaging/rpm/globalprotect-openconnect.spec.in b/packaging/rpm/globalprotect-openconnect.spec.in index 4571357..32b6e24 100644 --- a/packaging/rpm/globalprotect-openconnect.spec.in +++ b/packaging/rpm/globalprotect-openconnect.spec.in @@ -73,6 +73,8 @@ make build %{_bindir}/* %{_libexecdir}/gpclient/vpnc-script %{_libexecdir}/gpclient/hipreport.sh +%{_libexecdir}/gpclient/gp-hip-runner +%{_libexecdir}/gpclient/gp-hip-script-installer %{_libexecdir}/gpclient/gp-vpnc-script-installer %{_datadir}/applications/gpgui.desktop %{_datadir}/icons/hicolor/32x32/apps/gpgui.png