diff --git a/Cargo.lock b/Cargo.lock index 8e67435..48e5d07 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -321,6 +321,7 @@ dependencies = [ "webkit2gtk", "webview2-com", "windows", + "windows-sys 0.61.2", "winreg 0.55.0", ] diff --git a/crates/auth/Cargo.toml b/crates/auth/Cargo.toml index e766cbc..91eab63 100644 --- a/crates/auth/Cargo.toml +++ b/crates/auth/Cargo.toml @@ -102,6 +102,7 @@ tempfile.workspace = true uzers = { workspace = true, optional = true } [target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Pipes", "Win32_UI_WindowsAndMessaging"] } # Child webviews let the Windows host own layout beside native controls. tauri = { workspace = true, optional = true, features = ["unstable"] } webview2-com = { version = "0.39", optional = true } diff --git a/crates/auth/src/callback/windows.rs b/crates/auth/src/callback/windows.rs index 42500c7..354b05f 100644 --- a/crates/auth/src/callback/windows.rs +++ b/crates/auth/src/callback/windows.rs @@ -1,15 +1,19 @@ //! Per-user Windows named pipe for browser authentication callbacks. use anyhow::{Context, bail}; use gpapi::{auth::SamlAuthData, error::AuthDataParseError}; +use std::{io, os::windows::io::AsRawHandle}; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, - net::windows::named_pipe::{ClientOptions, NamedPipeServer}, + net::windows::named_pipe::{ClientOptions, NamedPipeClient, NamedPipeServer}, time::timeout, }; #[path = "protocol.rs"] mod protocol; pub use protocol::validate_auth_callback; use protocol::*; +use windows_sys::Win32::{ + System::Pipes::GetNamedPipeServerProcessId, UI::WindowsAndMessaging::AllowSetForegroundWindow, +}; pub struct AuthCallbackReceiver { listener: NamedPipeServer, @@ -52,6 +56,9 @@ impl AuthCallbackReceiver { let _ = timeout(IO_TIMEOUT, stream.read_u8()).await; self.listener.disconnect()?; if let Some(result) = result { + if let Err(error) = delegate_foreground_to_parent() { + log::debug!("Could not delegate authentication foreground permission to the parent: {error}"); + } return result; } } @@ -76,6 +83,12 @@ pub async fn forward_auth_callback(callback: &str) -> anyhow::Result<()> { stream.write_all(callback.as_bytes()).await?; let version = stream.read_u8().await?; let status = stream.read_u8().await?; + // The receiver waits for our acknowledgement before returning to its caller. + if version == PROTOCOL_VERSION && status == STATUS_ACCEPTED { + if let Err(error) = delegate_foreground_to_receiver(&stream) { + log::debug!("Could not delegate browser foreground permission to the authenticator: {error}"); + } + } stream.write_u8(status).await?; anyhow::ensure!( version == PROTOCOL_VERSION, @@ -91,6 +104,32 @@ pub async fn forward_auth_callback(callback: &str) -> anyhow::Result<()> { .context("Timed out forwarding the authentication callback")? } +fn delegate_foreground_to_receiver(stream: &NamedPipeClient) -> io::Result<()> { + let mut process_id = 0; + unsafe { + if GetNamedPipeServerProcessId(stream.as_raw_handle(), &mut process_id) == 0 { + return Err(io::Error::last_os_error()); + } + } + allow_foreground(process_id) +} + +fn delegate_foreground_to_parent() -> anyhow::Result<()> { + let Some(process_id) = std::env::var_os(gpapi::process::auth_launcher::AUTH_PARENT_PROCESS_ID_ENV) else { + return Ok(()); + }; + let process_id = process_id.to_string_lossy().parse::()?; + allow_foreground(process_id)?; + Ok(()) +} + +fn allow_foreground(process_id: u32) -> io::Result<()> { + if unsafe { AllowSetForegroundWindow(process_id) } == 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + pub fn ensure_auth_callback_handler() -> anyhow::Result<()> { use winreg::{RegKey, enums::HKEY_CURRENT_USER}; let executable = common::binary_paths::gpauth(); diff --git a/crates/gpapi/src/process/auth_launcher.rs b/crates/gpapi/src/process/auth_launcher.rs index c54028a..fdd51c5 100644 --- a/crates/gpapi/src/process/auth_launcher.rs +++ b/crates/gpapi/src/process/auth_launcher.rs @@ -21,6 +21,10 @@ use super::rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible, is_c 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, @@ -197,6 +201,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 { @@ -493,6 +499,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. diff --git a/crates/openconnect/deps/openconnect b/crates/openconnect/deps/openconnect index c312e48..80b4f80 160000 --- a/crates/openconnect/deps/openconnect +++ b/crates/openconnect/deps/openconnect @@ -1 +1 @@ -Subproject commit c312e48d4fb5ff40f074e1c75bb848bf34e45871 +Subproject commit 80b4f80926c45f1210af4dcc2b332af199027d20 diff --git a/packaging/windows/README.md b/packaging/windows/README.md index 546084c..519a0d3 100644 --- a/packaging/windows/README.md +++ b/packaging/windows/README.md @@ -11,6 +11,11 @@ the payload. Each installer accepts only its native Windows architecture. ARM64 requires Windows 11; x64 requires Windows 10 build 19041 or newer. +The native library build accepts `scripts/build-openconnect-windows.ps1 -TunnelType 'GP Connect'` +(the default). This passes OpenConnect's `--with-wintun-tunnel-type` build option; +OpenConnect itself defaults to `OpenConnect`. Wintun appends ` Tunnel` to the +selected type. The gateway-based connection name is unchanged. + `BUILD_VERSION` must contain four numeric components. `PRODUCT_VERSION` must match the payload's `build-info.json`. `DISPLAY_VERSION` is the full release identity, including the snapshot build when applicable. The payload must contain matching diff --git a/scripts/build-openconnect-windows.ps1 b/scripts/build-openconnect-windows.ps1 index 385cfcb..9b173e2 100644 --- a/scripts/build-openconnect-windows.ps1 +++ b/scripts/build-openconnect-windows.ps1 @@ -5,7 +5,8 @@ param( [string]$MsysRoot = 'C:\msys64', [ValidateSet('mingw64','ucrt64','clangarm64')][string]$MsysSubsystem = 'mingw64', [string]$Prefix, - [int]$Jobs = 4 + [int]$Jobs = 4, + [ValidateNotNullOrEmpty()][string]$TunnelType = 'GP Connect' ) $ErrorActionPreference = 'Stop' $repo = Split-Path $PSScriptRoot -Parent @@ -14,7 +15,7 @@ $Prefix = [System.IO.Path]::GetFullPath($Prefix) $bash = Join-Path $MsysRoot 'usr\bin\bash.exe' if (!(Test-Path $bash)) { throw 'MSYS2 is required to build OpenConnect.' } $ErrorActionPreference = 'Continue' -& $bash "$PSScriptRoot/build-openconnect-windows.sh" $repo $Prefix $Jobs $MsysSubsystem +& $bash "$PSScriptRoot/build-openconnect-windows.sh" $repo $Prefix $Jobs $MsysSubsystem $TunnelType $nativeExit = $LASTEXITCODE $ErrorActionPreference = 'Stop' if ($nativeExit -ne 0) { throw 'OpenConnect compilation failed.' } diff --git a/scripts/build-openconnect-windows.sh b/scripts/build-openconnect-windows.sh index 9399f28..294b512 100644 --- a/scripts/build-openconnect-windows.sh +++ b/scripts/build-openconnect-windows.sh @@ -6,6 +6,7 @@ export PATH="/$subsystem/bin:/usr/bin:$PATH" repo=$(cygpath -u "$1") prefix=$(cygpath -u "$2") jobs=$3 +tunnel_type=$5 export ACLOCAL_PATH="/$subsystem/share/aclocal" source_dir="$repo/crates/openconnect/deps/openconnect" build_dir="$repo/target/openconnect-windows" @@ -22,7 +23,7 @@ fi --enable-shared --disable-static --disable-nls --disable-docs --disable-dsa-tests \ --without-libproxy --without-stoken --without-libpcsclite --without-libpskc \ --without-gssapi --with-gnutls --without-openssl --with-gnutls-tss2=no \ - --with-vpnc-script=unused + --with-vpnc-script=unused --with-wintun-tunnel-type="$tunnel_type" grep -q '^#define OPENCONNECT_GNUTLS 1$' config.h make -j"$jobs" libopenconnect.la make install-libLTLIBRARIES