diff --git a/Cargo.lock b/Cargo.lock index 439ce21..4508d1d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -119,6 +119,48 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" +[[package]] +name = "askama" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75363874b771be265f4ffe307ca705ef6f3baa19011c149da8674a87f1b75c4" +dependencies = [ + "askama_derive", + "itoa", + "percent-encoding", + "serde", + "serde_json", +] + +[[package]] +name = "askama_derive" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "129397200fe83088e8a68407a8e2b1f826cf0086b21ccdb866a722c8bcd3a94f" +dependencies = [ + "askama_parser", + "basic-toml", + "memchr", + "proc-macro2", + "quote", + "rustc-hash", + "serde", + "serde_derive", + "syn 2.0.111", +] + +[[package]] +name = "askama_parser" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6ab5630b3d5eaf232620167977f95eb51f3432fc76852328774afbd242d4358" +dependencies = [ + "memchr", + "serde", + "serde_derive", + "winnow 0.7.14", +] + [[package]] name = "async-trait" version = "0.1.89" @@ -266,6 +308,15 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "basic-toml" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" +dependencies = [ + "serde", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -503,8 +554,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "145052bdd345b87320e369255277e3fb5152762ad123a901ef5c262dd38fe8d2" dependencies = [ "iana-time-zone", + "js-sys", "num-traits", "serde", + "wasm-bindgen", "windows-link 0.2.1", ] @@ -964,6 +1017,17 @@ dependencies = [ "syn 2.0.111", ] +[[package]] +name = "dlopen2" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09b4f5f101177ff01b8ec4ecc81eead416a8aa42819a2869311b3420fa114ffa" +dependencies = [ + "libc", + "once_cell", + "winapi", +] + [[package]] name = "dlopen2" version = "0.8.2" @@ -1622,13 +1686,14 @@ dependencies = [ "gtk", "log", "log-reload", + "machine-uid", "md5", "openssl", + "os_info", "pem", "redact-engine", "regex", "reqwest", - "roxmltree", "serde", "serde_json", "serde_urlencoded", @@ -1640,9 +1705,11 @@ dependencies = [ "tokio", "url", "urlencoding", + "uuid", "uzers", "version-compare", "whoami", + "xmltree", ] [[package]] @@ -1670,6 +1737,8 @@ name = "gpclient" version = "2.5.0" dependencies = [ "anyhow", + "askama", + "chrono", "clap", "common", "compile-time", @@ -1678,13 +1747,16 @@ dependencies = [ "gpapi", "inquire", "log", + "netdev", "openconnect", "reqwest", "serde_json", + "serde_urlencoded", "sysinfo", "tempfile", "tokio", "whoami", + "xmltree", ] [[package]] @@ -2477,6 +2549,23 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" +[[package]] +name = "mac-addr" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3d25b0e0b648a86960ac23b7ad4abb9717601dec6f66c165f5b037f3f03065f" + +[[package]] +name = "machine-uid" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d7217d573cdb141d6da43113b098172e057d39915d79c4bdedbc3aacd46bd96" +dependencies = [ + "libc", + "windows-registry", + "windows-sys 0.61.2", +] + [[package]] name = "markup5ever" version = "0.14.1" @@ -2631,12 +2720,74 @@ dependencies = [ "jni-sys", ] +[[package]] +name = "netdev" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a703aa1a87cd885b9f674922445a42dbb0c0f4f1b28fef21b227ae32375d21" +dependencies = [ + "dlopen2 0.5.0", + "ipnet", + "libc", + "mac-addr", + "netlink-packet-core", + "netlink-packet-route", + "netlink-sys", + "once_cell", + "system-configuration", + "windows-sys 0.59.0", +] + +[[package]] +name = "netlink-packet-core" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3463cbb78394cb0141e2c926b93fc2197e473394b761986eca3b9da2c63ae0f4" +dependencies = [ + "paste", +] + +[[package]] +name = "netlink-packet-route" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ec2f5b6839be2a19d7fa5aab5bc444380f6311c2b693551cb80f45caaa7b5ef" +dependencies = [ + "bitflags 2.10.0", + "libc", + "log", + "netlink-packet-core", +] + +[[package]] +name = "netlink-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16c903aa70590cb93691bf97a767c8d1d6122d2cc9070433deb3bbf36ce8bd23" +dependencies = [ + "bytes", + "libc", + "log", +] + [[package]] name = "new_debug_unreachable" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "nix" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6" +dependencies = [ + "bitflags 2.10.0", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nodrop" version = "0.1.14" @@ -2792,6 +2943,16 @@ dependencies = [ "objc2-foundation 0.3.2", ] +[[package]] +name = "objc2-core-location" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009" +dependencies = [ + "objc2 0.6.3", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-core-text" version = "0.3.2" @@ -2921,6 +3082,7 @@ checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" dependencies = [ "bitflags 2.10.0", "objc2 0.6.3", + "objc2-core-foundation", "objc2-foundation 0.3.2", ] @@ -2942,8 +3104,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" dependencies = [ "bitflags 2.10.0", + "block2 0.6.2", "objc2 0.6.3", + "objc2-cloud-kit", + "objc2-core-data", "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image", + "objc2-core-location", + "objc2-core-text", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e" +dependencies = [ + "objc2 0.6.3", "objc2-foundation 0.3.2", ] @@ -3054,6 +3235,21 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "os_info" +version = "3.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c39b5918402d564846d5aba164c09a66cc88d232179dfd3e3c619a25a268392" +dependencies = [ + "android_system_properties", + "log", + "nix", + "objc2 0.6.3", + "objc2-foundation 0.3.2", + "objc2-ui-kit", + "windows-sys 0.61.2", +] + [[package]] name = "pango" version = "0.18.3" @@ -3102,6 +3298,12 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + [[package]] name = "pathdiff" version = "0.2.3" @@ -3727,13 +3929,10 @@ dependencies = [ ] [[package]] -name = "roxmltree" -version = "0.21.1" +name = "rustc-hash" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb" -dependencies = [ - "memchr", -] +checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" [[package]] name = "rustc_version" @@ -4130,6 +4329,12 @@ dependencies = [ "digest", ] +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + [[package]] name = "sha2" version = "0.10.9" @@ -4456,7 +4661,7 @@ dependencies = [ "core-graphics", "crossbeam-channel", "dispatch", - "dlopen2", + "dlopen2 0.8.2", "dpi", "gdkwayland-sys", "gdkx11-sys", @@ -5282,6 +5487,7 @@ dependencies = [ "getrandom 0.3.4", "js-sys", "serde_core", + "sha1_smol", "wasm-bindgen", ] @@ -6145,6 +6351,21 @@ dependencies = [ "rustix", ] +[[package]] +name = "xml" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2df5825faced2427b2da74d9100f1e2e93c533fff063506a81ede1cf517b2e7e" + +[[package]] +name = "xmltree" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbc04313cab124e498ab1724e739720807b6dc405b9ed0edc5860164d2e4ff70" +dependencies = [ + "xml", +] + [[package]] name = "xz2" version = "0.1.7" diff --git a/Cargo.toml b/Cargo.toml index 0895d52..9fb4148 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,9 @@ license = "GPL-3.0" [workspace.dependencies] anyhow = "1.0" +askama = "0.14" base64 = "0.22" +chrono = "0.4" clap = { version = "4", features = ["derive"] } clap-verbosity-flag = "3" ctrlc = "3.4" @@ -32,7 +34,7 @@ regex = "1" reqwest = { version = "0.12", features = ["native-tls", "json"] } openssl = "0.10" pem = "3" -roxmltree = "0.21" +xmltree = "0.12" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" # Use 0.36 as newer versions requires Rust 1.88+ @@ -54,6 +56,9 @@ serde_urlencoded = "0.7" md5 = "0.8" sha256 = "1" which = "8" +uuid = "1" +netdev = "0.39" +machine-uid = "0.5" # Tauri dependencies tauri = { version = "2" } diff --git a/Makefile b/Makefile index f741895..9c08a8b 100644 --- a/Makefile +++ b/Makefile @@ -136,6 +136,9 @@ install: install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/bin/gpgui; \ fi + # Install the HIP report script + install -Dm755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh + # Install the disconnect hooks install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook @@ -156,6 +159,8 @@ uninstall: rm -f $(DESTDIR)/usr/bin/gpgui-helper rm -f $(DESTDIR)/usr/bin/gpgui + rm -f $(DESTDIR)/usr/libexec/gpclient/hipreport.sh + rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook diff --git a/apps/gpclient/Cargo.toml b/apps/gpclient/Cargo.toml index bd57745..9db9105 100644 --- a/apps/gpclient/Cargo.toml +++ b/apps/gpclient/Cargo.toml @@ -12,6 +12,8 @@ gpapi = { path = "../../crates/gpapi", features = ["clap"] } openconnect = { path = "../../crates/openconnect" } anyhow.workspace = true +askama.workspace = true +chrono.workspace = true clap.workspace = true env_logger.workspace = true inquire = "0.9" @@ -19,11 +21,14 @@ log.workspace = true tokio = { workspace = true, features = ["rt-multi-thread"] } sysinfo.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 [features] default = ["webview-auth"] diff --git a/apps/gpclient/src/cli.rs b/apps/gpclient/src/cli.rs index 443e53c..cff6aa1 100644 --- a/apps/gpclient/src/cli.rs +++ b/apps/gpclient/src/cli.rs @@ -3,7 +3,7 @@ use std::{env::temp_dir, fs::File, str::FromStr}; use anyhow::bail; use clap::{Parser, Subcommand}; use gpapi::{ - clap::{handle_error, Args, InfoLevelVerbosity}, + clap::{Args, InfoLevelVerbosity, handle_error}, utils::openssl, }; use log::info; @@ -12,10 +12,11 @@ use tempfile::NamedTempFile; use tokio::fs; use crate::{ + GP_CLIENT_LOCK_FILE, connect::{ConnectArgs, ConnectHandler}, disconnect::{DisconnectArgs, DisconnectHandler}, + hip::{HipArgs, HipHandler}, launch_gui::{LaunchGuiArgs, LaunchGuiHandler}, - GP_CLIENT_LOCK_FILE, }; const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")"); @@ -34,6 +35,8 @@ enum CliCommand { Disconnect(DisconnectArgs), #[command(about = "Launch the GUI")] LaunchGui(LaunchGuiArgs), + #[command(about = "Generate HIP report")] + Hip(HipArgs), } #[derive(Parser)] @@ -132,6 +135,7 @@ impl Cli { CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await, CliCommand::Disconnect(args) => DisconnectHandler::new(args).handle().await, CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await, + CliCommand::Hip(args) => HipHandler::new(args).handle().await, } } } diff --git a/apps/gpclient/src/connect.rs b/apps/gpclient/src/connect.rs index c4208f5..ae76fd3 100644 --- a/apps/gpclient/src/connect.rs +++ b/apps/gpclient/src/connect.rs @@ -15,7 +15,7 @@ use gpapi::{ auth_launcher::SamlAuthLauncher, users::{get_non_root_user, get_user_by_name}, }, - utils::{request::RequestIdentityError, shutdown_signal}, + utils::{host_utils, request::RequestIdentityError, shutdown_signal}, }; use inquire::{Password, PasswordDisplayMode, Select, Text}; use log::{info, warn}; @@ -130,18 +130,29 @@ pub(crate) struct ConnectArgs { impl ConnectArgs { fn default_os() -> Os { - if cfg!(target_os = "macos") { Os::Mac } else { Os::Linux } + #[cfg(target_os = "macos")] + { + Os::Mac + } + #[cfg(target_os = "windows")] + { + Os::Windows + } + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + { + Os::Linux + } } - fn os_version(&self) -> String { + fn os_version(&self) -> &str { if let Some(os_version) = self.os_version.as_deref() { - return os_version.to_string(); + return os_version; } match self.os { - Os::Linux => format!("Linux {}", whoami::distro()), - Os::Windows => String::from("Microsoft Windows 11 Pro , 64-bit"), - Os::Mac => String::from("Apple Mac OS X 13.4.0"), + Os::Linux => host_utils::get_linux_os_string(), + Os::Windows => host_utils::get_windows_os_string(), + Os::Mac => host_utils::get_macos_os_string(), } } } @@ -167,7 +178,7 @@ impl<'a> ConnectHandler<'a> { GpParams::builder() .user_agent(&self.args.user_agent) .client_os(ClientOs::from(&self.args.os)) - .os_version(self.args.os_version()) + .os_version(self.args.os_version().to_owned()) .ignore_tls_errors(self.shared_args.ignore_tls_errors) .certificate(self.args.certificate.clone()) .sslkey(self.args.sslkey.clone()) diff --git a/apps/gpclient/src/hip.rs b/apps/gpclient/src/hip.rs new file mode 100644 index 0000000..4d073bd --- /dev/null +++ b/apps/gpclient/src/hip.rs @@ -0,0 +1,381 @@ +use askama::Template; +use clap::Args; +use gpapi::utils::host_utils; +use log::debug; +use std::collections::HashMap; +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, + md5: &'a str, + user_name: &'a str, + host_info: HostInfo, +} + +/// Host information for HIP reporting +struct HostInfo { + /// Only for macOS and Windows + host_id: String, + /// Common for all OSes + host_name: String, + os: &'static str, + /// Only for macOS and Windows + os_version: &'static str, + os_vendor: &'static str, + domain: String, + network_interfaces: Vec, +} + +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 + } +} + +#[derive(Args)] +pub(crate) struct HipArgs { + #[arg(long, help = "The authentication cookie")] + cookie: String, + + #[arg(long, help = "The client IPv4 address")] + client_ip: Option, + + #[arg(long, help = "The client IPv6 address")] + client_ipv6: Option, + + #[arg(long, help = "The MD5 digest to encode into the HIP report")] + md5: String, + + #[arg(long, default_value = "Windows", help = "The client OS (Linux, Mac, or Windows)")] + client_os: String, + + #[arg(long, default_value = "", help = "The client software version")] + client_version: String, +} + +pub(crate) struct HipHandler<'a> { + args: &'a HipArgs, +} + +impl<'a> HipHandler<'a> { + pub(crate) fn new(args: &'a HipArgs) -> Self { + Self { args } + } + + pub(crate) async fn handle(&self) -> anyhow::Result<()> { + self.validate_args()?; + let cookie_params = self.parse_cookie(); + let report = self.generate_hip_report(&cookie_params)?; + + debug!("Generated HIP report:\n{}", report); + println!("{}", report); + + Ok(()) + } + + /// Validate that at least one IP address is provided + fn validate_args(&self) -> anyhow::Result<()> { + if self.args.client_ip.is_none() && self.args.client_ipv6.is_none() { + anyhow::bail!("At least one of --client-ip or --client-ipv6 must be provided"); + } + 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 client_version = std::env::var("APP_VERSION") + .map(|v| v.leak() as &'a str) + .unwrap_or(&self.args.client_version); + + let template = HipReportTemplate { + client_version, + generate_time, + day, + month, + year, + md5: &self.args.md5, + user_name, + host_info, + }; + + let report = template.render()?; + format_xml(&report) + } + + /// Collect host information based on the client OS + fn collect_host_info(&self, cookie_params: &HashMap) -> HostInfo { + let collector = HostInfoCollector::new(self.args, cookie_params); + + match self.args.client_os.as_str() { + "Linux" => collector.collect_linux(), + "Mac" => collector.collect_macos(), + _ => collector.collect_windows(), + } + } +} + +// ============================================================================ +// Host Information Collector +// ============================================================================ + +/// Helper struct for collecting host information +struct HostInfoCollector<'a> { + args: &'a HipArgs, + cookie_params: &'a HashMap, +} + +impl<'a> HostInfoCollector<'a> { + fn new(args: &'a HipArgs, cookie_params: &'a HashMap) -> Self { + Self { args, cookie_params } + } + + /// Get domain from cookie parameters + 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()), + } + } + + /// Collect Linux-specific host information + fn collect_linux(&self) -> HostInfo { + let iface = self.collect_network_interface(); + + // Use the fixed interface name enp1s0f0 for Linux if it is not on Linux + let iface = NetworkInterface { + #[cfg(target_os = "linux")] + name: iface.name, + #[cfg(target_os = "linux")] + description: iface.description, + + #[cfg(not(target_os = "linux"))] + name: "enp1s0f0".to_string(), + #[cfg(not(target_os = "linux"))] + description: "enp1s0f0".to_string(), + + mac_address: iface.mac_address, + ipv4: iface.ipv4, + ipv6: iface.ipv6, + }; + + HostInfo { + os_vendor: "Linux", + host_id: host_utils::derive_uuid(&[]), + os: host_utils::get_linux_os_string(), + host_name: whoami::devicename(), + os_version: "", + domain: String::new(), + network_interfaces: vec![iface], + } + } + + /// Collect macOS-specific host information + fn collect_macos(&self) -> HostInfo { + let iface = self.collect_network_interface(); + // macOS use the mac address as host ID + let host_id = iface + .mac_address + .as_ref() + .map(|s| s.to_string()) + .unwrap_or_else(|| "00:00:00:00:00:00".to_string()); + + // Use the fixed interface name en0 for macOS if it is not on macOS + let iface = NetworkInterface { + #[cfg(target_os = "macos")] + name: iface.name, + #[cfg(target_os = "macos")] + description: iface.description, + + #[cfg(not(target_os = "macos"))] + name: "en0".to_string(), + #[cfg(not(target_os = "macos"))] + description: "en0".to_string(), + + mac_address: iface.mac_address, + ipv4: iface.ipv4, + ipv6: iface.ipv6, + }; + + HostInfo { + os_vendor: "Apple", + host_id, + os: host_utils::get_macos_os_string(), + host_name: whoami::devicename(), + os_version: host_utils::get_macos_version(), + domain: self.get_domain(), + network_interfaces: vec![iface], + } + } + + /// Collect Windows-specific host information + fn collect_windows(&self) -> HostInfo { + // Use the actual machine ID on Windows + #[cfg(target_os = "windows")] + let host_id = host_utils::get_machine_id().to_string(); + #[cfg(not(target_os = "windows"))] + let host_id = host_utils::derive_uuid(&[]); + + let iface = self.collect_network_interface(); + + // Use the fixed interface name if it is not on Windows + let iface = NetworkInterface { + #[cfg(target_os = "windows")] + name: iface.name, + #[cfg(target_os = "windows")] + description: iface.description, + + #[cfg(not(target_os = "windows"))] + name: derive_windows_network_name(&iface), + #[cfg(not(target_os = "windows"))] + description: "PANGP Virtual Ethernet Adapter Secure".to_string(), + + // mac address on windows should replace ':' with '-' + mac_address: iface.mac_address.map(|mac| mac.replace(':', "-")), + ipv4: iface.ipv4, + ipv6: iface.ipv6, + }; + + // Add the local loopback interface + let loopback_iface = NetworkInterface { + name: derive_windows_network_name(&iface), + 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()), + }; + + let ifaces = vec![iface, loopback_iface]; + + HostInfo { + os_vendor: "Microsoft", + host_id, + os: host_utils::get_windows_os_string(), + host_name: whoami::devicename(), + os_version: host_utils::get_windows_version(), + domain: self.get_domain(), + network_interfaces: ifaces, + } + } +} + +// ============================================================================ +// 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(iface: &NetworkInterface) -> String { + let seeds = [ + iface.mac_address.as_deref().unwrap_or("00:00:00:00:00:00"), + iface.name.as_str(), + ]; + + format!("{{{}}}", host_utils::derive_uuid(&seeds).to_uppercase()) +} diff --git a/apps/gpclient/src/main.rs b/apps/gpclient/src/main.rs index 41343ed..eacc565 100644 --- a/apps/gpclient/src/main.rs +++ b/apps/gpclient/src/main.rs @@ -1,6 +1,7 @@ mod cli; mod connect; mod disconnect; +mod hip; mod launch_gui; pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock"; diff --git a/apps/gpclient/templates/hip_report.xml b/apps/gpclient/templates/hip_report.xml new file mode 100644 index 0000000..067a3fe --- /dev/null +++ b/apps/gpclient/templates/hip_report.xml @@ -0,0 +1,277 @@ + + + {{ md5 }} + {{ user_name }} + {{ host_info.domain }}.internal + {{ host_info.host_name }} + {{ host_info.host_id }} + {{ host_info.default_ipv4() }} + {{ host_info.default_ipv6() }} + {{ generate_time }} + 4 + + + {{ client_version }} + {{ host_info.os }} + {{ host_info.os_vendor }} + {{ host_info.domain }}.internal + {{ host_info.host_name }} + {{ host_info.host_id }} + + {% for iface in host_info.network_interfaces.iter() -%} + + {{ iface.description }} + {% if let Some(mac) = iface.mac_address -%} + {{ mac }} + {% endif -%} + {% if let Some(ipv4) = iface.ipv4 -%} + + + + {% endif -%} + {% if let Some(ipv6) = iface.ipv6 -%} + + + + {% endif -%} + + {% endfor -%} + + + {% if host_info.os_vendor == "Microsoft" -%} + + + + + + + yes + {{ generate_time }} + + + + + + + no + n/a + + + + + + + + + + + yes + {{ generate_time }} + + + + + + + no + n/a + + + + + + + + + + + n/a + + + + + + + + + + + + + C:\\ + full + + + + + + + + + + + + + yes + + + + + + + + + + + yes + + + + + + + yes + + + + + + {% elif host_info.os_vendor == "Apple" -%} + + + + + + yes + n/a + + + + + + yes + n/a + + + + + + + + + + n/a + + + + + + + + + + + + Macintosh HD + encrypted + + + Data + encrypted + + + All + encrypted + + + + + + + + + + + + yes + + + + + + no + + + + + + + + + + yes + + + + + + + {% elif host_info.os_vendor == "Linux" -%} + + + + + + + + + + + + + + + / + encrypted + + + + + + + + + + + + + no + + + + + + + n/a + + + + + + + + + + + yes + + + + + + {% endif -%} + + + + + diff --git a/crates/common/src/constants.rs b/crates/common/src/constants.rs index 28958e3..99d4177 100644 --- a/crates/common/src/constants.rs +++ b/crates/common/src/constants.rs @@ -1,4 +1,5 @@ pub const GP_USER_AGENT: &str = "PAN GlobalProtect"; +pub const GP_CLIENT_VERSION: &str = "6.3.0-33"; pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock"; pub const GP_CALLBACK_PORT_FILENAME: &str = "gpcallback.port"; diff --git a/crates/gpapi/Cargo.toml b/crates/gpapi/Cargo.toml index 87d4fc6..47fe0e3 100644 --- a/crates/gpapi/Cargo.toml +++ b/crates/gpapi/Cargo.toml @@ -15,7 +15,7 @@ reqwest.workspace = true openssl.workspace = true version-compare = "0.2" pem.workspace = true -roxmltree.workspace = true +xmltree.workspace = true serde.workspace = true specta = { workspace = true, features = ["derive"] } urlencoding.workspace = true @@ -32,7 +32,10 @@ uzers.workspace = true serde_urlencoded.workspace = true md5.workspace = true sha256.workspace = true +machine-uid.workspace = true +uuid = { workspace = true, features = ["v5"] } +# Optional dependencies for features tauri = { workspace = true, optional = true } clap = { workspace = true, optional = true } clap-verbosity-flag = { workspace = true, optional = true } @@ -40,6 +43,11 @@ clap-verbosity-flag = { workspace = true, optional = true } env_logger = { workspace = true, optional = true } log-reload = { version = "0.1", optional = true } +# Dependencies for macOS and Windows only +[target.'cfg(any(target_os="macos", target_os="windows"))'.dependencies] +os_info = { version = "3", default-features = false } + +# Dependencies for Linux and other OSes only [target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies] gtk = "0.18" diff --git a/crates/gpapi/src/gateway/hip.rs b/crates/gpapi/src/gateway/hip.rs index 1620002..652b103 100644 --- a/crates/gpapi/src/gateway/hip.rs +++ b/crates/gpapi/src/gateway/hip.rs @@ -2,9 +2,13 @@ use std::collections::HashMap; use log::{info, warn}; use reqwest::Client; -use roxmltree::Document; +use xmltree::Element; -use crate::{gp_params::GpParams, process::hip_launcher::HipLauncher, utils::normalize_server}; +use crate::{ + gp_params::GpParams, + process::hip_launcher::HipLauncher, + utils::{normalize_server, xml::ElementExt}, +}; struct HipReporter<'a> { server: String, @@ -65,13 +69,11 @@ impl HipReporter<'_> { let res = self.client.post(&config_url).form(¶ms).send().await?; let res_xml = res.error_for_status()?.text().await?; - let doc = Document::parse(&res_xml)?; + let root = Element::parse(res_xml.as_bytes())?; // Get - let ip = doc - .descendants() - .find(|n| n.has_tag_name("ip-address")) - .and_then(|n| n.text()) + let ip = root + .descendant_text("ip-address") .ok_or_else(|| anyhow::anyhow!("ip-address not found"))?; Ok(ip.to_string()) @@ -122,12 +124,9 @@ impl HipReporter<'_> { } fn is_hip_needed(res_xml: &str) -> anyhow::Result { - let doc = Document::parse(res_xml)?; - - let hip_needed = doc - .descendants() - .find(|n| n.has_tag_name("hip-report-needed")) - .and_then(|n| n.text()) + let root = Element::parse(res_xml.as_bytes())?; + let hip_needed = root + .descendant_text("hip-report-needed") .ok_or_else(|| anyhow::anyhow!("hip-report-needed not found"))?; Ok(hip_needed == "yes") diff --git a/crates/gpapi/src/gateway/login.rs b/crates/gpapi/src/gateway/login.rs index a0f7854..6fd7e19 100644 --- a/crates/gpapi/src/gateway/login.rs +++ b/crates/gpapi/src/gateway/login.rs @@ -1,14 +1,16 @@ +use std::borrow::Cow; + use anyhow::bail; -use log::{info, warn}; +use log::{debug, info, warn}; use reqwest::Client; -use roxmltree::Document; use urlencoding::encode; +use xmltree::Element; use crate::{ credential::Credential, error::PortalError, gp_params::GpParams, - utils::{normalize_server, parse_gp_response, remove_url_scheme}, + utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, }; pub enum GatewayLogin { @@ -50,18 +52,20 @@ pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParam return Ok(GatewayLogin::Mfa(message, input_str)); } - let doc = Document::parse(&res)?; + debug!("Gateway login response: {}", res); - let cookie = build_gateway_token(&doc, gp_params.computer())?; + let root = Element::parse(res.as_bytes())?; + + let cookie = build_gateway_token(&root, gp_params.computer())?; Ok(GatewayLogin::Cookie(cookie)) } -fn build_gateway_token(doc: &Document, computer: &str) -> anyhow::Result { - let args = doc - .descendants() - .filter(|n| n.has_tag_name("argument")) - .map(|n| n.text().unwrap_or("").to_string()) +fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result { + let args = element + .descendants("argument") + .iter() + .map(|e| e.get_text().unwrap_or_default()) .collect::>(); let params = [ @@ -82,7 +86,7 @@ fn build_gateway_token(doc: &Document, computer: &str) -> anyhow::Result Ok(token) } -fn read_args<'a>(args: &'a [String], index: usize, key: &'a str) -> anyhow::Result<(&'a str, &'a str)> { +fn read_args<'a>(args: &'a [Cow<'_, str>], index: usize, key: &'a str) -> anyhow::Result<(&'a str, &'a str)> { args .get(index) .ok_or_else(|| anyhow::anyhow!("Failed to read {key} from args")) diff --git a/crates/gpapi/src/gateway/parse_gateways.rs b/crates/gpapi/src/gateway/parse_gateways.rs index 9ed8d41..489b876 100644 --- a/crates/gpapi/src/gateway/parse_gateways.rs +++ b/crates/gpapi/src/gateway/parse_gateways.rs @@ -1,64 +1,64 @@ use log::info; -use roxmltree::Node; +use xmltree::Element; -use crate::utils::xml::NodeExt; +use crate::utils::xml::ElementExt; use super::{Gateway, PriorityRule}; -pub(crate) fn parse_gateways(node: &Node, prefer_internal: bool) -> Option> { - let node_gateways = node.find_descendant("gateways")?; +pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option> { + let node_gateways = element.descendant("gateways")?; let internal_gateway_list = if prefer_internal { info!("Try to parse the internal gateways..."); - node_gateways.find_descendant("internal").and_then(|n| n.find_child("list")) + node_gateways.descendant("internal").and_then(|n| n.child("list")) } else { None }; let gateway_list = internal_gateway_list.or_else(|| { info!("Try to parse the external gateways..."); - node_gateways.find_descendant("external").and_then(|n| n.find_child("list")) + node_gateways.descendant("external").and_then(|n| n.child("list")) })?; let gateways = gateway_list - .children() - .filter_map(|gateway_item| { - if !gateway_item.has_tag_name("entry") { - return None; - } - let address = gateway_item.attribute("name").unwrap_or_default().to_string(); - let name = gateway_item.child_text("description").unwrap_or_default().to_string(); - let priority = gateway_item - .child_text("priority") - .and_then(|s| s.parse().ok()) - .unwrap_or(u32::MAX); + .children("entry") + .iter() + .map(|gateway_item| { + let address = gateway_item.attr("name").map(|s| s.to_string()).unwrap_or_default(); + let name = gateway_item.child_text("description").unwrap_or_default(); + let priority = parse_priority(gateway_item); let priority_rules = gateway_item - .find_child("priority-rule") - .map(|n| { - n.children() - .filter_map(|n| { - if !n.has_tag_name("entry") { - return None; - } - let name = n.attribute("name").unwrap_or_default().to_string(); - let priority: u32 = n - .child_text("priority") - .and_then(|s| s.parse().ok()) - .unwrap_or(u32::MAX); - - Some(PriorityRule { name, priority }) - }) - .collect() - }) + .child("priority-rule") + .map(|n| parse_priority_rules(n)) .unwrap_or_default(); - Some(Gateway { + Gateway { name, address, priority, priority_rules, - }) + } }) .collect(); Some(gateways) } + +fn parse_priority_rules(element: &Element) -> Vec { + element + .children("entry") + .iter() + .map(|n| { + let name = n.attr("name").map(|s| s.to_string()).unwrap_or_default(); + let priority: u32 = parse_priority(n); + + PriorityRule { name, priority } + }) + .collect() +} + +fn parse_priority(element: &Element) -> u32 { + element + .child_text("priority") + .and_then(|s| s.parse().ok()) + .unwrap_or(u32::MAX) +} diff --git a/crates/gpapi/src/portal/config.rs b/crates/gpapi/src/portal/config.rs index 33cf7dd..17389d3 100644 --- a/crates/gpapi/src/portal/config.rs +++ b/crates/gpapi/src/portal/config.rs @@ -2,16 +2,16 @@ use anyhow::bail; use dns_lookup::lookup_addr; use log::{debug, info, warn}; use reqwest::{Client, StatusCode}; -use roxmltree::{Document, Node}; use serde::Serialize; use specta::Type; +use xmltree::Element; use crate::{ credential::{AuthCookieCredential, Credential}, error::PortalError, gateway::{Gateway, parse_gateways}, gp_params::GpParams, - utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::NodeExt}, + utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, }; #[derive(Debug, Serialize, Type)] @@ -142,12 +142,11 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara } debug!("Portal config response: {}", res_xml); - let doc = Document::parse(&res_xml).map_err(|e| PortalError::ConfigError(e.to_string()))?; - let root = doc.root(); + let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?; let mut ihd_enabled = false; let mut prefer_internal = false; - if let Some(ihd_node) = root.find_descendant("internal-host-detection") { + if let Some(ihd_node) = root.descendant("internal-host-detection") { ihd_enabled = true; prefer_internal = internal_host_detect(&ihd_node) } @@ -172,7 +171,7 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara Ok(PortalConfig { portal: server.to_string(), - auth_cookie: AuthCookieCredential::new(cred.username(), user_auth_cookie, prelogon_user_auth_cookie), + auth_cookie: AuthCookieCredential::new(cred.username(), &user_auth_cookie, &prelogon_user_auth_cookie), config_cred: cred.clone(), gateways, config_digest: config_digest.map(|s| s.to_string()), @@ -182,10 +181,10 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara } // Perform DNS lookup and compare the result with the expected hostname -fn internal_host_detect(node: &Node) -> bool { +fn internal_host_detect(element: &Element) -> bool { let ip_info = [ - (node.child_text("ip-address"), node.child_text("host")), - (node.child_text("ipv6-address"), node.child_text("ipv6-host")), + (element.child_text("ip-address"), element.child_text("host")), + (element.child_text("ipv6-address"), element.child_text("ipv6-host")), ]; info!("Found internal-host-detection, performing DNS lookup"); diff --git a/crates/gpapi/src/portal/prelogin.rs b/crates/gpapi/src/portal/prelogin.rs index 9d52189..05f681e 100644 --- a/crates/gpapi/src/portal/prelogin.rs +++ b/crates/gpapi/src/portal/prelogin.rs @@ -1,14 +1,14 @@ use anyhow::{anyhow, bail}; use log::{info, warn}; use reqwest::{Client, StatusCode}; -use roxmltree::Document; use serde::Serialize; use specta::Type; +use xmltree::Element; use crate::{ error::PortalError, gp_params::GpParams, - utils::{base64, normalize_server, parse_gp_response, xml::NodeExt}, + utils::{base64, normalize_server, parse_gp_response, xml::ElementExt}, }; const REQUIRED_PARAMS: [&str; 8] = [ @@ -143,32 +143,30 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result anyhow::Result { - let doc = Document::parse(res_xml)?; - let root = doc.root(); + let root = Element::parse(res_xml.as_bytes())?; let status = root .descendant_text("status") .ok_or_else(|| anyhow::anyhow!("Prelogin response does not contain status element"))?; // Check the status of the prelogin response if status.to_uppercase() != "SUCCESS" { - let msg = root.descendant_text("msg").unwrap_or("Unknown error"); + let msg = root + .descendant_text("msg") + .unwrap_or_else(|| String::from("Unknown error")); bail!("{}", msg) } - let region = root - .descendant_text("region") - .unwrap_or_else(|| { - info!("Prelogin response does not contain region element"); - "Unknown" - }) - .to_string(); + let region = root.descendant_text("region").unwrap_or_else(|| { + info!("Prelogin response does not contain region element"); + String::from("Unknown") + }); let saml_method = root.descendant_text("saml-auth-method"); let saml_request = root.descendant_text("saml-request"); let saml_default_browser = root.descendant_text("saml-default-browser"); // Check if the prelogin response is SAML if saml_method.is_some() && saml_request.is_some() { - let saml_request = base64::decode_to_string(saml_request.unwrap())?; + let saml_request = base64::decode_to_string(&saml_request.unwrap())?; let support_default_browser = saml_default_browser.map(|s| s.to_lowercase() == "yes").unwrap_or(false); let saml_prelogin = SamlPrelogin { @@ -181,25 +179,18 @@ fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result { return Ok(Prelogin::Saml(saml_prelogin)); } - let label_username = root - .descendant_text("username-label") - .unwrap_or_else(|| { - info!("Username label has no value, using default"); - "Username" - }) - .to_string(); - let label_password = root - .descendant_text("password-label") - .unwrap_or_else(|| { - info!("Password label has no value, using default"); - "Password" - }) - .to_string(); + let label_username = root.descendant_text("username-label").unwrap_or_else(|| { + info!("Username label has no value, using default"); + String::from("Username") + }); + let label_password = root.descendant_text("password-label").unwrap_or_else(|| { + info!("Password label has no value, using default"); + String::from("Password") + }); let auth_message = root .descendant_text("authentication-message") - .unwrap_or("Please enter the login credentials") - .to_string(); + .unwrap_or_else(|| String::from("Please enter the login credentials")); let standard_prelogin = StandardPrelogin { region, is_gateway, diff --git a/crates/gpapi/src/utils/host_utils.rs b/crates/gpapi/src/utils/host_utils.rs new file mode 100644 index 0000000..b7f982a --- /dev/null +++ b/crates/gpapi/src/utils/host_utils.rs @@ -0,0 +1,108 @@ +use std::sync::OnceLock; + +const DEFAULT_MACOS_VERSION: &str = "13.4.0"; +#[cfg(not(target_os = "linux"))] +const DEFAULT_LINUX_DISTRO: &str = "Ubuntu 24.04.3 LTS"; +#[cfg(not(target_os = "windows"))] +const DEFAULT_WINDOWS_DISTRO: &str = "Windows 11 Pro"; +const DEFAULT_WINDOWS_VERSION: &str = "10.0.22631.0"; +const DEFAULT_MACHINE_ID: &str = "DEADBEEF-DEAD-BEEF-DEAD-BEEFDEADBEEF"; + +static MACHINE_ID: OnceLock<&'static str> = OnceLock::new(); +static MACOS_VERSION: OnceLock<&'static str> = OnceLock::new(); +static MACOS_OS_STRING: OnceLock = OnceLock::new(); +static LINUX_OS_STRING: OnceLock = OnceLock::new(); +static WINDOWS_VERSION: OnceLock<&'static str> = OnceLock::new(); +static WINDOWS_OS_STRING: OnceLock = OnceLock::new(); + +/// On macOS, get the OS version, or fallback to default +/// On other OSes, always return default +pub fn get_macos_version() -> &'static str { + MACOS_VERSION.get_or_init(|| { + #[cfg(target_os = "macos")] + { + match os_info::get().version() { + os_info::Version::Unknown => DEFAULT_MACOS_VERSION, + v => v.to_string().leak(), + } + } + + #[cfg(not(target_os = "macos"))] + DEFAULT_MACOS_VERSION + }) +} + +pub fn get_macos_os_string() -> &'static str { + MACOS_OS_STRING.get_or_init(|| format!("Apple Mac OS X {}", get_macos_version())) +} + +/// On Linux, use the real distro name if possible +/// On other OSes, fallback to default +pub fn get_linux_os_string() -> &'static str { + LINUX_OS_STRING.get_or_init(|| { + #[cfg(target_os = "linux")] + { + format!("Linux {}", whoami::distro()) + } + #[cfg(not(target_os = "linux"))] + { + format!("Linux {}", DEFAULT_LINUX_DISTRO) + } + }) +} + +/// On Windows, get the OS version, or fallback to default +/// On other OSes, always return default +pub fn get_windows_version() -> &'static str { + WINDOWS_VERSION.get_or_init(|| { + #[cfg(target_os = "windows")] + { + match os_info::get().version() { + os_info::Version::Unknown => DEFAULT_WINDOWS_VERSION, + v => format!("{}.0", v).leak(), + } + } + #[cfg(not(target_os = "windows"))] + DEFAULT_WINDOWS_VERSION + }) +} + +/// On Windows, use the real edition if possible +/// On other OSes, fallback to default +/// The trailing space is intentional +pub fn get_windows_os_string() -> &'static str { + WINDOWS_OS_STRING.get_or_init(|| { + #[cfg(target_os = "windows")] + { + let edition = os_info::get() + .edition() + .map(|e| e.to_string()) + .unwrap_or_else(|| whoami::distro()); + format!("Microsoft {} , 64-bit", edition) + } + #[cfg(not(target_os = "windows"))] + { + format!("Microsoft {} , 64-bit", DEFAULT_WINDOWS_DISTRO) + } + }) +} + +/// Get machine ID or fallback to default +pub fn get_machine_id() -> &'static str { + MACHINE_ID.get_or_init(|| { + machine_uid::get() + .map(|id| id.to_string().leak() as &'static str) + .unwrap_or(DEFAULT_MACHINE_ID) + }) +} + +/// Generate a UUID v5 based on machine ID and provided seeds +pub fn derive_uuid(seeds: &[&str]) -> String { + use uuid::Uuid; + + let namespace = Uuid::NAMESPACE_DNS; + let name = format!("{}-{}", get_machine_id(), seeds.join("-")); + + let uuid = Uuid::new_v5(&namespace, name.as_bytes()); + uuid.hyphenated().to_string() +} diff --git a/crates/gpapi/src/utils/mod.rs b/crates/gpapi/src/utils/mod.rs index 7907512..2b46e94 100644 --- a/crates/gpapi/src/utils/mod.rs +++ b/crates/gpapi/src/utils/mod.rs @@ -5,6 +5,7 @@ pub mod checksum; pub mod crypto; pub mod endpoint; pub mod env_utils; +pub mod host_utils; pub mod lock_file; pub mod openssl; pub mod redact; diff --git a/crates/gpapi/src/utils/xml.rs b/crates/gpapi/src/utils/xml.rs index 2885130..363d859 100644 --- a/crates/gpapi/src/utils/xml.rs +++ b/crates/gpapi/src/utils/xml.rs @@ -1,27 +1,87 @@ -use roxmltree::Node; +use xmltree::Element; -pub(crate) trait NodeExt<'a> { - fn find_descendant(&self, name: &str) -> Option>; - fn descendant_text(&self, name: &str) -> Option<&'a str>; +pub(crate) trait ElementExt { + /// Recursively find all descendants with the given name + fn descendants(&self, name: &str) -> Vec<&Element>; - fn find_child(&self, name: &str) -> Option>; - fn child_text(&self, name: &str) -> Option<&'a str>; + /// Recursively find the first descendant with the given name + fn descendant(&self, name: &str) -> Option<&Element>; + + /// Recursively find the text of the first descendant with the given name + fn descendant_text(&self, name: &str) -> Option; + + /// Find the first child with the given name + fn child(&self, name: &str) -> Option<&Element>; + + /// Find the text of the first child with the given name + fn child_text(&self, name: &str) -> Option; + + /// Get the direct child element with the given name + fn children(&self, name: &str) -> Vec<&Element>; + + /// Get the attribute value by name + fn attr(&self, name: &str) -> Option<&str>; } -impl<'a> NodeExt<'a> for Node<'a, 'a> { - fn find_descendant(&self, name: &str) -> Option> { - self.descendants().find(|n| n.has_tag_name(name)) +impl ElementExt for Element { + fn descendants(&self, name: &str) -> Vec<&Element> { + let mut results = Vec::new(); + + if self.name == name { + results.push(self); + } + + for child in &self.children { + if let Some(element) = child.as_element() { + results.extend(element.descendants(name)); + } + } + + results } - fn descendant_text(&self, name: &str) -> Option<&'a str> { - self.find_descendant(name).and_then(|node| node.text()) + fn descendant(&self, name: &str) -> Option<&Element> { + if self.name == name { + return Some(self); + } + + for child in &self.children { + if let Some(element) = child.as_element() { + if let Some(found) = element.descendant(name) { + return Some(found); + } + } + } + + None } - fn find_child(&self, name: &str) -> Option> { - self.children().find(|n| n.has_tag_name(name)) + fn descendant_text(&self, name: &str) -> Option { + self + .descendant(name) + .and_then(|element| element.get_text().map(|s| s.to_string())) } - fn child_text(&self, name: &str) -> Option<&'a str> { - self.find_child(name).and_then(|node| node.text()) + fn child(&self, name: &str) -> Option<&Element> { + self.get_child(name) + } + + fn child_text(&self, name: &str) -> Option { + self + .get_child(name) + .and_then(|element| element.get_text().map(|s| s.to_string())) + } + + fn children(&self, name: &str) -> Vec<&Element> { + self + .children + .iter() + .filter_map(|child| child.as_element()) + .filter(|element| element.name == name) + .collect() + } + + fn attr(&self, name: &str) -> Option<&str> { + self.attributes.get(name).map(|s| s.as_str()) } } diff --git a/crates/openconnect/src/vpn_utils.rs b/crates/openconnect/src/vpn_utils.rs index 2ed704c..0e8f270 100644 --- a/crates/openconnect/src/vpn_utils.rs +++ b/crates/openconnect/src/vpn_utils.rs @@ -15,6 +15,7 @@ const VPNC_SCRIPT_LOCATIONS: &[&str] = &[ ]; const CSD_WRAPPER_LOCATIONS: &[&str] = &[ + "/usr/libexec/gpclient/hipreport.sh", #[cfg(target_arch = "x86_64")] "/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh", #[cfg(target_arch = "aarch64")] diff --git a/deps/patches/openconnect-gp-version.patch b/deps/patches/openconnect-gp-version.patch index 9c2cb3c..844c92b 100644 --- a/deps/patches/openconnect-gp-version.patch +++ b/deps/patches/openconnect-gp-version.patch @@ -1,12 +1,12 @@ diff --git a/gpst.c b/gpst.c -index 244aaf04..205bec1d 100644 +index 244aaf04..17fc1f45 100644 --- a/gpst.c +++ b/gpst.c @@ -650,8 +650,11 @@ static int gpst_get_config(struct openconnect_info *vpninfo) /* submit getconfig request */ -+ char *app_version = vpninfo->csd_ticket ? : (vpninfo->gp_app_version ? : "6.3.0-33"); ++ char *app_version = openconnect_get_gp_app_version(vpninfo); + vpn_progress(vpninfo, PRG_DEBUG, _("Using GlobalProtect app version: %s\n"), app_version); + buf_append(request_body, "client-type=1&protocol-version=p1&internal=no"); @@ -15,8 +15,20 @@ index 244aaf04..205bec1d 100644 append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes"); append_opt(request_body, "clientos", gpst_os_name(vpninfo)); append_opt(request_body, "os-version", vpninfo->platname); +@@ -1040,9 +1043,8 @@ static int run_hip_script(struct openconnect_info *vpninfo) + * accept new ones. + */ + unsetenv("APP_VERSION"); +- if (vpninfo->csd_ticket) +- if (setenv("APP_VERSION", vpninfo->csd_ticket, 1)) +- goto out; ++ if (setenv("APP_VERSION", openconnect_get_gp_app_version(vpninfo), 1)) ++ goto out; + + execv(hip_argv[0], (char **)hip_argv); + diff --git a/library.c b/library.c -index b5e74e9b..fff28f77 100644 +index b5e74e9b..18334c76 100644 --- a/library.c +++ b/library.c @@ -896,6 +896,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo) @@ -27,7 +39,7 @@ index b5e74e9b..fff28f77 100644 free(vpninfo->authgroup); #ifdef HAVE_LIBSTOKEN if (vpninfo->stoken_pin) -@@ -1019,6 +1020,15 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo, +@@ -1019,6 +1020,20 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo, return 0; } @@ -39,12 +51,17 @@ index b5e74e9b..fff28f77 100644 + STRDUP(vpninfo->gp_app_version, gp_app_version); + return 0; +} ++ ++const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo) ++{ ++ return vpninfo->csd_ticket ?: (vpninfo->gp_app_version ?: "6.3.0-33"); ++} + int openconnect_set_urlpath(struct openconnect_info *vpninfo, const char *urlpath) { diff --git a/openconnect-internal.h b/openconnect-internal.h -index abf45bbd..85933f4a 100644 +index abf45bbd..988f85f0 100644 --- a/openconnect-internal.h +++ b/openconnect-internal.h @@ -786,6 +786,7 @@ struct openconnect_info { @@ -55,6 +72,16 @@ index abf45bbd..85933f4a 100644 const char *quit_reason; const char *delay_tunnel_reason; /* If non-null, provides a reason why protocol is not yet ready for tunnel setup */ +@@ -1677,6 +1678,9 @@ void openconnect_set_juniper(struct openconnect_info *vpninfo); + /* hpke.c */ + int handle_external_browser(struct openconnect_info *vpninfo); + ++/* Get the app version */ ++const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo); ++ + /* version.c */ + extern const char openconnect_version_str[]; + diff --git a/openconnect.h b/openconnect.h index 136f181a..67fc1283 100644 --- a/openconnect.h diff --git a/packaging/binary/Makefile.in b/packaging/binary/Makefile.in index a9f9bdd..1b533a0 100644 --- a/packaging/binary/Makefile.in +++ b/packaging/binary/Makefile.in @@ -10,6 +10,9 @@ install: install -Dm755 artifacts/usr/bin/gpgui $(DESTDIR)/usr/bin/gpgui; \ fi + # Install the HIP report script + install -Dm755 artifacts/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh + # Install the disconnect hooks install -Dm755 artifacts/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down install -Dm755 artifacts/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook @@ -30,6 +33,8 @@ uninstall: rm -f $(DESTDIR)/usr/bin/gpgui-helper rm -f $(DESTDIR)/usr/bin/gpgui + rm -f $(DESTDIR)/usr/libexec/gpclient/hipreport.sh + rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook diff --git a/packaging/files/usr/libexec/gpclient/hipreport.sh b/packaging/files/usr/libexec/gpclient/hipreport.sh new file mode 100755 index 0000000..079e441 --- /dev/null +++ b/packaging/files/usr/libexec/gpclient/hipreport.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +# Wrapper for gpclient hip +GPCLIENT_BIN="/usr/bin/gpclient" + +# Redirect the output to a file for debugging then output to stdout +LOGFILE="/tmp/gpclient-hipreport.log" + +HIP_REPORT_OUTPUT=$(exec 2> "$LOGFILE" "$GPCLIENT_BIN" hip -vv "$@") + +echo "$HIP_REPORT_OUTPUT" diff --git a/packaging/rpm/globalprotect-openconnect.spec.in b/packaging/rpm/globalprotect-openconnect.spec.in index 2f5b979..db988d5 100644 --- a/packaging/rpm/globalprotect-openconnect.spec.in +++ b/packaging/rpm/globalprotect-openconnect.spec.in @@ -52,6 +52,7 @@ make build OFFLINE=@OFFLINE@ BUILD_FE=0 %files %defattr(-,root,root) %{_bindir}/* +%{_libexecdir}/gpclient/hipreport.sh %{_datadir}/applications/gpgui.desktop %{_datadir}/icons/hicolor/32x32/apps/gpgui.png %{_datadir}/icons/hicolor/128x128/apps/gpgui.png @@ -66,6 +67,8 @@ make build OFFLINE=@OFFLINE@ BUILD_FE=0 /usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down /usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook +%dir %{_libexecdir} +%dir %{_libexecdir}/gpclient %dir %{_datadir}/icons/hicolor %dir %{_datadir}/icons/hicolor/32x32 %dir %{_datadir}/icons/hicolor/32x32/apps