From 623cb8caf1659aaae0a46d0acd82e09555a9076f Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Sun, 10 May 2026 15:33:04 +0800 Subject: [PATCH] fix: support portal csc config flow --- Cargo.lock | 1 + crates/gpapi/Cargo.toml | 1 + crates/gpapi/src/portal/config.rs | 116 +++++++- crates/gpapi/src/portal/csc.rs | 459 ++++++++++++++++++++++++++++++ crates/gpapi/src/portal/mod.rs | 1 + 5 files changed, 572 insertions(+), 6 deletions(-) create mode 100644 crates/gpapi/src/portal/csc.rs diff --git a/Cargo.lock b/Cargo.lock index 7613e0c..232ee25 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1702,6 +1702,7 @@ dependencies = [ "log-reload", "machine-uid", "md5", + "netdev", "openssl", "os_info", "pem", diff --git a/crates/gpapi/Cargo.toml b/crates/gpapi/Cargo.toml index 027adc6..4076142 100644 --- a/crates/gpapi/Cargo.toml +++ b/crates/gpapi/Cargo.toml @@ -36,6 +36,7 @@ machine-uid.workspace = true uuid = { workspace = true, features = ["v5"] } chrono.workspace = true humantime.workspace = true +netdev.workspace = true # Optional dependencies for features tauri = { workspace = true, optional = true } diff --git a/crates/gpapi/src/portal/config.rs b/crates/gpapi/src/portal/config.rs index 5b84151..ea60a74 100644 --- a/crates/gpapi/src/portal/config.rs +++ b/crates/gpapi/src/portal/config.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use anyhow::bail; use dns_lookup::lookup_addr; use log::{debug, info, warn}; @@ -14,6 +16,8 @@ use crate::{ utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, }; +use super::csc; + #[derive(Debug, Serialize, Type)] #[serde(rename_all = "camelCase")] pub struct PortalConfig { @@ -123,12 +127,8 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara let url = format!("{}/global-protect/getconfig.esp", portal); let client = Client::try_from(gp_params)?; - let mut params = cred.to_params(); - let extra_params = gp_params.to_params(); - - params.extend(extra_params); - params.insert("server", &server); - params.insert("host", &server); + let swg_nonce = csc::swg_nonce(); + let params = build_config_params(cred, gp_params, &server, &swg_nonce); info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent()); @@ -157,6 +157,70 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara debug!("Portal config response: {}", res_xml); let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?; + if csc::is_config_criteria(&root) { + info!("Portal returned CSC criteria, retrieving CSC portal config"); + let csc_xml = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params).await?; + debug!("Portal CSC config response: {}", csc_xml); + let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?; + return parse_portal_config(&server, cred, root); + } + + parse_portal_config(&server, cred, root) +} + +fn build_config_params<'a>( + cred: &'a Credential, + gp_params: &'a GpParams, + server: &'a str, + swg_nonce: &'a str, +) -> HashMap<&'a str, &'a str> { + let mut params = cred.to_params(); + let extra_params = gp_params.to_params(); + + params.extend(extra_params); + params.insert("server", server); + params.insert("host", server); + params.insert("csc-digest", ""); + params.insert("config-digest", ""); + params.insert("csc-support", "yes"); + params.insert("swg-auth-token", "0"); + params.insert("swg-nonce", swg_nonce); + + params +} + +async fn retrieve_csc_config( + client: &Client, + portal: &str, + root: &Element, + username: &str, + gp_params: &GpParams, +) -> anyhow::Result { + let csc_req = csc::build_csc_request(root, username, gp_params)?; + let swg_nonce = csc::swg_nonce(); + let params = csc::csc_params(&csc_req, username, gp_params, &swg_nonce); + let url = format!("{}/global-protect/getconfig_csc.esp", portal); + + let res = client.post(&url).form(¶ms).send().await.map_err(|e| { + warn!("Network error: {:?}", e); + anyhow::anyhow!(PortalError::NetworkError(e)) + })?; + + parse_gp_response(res).await.or_else(|err| { + if err.status == StatusCode::NOT_FOUND { + bail!(PortalError::ConfigError("CSC config endpoint not found".to_string())); + } + + if err.is_status_error() { + warn!("{err}"); + bail!("Portal CSC config error: {}", err.reason); + } + + Err(anyhow::anyhow!(PortalError::ConfigError(err.reason))) + }) +} + +fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow::Result { let mut ihd_enabled = false; let mut prefer_internal = false; if let Some(ihd_node) = root.descendant("internal-host-detection") { @@ -254,6 +318,20 @@ mod tests { Element::parse(xml.as_bytes()).unwrap() } + #[test] + fn getconfig_params_include_csc_support_fields() { + let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret")); + let gp_params = GpParams::builder().build(); + let params = build_config_params(&cred, &gp_params, "vpn.example.com", "123"); + + assert_eq!(params.get("csc-support"), Some(&"yes")); + assert_eq!(params.get("csc-digest"), Some(&"")); + assert_eq!(params.get("config-digest"), Some(&"")); + assert_eq!(params.get("swg-auth-token"), Some(&"0")); + assert_eq!(params.get("swg-nonce"), Some(&"123")); + assert_eq!(params.get("host"), Some(&"vpn.example.com")); + } + #[test] fn parses_allow_extend_session_yes() { let root = parse_xml("yes"); @@ -288,4 +366,30 @@ mod tests { assert_eq!(parse_connect_method(&root).as_deref(), Some("on-demand")); } + + #[test] + fn parses_csc_policy_response_as_portal_config() { + let root = parse_xml( + r#" + user-cookie + prelogon-cookie + + + + + us1.vpn.example.com + + + + + "#, + ); + let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret")); + + let config = parse_portal_config("vpn.example.com", &cred, root).unwrap(); + + assert_eq!(config.auth_cookie().user_auth_cookie(), "user-cookie"); + assert_eq!(config.auth_cookie().prelogon_user_auth_cookie(), "prelogon-cookie"); + assert_eq!(config.gateways().len(), 1); + } } diff --git a/crates/gpapi/src/portal/csc.rs b/crates/gpapi/src/portal/csc.rs new file mode 100644 index 0000000..84b323d --- /dev/null +++ b/crates/gpapi/src/portal/csc.rs @@ -0,0 +1,459 @@ +use std::{ + collections::HashMap, + fs, + process::Command, + time::{SystemTime, UNIX_EPOCH}, +}; + +use xmltree::{Element, EmitterConfig, XMLNode}; + +use crate::{ + gp_params::GpParams, + utils::{host_utils, xml::ElementExt}, +}; + +const DIGEST_PLACEHOLDER: &str = "__#_PAN_CSC_DATA_DIGEST_#__"; + +pub(super) struct CscRequest { + pub(super) auth_cookie: String, + pub(super) config_digest: String, + pub(super) csc_digest: String, + pub(super) csc_data: String, + host_id: String, + serial_number: String, +} + +pub(super) trait PreferenceReader { + fn read_preference(&self, domain: &str, key: &str) -> Option; +} + +struct SystemPreferenceReader; + +impl PreferenceReader for SystemPreferenceReader { + fn read_preference(&self, domain: &str, key: &str) -> Option { + read_macos_preference(domain, key) + } +} + +pub(super) fn swg_nonce() -> String { + let millis = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_millis()) + .unwrap_or_default(); + + (millis % 2_147_483_647).to_string() +} + +pub(super) fn is_config_criteria(root: &Element) -> bool { + root.name == "config-criteria" +} + +pub(super) fn build_csc_request(root: &Element, username: &str, gp_params: &GpParams) -> anyhow::Result { + let reader = SystemPreferenceReader; + build_csc_request_with_reader(root, username, gp_params, &reader) +} + +pub(super) fn build_csc_request_with_reader( + root: &Element, + username: &str, + gp_params: &GpParams, + reader: &dyn PreferenceReader, +) -> anyhow::Result { + let auth_cookie = root + .descendant_text("portal-csc-auth-cookie") + .filter(|value| !value.is_empty()) + .ok_or_else(|| anyhow::anyhow!("CSC criteria response does not contain portal-csc-auth-cookie"))?; + let config_digest = root.descendant_text("config-digest").unwrap_or_default(); + let host_id = collect_host_id(gp_params); + let serial_number = collect_serial_number(); + + let csc_data = build_csc_data( + root, + &auth_cookie, + username, + gp_params, + &host_id, + &serial_number, + DIGEST_PLACEHOLDER, + reader, + )?; + let csc_digest = format!("{:x}", md5::compute(csc_data.as_bytes())); + let csc_data = csc_data.replace(DIGEST_PLACEHOLDER, &csc_digest); + + Ok(CscRequest { + auth_cookie, + config_digest, + csc_digest, + csc_data, + host_id, + serial_number, + }) +} + +pub(super) fn csc_params<'a>( + req: &'a CscRequest, + username: &'a str, + gp_params: &'a GpParams, + swg_nonce: &'a str, +) -> HashMap<&'a str, &'a str> { + let mut params = HashMap::new(); + + params.insert("user", username); + params.insert("clientVer", "4100"); + params.insert("clientos", gp_params.client_os()); + params.insert("os-version", gp_params.os_version().unwrap_or_default()); + params.insert("hostid", req.host_id.as_str()); + params.insert("serialno", req.serial_number.as_str()); + params.insert("portal-cc-auth-cookie", req.auth_cookie.as_str()); + params.insert("config-digest", req.config_digest.as_str()); + params.insert("csc-digest", req.csc_digest.as_str()); + params.insert("csc-data", req.csc_data.as_str()); + params.insert("swg-auth-token", "0"); + params.insert("swg-nonce", swg_nonce); + + params +} + +fn build_csc_data( + criteria: &Element, + auth_cookie: &str, + username: &str, + gp_params: &GpParams, + host_id: &str, + serial_number: &str, + csc_digest: &str, + reader: &dyn PreferenceReader, +) -> anyhow::Result { + let mut root = Element::new("hip-report"); + push_text(&mut root, "portal-csc-auth-cookie", auth_cookie); + push_text(&mut root, "user-name", &urlencoding::encode(username)); + push_text(&mut root, "client-os", &client_os_report_value(gp_params)); + push_text(&mut root, "host-id", host_id); + push_text(&mut root, "device-serial-number", serial_number); + push_text(&mut root, "csc-digest", csc_digest); + root.children.push(XMLNode::Element(Element::new("categories"))); + root + .children + .push(XMLNode::Element(build_custom_checks(criteria, gp_params, reader))); + + let mut bytes = Vec::new(); + root.write_with_config( + &mut bytes, + EmitterConfig::new() + .perform_indent(true) + .write_document_declaration(true), + )?; + + String::from_utf8(bytes).map_err(Into::into) +} + +fn build_custom_checks(criteria: &Element, gp_params: &GpParams, reader: &dyn PreferenceReader) -> Element { + let mut custom_checks = Element::new("custom-checks"); + let Some(requested_checks) = criteria.descendant("custom-checks") else { + return custom_checks; + }; + + if let Some(mac_os) = requested_checks.child("mac-os") { + if let Some(plist) = mac_os.child("plist") { + custom_checks.children.push(XMLNode::Element(build_plist_checks( + plist, + gp_params.client_os() == "Mac", + reader, + ))); + } + } + + custom_checks +} + +fn build_plist_checks(plist: &Element, can_read: bool, reader: &dyn PreferenceReader) -> Element { + let mut out = Element::new("plist"); + + for entry in plist.children("entry") { + let domain = entry.attr("name").unwrap_or_default(); + let mut out_entry = Element::new("entry"); + out_entry.attributes.insert("name".to_string(), domain.to_string()); + + let keys = plist_entry_keys(entry); + let values: Vec<_> = keys + .iter() + .map(|key| { + let value = if can_read { + reader.read_preference(domain, key) + } else { + None + }; + (key.as_str(), value) + }) + .collect(); + let plist_exists = values.iter().any(|(_, value)| value.is_some()); + + push_text(&mut out_entry, "exist", yes_no(plist_exists)); + push_text(&mut out_entry, "value", ""); + + let mut preference_value = Element::new("preference-value"); + for (key, value) in values { + let mut pref_entry = Element::new("entry"); + pref_entry.attributes.insert("name".to_string(), key.to_string()); + push_text(&mut pref_entry, "exist", yes_no(value.is_some())); + push_text(&mut pref_entry, "value", value.as_deref().unwrap_or_default()); + preference_value.children.push(XMLNode::Element(pref_entry)); + } + + out_entry.children.push(XMLNode::Element(preference_value)); + out.children.push(XMLNode::Element(out_entry)); + } + + out +} + +fn plist_entry_keys(entry: &Element) -> Vec { + let keys: Vec = entry + .descendants("member") + .into_iter() + .filter_map(|element| element.get_text()) + .map(|text| text.to_string()) + .collect(); + + if keys.is_empty() { + entry + .attr("name") + .map(|name| vec![name.to_string()]) + .unwrap_or_default() + } else { + keys + } +} + +fn collect_host_id(gp_params: &GpParams) -> String { + match gp_params.client_os() { + "Mac" => netdev::get_default_interface() + .ok() + .and_then(|iface| iface.mac_addr.map(|mac| mac.address())) + .unwrap_or_default(), + "Windows" => host_utils::get_machine_id().to_string(), + _ => host_utils::derive_uuid(&[]), + } +} + +fn collect_serial_number() -> String { + collect_macos_serial_number() + .or_else(collect_linux_serial_number) + .or_else(collect_windows_serial_number) + .unwrap_or_default() +} + +fn collect_macos_serial_number() -> Option { + let output = Command::new("ioreg") + .args(["-rd1", "-c", "IOPlatformExpertDevice"]) + .output() + .ok()?; + let stdout = String::from_utf8(output.stdout).ok()?; + + stdout.lines().find_map(|line| { + line + .split_once("IOPlatformSerialNumber") + .and_then(|(_, value)| value.split_once('=')) + .map(|(_, value)| value.trim().trim_matches('"').to_string()) + .filter(|value| !value.is_empty()) + }) +} + +fn collect_linux_serial_number() -> Option { + ["/sys/class/dmi/id/product_serial", "/sys/class/dmi/id/product_uuid"] + .into_iter() + .filter_map(|path| fs::read_to_string(path).ok()) + .map(|value| value.trim().to_string()) + .find(|value| !value.is_empty() && value != "None" && value != "To Be Filled By O.E.M.") +} + +fn collect_windows_serial_number() -> Option { + let output = Command::new("wmic") + .args(["bios", "get", "serialnumber"]) + .output() + .ok()?; + let stdout = String::from_utf8(output.stdout).ok()?; + + stdout + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && *line != "SerialNumber") + .map(str::to_string) + .next() +} + +fn read_macos_preference(domain: &str, key: &str) -> Option { + if cfg!(not(target_os = "macos")) { + return None; + } + + let output = Command::new("defaults").args(["read", domain, key]).output().ok()?; + if !output.status.success() { + return None; + } + + String::from_utf8(output.stdout) + .ok() + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) +} + +fn client_os_report_value(gp_params: &GpParams) -> String { + gp_params + .os_version() + .unwrap_or_else(|| gp_params.client_os()) + .replace(' ', "+") +} + +fn push_text(parent: &mut Element, name: &str, value: &str) { + let mut element = Element::new(name); + element.children.push(XMLNode::Text(value.to_string())); + parent.children.push(XMLNode::Element(element)); +} + +fn yes_no(value: bool) -> &'static str { + if value { "yes" } else { "no" } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gp_params::{ClientOs, GpParams}; + + struct TestPreferenceReader { + values: HashMap, + } + + impl PreferenceReader for TestPreferenceReader { + fn read_preference(&self, domain: &str, key: &str) -> Option { + self.values.get(&format!("{domain}:{key}")).cloned() + } + } + + fn parse_xml(xml: &str) -> Element { + Element::parse(xml.as_bytes()).unwrap() + } + + fn gp_params(client_os: ClientOs) -> GpParams { + GpParams::builder() + .client_os(client_os) + .os_version(Some("Apple Mac OS X 26.4.1".to_string())) + .build() + } + + #[test] + fn detects_config_criteria_response() { + assert!(is_config_criteria(&parse_xml(""))); + assert!(!is_config_criteria(&parse_xml(""))); + } + + #[test] + fn builds_macos_plist_csc_report_with_existing_value() { + let root = parse_xml( + r#" + + + + + HipID + + + + + cookie + "#, + ); + let reader = TestPreferenceReader { + values: HashMap::from([( + "com.paloaltonetworks.GlobalProtect.settings:HipID".to_string(), + "MicroStrategyGP".to_string(), + )]), + }; + + let req = build_csc_request_with_reader(&root, "alice@example.com", &gp_params(ClientOs::Mac), &reader).unwrap(); + + assert_eq!(req.auth_cookie, "cookie"); + assert!(req.csc_data.contains("alice%40example.com")); + assert!(req.csc_data.contains("Apple+Mac+OS+X+26.4.1")); + assert!(req.csc_data.contains("yes")); + assert!(req.csc_data.contains("MicroStrategyGP")); + assert!( + req + .csc_data + .contains(&format!("{}", req.csc_digest)) + ); + assert!(!req.csc_data.contains(DIGEST_PLACEHOLDER)); + } + + #[test] + fn reports_missing_macos_plist_value() { + let root = parse_xml( + r#" + + + + Missing + + + + cookie + "#, + ); + let reader = TestPreferenceReader { values: HashMap::new() }; + + let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Mac), &reader).unwrap(); + + assert!(req.csc_data.contains("no")); + assert!(req.csc_data.contains("") || req.csc_data.contains("")); + } + + #[test] + fn unsupported_client_os_reports_macos_plist_missing() { + let root = parse_xml( + r#" + + + + HipID + + + + cookie + "#, + ); + let reader = TestPreferenceReader { + values: HashMap::from([("com.example:HipID".to_string(), "present".to_string())]), + }; + + let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Linux), &reader).unwrap(); + + assert!(req.csc_data.contains("no")); + assert!(!req.csc_data.contains("present")); + } + + #[test] + fn builds_getconfig_csc_params() { + let req = CscRequest { + auth_cookie: "cookie".to_string(), + config_digest: "config-digest".to_string(), + csc_digest: "csc-digest".to_string(), + csc_data: "hostserial" + .to_string(), + host_id: "host".to_string(), + serial_number: "serial".to_string(), + }; + let nonce = "123"; + let gp_params = gp_params(ClientOs::Mac); + let params = csc_params(&req, "alice", &gp_params, nonce); + + assert_eq!(params.get("user"), Some(&"alice")); + assert_eq!(params.get("hostid"), Some(&"host")); + assert_eq!(params.get("serialno"), Some(&"serial")); + assert_eq!(params.get("portal-cc-auth-cookie"), Some(&"cookie")); + assert_eq!(params.get("config-digest"), Some(&"config-digest")); + assert_eq!(params.get("csc-digest"), Some(&"csc-digest")); + assert_eq!(params.get("csc-data"), Some(&req.csc_data.as_str())); + assert_eq!(params.get("swg-auth-token"), Some(&"0")); + assert_eq!(params.get("swg-nonce"), Some(&"123")); + } +} diff --git a/crates/gpapi/src/portal/mod.rs b/crates/gpapi/src/portal/mod.rs index 8c111db..34618f6 100644 --- a/crates/gpapi/src/portal/mod.rs +++ b/crates/gpapi/src/portal/mod.rs @@ -1,4 +1,5 @@ mod config; +mod csc; mod prelogin; pub use config::*;