mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
merge: reconcile reviewed desktop fixes for the next snapshot
This commit is contained in:
25 files changed
+791
-261
No files matched your search
Generated
+10
@@ -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",
|
||||
|
||||
@@ -36,6 +36,27 @@ fn login_response() -> String {
|
||||
)
|
||||
}
|
||||
|
||||
async fn read_request(stream: &mut tokio::net::TcpStream) -> String {
|
||||
let mut request = Vec::new();
|
||||
loop {
|
||||
let mut buf = [0; 4096];
|
||||
let count = stream.read(&mut buf).await.unwrap();
|
||||
assert_ne!(count, 0, "Request ended before its body");
|
||||
request.extend_from_slice(&buf[..count]);
|
||||
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
|
||||
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length:"))
|
||||
.map(|value| value.trim().parse::<usize>().unwrap())
|
||||
.unwrap_or(0);
|
||||
if request.len() >= end + 4 + length {
|
||||
return String::from_utf8(request).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task::JoinHandle<Vec<String>>) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
@@ -44,25 +65,7 @@ async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task
|
||||
let mut requests = Vec::new();
|
||||
for (status, body) in responses {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let mut request = Vec::new();
|
||||
loop {
|
||||
let mut buf = [0; 4096];
|
||||
let count = stream.read(&mut buf).await.unwrap();
|
||||
assert_ne!(count, 0, "Request ended before its body");
|
||||
request.extend_from_slice(&buf[..count]);
|
||||
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
|
||||
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
|
||||
let length = headers
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length:"))
|
||||
.map(|value| value.trim().parse::<usize>().unwrap())
|
||||
.unwrap_or(0);
|
||||
if request.len() >= end + 4 + length {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
requests.push(String::from_utf8(request).unwrap());
|
||||
requests.push(read_request(&mut stream).await);
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
@@ -126,6 +129,154 @@ async fn cached_tunnel_authentication_does_not_require_portal_discovery() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unreachable_gateway_keeps_cached_cookie() {
|
||||
// Nothing listens here: the cached gateway login gets no answer at all.
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let gateway = format!("http://{}", listener.local_addr().unwrap());
|
||||
drop(listener);
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let cache = directory.path().join("cookie.json");
|
||||
let args = TestArgs::parse_from([
|
||||
"test",
|
||||
"http://unavailable-portal.invalid",
|
||||
"--cookie-only",
|
||||
"--cookie-cache",
|
||||
cache.to_str().unwrap(),
|
||||
])
|
||||
.connect;
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
cookie_store::save(
|
||||
&cache,
|
||||
&StoredCookie::new(
|
||||
args.server.clone(),
|
||||
"alice".into(),
|
||||
handler.os_profile.borrow().host_identity().host_id().into(),
|
||||
gateway,
|
||||
AuthCookieCredential::new("alice", "portal-cookie", ""),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(handler.handle_impl().await.is_err());
|
||||
assert!(
|
||||
cache.exists(),
|
||||
"a login that got no answer must not delete the cookie cache"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gateway_closing_without_response_keeps_cached_cookie() {
|
||||
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, false).await;
|
||||
}
|
||||
|
||||
#[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 {
|
||||
tokio::time::timeout(Duration::from_secs(5), async move {
|
||||
if portal_discovery {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
assert!(read_request(&mut stream).await.contains("/global-protect/prelogin.esp"));
|
||||
let body = "<prelogin-response><status>Success</status></prelogin-response>";
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
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<response>")
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
request
|
||||
})
|
||||
.await
|
||||
.expect("Connection-closing fixture timed out")
|
||||
});
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let cache = directory.path().join("cookie.json");
|
||||
let args = TestArgs::parse_from([
|
||||
"test",
|
||||
&origin,
|
||||
"--cookie-only",
|
||||
"--cookie-cache",
|
||||
cache.to_str().unwrap(),
|
||||
])
|
||||
.connect;
|
||||
let lock = directory.path().join("client.pid");
|
||||
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
|
||||
let shared = SharedArgs {
|
||||
ignore_tls_errors: true,
|
||||
lock_file: &lock,
|
||||
verbose: &verbose,
|
||||
log_format: LogFormat::Text,
|
||||
};
|
||||
let handler = ConnectHandler::new(&args, &shared);
|
||||
cookie_store::save(
|
||||
&cache,
|
||||
&StoredCookie::new(
|
||||
args.server.clone(),
|
||||
"alice".into(),
|
||||
handler.os_profile.borrow().host_identity().host_id().into(),
|
||||
origin.clone(),
|
||||
AuthCookieCredential::new("alice", "portal-cookie", ""),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let result = if portal_discovery {
|
||||
handler.connect_portal_with_prelogin(&origin).await
|
||||
} else {
|
||||
handler.handle_impl().await
|
||||
};
|
||||
let error = result.unwrap_err();
|
||||
let Some(gpapi::error::PortalError::NetworkError(network)) = error.downcast_ref() else {
|
||||
panic!("Expected a network error, got {error:?}");
|
||||
};
|
||||
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");
|
||||
let request = worker.await.unwrap();
|
||||
assert!(request.contains("portal-cookie"));
|
||||
if portal_discovery {
|
||||
assert!(request.starts_with("POST /global-protect/getconfig.esp "));
|
||||
} else {
|
||||
assert!(request.starts_with("POST /ssl-vpn/login.esp "));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_rejection() {
|
||||
let (origin, worker) = gateway(vec![
|
||||
|
||||
@@ -101,6 +101,11 @@ impl ConnectHandler<'_> {
|
||||
{
|
||||
return Some(Err(error));
|
||||
}
|
||||
// A failed request does not establish that the cookie was rejected.
|
||||
if is_network_error(&error) {
|
||||
warn!("Cached gateway authentication request failed: {error}");
|
||||
return Some(Err(error));
|
||||
}
|
||||
cookie_store::clear(&path);
|
||||
warn!("Cached gateway authentication failed: {error}");
|
||||
return None;
|
||||
@@ -830,3 +835,11 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A failed request says nothing about whether a cached cookie is still valid.
|
||||
pub(super) fn is_network_error(error: &anyhow::Error) -> bool {
|
||||
matches!(
|
||||
error.downcast_ref::<gpapi::error::PortalError>(),
|
||||
Some(gpapi::error::PortalError::NetworkError(_))
|
||||
)
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -292,6 +292,11 @@ impl<'a> ConnectHandler<'a> {
|
||||
Ok(config) => Some((cred, config)),
|
||||
Err(error) => {
|
||||
self.check_cancelled()?;
|
||||
// A failed request does not establish that the cookie was rejected.
|
||||
if gateway::is_network_error(&error) {
|
||||
warn!("Cached portal authentication request failed: {error}");
|
||||
return Err(error);
|
||||
}
|
||||
warn!("Cached portal authentication failed: {error}");
|
||||
self.clear_cookie_cache();
|
||||
None
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
@@ -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("<!doctype") {
|
||||
return "[XML omitted: DTD]".into();
|
||||
}
|
||||
let Ok(nodes) = Element::parse_all(body) else {
|
||||
return "[XML omitted: malformed or non-XML response]".into();
|
||||
};
|
||||
let mut roots = nodes.into_iter().filter_map(|node| match node {
|
||||
XMLNode::Element(element) => 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#"<response><jnlp><application-desc><argument>fixture-auth-cookie</argument><argument>fixture-user</argument></application-desc></jnlp><ipsec><ekey-c2s><bits>256</bits><val>fixture-key-c2s</val></ekey-c2s><ekey-s2c>fixture-key-s2c</ekey-s2c><akey-c2s><val>fixture-auth-c2s</val></akey-c2s><akey-s2c>fixture-auth-s2c</akey-s2c></ipsec><enc-hs-key>fixture-hs-key</enc-hs-key><PrivateKey>fixture-private-key</PrivateKey><SAMLResponse>fixture-saml-response</SAMLResponse><tunnel-opaque><val>fixture-opaque</val></tunnel-opaque><mtu>1400</mtu></response>"#);
|
||||
assert!(!xml.contains("fixture-"));
|
||||
assert!(xml.contains("<mtu>1400</mtu>"));
|
||||
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"<response><cookie>fixture-secret",
|
||||
b"<html><body>fixture-secret</body></html>",
|
||||
b"<!DOCTYPE response [<!ENTITY secret 'fixture-secret'>]><response>&secret;</response>",
|
||||
b"<response/>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]"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ edition.workspace = true
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
gp-xml = { path = "../gp-xml" }
|
||||
common = { path = "../common" }
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
@@ -64,8 +65,10 @@ oslog = { version = "0.2", default-features = false, optional = true }
|
||||
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
|
||||
gtk = { version = "0.18", optional = true }
|
||||
|
||||
[target.'cfg(target_os="linux")'.dependencies]
|
||||
[target.'cfg(any(target_os="linux", target_os="freebsd", target_os="openbsd"))'.dependencies]
|
||||
directories = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(target_os="linux")'.dependencies]
|
||||
libloading = { version = "0.9", optional = true }
|
||||
|
||||
[target.'cfg(target_os="macos")'.dependencies]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
+40
-6
@@ -70,17 +70,17 @@ impl GuiVariant {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn preference_path() -> anyhow::Result<PathBuf> {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn preference_path(name: &str) -> anyhow::Result<PathBuf> {
|
||||
let dirs = directories::ProjectDirs::from("com.yuezk", "GlobalProtect-openconnect", "gpclient")
|
||||
.ok_or_else(|| anyhow::anyhow!("Failed to locate GUI preference directory"))?;
|
||||
Ok(dirs.config_dir().join("gui"))
|
||||
Ok(dirs.config_dir().join(name))
|
||||
}
|
||||
|
||||
pub fn preferred() -> anyhow::Result<GuiVariant> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
match std::fs::read_to_string(preference_path()?) {
|
||||
match std::fs::read_to_string(preference_path("gui")?) {
|
||||
Ok(value) => match value.trim() {
|
||||
"gpgui" => Ok(GuiVariant::Tauri),
|
||||
"gpgui-nsh" => Ok(GuiVariant::Nsh),
|
||||
@@ -96,12 +96,46 @@ pub fn preferred() -> anyhow::Result<GuiVariant> {
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn save_preference(variant: GuiVariant) -> anyhow::Result<()> {
|
||||
save_launch_preference("gui", variant.binary_name())
|
||||
}
|
||||
|
||||
pub const COMPATIBILITY_GRAPHICS_SUPPORTED: bool =
|
||||
cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"));
|
||||
|
||||
pub const FORCE_SHARED_MEMORY: &str = "WEBKIT_DMABUF_RENDERER_FORCE_SHM";
|
||||
|
||||
const COMPATIBILITY_GRAPHICS: &str = "compatibility-graphics";
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
|
||||
fn preference_path(_: &str) -> anyhow::Result<PathBuf> {
|
||||
anyhow::bail!("Compatibility graphics is unavailable")
|
||||
}
|
||||
|
||||
pub fn compatibility_graphics_enabled() -> bool {
|
||||
COMPATIBILITY_GRAPHICS_SUPPORTED && preference_path(COMPATIBILITY_GRAPHICS).is_ok_and(|path| path.is_file())
|
||||
}
|
||||
|
||||
pub fn set_compatibility_graphics(enabled: bool) -> anyhow::Result<()> {
|
||||
anyhow::ensure!(
|
||||
COMPATIBILITY_GRAPHICS_SUPPORTED,
|
||||
"Compatibility graphics is unavailable"
|
||||
);
|
||||
if enabled {
|
||||
return save_launch_preference(COMPATIBILITY_GRAPHICS, "enabled");
|
||||
}
|
||||
match std::fs::remove_file(preference_path(COMPATIBILITY_GRAPHICS)?) {
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
result => result.map_err(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
fn save_launch_preference(name: &str, value: &str) -> anyhow::Result<()> {
|
||||
use std::io::Write;
|
||||
let path = preference_path()?;
|
||||
let path = preference_path(name)?;
|
||||
let directory = path.parent().unwrap();
|
||||
std::fs::create_dir_all(directory)?;
|
||||
let mut file = tempfile::NamedTempFile::new_in(directory)?;
|
||||
writeln!(file, "{}", variant.binary_name())?;
|
||||
writeln!(file, "{value}")?;
|
||||
file.persist(path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -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<u64>,
|
||||
/// 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<u64>,
|
||||
}
|
||||
|
||||
impl WindowsUpdateStatus {
|
||||
pub fn refresh_cursor(&self) -> Option<u64> {
|
||||
self.checked_at.or(self.omitted_snapshot_at)
|
||||
}
|
||||
}
|
||||
@@ -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()));
|
||||
}
|
||||
|
||||
@@ -17,7 +17,10 @@ use super::{
|
||||
command_traits::CommandExt,
|
||||
};
|
||||
|
||||
use super::rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible, is_crash_exit};
|
||||
use super::rendering_recovery::{
|
||||
AUTH_STDERR_PREFIX, GbmBufferFailure, RenderingCrash, StderrDiagnostic, allows_shared_memory_override, eligible,
|
||||
is_crash_exit, is_gbm_diagnostic,
|
||||
};
|
||||
|
||||
const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024;
|
||||
|
||||
@@ -53,6 +56,7 @@ pub struct SamlAuthLauncher<'a> {
|
||||
verbose: Option<&'a str>,
|
||||
log_format: LogFormat,
|
||||
dmabuf_disabled: bool,
|
||||
desktop_compatibility_graphics: bool,
|
||||
}
|
||||
|
||||
impl<'a> SamlAuthLauncher<'a> {
|
||||
@@ -85,9 +89,15 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
verbose: None,
|
||||
log_format: LogFormat::Text,
|
||||
dmabuf_disabled: false,
|
||||
desktop_compatibility_graphics: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn desktop_compatibility_graphics(mut self) -> Self {
|
||||
self.desktop_compatibility_graphics = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn dmabuf_disabled(mut self, disabled: bool) -> Self {
|
||||
self.dmabuf_disabled = disabled;
|
||||
self
|
||||
@@ -298,41 +308,68 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
if embedded && bundled && self.dmabuf_disabled {
|
||||
command.env("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
|
||||
}
|
||||
let desktop_webview = embedded && bundled && self.desktop_compatibility_graphics;
|
||||
let can_use_shared_memory = desktop_webview && allows_shared_memory_override(&command, true);
|
||||
let use_shared_memory = can_use_shared_memory && crate::gui::compatibility_graphics_enabled();
|
||||
if use_shared_memory {
|
||||
command.env(crate::gui::FORCE_SHARED_MEMORY, "1");
|
||||
}
|
||||
let detect_gbm_failure = can_use_shared_memory && !use_shared_memory;
|
||||
let stdin = auth_stdin(self.browser);
|
||||
let cancellation = self.cancellation.clone();
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
#[cfg(feature = "logger")]
|
||||
let stderr = crate::logger::diagnostic_writer();
|
||||
#[cfg(not(feature = "logger"))]
|
||||
let stderr: Box<dyn std::io::Write + Send> = Box::new(std::io::stderr());
|
||||
let mut stderr = if desktop_webview {
|
||||
Box::new(std::io::LineWriter::new(AuthStderr(stderr)))
|
||||
} else {
|
||||
stderr
|
||||
};
|
||||
let gbm_failed = std::cell::Cell::new(false);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Authentication cancelled",
|
||||
))
|
||||
} else if gbm_failed.get() {
|
||||
Err(std::io::Error::other(GbmBufferFailure))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let mut diagnostic = StderrDiagnostic::default();
|
||||
#[cfg(feature = "logger")]
|
||||
let mut stderr = crate::logger::diagnostic_writer();
|
||||
#[cfg(not(feature = "logger"))]
|
||||
let mut stderr = std::io::stderr();
|
||||
let output = run_observed(
|
||||
command,
|
||||
&check,
|
||||
Some(MAX_AUTH_RESULT_BYTES),
|
||||
&mut |bytes| diagnostic.push(bytes),
|
||||
&mut |bytes| {
|
||||
diagnostic.push(bytes);
|
||||
gbm_failed.set(detect_gbm_failure && diagnostic.should_retry_gbm(can_recover));
|
||||
},
|
||||
&mut stderr,
|
||||
stdin,
|
||||
)?;
|
||||
Ok::<_, std::io::Error>((output.output, diagnostic.matched()))
|
||||
);
|
||||
std::io::Write::flush(&mut stderr)?;
|
||||
if gbm_failed.get() && !cancellation.is_cancelled() {
|
||||
return Err(GbmBufferFailure.into());
|
||||
}
|
||||
let output = output?;
|
||||
Ok::<_, anyhow::Error>((output.output, diagnostic.matched()))
|
||||
})
|
||||
.await?;
|
||||
let (output, rendering_diagnostic) = match output {
|
||||
Ok(output) => output,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
|
||||
Err(error)
|
||||
if error
|
||||
.downcast_ref::<std::io::Error>()
|
||||
.is_some_and(|error| error.kind() == std::io::ErrorKind::Interrupted) =>
|
||||
{
|
||||
return Err(crate::auth::AuthenticationCancelled.into());
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
|
||||
if self.cancellation.is_cancelled() {
|
||||
@@ -342,6 +379,26 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
// Attribute GBM failures to gpauth before forwarding them to the desktop supervisor.
|
||||
struct AuthStderr(Box<dyn std::io::Write + Send>);
|
||||
|
||||
impl std::io::Write for AuthStderr {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
for line in bytes.split_inclusive(|&byte| byte == b'\n') {
|
||||
if is_gbm_diagnostic(line) {
|
||||
self.0.write_all(&[AUTH_STDERR_PREFIX, line].concat())?;
|
||||
} else {
|
||||
self.0.write_all(line)?;
|
||||
}
|
||||
}
|
||||
Ok(bytes.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
self.0.flush()
|
||||
}
|
||||
}
|
||||
|
||||
/// `gpauth --browser manual` reads the pasted `globalprotectcallback:` data from the user's terminal.
|
||||
fn auth_stdin(browser: Option<&str>) -> ChildInput<'static> {
|
||||
match browser {
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
use super::{
|
||||
command_runner::{ChildInput, run_observed},
|
||||
rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible_with_inheritance, is_crash_exit},
|
||||
rendering_recovery::{
|
||||
GbmBufferFailure, RenderingCrash, StderrDiagnostic, allows_shared_memory_override, eligible_with_inheritance,
|
||||
is_crash_exit,
|
||||
},
|
||||
};
|
||||
use crate::service::transport::SessionCredential;
|
||||
use anyhow::Context;
|
||||
use std::{
|
||||
cell::Cell,
|
||||
collections::HashMap,
|
||||
fs::OpenOptions,
|
||||
path::PathBuf,
|
||||
@@ -19,8 +23,10 @@ pub(super) async fn launch_desktop_child(
|
||||
envs: Option<&HashMap<String, String>>,
|
||||
credential: &SessionCredential,
|
||||
cancellation: &CancellationToken,
|
||||
detect_gbm_failure: bool,
|
||||
) -> anyhow::Result<ExitStatus> {
|
||||
let retry_eligible = eligible_with_inheritance(&command, envs.is_none());
|
||||
let detect_gbm_failure = detect_gbm_failure && allows_shared_memory_override(&command, envs.is_none());
|
||||
let log_file = match envs {
|
||||
Some(envs) => envs.get("GP_LOG_FILE").map(PathBuf::from),
|
||||
None => std::env::var_os("GP_LOG_FILE").map(PathBuf::from),
|
||||
@@ -38,12 +44,15 @@ pub(super) async fn launch_desktop_child(
|
||||
let cancellation = cancellation.clone();
|
||||
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let gbm_failed = Cell::new(false);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Desktop child launch cancelled",
|
||||
))
|
||||
} else if gbm_failed.get() {
|
||||
Err(std::io::Error::other(GbmBufferFailure))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
@@ -53,10 +62,17 @@ pub(super) async fn launch_desktop_child(
|
||||
command,
|
||||
&check,
|
||||
None,
|
||||
&mut |bytes| diagnostic.push(bytes),
|
||||
&mut |bytes| {
|
||||
diagnostic.push(bytes);
|
||||
gbm_failed.set(detect_gbm_failure && diagnostic.should_retry_gbm(retry_eligible));
|
||||
},
|
||||
&mut sink,
|
||||
ChildInput::Frame(&frame),
|
||||
)?;
|
||||
);
|
||||
if gbm_failed.get() && !cancellation.is_cancelled() {
|
||||
return Err(GbmBufferFailure.into());
|
||||
}
|
||||
let observed = observed?;
|
||||
let output = observed.output;
|
||||
if is_crash_exit(output.status) && retry_eligible && diagnostic.matched() {
|
||||
return Err(RenderingCrash { status: output.status }.into());
|
||||
|
||||
@@ -170,7 +170,11 @@ impl<'a> DesktopLauncher<'a> {
|
||||
}
|
||||
match outcome {
|
||||
Err(error) if recovery.recover(&error) => {
|
||||
warn!("{error}; restarting the desktop launch with DMABUF disabled and opaque windows");
|
||||
if recovery.shared_memory() {
|
||||
warn!("{error}; restarting the desktop launch with compatibility graphics");
|
||||
} else {
|
||||
warn!("{error}; restarting the desktop launch with DMABUF disabled and opaque windows");
|
||||
}
|
||||
expecting_renewal = true;
|
||||
input.write_all(&[DESKTOP_RENDERING_RETRY]).await?;
|
||||
}
|
||||
|
||||
@@ -79,6 +79,7 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
self.envs,
|
||||
self.credential,
|
||||
cancellation,
|
||||
false,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
|
||||
@@ -101,6 +101,12 @@ impl<'a> GuiLauncher<'a> {
|
||||
if let Some(envs) = &self.envs {
|
||||
cmd.env_clear().envs(envs);
|
||||
}
|
||||
if self.variant == crate::gui::GuiVariant::Tauri
|
||||
&& crate::gui::compatibility_graphics_enabled()
|
||||
&& super::rendering_recovery::allows_shared_memory_override(cmd.as_std(), self.envs.is_none())
|
||||
{
|
||||
cmd.env(crate::gui::FORCE_SHARED_MEMORY, "1");
|
||||
}
|
||||
cmd.arg("--service-credential-on-stdin");
|
||||
if self.minimized {
|
||||
cmd.arg("--minimized");
|
||||
@@ -112,6 +118,7 @@ impl<'a> GuiLauncher<'a> {
|
||||
self.envs.as_ref(),
|
||||
&self.credential,
|
||||
cancellation,
|
||||
self.variant == crate::gui::GuiVariant::Tauri,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -207,32 +214,45 @@ impl<'a> GuiLauncher<'a> {
|
||||
gui_switch::reply(&mut socket, Ok(GuiSwitchOutcome::DownloadRequired)).await?;
|
||||
return Ok(None);
|
||||
}
|
||||
service_input.write_all(&[DESKTOP_SWITCH_BEGIN]).await?;
|
||||
pending = true;
|
||||
let credential = super::desktop_launcher::read_credential(service_output).await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Service closed before issuing the switch credential"))?;
|
||||
anyhow::ensure!(credential.product_version() == self.version, "Service product version mismatch");
|
||||
let ready = gui_switch::SwitchListener::new()?;
|
||||
let mut envs = self.envs.clone().unwrap_or_else(|| std::env::vars().collect());
|
||||
envs.insert(gui_switch::READY_ENV.into(), ready.path().to_string_lossy().into_owned());
|
||||
let launcher = Self::new(self.version, Arc::new(credential), variant)
|
||||
.envs(envs)
|
||||
.minimized(false);
|
||||
let program = match program {
|
||||
Some(program) => program,
|
||||
None => launcher.resolve_program(cancellation, command.theme).await?,
|
||||
};
|
||||
let mut child = launcher.start_owned(program, cancellation.child_token());
|
||||
let start_result = tokio::select! {
|
||||
result = tokio::time::timeout(std::time::Duration::from_secs(30), ready.ready()) => {
|
||||
result.map_err(|_| anyhow::anyhow!("The selected GUI did not finish starting" )).and_then(|result| result)
|
||||
},
|
||||
outcome = &mut child.task => {
|
||||
return match outcome? {
|
||||
Ok(status) => Err(anyhow::anyhow!("The selected GUI exited during startup: {status}")),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
}
|
||||
use super::rendering_recovery::{GbmBufferFailure, RecoveryState};
|
||||
let mut recovery = RecoveryState::default();
|
||||
let mut program = program;
|
||||
let (mut child, start_result) = loop {
|
||||
service_input.write_all(&[DESKTOP_SWITCH_BEGIN]).await?;
|
||||
pending = true;
|
||||
let credential = super::desktop_launcher::read_credential(service_output).await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Service closed before issuing the switch credential"))?;
|
||||
anyhow::ensure!(credential.product_version() == self.version, "Service product version mismatch");
|
||||
let ready = gui_switch::SwitchListener::new()?;
|
||||
let mut envs = self.envs.clone().unwrap_or_else(|| std::env::vars().collect());
|
||||
envs.insert(gui_switch::READY_ENV.into(), ready.path().to_string_lossy().into_owned());
|
||||
let launcher = Self::new(self.version, Arc::new(credential), variant)
|
||||
.envs(envs)
|
||||
.minimized(false);
|
||||
let executable = match &program {
|
||||
Some(program) => program.clone(),
|
||||
None => launcher.resolve_program(cancellation, command.theme).await?,
|
||||
};
|
||||
let mut child = launcher.start_owned(executable.clone(), cancellation.child_token());
|
||||
let start_result = tokio::select! {
|
||||
result = tokio::time::timeout(std::time::Duration::from_secs(30), ready.ready()) => {
|
||||
result.map_err(|_| anyhow::anyhow!("The selected GUI did not finish starting" )).and_then(|result| result)
|
||||
},
|
||||
outcome = &mut child.task => {
|
||||
match outcome? {
|
||||
Ok(status) => return Err(anyhow::anyhow!("The selected GUI exited during startup: {status}")),
|
||||
Err(error) if error.is::<GbmBufferFailure>() && recovery.recover(&error) => {
|
||||
log::warn!("{error}; restarting the selected GUI with compatibility graphics");
|
||||
service_input.write_all(&[DESKTOP_SWITCH_CANCEL]).await?;
|
||||
pending = false;
|
||||
program = Some(executable);
|
||||
continue;
|
||||
}
|
||||
Err(error) => return Err(recovery.terminal(error)),
|
||||
}
|
||||
}
|
||||
};
|
||||
break (child, start_result);
|
||||
};
|
||||
if let Err(error) = start_result.and_then(|()| crate::gui::save_preference(variant)) {
|
||||
child.cancel.cancel();
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
use std::process::{Command, ExitStatus};
|
||||
|
||||
const DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER";
|
||||
pub const MAIN_WEBVIEW_INITIALIZED: &str = "GP Connect main webview initialized";
|
||||
const GBM_DIAGNOSTIC: &[u8] = b"Failed to create GBM buffer";
|
||||
pub(crate) const AUTH_STDERR_PREFIX: &[u8] = b"gpauth stderr: ";
|
||||
const DIAGNOSTIC: &[u8] = b"Error 71 (Protocol error) dispatching to Wayland display";
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -16,20 +19,33 @@ pub struct RecoveryFailed(#[source] anyhow::Error);
|
||||
#[derive(Default)]
|
||||
pub struct RecoveryState {
|
||||
first_failure: Option<String>,
|
||||
shared_memory: bool,
|
||||
}
|
||||
|
||||
impl RecoveryState {
|
||||
pub fn dmabuf_disabled(&self) -> bool {
|
||||
self.first_failure.is_some()
|
||||
self.first_failure.is_some() && !self.shared_memory
|
||||
}
|
||||
|
||||
pub fn shared_memory(&self) -> bool {
|
||||
self.shared_memory
|
||||
}
|
||||
|
||||
pub fn recover(&mut self, error: &anyhow::Error) -> bool {
|
||||
if self.first_failure.is_none() && error.downcast_ref::<RenderingCrash>().is_some() {
|
||||
self.first_failure = Some(error.to_string());
|
||||
true
|
||||
} else {
|
||||
false
|
||||
if self.first_failure.is_some() {
|
||||
return false;
|
||||
}
|
||||
let gbm_failure = error.downcast_ref::<GbmBufferFailure>().is_some();
|
||||
if !gbm_failure && error.downcast_ref::<RenderingCrash>().is_none() {
|
||||
return false;
|
||||
}
|
||||
if gbm_failure && let Err(error) = crate::gui::set_compatibility_graphics(true) {
|
||||
log::warn!("Could not save compatibility graphics setting: {error:#}");
|
||||
return false;
|
||||
}
|
||||
self.first_failure = Some(error.to_string());
|
||||
self.shared_memory = gbm_failure;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn terminal(&self, error: anyhow::Error) -> anyhow::Error {
|
||||
@@ -70,6 +86,16 @@ pub(crate) fn eligible_with_inheritance(command: &Command, inherits: bool) -> bo
|
||||
&& effective_env(command, DMABUF, inherits).is_none()
|
||||
}
|
||||
|
||||
pub(crate) fn allows_shared_memory_override(command: &Command, inherits: bool) -> bool {
|
||||
crate::gui::COMPATIBILITY_GRAPHICS_SUPPORTED
|
||||
&& effective_env(command, DMABUF, inherits).is_none()
|
||||
&& effective_env(command, crate::gui::FORCE_SHARED_MEMORY, inherits).is_none()
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("WebKit failed to create a GBM buffer")]
|
||||
pub(crate) struct GbmBufferFailure;
|
||||
|
||||
fn effective_env(command: &Command, key: &str, inherits: bool) -> Option<std::ffi::OsString> {
|
||||
for (name, value) in command.get_envs() {
|
||||
if name == key {
|
||||
@@ -79,12 +105,21 @@ fn effective_env(command: &Command, key: &str, inherits: bool) -> Option<std::ff
|
||||
inherits.then(|| std::env::var_os(key)).flatten()
|
||||
}
|
||||
|
||||
pub(crate) fn is_gbm_diagnostic(line: &[u8]) -> bool {
|
||||
!line.starts_with(AUTH_STDERR_PREFIX)
|
||||
&& line
|
||||
.windows(GBM_DIAGNOSTIC.len())
|
||||
.any(|message| message == GBM_DIAGNOSTIC)
|
||||
}
|
||||
|
||||
/// Observes diagnostic lines without retaining arbitrary application output.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct StderrDiagnostic {
|
||||
line: Vec<u8>,
|
||||
overflow: bool,
|
||||
matched: bool,
|
||||
gbm_failed: bool,
|
||||
main_webview_initialized: bool,
|
||||
}
|
||||
|
||||
impl StderrDiagnostic {
|
||||
@@ -104,6 +139,14 @@ impl StderrDiagnostic {
|
||||
|
||||
fn check_line(&mut self) {
|
||||
let line = self.line.trim_ascii_end();
|
||||
if !self.overflow {
|
||||
if line == MAIN_WEBVIEW_INITIALIZED.as_bytes() {
|
||||
self.main_webview_initialized = true;
|
||||
}
|
||||
if !self.main_webview_initialized && is_gbm_diagnostic(line) {
|
||||
self.gbm_failed = true;
|
||||
}
|
||||
}
|
||||
let message = line.strip_suffix(b".").unwrap_or(line);
|
||||
if !self.overflow
|
||||
&& (line.starts_with(b"Gdk-Message:")
|
||||
@@ -117,6 +160,10 @@ impl StderrDiagnostic {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn should_retry_gbm(&self, can_retry_wayland: bool) -> bool {
|
||||
self.gbm_failed && !(can_retry_wayland && self.matched)
|
||||
}
|
||||
|
||||
pub(crate) fn matched(&mut self) -> bool {
|
||||
self.check_line();
|
||||
self.matched
|
||||
@@ -127,6 +174,43 @@ impl StderrDiagnostic {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn detects_gbm_failure_before_main_webview_initializes() {
|
||||
for line in [
|
||||
b"Failed to create GBM buffer of size 280x404: Invalid argument\n".as_slice(),
|
||||
b"(WebKitWebProcess:42): Warning: Failed to create GBM buffer\n",
|
||||
b"gpauth: Failed to create GBM buffer\n",
|
||||
] {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
for bytes in line.chunks(7) {
|
||||
observer.push(bytes);
|
||||
}
|
||||
assert!(observer.gbm_failed);
|
||||
assert!(!observer.matched());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_gbm_failure_after_startup_and_from_auth_stderr() {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
observer
|
||||
.push(b"gpauth stderr: (WebKitWebProcess:42): Failed to create GBM buffer of size 900x648: Invalid argument\n");
|
||||
assert!(!observer.gbm_failed);
|
||||
observer.push(format!("{MAIN_WEBVIEW_INITIALIZED}\n").as_bytes());
|
||||
observer.push(b"Failed to create GBM buffer of size 840x640: Invalid argument\n");
|
||||
assert!(!observer.gbm_failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_wayland_retry_when_both_diagnostics_are_observed() {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
observer.push(b"Failed to create GBM buffer of size 280x404: Invalid argument\n");
|
||||
observer.push(b"Gdk-Message: Error 71 (Protocol error) dispatching to Wayland display.\n");
|
||||
assert!(observer.matched());
|
||||
assert!(!observer.should_retry_gbm(true));
|
||||
assert!(observer.should_retry_gbm(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recognizes_split_diagnostic_without_matching_quoted_warning() {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
|
||||
@@ -64,6 +64,14 @@ pub struct GpError {
|
||||
}
|
||||
|
||||
impl GpError {
|
||||
pub(crate) fn take_body_read_error(&mut self) -> Option<reqwest::Error> {
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -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("<!doctype") {
|
||||
return "[XML omitted: DTD]".into();
|
||||
}
|
||||
let Ok(nodes) = Element::parse_all(body) else {
|
||||
return "[XML omitted: malformed or non-XML response]".into();
|
||||
};
|
||||
let mut roots = nodes.into_iter().filter_map(|node| match node {
|
||||
XMLNode::Element(element) => 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#"<response><jnlp><application-desc><argument>fixture-auth-cookie</argument><argument>fixture-user</argument></application-desc></jnlp><ipsec><ekey-c2s><bits>256</bits><val>fixture-key-c2s</val></ekey-c2s><ekey-s2c>fixture-key-s2c</ekey-s2c></ipsec><enc-hs-key>fixture-hs-key</enc-hs-key><PrivateKey>fixture-private-key</PrivateKey><SAMLResponse>fixture-saml-response</SAMLResponse><tunnel-opaque><val>fixture-opaque</val></tunnel-opaque><mtu>1400</mtu></response>"#);
|
||||
assert!(!xml.contains("fixture-"));
|
||||
assert!(xml.contains("<mtu>1400</mtu>"));
|
||||
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"<response><cookie>fixture-secret",
|
||||
b"<html><body>fixture-secret</body></html>",
|
||||
b"<!DOCTYPE response [<!ENTITY secret 'fixture-secret'>]><response>&secret;</response>",
|
||||
b"<response/>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]"
|
||||
);
|
||||
}
|
||||
}
|
||||
+18
-10
@@ -246,11 +246,10 @@ pub fn generate_report(input: &ReportInput) -> anyhow::Result<String> {
|
||||
/// 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<String> {
|
||||
pub fn generate_identity_report(input: &ReportInput, control: &dyn CollectionControl) -> anyhow::Result<String> {
|
||||
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::<io::Error>().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("<domain>emulated-domain.internal</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"
|
||||
@@ -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")
|
||||
|
||||
@@ -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<String> {
|
||||
let mut categories = Vec::new();
|
||||
categories.push(category(
|
||||
@@ -245,6 +255,20 @@ fn category(name: &str, products: impl Iterator<Item = Element>) -> 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(
|
||||
|
||||
@@ -7,6 +7,7 @@ license = "MIT"
|
||||
links = "openconnect"
|
||||
|
||||
[dependencies]
|
||||
gp-xml = { path = "../gp-xml" }
|
||||
log.workspace = true
|
||||
libc = "0.2"
|
||||
is_executable.workspace = true
|
||||
|
||||
@@ -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<String>);
|
||||
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:\n<response><mtu>1400</mtu><akey-c2s><val>fixture-secret</val></akey-c2s><hs-key><bits>128</bits><val>fixture-handshake-key</val></hs-key></response>\n";
|
||||
vpn_log(2, message.as_ptr());
|
||||
vpn_log(
|
||||
2,
|
||||
c"GlobalProtect getconfig.esp response:\n<malformed>fixture-secret".as_ptr(),
|
||||
);
|
||||
let output = CAPTURE.0.lock().unwrap();
|
||||
assert!(output.contains("<mtu>1400</mtu>"));
|
||||
assert!(output.contains("[redacted]"));
|
||||
assert!(output.contains("[XML omitted:"));
|
||||
assert!(!output.contains("fixture-secret"));
|
||||
assert!(!output.contains("fixture-handshake-key"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user