release: prepare GP Connect 3.5.0 with Windows support

This commit is contained in:
Kevin Yue committed 2026-11-19 01:40:22 +08:00
1 parent 6ffb1e8709
commit 43c20d0976
172 files changed
+9629 -1171

No files matched your search

+36 -5
View File
@@ -6,7 +6,7 @@ edition.workspace = true
license = "MIT"
[dependencies]
nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true }
gp-xml = { path = "../gp-xml" }
common = { path = "../common" }
anyhow.workspace = true
base64.workspace = true
@@ -35,7 +35,6 @@ thiserror.workspace = true
chacha20poly1305 = { version = "0.11", features = ["zeroize"] }
url.workspace = true
regex.workspace = true
uzers = { workspace = true, optional = true }
serde_urlencoded.workspace = true
md5.workspace = true
sha2.workspace = true
@@ -48,6 +47,9 @@ snow.workspace = true
zeroize = { workspace = true, features = ["serde"] }
getrandom = "0.4"
# Used only by the opt-in certificate interoperability tests.
openssl = { workspace = true, optional = true }
# Optional dependencies for features
tauri = { workspace = true, optional = true }
clap = { workspace = true, optional = true }
@@ -63,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]
@@ -78,7 +82,6 @@ cc = "1"
pkg-config = "0.3"
[dev-dependencies]
openssl.workspace = true
libloading = "0.9"
proptest.workspace = true
tokio = { workspace = true, features = ["test-util"] }
@@ -89,4 +92,32 @@ desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:u
tauri = ["desktop", "dep:tauri", "dep:gtk", "dep:os_info"]
clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"]
webview-auth = []
logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog"]
openssl-tests = ["dep:openssl"]
logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog", "dep:file-rotate"]
[target.'cfg(unix)'.dependencies]
nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true }
uzers = { workspace = true, optional = true }
[target.'cfg(windows)'.dependencies]
file-rotate = { version = "0.8.0", optional = true }
windows-sys = { version = "0.61", features = ["Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Pipes", "Win32_System_Threading", "Win32_System_Services", "Win32_Globalization", "Win32_System_Environment", "Win32_System_JobObjects", "Win32_System_IO", "Win32_System_Registry", "Win32_System_SystemInformation"] }
[target.'cfg(windows)'.dev-dependencies]
windows-sys = { version = "0.61", features = ["Win32_UI_Shell"] }
[[test]]
name = "certificate_compatibility"
required-features = ["openssl-tests"]
[[test]]
name = "client_certificate_chain"
required-features = ["openssl-tests"]
[[test]]
name = "client_certificate_extensions"
required-features = ["openssl-tests"]
[[test]]
name = "client_certificate_tls12_hash"
required-features = ["openssl-tests"]
+16
View File
@@ -0,0 +1,16 @@
# gpapi tests
Ordinary tests do not require OpenSSL. To run the Windows logger regression test:
```sh
cargo test -p gpapi --features logger --lib logger::windows::tests
```
The certificate interoperability suite uses OpenSSL as an independent TLS and
signature implementation. Full CI enables it explicitly:
```sh
cargo test -p gpapi --features logger,openssl-tests
```
This optional suite requires OpenSSL development headers and libraries.
+16 -2
View File
@@ -10,6 +10,7 @@ pub enum AnchorSource {
UnixMac,
UnixRandom,
MacosIokit,
WindowsSmbios,
}
impl From<AnchorSource> for u8 {
@@ -18,6 +19,7 @@ impl From<AnchorSource> for u8 {
AnchorSource::UnixMac => 1,
AnchorSource::UnixRandom => 2,
AnchorSource::MacosIokit => 3,
AnchorSource::WindowsSmbios => 4,
}
}
}
@@ -41,6 +43,7 @@ impl TryFrom<u8> for AnchorSource {
1 => Ok(Self::UnixMac),
2 => Ok(Self::UnixRandom),
3 => Ok(Self::MacosIokit),
4 => Ok(Self::WindowsSmbios),
value => Err(InvalidAnchorSource(value)),
}
}
@@ -65,6 +68,7 @@ impl DeviceAnchor {
AnchorSource::UnixMac => b"gp-device-anchor:v1:unix-mac:".as_slice(),
AnchorSource::UnixRandom => b"gp-device-anchor:v1:unix-random:".as_slice(),
AnchorSource::MacosIokit => b"gp-device-anchor:v1:macos-platform-uuid:".as_slice(),
AnchorSource::WindowsSmbios => b"gp-device-anchor:v1:windows-smbios-uuid:".as_slice(),
};
let mut input = domain.to_vec();
input.extend_from_slice(seed.as_ref());
@@ -81,7 +85,7 @@ mod tests {
#[test]
fn preserves_existing_hardware_ids_for_all_sources() {
let cases: [(AnchorSource, &[u8], &str); 3] = [
let cases: [(AnchorSource, &[u8], &str); 4] = [
(
AnchorSource::UnixMac,
&[0, 17, 34, 51, 68, 85],
@@ -97,6 +101,11 @@ mod tests {
b"12345678-1234-5678-9abc-def012345678",
"K1KMtAwiOiXKQvQuRmTDKPA6-ZPF5QKUWZzmvRzeP34",
),
(
AnchorSource::WindowsSmbios,
b"12345678-1234-5678-9abc-def012345678",
"C843jG-lDX91Tab02VelrMJl_OmOji_pCtNWilwzW5s",
),
];
for (source, seed, expected) in cases {
let anchor = DeviceAnchor::derive(source, seed);
@@ -124,12 +133,17 @@ mod tests {
assert_eq!(serde_json::to_string(&AnchorSource::UnixMac).unwrap(), "1");
assert_eq!(serde_json::to_string(&AnchorSource::UnixRandom).unwrap(), "2");
assert_eq!(serde_json::to_string(&AnchorSource::MacosIokit).unwrap(), "3");
assert_eq!(serde_json::to_string(&AnchorSource::WindowsSmbios).unwrap(), "4");
assert_eq!(
serde_json::from_str::<AnchorSource>("4").unwrap(),
AnchorSource::WindowsSmbios
);
assert_eq!(
serde_json::from_str::<AnchorSource>("1").unwrap(),
AnchorSource::UnixMac
);
assert!(serde_json::from_str::<AnchorSource>("0").is_err());
assert!(serde_json::from_str::<AnchorSource>("4").is_err());
assert!(serde_json::from_str::<AnchorSource>("5").is_err());
assert!(serde_json::from_str::<AnchorSource>(r#""unix_mac""#).is_err());
}
}
+11 -1
View File
@@ -109,6 +109,7 @@ fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bo
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "openssl-tests")]
use openssl::{
asn1::Asn1Time,
hash::MessageDigest,
@@ -180,10 +181,12 @@ mod tests {
);
}
#[cfg(feature = "openssl-tests")]
fn server(tls: bool) -> (String, thread::JoinHandle<()>) {
server_with_client_auth(tls, SslVerifyMode::NONE)
}
#[cfg(feature = "openssl-tests")]
fn server_with_client_auth(tls: bool, verify: SslVerifyMode) -> (String, thread::JoinHandle<()>) {
let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap();
let mut name = X509NameBuilder::new().unwrap();
@@ -233,6 +236,7 @@ mod tests {
(address, worker)
}
#[cfg(feature = "openssl-tests")]
#[tokio::test]
async fn prelogin_returns_typed_certificate_failure_with_only_the_server_origin() {
use crate::{
@@ -254,6 +258,7 @@ mod tests {
assert_eq!(tls.server, address);
}
#[cfg(feature = "openssl-tests")]
#[tokio::test]
async fn certificate_bypass_allows_prelogin() {
use crate::{
@@ -270,6 +275,7 @@ mod tests {
assert!(matches!(result.unwrap(), crate::portal::Prelogin::Saml(_)));
}
#[cfg(feature = "openssl-tests")]
#[tokio::test]
async fn incompatible_tls_is_not_a_certificate_error_even_with_bypass() {
let (address, worker) = server(false);
@@ -303,7 +309,7 @@ mod tests {
assert_eq!(classify(&error), None);
}
#[cfg(feature = "desktop")]
#[cfg(all(feature = "desktop", unix))]
#[test]
fn rendering_recovery_retains_client_certificate_requirement() {
use crate::process::rendering_recovery::{RecoveryState, RenderingCrash};
@@ -330,6 +336,7 @@ mod tests {
);
}
#[cfg(feature = "openssl-tests")]
#[tokio::test]
async fn required_client_certificate_is_not_bypassed_by_ignoring_server_trust() {
use crate::{
@@ -371,6 +378,7 @@ mod tests {
}
}
#[cfg(feature = "openssl-tests")]
#[tokio::test]
async fn prelogin_explains_peer_rejection_of_an_already_configured_identity() {
use crate::{
@@ -403,6 +411,7 @@ mod tests {
assert!(!error.to_string().contains("passphrase"));
}
#[cfg(feature = "openssl-tests")]
#[tokio::test]
async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() {
use crate::{
@@ -435,6 +444,7 @@ mod tests {
}
}
#[cfg(feature = "openssl-tests")]
#[tokio::test]
async fn imported_identity_formats_complete_mutual_tls_prelogin() {
use crate::{
+4 -1
View File
@@ -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);
}
+5 -10
View File
@@ -111,7 +111,7 @@ pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
let response = client.post(&url).form(&form).send().await?;
let response = parse_gp_response(response).await?;
let root = Element::parse(response.as_bytes())?;
let status = parse_extend_session_status(&root, &response)?;
let status = parse_extend_session_status(&root)?;
info!("Extend-session gateway response status: {}", status);
@@ -151,11 +151,11 @@ fn build_extend_session_form(ctx: &SessionContext) -> anyhow::Result<HashMap<Str
Ok(form)
}
fn parse_extend_session_status(root: &Element, response: &str) -> anyhow::Result<String> {
fn parse_extend_session_status(root: &Element) -> anyhow::Result<String> {
match root.attr("status") {
Some(status) => Ok(status.to_string()),
None => {
warn!("Malformed extend-session response body: {}", response.trim());
warn!("Extend-session response is missing status");
bail!("Malformed extend session response")
}
}
@@ -231,10 +231,7 @@ mod tests {
fn parses_extend_session_status_attribute() {
let root = Element::parse(r#"<response status="success"></response>"#.as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root, r#"<response status="success"></response>"#).unwrap(),
"success"
);
assert_eq!(parse_extend_session_status(&root).unwrap(), "success");
}
#[test]
@@ -242,9 +239,7 @@ mod tests {
let root = Element::parse("<response><result>ok</result></response>".as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root, "<response><result>ok</result></response>")
.unwrap_err()
.to_string(),
parse_extend_session_status(&root).unwrap_err().to_string(),
"Malformed extend session response"
);
}
+40 -6
View File
@@ -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(())
}
+24
View File
@@ -45,3 +45,27 @@ mod tests {
assert_eq!(serde_json::from_value::<HipSource>(json).unwrap(), source);
}
}
/// Collection metadata for the exact XML returned by a generated preview.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HipReport {
pub xml: String,
pub windows_updates: Option<WindowsUpdateStatus>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
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)
}
}
+3
View File
@@ -31,3 +31,6 @@ pub mod clap;
#[cfg(feature = "desktop")]
pub mod script_tun;
#[cfg(all(feature = "desktop", windows))]
pub mod windows;
+14
View File
@@ -12,6 +12,20 @@ pub const MACOS_UNIFIED_LOG_BACKEND: &str = "macos-unified";
type BoxedLogger = Box<dyn Log + Send + Sync>;
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<BoxedLogger>>> = OnceLock::new();
#[cfg(windows)]
mod windows;
#[cfg(windows)]
pub use windows::init_file;
/// Keep helper diagnostics with the application's records when a file logger owns them.
pub fn diagnostic_writer() -> Box<dyn std::io::Write + Send> {
#[cfg(windows)]
if let Some(writer) = windows::diagnostic_writer() {
return writer;
}
Box::new(std::io::stderr())
}
pub fn init(level: Level, subsystem: &str, category: &str, log_format: LogFormat) {
#[cfg(target_os = "macos")]
if log_format == LogFormat::Text && macos_unified_log_enabled() {
+98
View File
@@ -0,0 +1,98 @@
use file_rotate::{ContentLimit, FileRotate, compression::Compression, suffix::AppendCount};
use std::{
fs::{self, OpenOptions},
io::{self, Write},
path::Path,
sync::{Arc, Mutex, OnceLock},
};
const ROTATE_BYTES: usize = 5 * 1024 * 1024;
const ARCHIVE_COUNT: usize = 3;
static DIAGNOSTICS: OnceLock<DiagnosticWriter> = OnceLock::new();
#[derive(Clone)]
struct DiagnosticWriter(Arc<Mutex<FileRotate<AppendCount>>>);
impl DiagnosticWriter {
fn open(path: &Path) -> io::Result<Self> {
if let Some(parent) = path.parent().filter(|parent| !parent.as_os_str().is_empty()) {
fs::create_dir_all(parent)?;
}
// FileRotate's constructor suppresses open errors, so check the destination first.
OpenOptions::new().create(true).append(true).open(path)?;
Ok(Self(Arc::new(Mutex::new(FileRotate::new(
path,
AppendCount::new(ARCHIVE_COUNT),
ContentLimit::BytesSurpassed(ROTATE_BYTES),
Compression::None,
None,
)))))
}
}
impl Write for DiagnosticWriter {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self
.0
.lock()
.map_err(|_| io::Error::other("Log writer lock is poisoned"))?
.write(bytes)
}
fn flush(&mut self) -> io::Result<()> {
self
.0
.lock()
.map_err(|_| io::Error::other("Log writer lock is poisoned"))?
.flush()
}
}
pub fn init_file(path: &Path, level: log::Level) -> io::Result<()> {
let writer = DiagnosticWriter::open(path)?;
let logger = super::build_env_logger(crate::log_format::LogFormat::Text)
.target(env_logger::Target::Pipe(Box::new(writer.clone())))
.build();
DIAGNOSTICS
.set(writer)
.map_err(|_| io::Error::other("File logging is already initialized"))?;
super::init_with_logger(level, logger);
Ok(())
}
pub(super) fn diagnostic_writer() -> Option<Box<dyn Write + Send>> {
DIAGNOSTICS
.get()
.map(|writer| Box::new(writer.clone()) as Box<dyn Write + Send>)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gui_and_helper_writers_share_rotation_and_keep_only_three_archives() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("logs/gui.log");
let mut gui = DiagnosticWriter::open(&path).unwrap();
let mut helper = gui.clone();
for marker in b'0'..=b'5' {
let writer = if marker % 2 == 0 { &mut gui } else { &mut helper };
writer.write_all(&vec![marker; ROTATE_BYTES + 1]).unwrap();
}
helper.flush().unwrap();
drop((gui, helper));
assert_eq!(fs::read(&path).unwrap(), vec![b'5'; ROTATE_BYTES + 1]);
for (suffix, marker) in [(1, b'4'), (2, b'3'), (3, b'2')] {
assert_eq!(
fs::read(path.with_extension(format!("log.{suffix}"))).unwrap(),
vec![marker; ROTATE_BYTES + 1]
);
}
assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 4);
let mut reopened = DiagnosticWriter::open(&path).unwrap();
reopened.write_all(b"after restart\n").unwrap();
reopened.flush().unwrap();
assert_eq!(fs::read(&path).unwrap(), b"after restart\n");
}
}
+8 -1
View File
@@ -173,6 +173,12 @@ pub fn collect_profile_with_control(
Some(identity) => identity.clone(),
None => collect_with_host_id_and_control(host_id_override, control)?,
};
#[cfg(windows)]
let identity = if builder.client_os == ClientOs::Windows {
windows::native_profile_identity(identity, host_id_override)?
} else {
identity
};
let runtime_os = runtime_client_os();
// Preserve the old behavior: only probe the native version when reporting it.
let (os_version, software_version) = if builder.client_os == runtime_os {
@@ -181,7 +187,8 @@ pub fn collect_profile_with_control(
(defaults::os_version(runtime_os), defaults::software_version(runtime_os))
};
control.check()?;
Ok(builder.build(HostSnapshot {
// The builder may carry cached hardware identity; use the resolved profile identity.
Ok(builder.host_identity(identity.clone()).build(HostSnapshot {
runtime_os,
identity,
os_version,
+85 -2
View File
@@ -137,14 +137,24 @@ fn assert_mac(value: &str, separator: char) {
}
#[test]
fn builder_delegates_default_identity_to_host_identity() {
fn builder_preserves_supplied_hardware_fields() {
let expected = collect_identity();
let profile = collect_profile(
OsProfileBuilder::new(runtime_client_os()).host_identity(expected.clone()),
None,
);
assert_eq!(profile.host_identity(), &expected);
assert!(
profile
.host_identity()
.computer()
.eq_ignore_ascii_case(expected.computer())
);
assert_eq!(profile.host_identity().serialno(), expected.serialno());
assert_eq!(profile.host_identity().mac_addr(), expected.mac_addr());
if runtime_client_os() != ClientOs::Windows {
assert_eq!(profile.host_identity().host_id(), expected.host_id());
}
}
#[test]
@@ -178,3 +188,76 @@ fn controlled_profile_collection_propagates_cancellation_and_deadline() {
let error = collect_profile_with_control(OsProfileBuilder::new(ClientOs::Linux), None, &expired).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
}
#[cfg(windows)]
#[test]
fn native_windows_profile_uses_installation_id_and_emulation_keeps_its_seed() {
let identity = HostIdentity::from_parts(
"test-host".into(),
"hardware-seed".into(),
"serial".into(),
"00:11:22:33:44:55".into(),
);
let control = CollectionBudget::new(Duration::from_secs(60));
let native = collect_profile_with_control(
OsProfile::builder(ClientOs::Windows).host_identity(identity.clone()),
None,
&control,
)
.unwrap();
// Read independently through the registry CLI to check the native API's source and view.
let output = std::process::Command::new("reg")
.args([
"query",
r"HKLM\SOFTWARE\Microsoft\Cryptography",
"/v",
"MachineGuid",
"/reg:64",
])
.output()
.unwrap();
assert!(output.status.success());
let text = String::from_utf8(output.stdout).unwrap();
let expected = text
.lines()
.find_map(|line| {
let mut parts = line.split_whitespace();
(parts.next()? == "MachineGuid").then(|| parts.last().unwrap())
})
.unwrap();
assert_eq!(native.host_id(), expected);
assert_eq!(native.host_identity().host_id(), expected);
assert!(native.computer().eq_ignore_ascii_case(&fallback_hostname()));
let with_host_id = collect_profile_with_control(
OsProfile::builder(ClientOs::Windows).host_identity(identity.clone()),
Some("explicit-host-id"),
&control,
)
.unwrap();
assert_eq!(with_host_id.host_id(), "explicit-host-id");
assert_eq!(with_host_id.computer(), native.computer());
let overridden = collect_profile_with_control(
OsProfile::builder(ClientOs::Windows)
.host_identity(identity.clone())
.computer_name_override("Custom-Host"),
None,
&control,
)
.unwrap();
assert_eq!(overridden.computer(), "Custom-Host");
for client_os in [ClientOs::Mac, ClientOs::Linux] {
let builder = OsProfile::builder(client_os).host_identity(identity.clone());
let expected = builder.clone().build(HostSnapshot {
runtime_os: ClientOs::Windows,
identity: identity.clone(),
os_version: String::new(),
software_version: String::new(),
});
let actual = collect_profile_with_control(builder, None, &control).unwrap();
assert_eq!(actual.host_identity(), &identity);
assert_eq!(actual.host_id(), expected.host_id());
assert_eq!(actual.serialno(), expected.serialno());
assert_eq!(actual.mac_addr(), expected.mac_addr());
}
}
+66 -19
View File
@@ -1,4 +1,7 @@
use std::process::Command;
use std::{io, os::windows::process::CommandExt, process::Command};
use windows_sys::Win32::System::Registry::{HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ, RRF_SUBKEY_WOW6464KEY, RegGetValueW};
use windows_sys::Win32::System::SystemInformation::{ComputerNamePhysicalNetBIOS, GetComputerNameExW};
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
use super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id};
@@ -36,6 +39,7 @@ impl RuntimeNativeHostIdentity {
fn collect_windows_serial_number() -> Option<String> {
let output = Command::new("wmic")
.creation_flags(CREATE_NO_WINDOW)
.args(["bios", "get", "serialnumber"])
.output()
.ok()?;
@@ -50,11 +54,15 @@ fn collect_windows_serial_number() -> Option<String> {
}
fn windows_machine_seed() -> Option<String> {
collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid)
collect_windows_csproduct_uuid().or_else(|| collect_windows_machine_guid().ok())
}
fn collect_windows_csproduct_uuid() -> Option<String> {
let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?;
let output = Command::new("wmic")
.creation_flags(CREATE_NO_WINDOW)
.args(["csproduct", "get", "uuid"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
@@ -65,24 +73,63 @@ fn collect_windows_csproduct_uuid() -> Option<String> {
.next()
}
fn collect_windows_machine_guid() -> Option<String> {
let output = Command::new("reg")
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
.output()
.ok()?;
if !output.status.success() {
return None;
// Native Windows uses the OS installation ID and physical NetBIOS name.
// Keep the hardware identity used to seed other OS profiles unchanged.
pub(super) fn native_profile_identity(
identity: super::HostIdentity,
host_id_override: Option<&str>,
) -> io::Result<super::HostIdentity> {
let host_id = match host_id_override.filter(|id| !id.trim().is_empty()) {
Some(id) => id.to_owned(),
None => collect_windows_machine_guid()?,
};
Ok(super::HostIdentity::from_parts(
collect_windows_computer_name()?,
host_id,
identity.serialno().into(),
identity.mac_addr().into(),
))
}
fn collect_windows_computer_name() -> io::Result<String> {
let mut name = [0u16; 256];
let mut size = name.len() as u32;
// SAFETY: the buffer and character count describe writable UTF-16 storage.
if unsafe { GetComputerNameExW(ComputerNamePhysicalNetBIOS, name.as_mut_ptr(), &mut size) } == 0 {
return Err(io::Error::last_os_error());
}
let stdout = String::from_utf8(output.stdout).ok()?;
String::from_utf16(&name[..size as usize]).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}
stdout.lines().find_map(|line| {
let mut parts = line.split_whitespace();
if parts.next()? != "MachineGuid" {
return None;
}
parts.last().map(str::to_string)
})
fn collect_windows_machine_guid() -> io::Result<String> {
let key: Vec<u16> = "SOFTWARE\\Microsoft\\Cryptography\0".encode_utf16().collect();
let value: Vec<u16> = "MachineGuid\0".encode_utf16().collect();
let mut buffer = [0u16; 128];
let mut size = std::mem::size_of_val(&buffer) as u32;
// SAFETY: both names are NUL-terminated; buffer and byte length describe writable storage.
let status = unsafe {
RegGetValueW(
HKEY_LOCAL_MACHINE,
key.as_ptr(),
value.as_ptr(),
RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY,
std::ptr::null_mut(),
buffer.as_mut_ptr().cast(),
&mut size,
)
};
if status != 0 {
return Err(io::Error::from_raw_os_error(status as i32));
}
let end = buffer.iter().position(|value| *value == 0).unwrap_or(buffer.len());
let guid = String::from_utf16(&buffer[..end]).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
if guid.trim().is_empty() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Windows MachineGuid is empty",
));
}
Ok(guid)
}
impl RuntimeNativeHostIdentity {
+1 -2
View File
@@ -124,8 +124,7 @@ impl OsProfile {
self.runtime_os == self.client_os
}
/// Default software version string for the target OS, matching the
/// official client values.
/// Software version for the target OS profile.
pub fn software_version(&self) -> &str {
&self.software_version
}
+6 -6
View File
@@ -18,14 +18,14 @@ fn negotiated_os_version_is_used_in_profile_and_user_agent() {
}
#[test]
fn csc_support_defaults_match_official_profiles() {
fn csc_support_defaults_match_platform_profiles() {
assert!(!ClientOs::Linux.default_csc_support());
assert!(ClientOs::Mac.default_csc_support());
assert!(ClientOs::Windows.default_csc_support());
}
#[test]
fn prelogin_param_location_matches_official_profiles() {
fn prelogin_param_location_matches_platform_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
@@ -91,7 +91,7 @@ fn embedded_gateway_default_browser_is_zero_for_all() {
}
#[test]
fn external_default_browser_values_match_official_profiles() {
fn external_default_browser_values_match_platform_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
@@ -132,7 +132,7 @@ fn external_default_browser_values_match_official_profiles() {
}
#[test]
fn saml_password_matches_official_profiles() {
fn saml_password_matches_platform_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
@@ -173,7 +173,7 @@ fn gateway_server_uses_resolved_ipv4_for_all() {
}
#[test]
fn kerberos_support_in_query_matches_official_profiles() {
fn kerberos_support_in_query_matches_platform_profiles() {
assert!(
!OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
@@ -192,7 +192,7 @@ fn kerberos_support_in_query_matches_official_profiles() {
}
#[test]
fn os_vendor_matches_official_profiles() {
fn os_vendor_matches_platform_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
+9 -5
View File
@@ -1,7 +1,7 @@
use std::collections::HashMap;
use anyhow::bail;
use log::{debug, info, warn};
use log::{info, warn};
use reqwest::{Client, StatusCode};
use serde::Serialize;
use specta::Type;
@@ -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));
}
@@ -232,7 +235,6 @@ pub async fn retrieve_config(
bail!(PortalError::ConfigError("Empty portal config response".to_string()))
}
debug!("Portal config response received: {} bytes", res_xml.len());
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
if csc::is_config_criteria(&root) {
@@ -247,7 +249,6 @@ pub async fn retrieve_config(
_ = cancellation.cancelled() => bail!("Portal configuration cancelled"),
result = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params) => result?,
};
debug!("Portal CSC config response received: {} bytes", csc_xml.len());
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
return parse_portal_policy(&server, cred, root, cancellation).await;
}
@@ -280,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()));
}
+2 -4
View File
@@ -1,5 +1,5 @@
use anyhow::{anyhow, bail};
use log::{debug, info, warn};
use log::{info, warn};
use reqwest::{Client, StatusCode};
use serde::Serialize;
use specta::Type;
@@ -174,10 +174,8 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams, options: PreloginOptio
Err(anyhow!(PortalError::PreloginError(err.reason)))
})?;
debug!("Prelogin response XML: {}", res_xml);
let prelogin = parse_prelogin_response(&res_xml, is_gateway).map_err(|err| {
warn!("Parse response error, response: {}", res_xml);
warn!("Failed to parse prelogin response: {err}");
PortalError::PreloginError(err.to_string())
})?;
+140 -16
View File
@@ -17,10 +17,17 @@ 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;
#[cfg(windows)]
/// The caller that receives foreground permission after browser authentication.
pub const AUTH_PARENT_PROCESS_ID_ENV: &str = "GPAUTH_PARENT_PROCESS_ID";
pub struct SamlAuthLauncher<'a> {
cancellation: CancellationToken,
server: &'a str,
@@ -49,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> {
@@ -81,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
@@ -197,6 +211,8 @@ impl<'a> SamlAuthLauncher<'a> {
/// argument that never gets appended.
fn build_command(&self, program: &Path) -> Command {
let mut auth_cmd = Command::new(program);
#[cfg(windows)]
auth_cmd.env(AUTH_PARENT_PROCESS_ID_ENV, std::process::id().to_string());
auth_cmd.arg(self.server);
if self.gateway {
@@ -236,7 +252,7 @@ impl<'a> SamlAuthLauncher<'a> {
}
#[cfg(feature = "webview-auth")]
{
if self.browser.is_none() {
if self.hidpi {
auth_cmd.arg("--hidpi");
}
@@ -292,15 +308,34 @@ 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(())
}
@@ -310,19 +345,31 @@ impl<'a> SamlAuthLauncher<'a> {
command,
&check,
Some(MAX_AUTH_RESULT_BYTES),
&mut |bytes| diagnostic.push(bytes),
&mut std::io::stderr(),
&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() {
@@ -332,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 {
@@ -366,11 +433,14 @@ fn decode_auth_output(output: std::process::Output, rendering_failure: bool) ->
mod tests {
use super::*;
use crate::os_profile::{ClientOs, OsProfileBuilder};
#[cfg(unix)]
use std::os::unix::process::ExitStatusExt;
#[cfg(windows)]
use std::os::windows::process::ExitStatusExt;
#[test]
fn server_tls_result_survives_process_decoding_as_a_typed_error() {
use crate::error::{ServerTlsError, ServerTlsErrorKind};
use std::os::unix::process::ExitStatusExt;
let output = std::process::Output {
status: std::process::ExitStatus::from_raw(0),
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com:8443","kind":"certificate"}}"#.to_vec(),
@@ -389,7 +459,6 @@ mod tests {
#[test]
fn client_certificate_required_result_survives_process_decoding() {
use crate::error::{ServerTlsError, ServerTlsErrorKind};
use std::os::unix::process::ExitStatusExt;
let output = std::process::Output {
status: std::process::ExitStatus::from_raw(0),
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com","kind":"clientCertificateRequired"}}"#.to_vec(),
@@ -409,6 +478,42 @@ mod tests {
assert!(args.iter().any(|arg| arg == "--ignore-tls-errors"));
}
#[cfg(feature = "webview-auth")]
#[test]
fn external_browser_receives_no_embedded_window_arguments() {
let args = child_args(
SamlAuthLauncher::new("vpn.example.com")
.browser(Some("edge"))
.clean(true)
.hidpi(true)
.window_title("GP Connect Login")
.window_theme(AuthWindowTheme::Dark),
);
assert!(args.windows(2).any(|pair| pair == ["--browser", "edge"]));
for option in ["--clean", "--hidpi", "--window-title", "--window-theme"] {
assert!(!args.iter().any(|arg| arg == option), "unexpected {option} in {args:?}");
}
}
#[cfg(feature = "webview-auth")]
#[test]
fn embedded_window_receives_auth_preferences() {
let args = child_args(
SamlAuthLauncher::new("vpn.example.com")
.clean(true)
.window_title("GP Connect Login")
.window_theme(AuthWindowTheme::Dark),
);
assert!(args.iter().any(|arg| arg == "--clean"));
assert!(
args
.windows(2)
.any(|pair| pair == ["--window-title", "GP Connect Login"])
);
assert!(args.windows(2).any(|pair| pair == ["--window-theme", "dark"]));
assert!(!args.iter().any(|arg| arg == "--browser"));
}
#[test]
fn os_profile_sets_os_from_profile() {
let profile = OsProfileBuilder::new(ClientOs::Linux)
@@ -451,6 +556,19 @@ mod tests {
.collect()
}
#[cfg(windows)]
#[test]
fn auth_child_receives_its_foreground_parent() {
let command = SamlAuthLauncher::new("portal.example.com").build_command(Path::new("gpauth"));
let parent = command
.as_std()
.get_envs()
.find(|(name, _)| *name == AUTH_PARENT_PROCESS_ID_ENV)
.and_then(|(_, value)| value)
.expect("the authenticator must know its foreground recipient");
assert_eq!(parent, std::process::id().to_string().as_str());
}
/// gpauth writes to the same stderr as its parent, so a caller reading the
/// parent's JSON would hit gpauth's text records mid-stream unless the format
/// is passed down.
@@ -513,11 +631,14 @@ mod tests {
#[test]
fn failed_authenticator_discards_partial_or_valid_stdout_before_decoding() {
use std::os::unix::process::ExitStatusExt;
#[cfg(unix)]
let status = std::process::ExitStatus::from_raw(71 << 8);
#[cfg(windows)]
let status = std::process::ExitStatus::from_raw(0xC0000005);
for stdout in [b"{partial".to_vec(), br#"{"cancelled":null}"#.to_vec()] {
let error = decode_auth_output(
std::process::Output {
status: std::process::ExitStatus::from_raw(71 << 8),
status,
stdout,
stderr: Vec::new(),
},
@@ -530,7 +651,6 @@ mod tests {
#[test]
fn successful_malformed_auth_output_is_not_a_rendering_crash() {
use std::os::unix::process::ExitStatusExt;
let error = decode_auth_output(
std::process::Output {
status: std::process::ExitStatus::from_raw(0),
@@ -544,6 +664,7 @@ mod tests {
assert_eq!(error.to_string(), "Failed to parse auth data");
}
#[cfg(unix)]
#[tokio::test]
async fn custom_authenticator_crash_does_not_request_recovery() {
use std::os::unix::fs::PermissionsExt;
@@ -579,8 +700,11 @@ mod tests {
std::fs::write(&custom, "custom").unwrap();
assert!(is_bundled_authenticator(&bundled, &bundled));
assert!(!is_bundled_authenticator(&custom, &bundled));
let alias = directory.path().join("auth-alias");
std::os::unix::fs::symlink(&bundled, &alias).unwrap();
assert!(is_bundled_authenticator(&alias, &bundled));
#[cfg(unix)]
{
let alias = directory.path().join("auth-alias");
std::os::unix::fs::symlink(&bundled, &alias).unwrap();
assert!(is_bundled_authenticator(&alias, &bundled));
}
}
}
+19 -3
View File
@@ -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());
+5 -1
View File
@@ -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(())
+46 -26
View File
@@ -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();
+23 -2
View File
@@ -1,20 +1,41 @@
#[cfg(unix)]
mod command_runner;
#[cfg(windows)]
#[path = "windows/command_runner.rs"]
mod command_runner;
#[cfg(unix)]
mod command_traits;
#[cfg(windows)]
#[path = "windows/command_traits.rs"]
mod command_traits;
#[cfg(unix)]
mod desktop_child;
#[cfg(unix)]
mod desktop_session_env;
#[cfg(unix)]
pub(crate) mod gui_helper_launcher;
pub use command_traits::CommandExt;
pub mod auth_launcher;
#[cfg(unix)]
pub mod desktop_launcher;
#[cfg(unix)]
pub mod gui_launcher;
#[cfg(any(target_os = "linux", test))]
#[cfg(any(target_os = "linux", all(test, unix)))]
pub mod gui_switch;
#[cfg(any(target_os = "linux", test))]
#[cfg(any(target_os = "linux", all(test, unix)))]
mod nsh_runtime;
#[cfg(unix)]
pub mod users;
#[cfg(unix)]
pub mod collection;
#[cfg(windows)]
#[path = "windows/collection.rs"]
pub mod collection;
pub mod rendering_recovery;
#[cfg(windows)]
#[path = "windows/user_process.rs"]
pub mod user_process;
+98 -6
View File
@@ -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 {
@@ -49,11 +65,17 @@ impl RecoveryState {
}
}
#[cfg(unix)]
pub(crate) fn is_crash_exit(status: ExitStatus) -> bool {
use std::os::unix::process::ExitStatusExt;
!status.success() && !matches!(status.signal(), Some(1 | 2 | 9 | 15))
}
#[cfg(windows)]
pub(crate) fn is_crash_exit(status: ExitStatus) -> bool {
status.code().is_some_and(|code| (code as u32) >= 0xC0000000)
}
pub fn eligible(command: &Command) -> bool {
eligible_with_inheritance(command, true)
}
@@ -64,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 {
@@ -73,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 {
@@ -98,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:")
@@ -111,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
@@ -121,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();
@@ -192,6 +282,7 @@ mod tests {
assert!(!eligible_with_inheritance(&command, false));
}
#[cfg(unix)]
#[test]
fn recovery_is_once_and_preserves_cancellation_and_both_failures() {
use std::os::unix::process::ExitStatusExt;
@@ -213,6 +304,7 @@ mod tests {
assert!(error.to_string().contains("71"));
assert!(error.to_string().contains("second exit 72"));
}
#[cfg(unix)]
#[test]
fn explicit_termination_is_not_a_rendering_crash() {
use std::os::unix::process::ExitStatusExt;
@@ -0,0 +1,42 @@
//! Resolve system collectors from Windows' system directory, never the working directory.
use super::command_runner::run_controlled;
use crate::collection::CollectionControl;
use std::{
io,
path::{Path, PathBuf},
process::{Command, Output},
};
pub struct CollectorCommands<'a> {
control: &'a dyn CollectionControl,
}
impl<'a> CollectorCommands<'a> {
pub fn new(control: &'a dyn CollectionControl) -> Self {
Self { control }
}
pub fn resolve(&self, name: &str) -> Option<PathBuf> {
let system = std::env::var_os("SystemRoot")?;
let path = PathBuf::from(system).join("System32").join(name).with_extension("exe");
path.is_file().then_some(path)
}
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
match self.resolve(name) {
Some(path) => self.run_path(&path, args),
None => Ok(None),
}
}
pub fn run_executable(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
self.run_path(path, args)
}
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
let mut command = Command::new(path);
command.args(args);
match run_controlled(command, self.control, 256 * 1024) {
Ok(output) => Ok(Some(output)),
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => Ok(None),
Err(error) => Err(error),
}
}
}
@@ -0,0 +1,198 @@
//! Controlled Windows child execution. Pipe polling keeps cancellation responsive.
use crate::collection::CollectionControl;
use std::{
io::{self, Read, Write},
os::windows::io::AsRawHandle,
process::{Child, Command, Output, Stdio},
thread,
time::Duration,
};
use windows_sys::Win32::System::Pipes::PeekNamedPipe;
pub(crate) enum ChildInput<'a> {
Null,
Terminal,
// Preserve the borrowed input type shared by callers without a Windows launcher.
#[allow(dead_code)]
Frame(&'a [u8]),
}
#[derive(Debug)]
pub(crate) struct ObservedOutput {
pub output: Output,
}
pub(crate) fn run_controlled(command: Command, control: &dyn CollectionControl, limit: usize) -> io::Result<Output> {
run_observed(
command,
control,
Some(limit),
&mut |_| {},
&mut io::sink(),
ChildInput::Null,
)
.map(|observed| observed.output)
}
pub(crate) fn run_observed(
mut command: Command,
control: &dyn CollectionControl,
output_limit: Option<usize>,
observer: &mut dyn FnMut(&[u8]),
stderr_sink: &mut dyn Write,
stdin: ChildInput<'_>,
) -> io::Result<ObservedOutput> {
control.check()?;
// Windows desktop processes must not open a console for each helper.
use std::os::windows::process::CommandExt;
if !matches!(stdin, ChildInput::Terminal) {
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
}
command.stdout(if output_limit.is_some() {
Stdio::piped()
} else {
Stdio::inherit()
});
command.stderr(Stdio::piped());
command.stdin(match stdin {
ChildInput::Terminal => Stdio::inherit(),
ChildInput::Null => Stdio::null(),
ChildInput::Frame(_) => Stdio::piped(),
});
let mut child = ControlledChild(command.spawn()?);
let input = if let ChildInput::Frame(frame) = stdin {
let mut pipe = child.0.stdin.take().expect("piped stdin");
let frame = frame.to_vec();
Some(thread::spawn(move || pipe.write_all(&frame)))
} else {
None
};
let mut stdout = child.0.stdout.take();
let mut stderr = child.0.stderr.take().expect("piped stderr");
let mut output = Vec::new();
let mut buffer = [0u8; 8192];
loop {
control.check()?;
if let Some(pipe) = &mut stdout {
let length = read_available(pipe, &mut buffer)?;
if length > output_limit.unwrap().saturating_sub(output.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Command output exceeds its limit",
));
}
output.extend_from_slice(&buffer[..length]);
}
let length = read_available(&mut stderr, &mut buffer)?;
observer(&buffer[..length]);
stderr_sink.write_all(&buffer[..length])?;
if let Some(status) = child.0.try_wait()? {
// Drain the remaining buffered output after the process exits.
if let Some(pipe) = &mut stdout {
loop {
let length = read_available(pipe, &mut buffer)?;
if length == 0 {
break;
}
if length > output_limit.unwrap().saturating_sub(output.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Command output exceeds its limit",
));
}
output.extend_from_slice(&buffer[..length]);
}
}
loop {
let length = read_available(&mut stderr, &mut buffer)?;
if length == 0 {
break;
}
observer(&buffer[..length]);
stderr_sink.write_all(&buffer[..length])?;
}
if let Some(result) = input.and_then(|worker| worker.join().ok()) {
result?;
}
return Ok(ObservedOutput {
output: Output {
status,
stdout: output,
stderr: Vec::new(),
},
});
}
thread::sleep(Duration::from_millis(10));
}
}
fn read_available(pipe: &mut (impl Read + AsRawHandle), buffer: &mut [u8]) -> io::Result<usize> {
let mut available = 0;
let success = unsafe {
PeekNamedPipe(
pipe.as_raw_handle(),
std::ptr::null_mut(),
0,
std::ptr::null_mut(),
&mut available,
std::ptr::null_mut(),
)
};
if success == 0 {
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(109) {
return Ok(0);
} // ERROR_BROKEN_PIPE
return Err(error);
}
let length = buffer.len().min(available as usize);
if length == 0 {
return Ok(0);
}
pipe.read(&mut buffer[..length])
}
struct ControlledChild(Child);
impl Drop for ControlledChild {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn captures_output_and_rejects_excess_output() {
let mut command = Command::new("cmd.exe");
command.args(["/D", "/C", "echo hello"]);
let result = run_controlled(command, &|| Ok(()), 1024).unwrap();
assert!(result.status.success());
assert_eq!(String::from_utf8(result.stdout).unwrap().trim(), "hello");
let mut command = Command::new("cmd.exe");
command.args(["/D", "/C", "echo too much"]);
assert_eq!(
run_controlled(command, &|| Ok(()), 2).unwrap_err().kind(),
io::ErrorKind::InvalidData
);
}
#[test]
fn cancels_a_running_helper() {
let start = std::time::Instant::now();
let mut command = Command::new("powershell.exe");
command.args(["-NoProfile", "-Command", "Start-Sleep -Seconds 30"]);
let control = || {
if start.elapsed() > Duration::from_millis(150) {
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
} else {
Ok(())
}
};
assert_eq!(
run_controlled(command, &control, 1024).unwrap_err().kind(),
io::ErrorKind::Interrupted
);
assert!(start.elapsed() < Duration::from_secs(3));
}
}
@@ -0,0 +1,12 @@
use tokio::process::Command;
/// Windows authentication runs in the interactive user's GUI process.
pub trait CommandExt {
fn into_non_root(self) -> anyhow::Result<Command>;
}
impl CommandExt for Command {
fn into_non_root(self) -> anyhow::Result<Command> {
Ok(self)
}
}
@@ -0,0 +1,309 @@
//! Launch a native worker with the admitted user's primary token and environment.
use std::{
ffi::{OsStr, c_void},
io,
os::windows::{
ffi::OsStrExt,
io::{AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle},
},
path::Path,
ptr,
};
use windows_sys::Win32::{
Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT},
Globalization::{CSTR_EQUAL, CompareStringOrdinal},
Security::{ImpersonateLoggedOnUser, RevertToSelf},
System::{
Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock},
JobObjects::*,
Threading::*,
},
};
pub struct UserProcess {
process: OwnedHandle,
job: Option<OwnedHandle>,
pid: u32,
}
struct Environment(*mut c_void);
impl Drop for Environment {
fn drop(&mut self) {
unsafe {
DestroyEnvironmentBlock(self.0);
}
}
}
fn invalid(message: &str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, message)
}
fn wide(value: &OsStr) -> io::Result<Vec<u16>> {
let value: Vec<_> = value.encode_wide().collect();
if value.contains(&0) {
return Err(invalid("Windows process strings cannot contain NUL"));
}
Ok(value)
}
fn quote(argument: &[u16], output: &mut Vec<u16>) {
output.push(b'"' as u16);
let mut backslashes = 0;
for &character in argument {
if character == b'\\' as u16 {
backslashes += 1;
continue;
}
let count = if character == b'"' as u16 {
backslashes * 2 + 1
} else {
backslashes
};
output.extend(std::iter::repeat_n(b'\\' as u16, count));
output.push(character);
backslashes = 0;
}
output.extend(std::iter::repeat_n(b'\\' as u16, backslashes * 2));
output.push(b'"' as u16);
}
fn command_line(program: &[u16], arguments: &[String]) -> io::Result<Vec<u16>> {
let mut output = Vec::new();
quote(program, &mut output);
for argument in arguments {
output.push(b' ' as u16);
quote(&wide(OsStr::new(argument))?, &mut output);
}
output.push(0);
if output.len() > 32767 {
return Err(invalid("Windows worker command line is too long"));
}
Ok(output)
}
fn key(entry: &[u16]) -> &[u16] {
let end = entry
.iter()
.enumerate()
.find(|(index, value)| *index != 0 && **value == b'=' as u16)
.map(|(index, _)| index)
.unwrap_or(entry.len());
&entry[..end]
}
fn compare(left: &[u16], right: &[u16]) -> std::cmp::Ordering {
// Environment names follow Windows' ordinal, case-insensitive ordering.
unsafe { CompareStringOrdinal(left.as_ptr(), left.len() as i32, right.as_ptr(), right.len() as i32, 1) }
.cmp(&CSTR_EQUAL)
}
fn user_environment(token: BorrowedHandle<'_>, variables: &[(&str, &str)]) -> io::Result<Vec<u16>> {
let mut pointer = ptr::null_mut();
if unsafe { CreateEnvironmentBlock(&mut pointer, token.as_raw_handle(), 0) } == 0 {
return Err(io::Error::last_os_error());
}
let environment = Environment(pointer);
let mut entries = Vec::new();
unsafe {
let mut current = environment.0.cast::<u16>();
while *current != 0 {
let mut length = 0;
while *current.add(length) != 0 {
length += 1;
}
entries.push(std::slice::from_raw_parts(current, length).to_vec());
current = current.add(length + 1);
}
}
for (name, value) in variables {
if name.is_empty() || name.contains('=') {
return Err(invalid("Invalid worker environment name"));
}
let name = wide(OsStr::new(name))?;
let value = wide(OsStr::new(value))?;
entries.retain(|entry| compare(key(entry), &name) != std::cmp::Ordering::Equal);
let mut entry = name;
entry.push(b'=' as u16);
entry.extend(value);
entries.push(entry);
}
entries.sort_by(|left, right| compare(key(left), key(right)));
let mut block = Vec::new();
for entry in entries {
block.extend(entry);
block.push(0);
}
if block.is_empty() {
block.push(0);
}
block.push(0);
Ok(block)
}
impl UserProcess {
/// No service handles or service environment are inherited. The user token
/// determines the Windows session, including an existing interactive desktop.
pub fn launch(
token: BorrowedHandle<'_>,
program: &Path,
arguments: &[String],
variables: &[(&str, &str)],
) -> io::Result<Self> {
if !program.is_absolute() {
return Err(invalid("Windows worker executable must be absolute"));
}
let mut executable = wide(program.as_os_str())?;
let mut command = command_line(&executable, arguments)?;
executable.push(0);
let mut environment = user_environment(token, variables)?;
let directory = program.parent().ok_or_else(|| invalid("Worker directory is missing"))?;
let mut directory = wide(directory.as_os_str())?;
directory.push(0);
let job = unsafe { CreateJobObjectW(ptr::null(), ptr::null()) };
if job.is_null() {
return Err(io::Error::last_os_error());
}
let job = unsafe { OwnedHandle::from_raw_handle(job) };
let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION {
LimitFlags: JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
..Default::default()
},
..Default::default()
};
if unsafe {
SetInformationJobObject(
job.as_raw_handle(),
JobObjectExtendedLimitInformation,
(&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
std::mem::size_of_val(&limits) as u32,
)
} == 0
{
return Err(io::Error::last_os_error());
}
let mut desktop: Vec<u16> = "winsta0\\default".encode_utf16().chain(Some(0)).collect();
let startup = STARTUPINFOW {
cb: std::mem::size_of::<STARTUPINFOW>() as u32,
lpDesktop: desktop.as_mut_ptr(),
..Default::default()
};
let mut information = PROCESS_INFORMATION::default();
// Read/execute the requested image as its user, as Unix exec-after-setuid
// does. The service's filesystem access must not authorize a private image.
if unsafe { ImpersonateLoggedOnUser(token.as_raw_handle()) } == 0 {
return Err(io::Error::last_os_error());
}
struct Revert;
impl Drop for Revert {
fn drop(&mut self) {
if unsafe { RevertToSelf() } == 0 {
std::process::abort();
}
}
}
let revert = Revert;
let created = unsafe {
CreateProcessAsUserW(
token.as_raw_handle(),
executable.as_ptr(),
command.as_mut_ptr(),
ptr::null(),
ptr::null(),
0,
CREATE_UNICODE_ENVIRONMENT | CREATE_SUSPENDED | CREATE_NO_WINDOW,
environment.as_mut_ptr().cast(),
directory.as_ptr(),
&startup,
&mut information,
)
};
let error = (created == 0).then(io::Error::last_os_error);
drop(revert);
if let Some(error) = error {
return Err(error);
}
let process = unsafe { OwnedHandle::from_raw_handle(information.hProcess) };
let thread = unsafe { OwnedHandle::from_raw_handle(information.hThread) };
if unsafe { AssignProcessToJobObject(job.as_raw_handle(), process.as_raw_handle()) } == 0 {
let error = io::Error::last_os_error();
// The suspended child is not owned by the job on this failure path.
unsafe {
TerminateProcess(process.as_raw_handle(), 1);
WaitForSingleObject(process.as_raw_handle(), 5000);
}
return Err(error);
}
let child = Self {
process,
job: Some(job),
pid: information.dwProcessId,
};
if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
return Err(io::Error::last_os_error());
}
Ok(child)
}
pub fn id(&self) -> u32 {
self.pid
}
pub fn has_exited(&self) -> io::Result<bool> {
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 0) } {
WAIT_OBJECT_0 => Ok(true),
WAIT_TIMEOUT => Ok(false),
_ => Err(io::Error::last_os_error()),
}
}
pub fn stop(&mut self) -> io::Result<()> {
if self.job.take().is_none() {
return Ok(());
}
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 5000) } {
WAIT_OBJECT_0 => Ok(()),
WAIT_TIMEOUT => Err(io::Error::new(
io::ErrorKind::TimedOut,
"Windows worker did not terminate",
)),
_ => Err(io::Error::last_os_error()),
}
}
}
impl Drop for UserProcess {
fn drop(&mut self) {
if let Err(error) = self.stop() {
log::warn!("Could not stop Windows worker: {error}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use windows_sys::Win32::{Foundation::LocalFree, UI::Shell::CommandLineToArgvW};
#[test]
fn command_line_round_trips_through_windows_parser() {
let program: Vec<u16> = r"C:\Program Files\GP Connect\gpgui-nsh.exe".encode_utf16().collect();
let arguments = [
"proxy-worker",
"",
"space value",
"quoted\"value",
"two\\\\\"quotes",
"trailing\\",
"雪",
"&|<>",
]
.map(String::from);
let command = command_line(&program, &arguments).unwrap();
let mut count = 0;
unsafe {
let parsed = CommandLineToArgvW(command.as_ptr(), &mut count);
assert!(!parsed.is_null());
let result = std::slice::from_raw_parts(parsed, count as usize)
.iter()
.map(|&value| {
let mut length = 0;
while *value.add(length) != 0 {
length += 1;
}
String::from_utf16_lossy(std::slice::from_raw_parts(value, length))
})
.collect::<Vec<_>>();
LocalFree(parsed.cast());
assert_eq!(result[0], String::from_utf16_lossy(&program));
assert_eq!(result[1..], arguments);
}
}
}
+2
View File
@@ -424,6 +424,8 @@ pub struct UpdateLogLevelRequest(pub String);
#[derive(Debug, Deserialize, Serialize)]
pub enum WsRequest {
SetTunnelStatisticsEnabled { enabled: bool },
SetWindowsPatchInterest { enabled: bool },
RefreshWindowsPatches { after: Option<u64> },
Connect(Box<ConnectRequest>),
Disconnect(DisconnectRequest),
StopNonTunnelAttachment { connection_id: uuid::Uuid },
@@ -187,19 +187,28 @@ mod tests {
#[test]
fn credential_round_trips_a_validated_device_anchor() {
let anchor = DeviceAnchor {
hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]),
source: crate::device_anchor::AnchorSource::UnixMac,
};
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5")
.unwrap()
.with_device_anchor(anchor.clone())
.unwrap();
let frame = credential.encode_frame().unwrap();
let payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
assert_eq!(payload["device_anchor"]["source"], 1);
let decoded = SessionCredential::decode_frame(&frame).unwrap();
assert_eq!(decoded.device_anchor(), Some(&anchor));
use crate::device_anchor::AnchorSource;
for (source, wire_source) in [
(AnchorSource::UnixMac, 1),
(AnchorSource::UnixRandom, 2),
(AnchorSource::MacosIokit, 3),
(AnchorSource::WindowsSmbios, 4),
] {
let anchor = DeviceAnchor {
hardware_id: general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]),
source,
};
let credential = SessionCredential::generate(Uuid::new_v4(), "2.6.5")
.unwrap()
.with_device_anchor(anchor.clone())
.unwrap();
let frame = credential.encode_frame().unwrap();
let payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
assert_eq!(payload["device_anchor"]["source"], wire_source);
let decoded = SessionCredential::decode_frame(&frame).unwrap();
assert_eq!(decoded.device_anchor(), Some(&anchor));
}
}
#[test]
@@ -209,7 +218,7 @@ mod tests {
let mut payload: serde_json::Value = serde_json::from_slice(&frame[2..]).unwrap();
let hardware_id = general_purpose::URL_SAFE_NO_PAD.encode([1_u8; 32]);
for source in [0, 4] {
for source in [0, u8::MAX] {
payload["device_anchor"] = serde_json::json!({
"hardware_id": hardware_id,
"source": source
@@ -55,6 +55,8 @@ pub enum ServiceResult {
offset: usize,
xml: String,
complete: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
windows_updates: Option<crate::hip::WindowsUpdateStatus>,
},
HipApprovalStatus(HipApprovalStatus),
NoSubmittedHipReport,
@@ -11,6 +11,8 @@ pub use message::{ClientMessage, ServerMessage, ServiceRejection, ServiceResult}
pub use noise::{NoiseInitiator, NoiseResponder, NoiseTransport};
pub const MAX_CREDENTIAL_FRAME: usize = 512;
/// First request read before a Windows service captures its pipe client's token.
pub const WINDOWS_ADMISSION_REQUEST: [u8; 4] = *b"GPC1";
pub const MAX_PRELUDE: usize = 256;
pub const MAX_PRODUCT_VERSION: usize = 64;
pub const HIP_PROTOCOL_VERSION: u16 = 1;
@@ -29,6 +29,11 @@ use linux as platform;
#[cfg(target_os = "macos")]
use macos as platform;
#[cfg(windows)]
mod windows;
#[cfg(windows)]
use windows as platform;
mod binding;
use super::detection;
pub mod native;
@@ -475,6 +480,7 @@ fn snapshot(interfaces: &[Interface], control: &dyn CollectionControl) -> anyhow
})
}
#[cfg(unix)]
fn command(name: &str, args: &[&str], control: &dyn CollectionControl) -> anyhow::Result<String> {
let output = CollectorCommands::new(control)
.run(name, args)?
@@ -172,6 +172,7 @@ mod tests {
);
}
#[cfg(unix)]
#[tokio::test]
async fn cancellation_kills_and_joins_the_running_resolver_process() {
let file = tempfile::NamedTempFile::new().unwrap();
@@ -0,0 +1,148 @@
//! Windows network identity from IP Helper and adapter DNS configuration.
use super::*;
use std::os::windows::io::AsRawSocket;
use windows_sys::Win32::{
NetworkManagement::IpHelper::{
DNS_INTERFACE_SETTINGS, DNS_INTERFACE_SETTINGS_VERSION1, FreeInterfaceDnsSettings, FreeMibTable,
GetInterfaceDnsSettings, GetIpForwardTable2,
},
Networking::WinSock::{
AF_INET, AF_INET6, AF_UNSPEC, IP_UNICAST_IF, IPPROTO_IP, IPPROTO_IPV6, IPV6_UNICAST_IF, SOCKADDR_INET,
SOCKET_ERROR, WSAGetLastError, setsockopt,
},
};
pub(super) fn scope_resolver_socket(
socket: &tokio::net::UdpSocket,
interface: &Interface,
endpoint: SocketAddr,
) -> anyhow::Result<()> {
ensure!(interface.index != 0, "Resolver interface index is missing");
// IP_UNICAST_IF uses network byte order; IPV6_UNICAST_IF uses host byte order.
let (level, option, index) = if endpoint.is_ipv4() {
(IPPROTO_IP, IP_UNICAST_IF, interface.index.to_be())
} else {
(IPPROTO_IPV6, IPV6_UNICAST_IF, interface.index)
};
let result = unsafe {
setsockopt(
socket.as_raw_socket() as usize,
level,
option,
(&index as *const u32).cast(),
std::mem::size_of::<u32>() as i32,
)
};
if result == SOCKET_ERROR {
return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }).into());
}
Ok(())
}
pub(super) fn routes(control: &dyn CollectionControl) -> anyhow::Result<Vec<RouteContext>> {
control.check()?;
let mut table = std::ptr::null_mut();
let status = unsafe { GetIpForwardTable2(AF_UNSPEC, &mut table) };
if status != 0 {
return Err(io::Error::from_raw_os_error(status as i32).into());
}
let interfaces = netdev::get_interfaces();
let result = unsafe {
let rows = std::slice::from_raw_parts((*table).Table.as_ptr(), (*table).NumEntries as usize);
rows
.iter()
.filter_map(|row| {
let destination = address(&row.DestinationPrefix.Prefix)?;
let gateway = address(&row.NextHop)?;
let interface = interfaces
.iter()
.find(|interface| interface.index == row.InterfaceIndex)?;
Some(RouteContext {
destination: format!("{destination}/{}", row.DestinationPrefix.PrefixLength),
gateway: gateway.to_string(),
interface: interface.name.clone(),
table: "main".into(),
metric: row.Metric.to_string(),
})
})
.collect()
};
unsafe {
FreeMibTable(table.cast());
}
control.check()?;
Ok(result)
}
unsafe fn address(address: &SOCKADDR_INET) -> Option<IpAddr> {
unsafe {
match address.si_family {
AF_INET => Some(std::net::Ipv4Addr::from(address.Ipv4.sin_addr.S_un.S_addr.to_ne_bytes()).into()),
AF_INET6 => Some(std::net::Ipv6Addr::from(address.Ipv6.sin6_addr.u.Byte).into()),
_ => None,
}
}
}
pub(super) fn resolvers(control: &dyn CollectionControl) -> anyhow::Result<Vec<ResolverContext>> {
control.check()?;
let mut resolvers = netdev::get_interfaces()
.into_iter()
.filter(|interface| !interface.dns_servers.is_empty())
.map(|interface| {
Ok(ResolverContext {
interface: Some(interface.name.clone()),
servers: interface.dns_servers.iter().map(ToString::to_string).collect(),
domains: resolver_domains(&interface.name)?,
})
})
.collect::<anyhow::Result<Vec<_>>>()?;
resolvers.sort();
control.check()?;
Ok(resolvers)
}
fn resolver_domains(interface: &str) -> anyhow::Result<Vec<String>> {
let id = uuid::Uuid::parse_str(interface.trim_matches(['{', '}']))?;
let (data1, data2, data3, data4) = id.as_fields();
let guid = windows_sys::core::GUID {
data1,
data2,
data3,
data4: *data4,
};
let mut settings = DNS_INTERFACE_SETTINGS {
Version: DNS_INTERFACE_SETTINGS_VERSION1,
..Default::default()
};
let status = unsafe { GetInterfaceDnsSettings(guid, &mut settings) };
if status != 0 {
return Err(io::Error::from_raw_os_error(status as i32).into());
}
let mut domains = Vec::new();
for pointer in [settings.Domain, settings.SearchList] {
if pointer.is_null() {
continue;
}
let text = unsafe {
let mut length = 0;
while *pointer.add(length) != 0 {
length += 1;
}
String::from_utf16_lossy(std::slice::from_raw_parts(pointer, length))
};
for domain in text
.split(|ch: char| ch == ',' || ch.is_whitespace())
.filter(|domain| !domain.is_empty())
{
let domain = domain.to_ascii_lowercase();
if !domains.contains(&domain) {
domains.push(domain);
}
}
}
unsafe {
FreeInterfaceDnsSettings(&mut settings);
}
Ok(domains)
}
@@ -45,7 +45,7 @@ fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) ->
Ok(builder.interface(binding.interface()))
}
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
#[cfg(any(target_os = "freebsd", target_os = "openbsd", windows))]
fn bind_interface(builder: reqwest::ClientBuilder, binding: &GatewayBinding) -> anyhow::Result<reqwest::ClientBuilder> {
if let std::net::SocketAddr::V6(source) = binding.source() {
anyhow::ensure!(
@@ -164,6 +164,7 @@ async fn post(
crate::utils::request::ResponseBodyError::Transport(error) => GatewayRequestError::Transport(error),
crate::utils::request::ResponseBodyError::TooLarge => GatewayRequestError::ResponseTooLarge,
})?;
crate::utils::log_response_xml(&format!("/ssl-vpn/{endpoint}"), status, &body);
parse_response(&body)
}
@@ -204,6 +204,7 @@ impl Signer for ClientSigner {
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "openssl-tests")]
use openssl::{
hash::MessageDigest,
pkey::PKey,
@@ -220,6 +221,7 @@ mod tests {
.unwrap()
}
#[cfg(feature = "openssl-tests")]
fn native_key(bytes: &[u8]) -> ClientKey {
let key = rustls_pemfile::private_key(&mut std::io::Cursor::new(bytes))
.unwrap()
@@ -227,6 +229,7 @@ mod tests {
ClientKey::load(&key).unwrap()
}
#[cfg(feature = "openssl-tests")]
#[test]
fn rsa_signatures_use_the_offered_scheme_and_tls_pss_salt_length() {
let bytes = fixture("rsa-pkcs8.pem");
@@ -255,6 +258,7 @@ mod tests {
assert!(key.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256]).is_none());
}
#[cfg(feature = "openssl-tests")]
#[test]
fn p256_signatures_verify_with_an_independent_backend() {
let bytes = fixture("ec-pkcs8.pem");
@@ -281,6 +285,7 @@ mod tests {
}
}
#[cfg(feature = "openssl-tests")]
#[test]
fn a_key_remains_usable_when_shared_clients_sign_concurrently() {
let key = native_key(&fixture("rsa-pkcs8.pem"));
+2 -2
View File
@@ -1,6 +1,6 @@
use std::path::{Path, PathBuf};
use common::constants::GP_SERVICE_LOCK_FILE;
use common::paths::service_lock_file;
use thiserror::Error;
use tokio::fs;
@@ -109,7 +109,7 @@ impl LockInfo {
}
pub async fn gpservice_lock_info() -> Result<LockInfo, LockFileError> {
gpservice_lock_info_at(GP_SERVICE_LOCK_FILE).await
gpservice_lock_info_at(service_lock_file()).await
}
pub async fn gpservice_lock_info_at(path: impl AsRef<Path>) -> Result<LockInfo, LockFileError> {
+28 -14
View File
@@ -13,6 +13,8 @@ mod identity_encoding;
#[cfg(feature = "desktop")]
pub mod lock_file;
pub mod redact;
mod response_log;
pub(crate) use response_log::log_response_xml;
pub mod request;
#[cfg(feature = "tauri")]
pub mod window;
@@ -53,16 +55,23 @@ pub fn remove_url_scheme(s: &str) -> String {
}
#[derive(Error, Debug)]
#[error("GP response error: reason={reason}, status={status}, body={body}")]
#[error("GP response error: reason={reason}, status={status}")]
pub struct GpError {
pub status: StatusCode,
pub reason: String,
body: String,
#[source]
source: Option<reqwest::Error>,
}
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()
}
@@ -79,16 +88,20 @@ pub async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError>
return Err(parse_gp_error(res).await);
}
res.text().await.map_err(|err| {
let path = log::log_enabled!(log::Level::Debug).then(|| res.url().path().to_owned());
let body = res.text().await.map_err(|err| {
warn!("Failed to read response: {}", err);
GpError {
status,
reason: "failed to read response".to_string(),
body: "<failed to read response>".to_string(),
source: Some(err),
}
})
})?;
if let Some(path) = path {
log_response_xml(&path, status, body.as_bytes());
}
Ok(body)
}
async fn parse_gp_error(res: Response) -> GpError {
@@ -99,15 +112,16 @@ async fn parse_gp_error(res: Response) -> GpError {
.map_or_else(|| "<none>", |v| v.to_str().unwrap_or("<invalid header>"))
.to_string();
let (body, source) = match res.text().await {
Ok(body) => (if body.is_empty() { "<empty>".to_string() } else { body }, None),
Err(error) => ("<failed to read response>".to_string(), Some(error)),
let path = log::log_enabled!(log::Level::Debug).then(|| res.url().path().to_owned());
let source = match res.text().await {
Ok(body) => {
if let Some(path) = path {
log_response_xml(&path, status, body.as_bytes());
}
None
}
Err(error) => Some(error),
};
GpError {
status,
reason,
body,
source,
}
GpError { status, reason, source }
}
+2
View File
@@ -266,6 +266,7 @@ mod tests {
#[test]
fn unencrypted_key_ignores_unused_password_and_archive_owned_file_is_private() {
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
let identity = ClientIdentity::from_data(
Zeroizing::new(CERTIFICATE.to_vec()),
@@ -280,6 +281,7 @@ mod tests {
let path = files.certificate().to_owned();
assert!(path.ends_with(".p12"));
assert!(files.key().is_none());
#[cfg(unix)]
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
drop(files);
assert!(!Path::new(&path).exists());
+59
View File
@@ -0,0 +1,59 @@
use gp_xml::redact_xml;
use reqwest::StatusCode;
pub(crate) fn log_response_xml(path: &str, status: StatusCode, body: &[u8]) {
if !log::log_enabled!(log::Level::Debug) {
return;
}
// Redirect paths can themselves contain authentication tokens.
let endpoint = match path {
"/global-protect/prelogin.esp"
| "/ssl-vpn/prelogin.esp"
| "/global-protect/getconfig.esp"
| "/global-protect/getconfig_csc.esp"
| "/ssl-vpn/login.esp"
| "/ssl-vpn/getconfig.esp"
| "/ssl-vpn/agentmessage.esp"
| "/ssl-vpn/hipreportcheck.esp"
| "/ssl-vpn/hipreport.esp"
| "/ssl-vpn/logout.esp" => path,
_ => "[response endpoint]",
};
// Individual XML lines remain readable in macOS unified logs with limited record sizes.
for line in redact_xml(body).lines() {
log::debug!("{endpoint} response XML (HTTP {}): {line}", status.as_u16());
}
}
#[cfg(test)]
mod tests {
use super::*;
use xmltree::Element;
#[test]
fn preserves_policy_checks_and_redacts_authentication_material() {
let input = include_str!("../../tests/fixtures/portal-response.xml");
let xml = redact_xml(input.as_bytes());
let root = Element::parse(xml.as_bytes()).unwrap();
assert!(xml.contains("custom-checks") && xml.contains("HipID") && xml.contains("NV Domain"));
assert!(xml.contains("Corp.Example.test"));
assert!(xml.contains("com.1password.1password") && xml.contains("Version"));
for secret in [
"fixture-user-cookie",
"fixture-prelogon-cookie",
"fixture-csc-cookie",
"fixture-username",
"fixture-saml",
"fixture-attribute-token",
"fixture-property-password",
"fixture-cookie-name",
"fixture-query-token",
"fixture-url-password",
"fixture-comment",
"fixture-pi",
] {
assert!(!xml.contains(secret), "secret retained: {secret}");
}
assert_eq!(root.name, "policy");
}
}
@@ -13,6 +13,9 @@ pub async fn shutdown_signal() {
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
+176
View File
@@ -0,0 +1,176 @@
//! Windows user identity and private local IPC.
use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle};
use std::{io, ptr};
mod pipes;
pub use pipes::{PacketPipe, connect_service_admission, connect_service_worker, create_service_admission_pipe};
use tokio::net::windows::named_pipe::NamedPipeServer;
use windows_sys::Win32::{
Foundation::{CloseHandle, LocalFree},
Security::{Authorization::ConvertSidToStringSidW, GetTokenInformation, TOKEN_QUERY, TOKEN_USER, TokenUser},
System::Threading::{GetCurrentProcess, OpenProcess, OpenProcessToken, PROCESS_QUERY_LIMITED_INFORMATION},
};
pub fn current_user_sid() -> io::Result<String> {
unsafe {
let mut token = ptr::null_mut();
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 {
return Err(io::Error::last_os_error());
}
let result = token_user_sid(token);
CloseHandle(token);
result
}
}
/// An authenticated pipe client's primary token, retained for its user-session worker.
/// Windows user identity is a SID and token; it is never represented as a Unix UID.
pub struct PipeClientIdentity {
sid: String,
token: OwnedHandle,
}
impl PipeClientIdentity {
pub fn sid(&self) -> &str {
&self.sid
}
pub fn primary_token(&self) -> BorrowedHandle<'_> {
self.token.as_handle()
}
/// Call after reading the client's admission request. Impersonation stays on
/// this thread and ends before returning; no asynchronous work can run in it.
pub fn from_pipe(pipe: &NamedPipeServer) -> io::Result<Self> {
use windows_sys::Win32::{
Security::{
DuplicateTokenEx, RevertToSelf, SecurityImpersonation, TOKEN_ASSIGN_PRIMARY, TOKEN_DUPLICATE, TokenPrimary,
},
System::{
Pipes::ImpersonateNamedPipeClient,
Threading::{GetCurrentThread, OpenThreadToken},
},
};
struct Revert;
impl Drop for Revert {
fn drop(&mut self) {
// Continuing a service thread as its client would corrupt its privilege
// boundary. Windows documents terminating if RevertToSelf fails.
if unsafe { RevertToSelf() } == 0 {
std::process::abort();
}
}
}
unsafe {
if ImpersonateNamedPipeClient(pipe.as_raw_handle()) == 0 {
return Err(io::Error::last_os_error());
}
let _revert = Revert;
let mut token = ptr::null_mut();
if OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_DUPLICATE, 1, &mut token) == 0 {
return Err(io::Error::last_os_error());
}
let token = OwnedHandle::from_raw_handle(token);
let sid = token_user_sid(token.as_raw_handle())?;
let mut primary = ptr::null_mut();
if DuplicateTokenEx(
token.as_raw_handle(),
TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY,
ptr::null(),
SecurityImpersonation,
TokenPrimary,
&mut primary,
) == 0
{
return Err(io::Error::last_os_error());
}
Ok(Self {
sid,
token: OwnedHandle::from_raw_handle(primary),
})
}
}
}
/// Resolve a local IPC peer from its OS process token.
pub fn process_user_sid(pid: u32) -> io::Result<String> {
unsafe {
let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
if process.is_null() {
return Err(io::Error::last_os_error());
}
let mut token = ptr::null_mut();
if OpenProcessToken(process, TOKEN_QUERY, &mut token) == 0 {
let error = io::Error::last_os_error();
CloseHandle(process);
return Err(error);
}
CloseHandle(process);
let result = token_user_sid(token);
CloseHandle(token);
result
}
}
unsafe fn token_user_sid(token: windows_sys::Win32::Foundation::HANDLE) -> io::Result<String> {
unsafe {
let mut length = 0;
GetTokenInformation(token, TokenUser, ptr::null_mut(), 0, &mut length);
// TOKEN_USER contains pointers; retain pointer alignment in its backing allocation.
let mut buffer = vec![0usize; (length as usize).div_ceil(std::mem::size_of::<usize>())];
if GetTokenInformation(token, TokenUser, buffer.as_mut_ptr().cast(), length, &mut length) == 0 {
return Err(io::Error::last_os_error());
}
let user = &*buffer.as_ptr().cast::<TOKEN_USER>();
let mut text = ptr::null_mut();
if ConvertSidToStringSidW(user.User.Sid, &mut text) == 0 {
return Err(io::Error::last_os_error());
}
let mut length = 0;
while *text.add(length) != 0 {
length += 1;
}
let sid = String::from_utf16_lossy(std::slice::from_raw_parts(text, length));
LocalFree(text.cast());
Ok(sid)
}
}
/// Only the owning user and SYSTEM can access authentication callbacks.
pub fn create_user_pipe(name: &str, first_instance: bool) -> io::Result<NamedPipeServer> {
pipes::user_pipe(&current_user_sid()?, name, first_instance)
}
/// Query a registered service without requiring access to its SYSTEM process token.
pub fn service_process_id(name: &str) -> io::Result<u32> {
use windows_sys::Win32::System::Services::*;
let name: Vec<u16> = name.encode_utf16().chain(Some(0)).collect();
unsafe {
let manager = OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT);
if manager.is_null() {
return Err(io::Error::last_os_error());
}
let service = OpenServiceW(manager, name.as_ptr(), SERVICE_QUERY_STATUS);
if service.is_null() {
let error = io::Error::last_os_error();
CloseServiceHandle(manager);
return Err(error);
}
let mut status = SERVICE_STATUS_PROCESS::default();
let mut length = 0;
let success = QueryServiceStatusEx(
service,
SC_STATUS_PROCESS_INFO,
(&mut status as *mut SERVICE_STATUS_PROCESS).cast(),
std::mem::size_of_val(&status) as u32,
&mut length,
);
let result = if success == 0 {
Err(io::Error::last_os_error())
} else {
Ok(status.dwProcessId)
};
CloseServiceHandle(service);
CloseServiceHandle(manager);
result
}
}
+202
View File
@@ -0,0 +1,202 @@
//! Local service admission and worker pipes with explicit user access.
use super::PipeClientIdentity;
use std::{
fs::OpenOptions,
io,
os::windows::{
fs::OpenOptionsExt,
io::{AsRawHandle, FromRawHandle, IntoRawHandle, OwnedHandle},
},
ptr,
time::Duration,
};
use tokio::net::windows::named_pipe::{NamedPipeClient, NamedPipeServer, ServerOptions};
use windows_sys::Win32::{
Foundation::{ERROR_IO_PENDING, ERROR_PIPE_CONNECTED, INVALID_HANDLE_VALUE, LocalFree, WAIT_OBJECT_0, WAIT_TIMEOUT},
Security::{Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW, SECURITY_ATTRIBUTES},
Storage::FileSystem::*,
System::{
IO::{CancelIoEx, GetOverlappedResult, OVERLAPPED},
Pipes::*,
Threading::{CreateEventW, WaitForSingleObject},
},
};
// Generic write also grants FILE_CREATE_PIPE_INSTANCE. Clients receive only
// data/metadata access; creating another instance remains SYSTEM-only.
const CLIENT_ACCESS: u32 = FILE_GENERIC_READ | FILE_WRITE_DATA | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES;
fn wide(value: &str) -> Vec<u16> {
value.encode_utf16().chain(Some(0)).collect()
}
fn with_security<T>(sddl: &str, operation: impl FnOnce(&SECURITY_ATTRIBUTES) -> io::Result<T>) -> io::Result<T> {
struct Descriptor(*mut std::ffi::c_void);
impl Drop for Descriptor {
fn drop(&mut self) {
unsafe {
LocalFree(self.0);
}
}
}
let mut pointer = ptr::null_mut();
if unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(wide(sddl).as_ptr(), 1, &mut pointer, ptr::null_mut())
} == 0
{
return Err(io::Error::last_os_error());
}
let descriptor = Descriptor(pointer);
operation(&SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: descriptor.0,
bInheritHandle: 0,
})
}
fn server(sddl: &str, name: &str, first: bool) -> io::Result<NamedPipeServer> {
with_security(sddl, |attributes| unsafe {
ServerOptions::new()
.first_pipe_instance(first)
.reject_remote_clients(true)
.create_with_security_attributes_raw(name, (attributes as *const SECURITY_ATTRIBUTES).cast_mut().cast())
})
}
pub(super) fn user_pipe(sid: &str, name: &str, first: bool) -> io::Result<NamedPipeServer> {
server(&format!("D:P(A;;GA;;;SY)(A;;GA;;;{sid})"), name, first)
}
pub fn create_service_admission_pipe(first: bool) -> io::Result<NamedPipeServer> {
server(
&format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;AU)"),
common::paths::SERVICE_PIPE,
first,
)
}
fn client(name: &str, message: bool, impersonation: bool) -> io::Result<NamedPipeClient> {
let file = OpenOptions::new()
.read(true)
.write(true)
.access_mode(CLIENT_ACCESS)
.custom_flags(FILE_FLAG_OVERLAPPED)
.security_qos_flags(if impersonation {
SECURITY_IMPERSONATION
} else {
SECURITY_IDENTIFICATION
})
.open(name)?;
let pipe = unsafe { NamedPipeClient::from_raw_handle(file.into_raw_handle()) }?;
let mut pid = 0;
if unsafe { GetNamedPipeServerProcessId(pipe.as_raw_handle(), &mut pid) } == 0 {
return Err(io::Error::last_os_error());
}
if pid == 0 || pid != super::service_process_id(common::paths::SERVICE_NAME)? {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"Pipe does not belong to the registered VPN service",
));
}
if message {
let mode = PIPE_READMODE_MESSAGE;
if unsafe { SetNamedPipeHandleState(pipe.as_raw_handle(), &mode, ptr::null(), ptr::null()) } == 0 {
return Err(io::Error::last_os_error());
}
}
Ok(pipe)
}
/// Verify the service before the first request permits it to impersonate this user.
pub fn connect_service_admission() -> io::Result<NamedPipeClient> {
client(common::paths::SERVICE_PIPE, false, true)
}
pub fn connect_service_worker(name: &str, message: bool) -> io::Result<NamedPipeClient> {
client(name, message, false)
}
impl PipeClientIdentity {
pub fn create_control_pipe(&self, name: &str) -> io::Result<NamedPipeServer> {
server(
&format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;{})", self.sid()),
name,
true,
)
}
pub fn create_packet_pipe(&self, name: &str) -> io::Result<PacketPipe> {
let name = wide(name);
with_security(
&format!("D:P(A;;GA;;;SY)(A;;0x{CLIENT_ACCESS:x};;;{})", self.sid()),
|attributes| {
let handle = unsafe {
CreateNamedPipeW(
name.as_ptr(),
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_REJECT_REMOTE_CLIENTS,
1,
256 * 1024,
256 * 1024,
0,
attributes,
)
};
if handle == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
Ok(PacketPipe(unsafe { OwnedHandle::from_raw_handle(handle) }))
},
)
}
}
/// Raw Win32 overlapped I/O, deliberately never registered with Tokio/Mio IOCP.
pub struct PacketPipe(OwnedHandle);
impl PacketPipe {
pub fn connect(&mut self, expected_pid: u32, timeout: Duration) -> io::Result<()> {
let event = unsafe { CreateEventW(ptr::null(), 1, 0, ptr::null()) };
if event.is_null() {
return Err(io::Error::last_os_error());
}
let event = unsafe { OwnedHandle::from_raw_handle(event) };
let mut overlap = OVERLAPPED {
hEvent: event.as_raw_handle(),
..Default::default()
};
if unsafe { ConnectNamedPipe(self.0.as_raw_handle(), &mut overlap) } == 0 {
let error = io::Error::last_os_error();
match error.raw_os_error().map(|code| code as u32) {
Some(ERROR_PIPE_CONNECTED) => {}
Some(ERROR_IO_PENDING) => {
let status = unsafe {
WaitForSingleObject(
event.as_raw_handle(),
timeout.as_millis().min(u32::MAX as u128 - 1) as u32,
)
};
let mut bytes = 0;
if status != WAIT_OBJECT_0 {
// Complete cancellation before OVERLAPPED/event storage is released.
unsafe {
CancelIoEx(self.0.as_raw_handle(), &overlap);
GetOverlappedResult(self.0.as_raw_handle(), &overlap, &mut bytes, 1);
}
if status == WAIT_TIMEOUT {
return Err(io::Error::new(io::ErrorKind::TimedOut, "Packet worker did not connect"));
}
return Err(io::Error::last_os_error());
}
if unsafe { GetOverlappedResult(self.0.as_raw_handle(), &overlap, &mut bytes, 0) } == 0 {
return Err(io::Error::last_os_error());
}
}
_ => return Err(error),
}
}
let mut pid = 0;
if unsafe { GetNamedPipeClientProcessId(self.0.as_raw_handle(), &mut pid) } == 0 {
return Err(io::Error::last_os_error());
}
if pid != expected_pid {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"Unexpected packet pipe client",
));
}
Ok(())
}
pub fn into_handle(self) -> OwnedHandle {
self.0
}
}
+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<?fixture fixture-pi?>
<policy>
<!--fixture-comment-->
<portal-userauthcookie>fixture-user-cookie</portal-userauthcookie>
<portal-prelogonuserauthcookie><![CDATA[fixture-prelogon-cookie]]></portal-prelogonuserauthcookie>
<portal-csc-auth-cookie>fixture-csc-cookie</portal-csc-auth-cookie>
<username>fixture-username</username>
<saml-request>fixture-saml</saml-request>
<property name="password" value="fixture-property-password"/>
<cookie name="fixture-cookie-name"/>
<settings auth_token="fixture-attribute-token"/>
<download href="https://user:[email protected]/client?auth=fixture-query-token"/>
<hip-collection>
<hip-report-interval>3600</hip-report-interval>
<collect-hip-data>yes</collect-hip-data>
<custom-checks>
<mac-os><plist><entry name="com.paloaltonetworks.GlobalProtect.settings"><key><member>HipID</member></key></entry><entry name="com.1password.1password"><key><member>Version</member></key></entry></plist></mac-os>
<windows><registry-key><entry name="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"><registry-value><member>Domain</member><member>NV Domain</member></registry-value></entry></registry-key></windows>
</custom-checks>
</hip-collection>
<domain>Corp.Example.test</domain>
</policy>
+13 -6
View File
@@ -93,12 +93,19 @@ fn traditional_encrypted_pem_preserves_password_errors() {
let result = load(&certificate, &key, password);
if password == Some(PASSWORD) {
let identity = result.unwrap_or_else(|error| panic!("{key:?}: {error}"));
let actual = openssl::pkey::PKey::private_key_from_pem(identity.key_data().unwrap()).unwrap();
let expected = openssl::pkey::PKey::private_key_from_pem(&bytes(&format!("{algorithm}-pkcs8.pem"))).unwrap();
assert!(
actual.public_eq(&expected),
"{key:?}: imported key differs from the fixture"
);
let public_key = |pem: &[u8]| {
let key = rustls_pemfile::private_key(&mut std::io::Cursor::new(pem))
.unwrap()
.unwrap();
rustls::crypto::ring::sign::any_supported_type(&key)
.unwrap()
.public_key()
.unwrap()
.into_owned()
};
let actual = public_key(identity.key_data().unwrap());
let expected = public_key(&bytes(&format!("{algorithm}-pkcs8.pem")));
assert!(actual == expected, "{key:?}: imported key differs from the fixture");
assert!(identity.key_password().is_none());
} else {
let error = result.unwrap_err();
+123
View File
@@ -0,0 +1,123 @@
use std::sync::Mutex;
use gpapi::utils::parse_gp_response;
use log::{LevelFilter, Log, Metadata, Record};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
};
struct Capture(Mutex<Vec<String>>);
static LOGS: Capture = Capture(Mutex::new(Vec::new()));
impl Log for Capture {
fn enabled(&self, _: &Metadata<'_>) -> bool {
true
}
fn log(&self, record: &Record<'_>) {
if record.target() == "gpapi::utils::response_log" {
self.0.lock().unwrap().push(record.args().to_string());
}
}
fn flush(&self) {}
}
async fn response(path: &str, status: &str, body: &str) -> reqwest::Response {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let data = format!(
"HTTP/1.1 {status}\r\nContent-Type: application/xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut request = [0; 4096];
socket.read(&mut request).await.unwrap();
socket.write_all(data.as_bytes()).await.unwrap();
});
reqwest::Client::builder()
.no_proxy()
.build()
.unwrap()
.get(format!("http://{address}{path}"))
.send()
.await
.unwrap()
}
#[tokio::test]
async fn logs_redacted_xml_at_debug_without_changing_responses_or_exposing_error_bodies() {
rustls::crypto::ring::default_provider().install_default().unwrap();
log::set_logger(&LOGS).unwrap();
log::set_max_level(LevelFilter::Debug);
let portal = include_str!("fixtures/portal-response.xml");
for path in [
"/global-protect/getconfig.esp",
"/global-protect/getconfig_csc.esp",
"/global-protect/prelogin.esp",
"/ssl-vpn/login.esp",
] {
let result = parse_gp_response(response(path, "200 OK", portal).await).await.unwrap();
assert_eq!(result, portal);
}
let logs = LOGS.0.lock().unwrap().join("\n");
assert!(logs.contains("getconfig.esp response XML"));
assert!(logs.contains("getconfig_csc.esp response XML"));
assert!(logs.contains("prelogin.esp response XML"));
assert!(logs.contains("login.esp response XML"));
assert!(logs.contains("custom-checks") && logs.contains("HipID"));
for secret in [
"fixture-user-cookie",
"fixture-prelogon-cookie",
"fixture-csc-cookie",
"fixture-username",
"fixture-saml",
"fixture-attribute-token",
"fixture-property-password",
"fixture-cookie-name",
"fixture-query-token",
"fixture-url-password",
"fixture-comment",
"fixture-pi",
] {
assert!(!logs.contains(secret), "logged secret: {secret}");
}
let error = parse_gp_response(response("/global-protect/getconfig.esp", "403 Forbidden", portal).await)
.await
.unwrap_err();
assert_eq!(error.status, reqwest::StatusCode::FORBIDDEN);
assert!(!format!("{error:?} {error}").contains("fixture-"));
assert!(LOGS.0.lock().unwrap().iter().any(|line| line.contains("HTTP 403")));
let error = parse_gp_response(
response(
"/global-protect/getconfig.esp",
"500 Internal Server Error",
"<html><body>fixture-error-secret</body></html>",
)
.await,
)
.await
.unwrap_err();
assert!(!format!("{error:?} {error}").contains("fixture-error-secret"));
assert!(!LOGS.0.lock().unwrap().join("\n").contains("fixture-error-secret"));
LOGS.0.lock().unwrap().clear();
let body = "<jnlp><application-desc><argument>fixture-login-cookie</argument></application-desc></jnlp>";
parse_gp_response(response("/redirect/fixture-path-token?token=fixture-query-token", "200 OK", body).await)
.await
.unwrap();
let logs = LOGS.0.lock().unwrap().join("\n");
assert!(logs.contains("[response endpoint]"));
assert!(!logs.contains("fixture-"));
LOGS.0.lock().unwrap().clear();
log::set_max_level(LevelFilter::Info);
assert_eq!(
parse_gp_response(response("/global-protect/getconfig.esp", "200 OK", portal).await)
.await
.unwrap(),
portal
);
assert!(LOGS.0.lock().unwrap().is_empty());
}
+87
View File
@@ -0,0 +1,87 @@
#![cfg(windows)]
use gpapi::windows::{PipeClientIdentity, create_user_pipe, current_user_sid};
use std::{io, os::windows::io::AsRawHandle, ptr, time::Duration};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::windows::named_pipe::ClientOptions,
};
use windows_sys::Win32::{
Foundation::{CloseHandle, ERROR_NO_TOKEN},
Security::{GetTokenInformation, TOKEN_QUERY, TOKEN_TYPE, TokenPrimary, TokenType},
Storage::FileSystem::{SECURITY_IDENTIFICATION, SECURITY_IMPERSONATION},
System::Threading::{GetCurrentThread, OpenThreadToken},
};
fn assert_reverted() {
let mut token = ptr::null_mut();
let success = unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut token) };
if success != 0 {
unsafe {
CloseHandle(token);
}
panic!("The service thread still impersonates its client");
}
assert_eq!(io::Error::last_os_error().raw_os_error(), Some(ERROR_NO_TOKEN as i32));
}
async fn admission(qos: u32) -> io::Result<PipeClientIdentity> {
let path = format!(r"\\.\pipe\GPConnect.IdentityTest.{}", uuid::Uuid::new_v4());
let mut pipe = create_user_pipe(&path, true)?;
let client = tokio::spawn(async move {
let mut pipe = ClientOptions::new().security_qos_flags(qos).open(path).unwrap();
pipe.write_all(b"admit").await.unwrap();
let mut response = [0];
pipe.read_exact(&mut response).await.unwrap();
// Confirm delivery before the server disconnects its Windows pipe.
pipe.write_all(b"ack").await.unwrap();
});
pipe.connect().await?;
let mut request = [0; 5];
pipe.read_exact(&mut request).await?;
assert_eq!(&request, b"admit");
let identity = PipeClientIdentity::from_pipe(&pipe);
assert_reverted();
pipe.write_all(&[1]).await?;
let mut ack = [0; 3];
pipe.read_exact(&mut ack).await?;
assert_eq!(&ack, b"ack");
client.await.unwrap();
identity
}
#[tokio::test]
async fn captures_primary_token_and_reverts_before_returning() {
let identity = tokio::time::timeout(Duration::from_secs(5), admission(SECURITY_IMPERSONATION))
.await
.unwrap()
.unwrap();
assert_eq!(identity.sid(), current_user_sid().unwrap());
let mut kind: TOKEN_TYPE = 0;
let mut length = 0;
assert_ne!(
unsafe {
GetTokenInformation(
identity.primary_token().as_raw_handle(),
TokenType,
(&mut kind as *mut TOKEN_TYPE).cast(),
std::mem::size_of_val(&kind) as u32,
&mut length,
)
},
0
);
assert_eq!(kind, TokenPrimary);
assert_reverted();
}
#[tokio::test]
async fn identification_only_client_cannot_supply_a_worker_token() {
assert!(
tokio::time::timeout(Duration::from_secs(5), admission(SECURITY_IDENTIFICATION))
.await
.unwrap()
.is_err()
);
assert_reverted();
}