From 9a43880c4d791f9feea23ce09b019c99f6f04d5e Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Wed, 18 Nov 2026 18:08:01 +0800 Subject: [PATCH] fix: redact tunnel keys, preserve cached login and correct HIP handling --- Cargo.lock | 10 ++ apps/gpclient/src/connect/flow_tests.rs | 28 +++- apps/gpclient/src/connect/internal.rs | 19 ++- apps/gpservice/src/vpn_task/non_tunnel.rs | 11 +- crates/gp-xml/Cargo.toml | 11 ++ crates/gp-xml/src/lib.rs | 172 ++++++++++++++++++++++ crates/gpapi/Cargo.toml | 1 + crates/gpapi/src/gateway/login.rs | 5 +- crates/gpapi/src/hip.rs | 9 ++ crates/gpapi/src/portal/config.rs | 10 +- crates/gpapi/src/utils/mod.rs | 8 + crates/gpapi/src/utils/response_log.rs | 166 +-------------------- crates/gphip/src/lib.rs | 28 ++-- crates/gphip/src/windows_report.rs | 24 +++ crates/openconnect/Cargo.toml | 1 + crates/openconnect/src/ffi/mod.rs | 46 ++++++ packaging/windows/machine-install.ps1 | 51 +++++++ scripts/test-windows-installer.ps1 | 8 +- 18 files changed, 412 insertions(+), 196 deletions(-) create mode 100644 crates/gp-xml/Cargo.toml create mode 100644 crates/gp-xml/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 48e5d07..594e74f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2131,6 +2131,14 @@ dependencies = [ "system-deps", ] +[[package]] +name = "gp-xml" +version = "3.4.0" +dependencies = [ + "url", + "xmltree", +] + [[package]] name = "gpapi" version = "3.4.0" @@ -2149,6 +2157,7 @@ dependencies = [ "env_logger", "file-rotate", "getrandom 0.4.3", + "gp-xml", "gtk", "humantime", "libloading 0.9.0", @@ -3856,6 +3865,7 @@ dependencies = [ "autotools", "cc", "fs_extra", + "gp-xml", "is_executable", "libc", "log", diff --git a/apps/gpclient/src/connect/flow_tests.rs b/apps/gpclient/src/connect/flow_tests.rs index 2852e5a..b3253f3 100644 --- a/apps/gpclient/src/connect/flow_tests.rs +++ b/apps/gpclient/src/connect/flow_tests.rs @@ -174,15 +174,21 @@ async fn unreachable_gateway_keeps_cached_cookie() { #[tokio::test] async fn gateway_closing_without_response_keeps_cached_cookie() { - closed_connection_keeps_cached_cookie(false).await; + closed_connection_keeps_cached_cookie(false, false).await; } #[tokio::test] async fn portal_closing_without_response_keeps_cached_cookie() { - closed_connection_keeps_cached_cookie(true).await; + closed_connection_keeps_cached_cookie(true, false).await; } -async fn closed_connection_keeps_cached_cookie(portal_discovery: bool) { +#[tokio::test] +async fn partial_responses_keep_cached_cookie() { + closed_connection_keeps_cached_cookie(false, true).await; + closed_connection_keeps_cached_cookie(true, true).await; +} + +async fn closed_connection_keeps_cached_cookie(portal_discovery: bool, partial_body: bool) { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let origin = format!("http://{}", listener.local_addr().unwrap()); let worker = tokio::spawn(async move { @@ -203,8 +209,14 @@ async fn closed_connection_keeps_cached_cookie(portal_discovery: bool) { .unwrap(); } let (mut stream, _) = listener.accept().await.unwrap(); - // Read the complete request, then close without sending HTTP headers. - read_request(&mut stream).await + let request = read_request(&mut stream).await; + if partial_body { + stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n") + .await + .unwrap(); + } + request }) .await .expect("Connection-closing fixture timed out") @@ -248,7 +260,11 @@ async fn closed_connection_keeps_cached_cookie(portal_discovery: bool) { let Some(gpapi::error::PortalError::NetworkError(network)) = error.downcast_ref() else { panic!("Expected a network error, got {error:?}"); }; - assert!(network.is_request()); + if partial_body { + assert!(network.is_body() || network.is_decode()); + } else { + assert!(network.is_request()); + } assert!(!network.is_connect()); assert!(!network.is_timeout()); assert!(cache.exists(), "an unanswered request must not delete the cookie cache"); diff --git a/apps/gpclient/src/connect/internal.rs b/apps/gpclient/src/connect/internal.rs index 8e0e9a0..f928d0c 100644 --- a/apps/gpclient/src/connect/internal.rs +++ b/apps/gpclient/src/connect/internal.rs @@ -128,15 +128,18 @@ impl ConnectHandler<'_> { produce_report: Arc::new(move |request, control| { control.check()?; if matches!(source.as_ref(), openconnect::HipSource::Disabled) { - return gphip::generate_identity_report(&gphip::ReportInput { - profile: profile.clone(), - context: gphip::ReportContext::Connected { - cookie: request.cookie.clone(), - client_ip: request.client_ip.clone(), - client_ipv6: request.client_ipv6.clone(), - md5: request.md5.clone(), + return gphip::generate_identity_report( + &gphip::ReportInput { + profile: profile.clone(), + context: gphip::ReportContext::Connected { + cookie: request.cookie.clone(), + client_ip: request.client_ip.clone(), + client_ipv6: request.client_ipv6.clone(), + md5: request.md5.clone(), + }, }, - }) + control, + ) .map_err(std::io::Error::other); } source.collect( diff --git a/apps/gpservice/src/vpn_task/non_tunnel.rs b/apps/gpservice/src/vpn_task/non_tunnel.rs index aa3bcb6..a012019 100644 --- a/apps/gpservice/src/vpn_task/non_tunnel.rs +++ b/apps/gpservice/src/vpn_task/non_tunnel.rs @@ -66,10 +66,13 @@ pub(super) async fn run( md5: request.md5.clone(), }; if !posture_enabled { - return gphip::generate_identity_report(&gphip::ReportInput { - profile: profile.clone(), - context, - }) + return gphip::generate_identity_report( + &gphip::ReportInput { + profile: profile.clone(), + context, + }, + control, + ) .map_err(std::io::Error::other); } source.collect( diff --git a/crates/gp-xml/Cargo.toml b/crates/gp-xml/Cargo.toml new file mode 100644 index 0000000..92a39bb --- /dev/null +++ b/crates/gp-xml/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "gp-xml" +edition.workspace = true +rust-version.workspace = true +version.workspace = true +license = "MIT" +description = "GlobalProtect response XML redaction for diagnostics" + +[dependencies] +url.workspace = true +xmltree.workspace = true diff --git a/crates/gp-xml/src/lib.rs b/crates/gp-xml/src/lib.rs new file mode 100644 index 0000000..9ba6697 --- /dev/null +++ b/crates/gp-xml/src/lib.rs @@ -0,0 +1,172 @@ +//! Redact GlobalProtect response bodies before writing diagnostics. +use xmltree::{Element, EmitterConfig, XMLNode}; + +const REDACTED: &str = "[redacted]"; +const MAX_XML_BYTES: usize = 1024 * 1024; + +pub fn redact_xml(body: &[u8]) -> String { + if body.len() > MAX_XML_BYTES { + return "[XML omitted: exceeds 1 MiB]".into(); + } + let Ok(text) = std::str::from_utf8(body) else { + return "[XML omitted: invalid UTF-8]".into(); + }; + if text.to_ascii_lowercase().contains(" Some(element), + _ => None, + }); + let Some(mut root) = roots.next() else { + return "[XML omitted: no document element]".into(); + }; + if roots.next().is_some() || root.name.eq_ignore_ascii_case("html") { + return "[XML omitted: unsupported response document]".into(); + } + redact_element(&mut root); + let mut output = Vec::new(); + if root + .write_with_config( + &mut output, + EmitterConfig::new() + .perform_indent(true) + .write_document_declaration(false), + ) + .is_err() + { + return "[XML omitted: serialization failed]".into(); + } + String::from_utf8(output).unwrap_or_else(|_| "[XML omitted: serialization failed]".into()) +} + +fn sensitive_name(name: &str) -> bool { + let name: String = name + .chars() + .filter(char::is_ascii_alphanumeric) + .map(|c| c.to_ascii_lowercase()) + .collect(); + if name.ends_with("label") { + return false; + } + name.contains("cookie") + || name.contains("token") + || name.contains("password") + || name.contains("passphrase") + || name.contains("secret") + || name.starts_with("ekey") + || name.starts_with("akey") + || matches!( + name.as_str(), + "argument" + | "samlrequest" + | "samlresponse" + | "samlrequestid" + | "assertion" + | "encryptedassertion" + | "authnrequest" + | "challenge" + | "privatekey" + | "encryptionkey" + | "enckey" + | "hskey" + | "enchskey" + | "tunnelopaque" + | "nonce" + | "user" + | "username" + | "ccusername" + | "credential" + ) +} + +fn redact_element(element: &mut Element) { + let named_secret = matches!(element.name.as_str(), "field" | "param" | "property" | "setting") + && ["name", "key"] + .iter() + .any(|name| element.attributes.get(*name).is_some_and(|value| sensitive_name(value))); + let secret = sensitive_name(&element.name) || named_secret; + for (name, value) in &mut element.attributes { + if sensitive_name(name) || (secret && !(named_secret && matches!(name.as_str(), "name" | "key"))) { + *value = REDACTED.into(); + } else { + *value = redact_url(value); + } + } + if secret { + element.children = vec![XMLNode::Text(REDACTED.into())]; + return; + } + element + .children + .retain(|node| matches!(node, XMLNode::Element(_) | XMLNode::Text(_) | XMLNode::CData(_))); + for node in &mut element.children { + match node { + XMLNode::Element(child) => redact_element(child), + XMLNode::Text(value) | XMLNode::CData(value) => *value = redact_url(value), + _ => {} + } + } +} + +fn redact_url(value: &str) -> String { + let Ok(mut url) = url::Url::parse(value) else { + return value.into(); + }; + if !matches!(url.scheme(), "http" | "https") { + return value.into(); + } + if !url.username().is_empty() { + let _ = url.set_username(REDACTED); + } + if url.password().is_some() { + let _ = url.set_password(Some(REDACTED)); + } + if url.query().is_some() { + let pairs: Vec<_> = url + .query_pairs() + .map(|(name, _)| (name.into_owned(), REDACTED)) + .collect(); + url.query_pairs_mut().clear().extend_pairs(pairs); + } + if url.fragment().is_some() { + url.set_fragment(Some(REDACTED)); + } + url.to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn redacts_positional_login_arguments_and_session_keys() { + let xml = redact_xml(br#"fixture-auth-cookiefixture-user256fixture-key-c2sfixture-key-s2cfixture-auth-c2sfixture-auth-s2cfixture-hs-keyfixture-private-keyfixture-saml-responsefixture-opaque1400"#); + assert!(!xml.contains("fixture-")); + assert!(xml.contains("1400")); + Element::parse(xml.as_bytes()).unwrap(); + } + + #[test] + fn omits_unparseable_html_dtd_and_oversized_bodies_without_echoing_them() { + for body in [ + b"not XML fixture-secret".as_slice(), + b"fixture-secret", + b"fixture-secret", + b"]>&secret;", + b"fixture-secret", + b"\xfffixture-secret", + ] { + let xml = redact_xml(body); + assert!(xml.starts_with("[XML omitted:")); + assert!(!xml.contains("fixture-secret")); + } + assert_eq!( + redact_xml(&vec![b'x'; MAX_XML_BYTES + 1]), + "[XML omitted: exceeds 1 MiB]" + ); + } +} diff --git a/crates/gpapi/Cargo.toml b/crates/gpapi/Cargo.toml index e3d402f..475a0e7 100644 --- a/crates/gpapi/Cargo.toml +++ b/crates/gpapi/Cargo.toml @@ -6,6 +6,7 @@ edition.workspace = true license = "MIT" [dependencies] +gp-xml = { path = "../gp-xml" } common = { path = "../common" } anyhow.workspace = true base64.workspace = true diff --git a/crates/gpapi/src/gateway/login.rs b/crates/gpapi/src/gateway/login.rs index d52661d..5c9b82c 100644 --- a/crates/gpapi/src/gateway/login.rs +++ b/crates/gpapi/src/gateway/login.rs @@ -202,7 +202,7 @@ async fn receive_gateway_login( let url = res.url().clone(); let http_version = res.version(); let content_type = res.headers().get(reqwest::header::CONTENT_TYPE).cloned(); - let res = parse_gp_response(res).await.map_err(|err| { + let res = parse_gp_response(res).await.map_err(|mut err| { // Redirect paths and query strings can contain authentication tokens. Log // only the redacted origin and whether the response is from the login path. warn!( @@ -221,6 +221,9 @@ async fn receive_gateway_login( if let Some(tls) = crate::error::ServerTlsError::from_request(origin, &err, gp_params.has_client_identity()) { return tls; } + if let Some(error) = err.take_body_read_error() { + return PortalError::NetworkError(error).into(); + } if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() { return anyhow::anyhow!(crate::error::AuthenticationRejected); } diff --git a/crates/gpapi/src/hip.rs b/crates/gpapi/src/hip.rs index 6c3829f..173716e 100644 --- a/crates/gpapi/src/hip.rs +++ b/crates/gpapi/src/hip.rs @@ -59,4 +59,13 @@ pub struct HipReport { pub struct WindowsUpdateStatus { /// Present only when this report includes a completed local patch observation. pub checked_at: Option, + /// Time of the observed snapshot when its patch details were too large to include. + #[serde(skip_serializing_if = "Option::is_none")] + pub omitted_snapshot_at: Option, +} + +impl WindowsUpdateStatus { + pub fn refresh_cursor(&self) -> Option { + self.checked_at.or(self.omitted_snapshot_at) + } } diff --git a/crates/gpapi/src/portal/config.rs b/crates/gpapi/src/portal/config.rs index 0efef57..7d7ddc5 100644 --- a/crates/gpapi/src/portal/config.rs +++ b/crates/gpapi/src/portal/config.rs @@ -207,10 +207,13 @@ pub async fn retrieve_config( } })?; - parse_gp_response(res).await.or_else(|err| { + parse_gp_response(res).await.or_else(|mut err| { if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) { return Err(tls); } + if let Some(error) = err.take_body_read_error() { + return Err(PortalError::NetworkError(error).into()); + } if gp_params.os_profile().client_os() == crate::os_profile::ClientOs::Ios && err.is_authentication_rejection() { return Err(anyhow::anyhow!(crate::error::AuthenticationRejected)); } @@ -278,10 +281,13 @@ async fn retrieve_csc_config( } })?; - parse_gp_response(res).await.or_else(|err| { + parse_gp_response(res).await.or_else(|mut err| { if let Some(tls) = ServerTlsError::from_request(&server_url, &err, gp_params.has_client_identity()) { return Err(tls); } + if let Some(error) = err.take_body_read_error() { + return Err(PortalError::NetworkError(error).into()); + } if err.status == StatusCode::NOT_FOUND { bail!(PortalError::ConfigError("CSC config endpoint not found".to_string())); } diff --git a/crates/gpapi/src/utils/mod.rs b/crates/gpapi/src/utils/mod.rs index 9f41643..2556261 100644 --- a/crates/gpapi/src/utils/mod.rs +++ b/crates/gpapi/src/utils/mod.rs @@ -64,6 +64,14 @@ pub struct GpError { } impl GpError { + pub(crate) fn take_body_read_error(&mut self) -> Option { + if self.is_status_error() { + None + } else { + self.source.take() + } + } + pub fn is_status_error(&self) -> bool { self.status.is_client_error() || self.status.is_server_error() } diff --git a/crates/gpapi/src/utils/response_log.rs b/crates/gpapi/src/utils/response_log.rs index a48d1c9..8a724b2 100644 --- a/crates/gpapi/src/utils/response_log.rs +++ b/crates/gpapi/src/utils/response_log.rs @@ -1,8 +1,5 @@ +use gp_xml::redact_xml; use reqwest::StatusCode; -use xmltree::{Element, EmitterConfig, XMLNode}; - -const REDACTED: &str = "[redacted]"; -const MAX_XML_BYTES: usize = 1024 * 1024; pub(crate) fn log_response_xml(path: &str, status: StatusCode, body: &[u8]) { if !log::log_enabled!(log::Level::Debug) { @@ -28,141 +25,10 @@ pub(crate) fn log_response_xml(path: &str, status: StatusCode, body: &[u8]) { } } -fn redact_xml(body: &[u8]) -> String { - if body.len() > MAX_XML_BYTES { - return "[XML omitted: exceeds 1 MiB]".into(); - } - let Ok(text) = std::str::from_utf8(body) else { - return "[XML omitted: invalid UTF-8]".into(); - }; - if text.to_ascii_lowercase().contains(" Some(element), - _ => None, - }); - let Some(mut root) = roots.next() else { - return "[XML omitted: no document element]".into(); - }; - if roots.next().is_some() || root.name.eq_ignore_ascii_case("html") { - return "[XML omitted: unsupported response document]".into(); - } - redact_element(&mut root); - let mut output = Vec::new(); - if root - .write_with_config( - &mut output, - EmitterConfig::new() - .perform_indent(true) - .write_document_declaration(false), - ) - .is_err() - { - return "[XML omitted: serialization failed]".into(); - } - String::from_utf8(output).unwrap_or_else(|_| "[XML omitted: serialization failed]".into()) -} - -fn sensitive_name(name: &str) -> bool { - let name: String = name - .chars() - .filter(char::is_ascii_alphanumeric) - .map(|c| c.to_ascii_lowercase()) - .collect(); - if name.ends_with("label") { - return false; - } - name.contains("cookie") - || name.contains("token") - || name.contains("password") - || name.contains("passphrase") - || name.contains("secret") - || name.starts_with("ekey") - || matches!( - name.as_str(), - "argument" - | "samlrequest" - | "samlresponse" - | "samlrequestid" - | "assertion" - | "encryptedassertion" - | "authnrequest" - | "challenge" - | "privatekey" - | "encryptionkey" - | "enckey" - | "enchskey" - | "tunnelopaque" - | "nonce" - | "user" - | "username" - | "ccusername" - | "credential" - ) -} - -fn redact_element(element: &mut Element) { - let named_secret = matches!(element.name.as_str(), "field" | "param" | "property" | "setting") - && ["name", "key"] - .iter() - .any(|name| element.attributes.get(*name).is_some_and(|value| sensitive_name(value))); - let secret = sensitive_name(&element.name) || named_secret; - for (name, value) in &mut element.attributes { - if sensitive_name(name) || (secret && !(named_secret && matches!(name.as_str(), "name" | "key"))) { - *value = REDACTED.into(); - } else { - *value = redact_url(value); - } - } - if secret { - element.children = vec![XMLNode::Text(REDACTED.into())]; - return; - } - element - .children - .retain(|node| matches!(node, XMLNode::Element(_) | XMLNode::Text(_) | XMLNode::CData(_))); - for node in &mut element.children { - match node { - XMLNode::Element(child) => redact_element(child), - XMLNode::Text(value) | XMLNode::CData(value) => *value = redact_url(value), - _ => {} - } - } -} - -fn redact_url(value: &str) -> String { - let Ok(mut url) = url::Url::parse(value) else { - return value.into(); - }; - if !matches!(url.scheme(), "http" | "https") { - return value.into(); - } - if !url.username().is_empty() { - let _ = url.set_username(REDACTED); - } - if url.password().is_some() { - let _ = url.set_password(Some(REDACTED)); - } - if url.query().is_some() { - let pairs: Vec<_> = url - .query_pairs() - .map(|(name, _)| (name.into_owned(), REDACTED)) - .collect(); - url.query_pairs_mut().clear().extend_pairs(pairs); - } - if url.fragment().is_some() { - url.set_fragment(Some(REDACTED)); - } - url.to_string() -} - #[cfg(test)] mod tests { use super::*; + use xmltree::Element; #[test] fn preserves_policy_checks_and_redacts_authentication_material() { @@ -190,32 +56,4 @@ mod tests { } assert_eq!(root.name, "policy"); } - - #[test] - fn redacts_positional_login_arguments_and_session_keys() { - let xml = redact_xml(br#"fixture-auth-cookiefixture-user256fixture-key-c2sfixture-key-s2cfixture-hs-keyfixture-private-keyfixture-saml-responsefixture-opaque1400"#); - assert!(!xml.contains("fixture-")); - assert!(xml.contains("1400")); - Element::parse(xml.as_bytes()).unwrap(); - } - - #[test] - fn omits_unparseable_html_dtd_and_oversized_bodies_without_echoing_them() { - for body in [ - b"not XML fixture-secret".as_slice(), - b"fixture-secret", - b"fixture-secret", - b"]>&secret;", - b"fixture-secret", - b"\xfffixture-secret", - ] { - let xml = redact_xml(body); - assert!(xml.starts_with("[XML omitted:")); - assert!(!xml.contains("fixture-secret")); - } - assert_eq!( - redact_xml(&vec![b'x'; MAX_XML_BYTES + 1]), - "[XML omitted: exceeds 1 MiB]" - ); - } } diff --git a/crates/gphip/src/lib.rs b/crates/gphip/src/lib.rs index 6fbfdc1..333b489 100644 --- a/crates/gphip/src/lib.rs +++ b/crates/gphip/src/lib.rs @@ -246,11 +246,10 @@ pub fn generate_report(input: &ReportInput) -> anyhow::Result { /// Identity-only maintenance report. This deliberately does not enumerate the /// interfaces or execute posture collectors; addresses come from the session owner. /// Native profiles read the computer domain, consistent with generated and refreshed reports. -pub fn generate_identity_report(input: &ReportInput) -> anyhow::Result { +pub fn generate_identity_report(input: &ReportInput, control: &dyn CollectionControl) -> anyhow::Result { let params = cookie_params(input); - let budget = CollectionBudget::new(Duration::from_secs(60)); let domain = - native_domain(&input.profile, &budget)?.unwrap_or_else(|| params.get("domain").cloned().unwrap_or_default()); + native_domain(&input.profile, control)?.unwrap_or_else(|| params.get("domain").cloned().unwrap_or_default()); let mut report = Element::new("hip-report"); for (name, value) in [ ("md5-sum", input.context.md5()), @@ -569,9 +568,7 @@ impl<'p, 'a> HostInfoCollector<'p, 'a> { #[cfg(windows)] if self.profile.client_os() == ClientOs::Windows && self.profile.is_native() { let report = windows::collect(&commands, control)?; - info.windows_updates = Some(gpapi::hip::WindowsUpdateStatus { - checked_at: report.patches_checked_at, - }); + info.windows_updates = Some(report.update_status()); info.windows_categories = Some(report.render()?); } @@ -813,6 +810,17 @@ mod tests { gpapi::os_profile::desktop::collect_profile(OsProfileBuilder::new(client_os), None) } + #[test] + fn cancelled_identity_report_stops_before_domain_collection() { + let input = make_input(make_profile(ClientOs::Linux)); + let cancelled = || Err(io::Error::from(io::ErrorKind::Interrupted)); + let error = generate_identity_report(&input, &cancelled).unwrap_err(); + assert_eq!( + error.downcast_ref::().unwrap().kind(), + io::ErrorKind::Interrupted + ); + } + #[test] fn identity_report_contains_session_identity_without_posture() { for os in [ClientOs::Linux, ClientOs::Mac, ClientOs::Windows] { @@ -823,7 +831,7 @@ mod tests { client_ipv6: Some("2001:db8::7".into()), md5: "identity-token".into(), }; - let xml = generate_identity_report(&input).unwrap(); + let xml = generate_identity_report(&input, &|| Ok(())).unwrap(); let root = Element::parse(xml.as_bytes()).unwrap(); assert_eq!( unique_child(&root, "user-name").unwrap().get_text().unwrap(), @@ -988,7 +996,7 @@ mod tests { "emulated-domain.internal" ); assert!(report.contains("emulated-domain.internal")); - let identity = Element::parse(generate_identity_report(&input).unwrap().as_bytes()).unwrap(); + let identity = Element::parse(generate_identity_report(&input, &|| Ok(())).unwrap().as_bytes()).unwrap(); assert_eq!( unique_child(&identity, "domain").unwrap().get_text().unwrap(), "emulated-domain" @@ -1063,7 +1071,7 @@ mod tests { expected_domain ); } - let identity = Element::parse(generate_identity_report(&input).unwrap().as_bytes()).unwrap(); + let identity = Element::parse(generate_identity_report(&input, &|| Ok(())).unwrap().as_bytes()).unwrap(); assert_eq!( unique_child(&identity, "domain").unwrap().get_text().unwrap(), "emulated-domain" @@ -1128,7 +1136,7 @@ mod tests { set_field(host_info_mut(&mut stale).unwrap(), "domain", "stale.internal").unwrap(); let refreshed = refresh_edited_report(&write_xml(&stale).unwrap(), &input).unwrap(); let refreshed = validate_edited_report(&refreshed).unwrap(); - let identity = Element::parse(generate_identity_report(&input).unwrap().as_bytes()).unwrap(); + let identity = Element::parse(generate_identity_report(&input, &|| Ok(())).unwrap().as_bytes()).unwrap(); for report in [&generated, &refreshed, &identity] { assert_eq!( unique_child(report, "domain") diff --git a/crates/gphip/src/windows_report.rs b/crates/gphip/src/windows_report.rs index 5d20347..00579c5 100644 --- a/crates/gphip/src/windows_report.rs +++ b/crates/gphip/src/windows_report.rs @@ -85,6 +85,16 @@ impl MissingPatch { } impl WindowsReport { + pub(super) fn update_status(&self) -> gpapi::hip::WindowsUpdateStatus { + let mut status = gpapi::hip::WindowsUpdateStatus::default(); + if self.missing_patches.is_some() { + status.checked_at = self.patches_checked_at; + } else { + status.omitted_snapshot_at = self.patches_checked_at; + } + status + } + pub fn render(&self) -> std::io::Result { let mut categories = Vec::new(); categories.push(category( @@ -245,6 +255,20 @@ fn category(name: &str, products: impl Iterator) -> Element { mod tests { use super::*; + #[test] + fn omitted_snapshot_can_be_refreshed_without_claiming_patch_details() { + let mut report = WindowsReport::default(); + assert_eq!(report.update_status().refresh_cursor(), None); + report.patches_checked_at = Some(123); + let status = report.update_status(); + assert_eq!(status.checked_at, None); + assert_eq!(status.refresh_cursor(), Some(123)); + assert!(!report.render().unwrap().contains("missing-patches")); + report.missing_patches = Some(Vec::new()); + assert_eq!(report.update_status().checked_at, Some(123)); + assert_eq!(report.update_status().refresh_cursor(), Some(123)); + } + #[test] fn real_posture_preserves_unavailable_values_and_escapes_product_text() { let report: WindowsReport = serde_json::from_str( diff --git a/crates/openconnect/Cargo.toml b/crates/openconnect/Cargo.toml index 2b6e7cb..5338b97 100644 --- a/crates/openconnect/Cargo.toml +++ b/crates/openconnect/Cargo.toml @@ -7,6 +7,7 @@ license = "MIT" links = "openconnect" [dependencies] +gp-xml = { path = "../gp-xml" } log.workspace = true libc = "0.2" is_executable.workspace = true diff --git a/crates/openconnect/src/ffi/mod.rs b/crates/openconnect/src/ffi/mod.rs index 7dcd3ac..ed79f3e 100644 --- a/crates/openconnect/src/ffi/mod.rs +++ b/crates/openconnect/src/ffi/mod.rs @@ -153,6 +153,14 @@ extern "C" fn on_vpn_connected(pipe_fd: CommandHandle, session_info: *const VpnS extern "C" fn vpn_log(level: i32, message: *const c_char) { let message = unsafe { std::ffi::CStr::from_ptr(message) }; let message = message.to_str().unwrap_or("Invalid log message"); + // This dump comes from the native GlobalProtect protocol handler. + if let Some(body) = message.strip_prefix("GlobalProtect getconfig.esp response:\n") { + debug!( + "GlobalProtect getconfig.esp response:\n{}", + gp_xml::redact_xml(body.as_bytes()) + ); + return; + } // Strip the trailing newline let message = message.trim_end_matches('\n'); @@ -172,3 +180,41 @@ extern "C" fn vpn_log(level: i32, message: *const c_char) { debug!("{}", message); } } + +#[cfg(test)] +mod log_tests { + use super::vpn_log; + use std::sync::Mutex; + + struct Capture(Mutex); + impl log::Log for Capture { + fn enabled(&self, _: &log::Metadata<'_>) -> bool { + true + } + fn flush(&self) {} + fn log(&self, record: &log::Record<'_>) { + if record.target() == module_path!().trim_end_matches("::log_tests") { + self.0.lock().unwrap().push_str(&record.args().to_string()); + } + } + } + + #[test] + fn native_config_dump_keeps_settings_and_redacts_keys_before_logging() { + static CAPTURE: Capture = Capture(Mutex::new(String::new())); + log::set_logger(&CAPTURE).unwrap(); + log::set_max_level(log::LevelFilter::Debug); + let message = c"GlobalProtect getconfig.esp response:\n1400fixture-secret128fixture-handshake-key\n"; + vpn_log(2, message.as_ptr()); + vpn_log( + 2, + c"GlobalProtect getconfig.esp response:\nfixture-secret".as_ptr(), + ); + let output = CAPTURE.0.lock().unwrap(); + assert!(output.contains("1400")); + assert!(output.contains("[redacted]")); + assert!(output.contains("[XML omitted:")); + assert!(!output.contains("fixture-secret")); + assert!(!output.contains("fixture-handshake-key")); + } +} diff --git a/packaging/windows/machine-install.ps1 b/packaging/windows/machine-install.ps1 index cee5a99..0f8d132 100644 --- a/packaging/windows/machine-install.ps1 +++ b/packaging/windows/machine-install.ps1 @@ -144,6 +144,56 @@ function Set-MachineState { } finally { $registry.Dispose() } } +# WScript.Shell creates the link but does not expose its shell property store. +function Set-ShortcutAppId([string]$Path, [string]$AppId) { + if (-not ('GPConnectShortcutProperties' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; + +public static class GPConnectShortcutProperties { + [StructLayout(LayoutKind.Sequential)] + struct PropertyKey { public Guid format; public uint id; } + + [StructLayout(LayoutKind.Explicit, Size = 24)] + struct StringPropVariant { + [FieldOffset(0)] public ushort type; + [FieldOffset(8)] public IntPtr text; + } + + [ComImport, Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + interface IPropertyStore { + void GetCount(out uint count); + void GetAt(uint index, out PropertyKey key); + void GetValue(ref PropertyKey key, IntPtr value); + void SetValue(ref PropertyKey key, ref StringPropVariant value); + void Commit(); + } + + [DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = false)] + static extern void SHGetPropertyStoreFromParsingName(string path, IntPtr context, uint flags, + ref Guid iid, [MarshalAs(UnmanagedType.Interface)] out IPropertyStore store); + + public static void SetAppId(string path, string appId) { + Guid iid = typeof(IPropertyStore).GUID; + IPropertyStore store; + SHGetPropertyStoreFromParsingName(path, IntPtr.Zero, 2 /* GPS_READWRITE */, ref iid, out store); + var key = new PropertyKey { format = new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), id = 5 }; + var value = new StringPropVariant { type = 31 /* VT_LPWSTR */, text = Marshal.StringToCoTaskMemUni(appId) }; + try { + store.SetValue(ref key, ref value); + store.Commit(); + } finally { + Marshal.FreeCoTaskMem(value.text); + Marshal.ReleaseComObject(store); + } + } +} +'@ + } + [GPConnectShortcutProperties]::SetAppId($Path, $AppId) +} + function Set-InstallationMetadata([string]$InstalledVersion) { $shell = New-Object -ComObject WScript.Shell $shortcut = $shell.CreateShortcut($shortcutPath) @@ -152,6 +202,7 @@ function Set-InstallationMetadata([string]$InstalledVersion) { $shortcut.Description = 'A GUI client for GlobalProtect VPN' $shortcut.IconLocation = (Join-Path $destination 'gpgui.exe') + ',0' $shortcut.Save() + Set-ShortcutAppId $shortcutPath 'com.yuezk.gpgui' if (Test-Path -LiteralPath (Join-Path $destination 'uninstall.exe')) { New-Item -Path $uninstallKey -Force | Out-Null $values = @{ diff --git a/scripts/test-windows-installer.ps1 b/scripts/test-windows-installer.ps1 index c50f7fd..2e6a733 100644 --- a/scripts/test-windows-installer.ps1 +++ b/scripts/test-windows-installer.ps1 @@ -18,6 +18,13 @@ if ($process.ExitCode -ne 0) { if (Test-Path $log) { Get-Content $log -Tail 80 | Write-Host } throw "The installer failed with exit code $($process.ExitCode)." } +$shortcut = Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs\GP Connect.lnk' +$shell = New-Object -ComObject Shell.Application +$folder = $shell.Namespace((Split-Path $shortcut)) +$link = $folder.ParseName((Split-Path $shortcut -Leaf)) +if (!$link -or $link.ExtendedProperty('System.AppUserModel.ID') -ne 'com.yuezk.gpgui') { + throw 'The Start menu shortcut is missing the GP Connect notification identity.' +} $info = Get-Content (Join-Path $destination 'build-info.json') -Raw | ConvertFrom-Json if ($info.architecture -ne $Architecture -or [string]$info.build_version -ne $Build) { throw 'The installed package identity does not match.' } $service = Get-CimInstance Win32_Service -Filter "Name='GPConnect'" @@ -44,7 +51,6 @@ if ($process.ExitCode -ne 0) { throw 'The uninstaller failed.' } if ((Get-Service GPConnect -ErrorAction SilentlyContinue) -or (Test-Path $destination) -or (Test-Path ($destination + '.previous'))) { throw 'The uninstaller left service registration or runtime files.' } -$shortcut = Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs\GP Connect.lnk' if ((Test-Path $shortcut) -or (Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\GPConnect')) { throw 'The uninstaller left its shortcut or registration.' }