From 918abeb9bc25a842181a4f9c55fa8697b464b3c3 Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Wed, 5 Aug 2026 20:07:28 +0800 Subject: [PATCH] feat: add standalone auth callback transport --- Cargo.lock | 3 +- Makefile | 3 + apps/gpauth/src/cli.rs | 48 +- apps/gpclient/src/cli.rs | 13 - apps/gpclient/src/launch_gui.rs | 36 +- crates/auth/Cargo.toml | 8 +- crates/auth/src/browser/browser_auth.rs | 50 +- crates/auth/src/callback.rs | 445 ++++++++++++++++++ crates/auth/src/lib.rs | 6 + crates/gpapi/src/auth.rs | 3 +- docs/bsd-source-build.md | 4 +- flake.nix | 81 ++-- .../globalprotect-openconnect-git/.SRCINFO | 1 + .../globalprotect-openconnect-git/PKGBUILD | 2 +- packaging/bsd/freebsd/MANIFEST.in | 4 + packaging/bsd/gpauth.desktop | 11 + packaging/bsd/gpgui.desktop | 3 +- packaging/deb/control.in | 1 + .../usr/share/applications/gpauth.desktop | 3 +- .../usr/share/applications/gpgui.desktop | 3 +- .../rpm/globalprotect-openconnect.spec.in | 1 + 21 files changed, 581 insertions(+), 148 deletions(-) create mode 100644 crates/auth/src/callback.rs create mode 100644 packaging/bsd/gpauth.desktop diff --git a/Cargo.lock b/Cargo.lock index ec1927a..543e405 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -219,7 +219,6 @@ dependencies = [ "anyhow", "block2", "browser-launcher", - "common", "gpapi", "html-escape", "log", @@ -228,10 +227,12 @@ dependencies = [ "objc2-web-kit", "regex", "tauri", + "tempfile", "tiny_http", "tokio", "tokio-util", "uuid", + "uzers", "webkit2gtk", ] diff --git a/Makefile b/Makefile index 5071797..25097d5 100644 --- a/Makefile +++ b/Makefile @@ -195,6 +195,7 @@ install-bsd: install -d $(DESTDIR)$(PREFIX)/share/applications install -m 644 packaging/bsd/gpgui.desktop $(DESTDIR)$(PREFIX)/share/applications/gpgui.desktop + install -m 644 packaging/bsd/gpauth.desktop $(DESTDIR)$(PREFIX)/share/applications/gpauth.desktop install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/scalable/apps install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/32x32/apps install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/128x128/apps @@ -260,6 +261,7 @@ package-openbsd: clean-bsd-package gnome_keyring_pkg=$$(pkg_info -e 'gnome-keyring-*' | sed 's/^inst://' | head -n 1); \ polkit_pkg=$$(pkg_info -e 'polkit-*' | sed 's/^inst://' | head -n 1); \ webkitgtk_pkg=$$(pkg_info -e 'webkitgtk41-*' | sed 's/^inst://' | head -n 1); \ + xdg_utils_pkg=$$(pkg_info -e 'xdg-utils-*' | sed 's/^inst://' | head -n 1); \ pkg_create \ -B .build/openbsd/pkgroot \ -D COMMENT="$$comment" \ @@ -269,6 +271,7 @@ package-openbsd: clean-bsd-package -P x11/gnome/keyring:gnome-keyring-*:$$gnome_keyring_pkg \ -P sysutils/polkit:polkit-*:$$polkit_pkg \ -P www/webkitgtk4,webkitgtk41:webkitgtk41-*:$$webkitgtk_pkg \ + -P devel/xdg-utils:xdg-utils-*:$$xdg_utils_pkg \ .build/openbsd/artifacts/$(PKG_NAME)-$(VERSION)-openbsd-$$openbsd_arch.tgz $(MAKE) bsd-gpgui-tarball BSD_FLAVOR=openbsd GPGUI_BINARY="$(GPGUI_BINARY)" diff --git a/apps/gpauth/src/cli.rs b/apps/gpauth/src/cli.rs index 18ae3fc..b2dbdcc 100644 --- a/apps/gpauth/src/cli.rs +++ b/apps/gpauth/src/cli.rs @@ -1,5 +1,5 @@ -use auth::{BrowserAuthenticator, auth_prelogin}; -use clap::Parser; +use auth::{BrowserAuthenticator, auth_prelogin, forward_auth_callback}; +use clap::{Parser, Subcommand}; #[cfg(feature = "webview-auth")] use gpapi::auth::AuthWindowTheme; use gpapi::{ @@ -27,6 +27,8 @@ const VERSION: &str = concat!( version = VERSION, author, about = "The authentication component for the GlobalProtect VPN client, supports the SSO authentication method.", + args_conflicts_with_subcommands = true, + subcommand_negates_reqs = true, help_template = "\ {before-help}{name} {version} {author} @@ -41,8 +43,11 @@ See 'gpauth -h' for more information. " )] struct Cli { - #[arg(help = "The portal server to authenticate")] - server: String, + #[command(subcommand)] + command: Option, + + #[arg(required = true, help = "The portal server to authenticate")] + server: Option, #[arg(long, help = "Treating the server as a gateway")] gateway: bool, @@ -110,6 +115,15 @@ struct Cli { verbose: InfoLevelVerbosity, } +#[derive(Subcommand)] +enum CliCommand { + #[command(hide = true)] + AuthCallback { + #[arg(help = "The globalprotectcallback URL to forward")] + callback: String, + }, +} + impl Args for Cli { fn fix_openssl(&self) -> bool { self.fix_openssl @@ -142,7 +156,7 @@ impl Cli { let openssl_conf = self.prepare_env()?; - let server = normalize_server(&self.server)?; + let server = normalize_server(self.server.as_deref().expect("server is required for authentication"))?; let gp_params = self.build_gp_params(); info!( "gpauth auth host-id: {}", @@ -235,6 +249,14 @@ fn init_logger(cli: &Cli) { pub async fn run() { let cli = Cli::parse(); + if let Some(CliCommand::AuthCallback { callback }) = &cli.command { + if let Err(err) = forward_auth_callback(callback).await { + eprintln!("Failed to forward authentication callback: {err}"); + std::process::exit(1); + } + return; + } + init_logger(&cli); info!("gpauth started: {}", VERSION); @@ -271,6 +293,22 @@ mod tests { assert_eq!(cli.os, Os::default()); } + #[test] + fn callback_arguments_parse_separately() { + let cli = Cli::try_parse_from([ + "gpauth", + "auth-callback", + "globalprotectcallback:cas-as=1&un=alice@example.com&token=token", + ]) + .unwrap(); + + assert!(matches!( + cli.command, + Some(CliCommand::AuthCallback { callback }) if callback.starts_with("globalprotectcallback:") + )); + assert!(cli.server.is_none()); + } + #[test] fn host_id_arg_sets_profile_host_id_seed() { let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--host-id", "host-seed"]) diff --git a/apps/gpclient/src/cli.rs b/apps/gpclient/src/cli.rs index 886637c..d8c26c0 100644 --- a/apps/gpclient/src/cli.rs +++ b/apps/gpclient/src/cli.rs @@ -1,6 +1,4 @@ use std::{ - env::temp_dir, - fs::File, path::{Path, PathBuf}, str::FromStr, }; @@ -165,17 +163,6 @@ fn init_logger(cli: &Cli) { let mut builder = env_logger::builder(); builder.filter_level(cli.verbose.log_level_filter()); - // Output the log messages to a file if the command is the auth callback - if let CliCommand::LaunchGui(args) = &cli.command { - let auth_data = args.auth_data.as_deref().unwrap_or_default(); - if !auth_data.is_empty() - && let Ok(log_file) = File::create(temp_dir().join("gpcallback.log")) - { - let target = Box::new(log_file); - builder.target(env_logger::Target::Pipe(target)); - } - } - builder.init(); } diff --git a/apps/gpclient/src/launch_gui.rs b/apps/gpclient/src/launch_gui.rs index 958270f..58bdf40 100644 --- a/apps/gpclient/src/launch_gui.rs +++ b/apps/gpclient/src/launch_gui.rs @@ -1,22 +1,15 @@ -use std::{collections::HashMap, env::temp_dir, fs, path::PathBuf}; +use std::{collections::HashMap, fs, path::PathBuf}; use clap::Args; -use common::constants::GP_CALLBACK_PORT_FILENAME; use directories::ProjectDirs; use gpapi::{ process::service_launcher::ServiceLauncher, utils::{endpoint::http_endpoint, env_utils, shutdown_signal}, }; use log::info; -use tokio::io::AsyncWriteExt; #[derive(Args)] pub(crate) struct LaunchGuiArgs { - #[arg( - required = false, - help = "The authentication data, used for the default browser authentication" - )] - pub auth_data: Option, #[arg(long, help = "Launch the GUI minimized")] minimized: bool, } @@ -37,13 +30,6 @@ impl<'a> LaunchGuiHandler<'a> { anyhow::bail!("`launch-gui` cannot be run as root"); } - let auth_data = self.args.auth_data.as_deref().unwrap_or_default(); - if !auth_data.is_empty() { - info!("Received auth callback data"); - // Process the authentication data, its format is `globalprotectcallback:` - return feed_auth_data(auth_data).await; - } - if try_active_gui().await.is_ok() { info!("The GUI is already running"); return Ok(()); @@ -80,26 +66,6 @@ impl<'a> LaunchGuiHandler<'a> { } } -async fn feed_auth_data(auth_data: &str) -> anyhow::Result<()> { - if let Err(err) = feed_auth_data_cli(auth_data).await { - info!("Failed to feed auth data to the CLI: {}", err); - } - - Ok(()) -} - -async fn feed_auth_data_cli(auth_data: &str) -> anyhow::Result<()> { - info!("Feeding auth data to the CLI"); - - let port_file = temp_dir().join(GP_CALLBACK_PORT_FILENAME); - let port = tokio::fs::read_to_string(port_file).await?; - let mut stream = tokio::net::TcpStream::connect(format!("127.0.0.1:{}", port.trim())).await?; - - stream.write_all(auth_data.as_bytes()).await?; - - Ok(()) -} - async fn try_active_gui() -> anyhow::Result<()> { let service_endpoint = http_endpoint().await?; diff --git a/crates/auth/Cargo.toml b/crates/auth/Cargo.toml index 79d86f7..be35c59 100644 --- a/crates/auth/Cargo.toml +++ b/crates/auth/Cargo.toml @@ -8,18 +8,18 @@ edition.workspace = true license.workspace = true [dependencies] -common = { path = "../common" } gpapi = { path = "../gpapi" } # Shared dependencies anyhow.workspace = true log.workspace = true -tokio.workspace = true +tokio = { workspace = true, features = ["io-util", "net", "time"] } # Browser auth dependencies browser-launcher = { path = "../browser-launcher", default-features = false, features = ["launcher"], optional = true } tiny_http = { version = "0.12", optional = true } uuid = { version = "1", optional = true, features = ["v4"] } +uzers = { workspace = true, optional = true } # Webview auth dependencies tauri = { workspace = true, optional = true } @@ -41,6 +41,7 @@ browser-auth = [ "dep:browser-launcher", "dep:tiny_http", "dep:uuid", + "dep:uzers", ] webview-auth = [ "gpapi/tauri", @@ -55,3 +56,6 @@ webview-auth = [ "dep:objc2-web-kit", ] release-devtools = ["webview-auth", "tauri/devtools"] + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/auth/src/browser/browser_auth.rs b/crates/auth/src/browser/browser_auth.rs index ff247f4..19558c2 100644 --- a/crates/auth/src/browser/browser_auth.rs +++ b/crates/auth/src/browser/browser_auth.rs @@ -1,15 +1,9 @@ -use std::{env::temp_dir, fs, os::unix::fs::PermissionsExt}; - use browser_launcher::Browser as LaunchBrowser; -use common::constants::GP_CALLBACK_PORT_FILENAME; use gpapi::auth::SamlAuthData; use log::info; -use tokio::{ - io::AsyncReadExt, - net::{TcpListener, UdpSocket}, -}; +use tokio::net::UdpSocket; -use crate::browser::auth_server::AuthServer; +use crate::{AuthCallbackReceiver, browser::auth_server::AuthServer, ensure_auth_callback_handler}; pub struct BrowserAuthenticator<'a> { auth_request: &'a str, @@ -22,6 +16,12 @@ impl<'a> BrowserAuthenticator<'a> { } pub async fn authenticate(&self) -> anyhow::Result { + let callback_receiver = if is_remote_browser(self.browser) { + None + } else { + ensure_auth_callback_handler()?; + Some(AuthCallbackReceiver::bind()?) + }; let addr = self.determine_addr().await?; let auth_server = AuthServer::new(&addr)?; let auth_url = auth_server.auth_url(); @@ -54,7 +54,7 @@ Note that the URL is only valid for a single use. browser_launcher::open_url(&auth_url, LaunchBrowser::from_name(self.browser))?; info!("Please continue the authentication process in the default browser"); - wait_auth_data().await + callback_receiver.unwrap().receive().await } async fn determine_addr(&self) -> anyhow::Result { @@ -84,38 +84,6 @@ async fn detect_local_ip() -> anyhow::Result { Ok(ip.to_string()) } -async fn wait_auth_data() -> anyhow::Result { - // Start a local server to receive the browser authentication data - let listener = TcpListener::bind("127.0.0.1:0").await?; - let port = listener.local_addr()?.port(); - let port_file = temp_dir().join(GP_CALLBACK_PORT_FILENAME); - - // Write the port to a file - fs::write(&port_file, port.to_string())?; - fs::set_permissions(&port_file, fs::Permissions::from_mode(0o600))?; - - // Remove the previous log file - let callback_log = temp_dir().join("gpcallback.log"); - let _ = fs::remove_file(&callback_log); - - info!("Listening authentication data on port {}", port); - info!( - "If it hangs, please check the logs at `{}` for more information", - callback_log.display() - ); - let (mut socket, _) = listener.accept().await?; - - info!("Received the browser authentication data from the socket"); - let mut data = String::new(); - socket.read_to_string(&mut data).await?; - - // Remove the port file - fs::remove_file(&port_file)?; - - let auth_data = SamlAuthData::from_gpcallback(&data)?; - Ok(auth_data) -} - fn read_auth_data_from_stdin() -> anyhow::Result { let mut data = String::new(); std::io::stdin().read_line(&mut data)?; diff --git a/crates/auth/src/callback.rs b/crates/auth/src/callback.rs new file mode 100644 index 0000000..e8907eb --- /dev/null +++ b/crates/auth/src/callback.rs @@ -0,0 +1,445 @@ +use std::{ + fs::{self, DirBuilder, OpenOptions, TryLockError}, + io::ErrorKind, + os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt}, + path::{Path, PathBuf}, + time::Duration, +}; + +use anyhow::{Context, bail}; +use gpapi::auth::SamlAuthData; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{UnixListener, UnixStream}, + time::timeout, +}; + +const CALLBACK_SCHEME: &str = "globalprotectcallback"; +const PROTOCOL_MAGIC: &[u8; 4] = b"GPAC"; +const PROTOCOL_VERSION: u8 = 1; +const MAX_CALLBACK_SIZE: usize = 1024 * 1024; +const IO_TIMEOUT: Duration = Duration::from_secs(5); + +const STATUS_ACCEPTED: u8 = 0; +const STATUS_INVALID_CALLBACK: u8 = 1; +const STATUS_UNSUPPORTED_VERSION: u8 = 2; + +pub struct AuthCallbackReceiver { + listener: UnixListener, + socket_path: PathBuf, + _lock_file: fs::File, +} + +impl AuthCallbackReceiver { + pub fn bind() -> anyhow::Result { + let socket_path = callback_socket_path(); + prepare_socket_directory(&socket_path)?; + Self::bind_at(socket_path) + } + + fn bind_at(socket_path: PathBuf) -> anyhow::Result { + let lock_file = acquire_lock(&socket_path)?; + match fs::symlink_metadata(&socket_path) { + Ok(_) => remove_stale_socket(&socket_path)?, + Err(err) if err.kind() == ErrorKind::NotFound => {} + Err(err) => return Err(err.into()), + } + finish_bind(UnixListener::bind(&socket_path)?, socket_path, lock_file) + } + + pub async fn receive(&self) -> anyhow::Result { + loop { + let (mut stream, _) = self.listener.accept().await?; + let callback = match timeout(IO_TIMEOUT, read_callback(&mut stream)).await { + Ok(callback) => callback, + Err(_) => continue, + }; + match callback { + Ok(callback) => match SamlAuthData::from_gpcallback(&callback) { + Ok(auth_data) => { + let _ = write_response(&mut stream, STATUS_ACCEPTED).await; + return Ok(auth_data); + } + Err(_) => { + let _ = write_response(&mut stream, STATUS_INVALID_CALLBACK).await; + } + }, + Err(CallbackReadError::UnsupportedVersion) => { + let _ = write_response(&mut stream, STATUS_UNSUPPORTED_VERSION).await; + } + Err(CallbackReadError::Invalid) => { + let _ = write_response(&mut stream, STATUS_INVALID_CALLBACK).await; + } + Err(CallbackReadError::Io) => continue, + } + } + } +} + +impl Drop for AuthCallbackReceiver { + fn drop(&mut self) { + if fs::symlink_metadata(&self.socket_path) + .is_ok_and(|metadata| metadata.file_type().is_socket() && metadata.uid() == uzers::get_current_uid()) + { + let _ = fs::remove_file(&self.socket_path); + } + } +} + +pub async fn forward_auth_callback(callback: &str) -> anyhow::Result<()> { + validate_callback(callback)?; + forward_auth_callback_to(callback, &callback_socket_path()).await +} + +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +pub fn ensure_auth_callback_handler() -> anyhow::Result<()> { + const MIME_TYPE: &str = "x-scheme-handler/globalprotectcallback"; + const HANDLER: &str = "gpauth.desktop"; + + let current_handler = query_callback_handler(MIME_TYPE)?; + if !should_register_handler(¤t_handler)? { + return Ok(()); + } + + let status = std::process::Command::new("xdg-mime") + .args(["default", HANDLER, MIME_TYPE]) + .status() + .context("xdg-mime is required for external-browser authentication")?; + if !status.success() { + bail!("Failed to register the globalprotectcallback URL handler"); + } + if query_callback_handler(MIME_TYPE)? != HANDLER { + bail!("The globalprotectcallback URL handler registration did not take effect"); + } + + Ok(()) +} + +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] +fn query_callback_handler(mime_type: &str) -> anyhow::Result { + let output = std::process::Command::new("xdg-mime") + .args(["query", "default", mime_type]) + .output() + .context("xdg-mime is required for external-browser authentication")?; + if !output.status.success() { + bail!("Failed to query the globalprotectcallback URL handler"); + } + Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()) +} + +#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))] +pub fn ensure_auth_callback_handler() -> anyhow::Result<()> { + Ok(()) +} + +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))] +fn should_register_handler(current_handler: &str) -> anyhow::Result { + match current_handler { + "gpauth.desktop" => Ok(false), + "" | "gpgui.desktop" => Ok(true), + handler => bail!("The globalprotectcallback URL scheme is owned by {handler}"), + } +} + +async fn forward_auth_callback_to(callback: &str, socket_path: &Path) -> anyhow::Result<()> { + validate_callback(callback)?; + + let (version, status) = timeout(IO_TIMEOUT, async { + let mut stream = UnixStream::connect(socket_path) + .await + .context("No external-browser authentication is waiting for a callback")?; + stream.write_all(PROTOCOL_MAGIC).await?; + stream.write_u8(PROTOCOL_VERSION).await?; + stream.write_u32(callback.len() as u32).await?; + stream.write_all(callback.as_bytes()).await?; + Ok::<_, anyhow::Error>((stream.read_u8().await?, stream.read_u8().await?)) + }) + .await + .context("Timed out forwarding the authentication callback")??; + if version != PROTOCOL_VERSION { + bail!("Authentication callback protocol version mismatch"); + } + + match status { + STATUS_ACCEPTED => Ok(()), + STATUS_INVALID_CALLBACK => bail!("Authentication callback was rejected"), + STATUS_UNSUPPORTED_VERSION => bail!("Authentication callback protocol version is unsupported"), + _ => bail!("Authentication callback handler returned an unknown status"), + } +} + +fn callback_socket_path() -> PathBuf { + let uid = uzers::get_current_uid(); + + #[cfg(target_os = "linux")] + { + let runtime_dir = PathBuf::from(format!("/run/user/{uid}")); + if fs::symlink_metadata(&runtime_dir).is_ok_and(|metadata| { + metadata.is_dir() + && !metadata.file_type().is_symlink() + && metadata.uid() == uid + && metadata.permissions().mode() & 0o077 == 0 + }) { + return runtime_dir.join("gp-connect/auth-callback.sock"); + } + } + + PathBuf::from(format!("/tmp/gp-connect-{uid}/auth-callback.sock")) +} + +fn prepare_socket_directory(socket_path: &Path) -> anyhow::Result<()> { + let directory = socket_path + .parent() + .ok_or_else(|| anyhow::anyhow!("Authentication callback socket has no parent directory"))?; + + match DirBuilder::new().mode(0o700).create(directory) { + Ok(()) => {} + Err(err) if err.kind() == ErrorKind::AlreadyExists => { + let metadata = fs::symlink_metadata(directory)?; + if !metadata.is_dir() || metadata.file_type().is_symlink() { + bail!("Authentication callback runtime path is not a directory"); + } + if metadata.uid() != uzers::get_current_uid() { + bail!("Authentication callback runtime directory has the wrong owner"); + } + if metadata.permissions().mode() & 0o077 != 0 { + bail!("Authentication callback runtime directory permissions are too broad"); + } + } + Err(err) => return Err(err.into()), + } + + Ok(()) +} + +fn finish_bind( + listener: UnixListener, + socket_path: PathBuf, + lock_file: fs::File, +) -> anyhow::Result { + fs::set_permissions(&socket_path, fs::Permissions::from_mode(0o600))?; + Ok(AuthCallbackReceiver { + listener, + socket_path, + _lock_file: lock_file, + }) +} + +fn acquire_lock(socket_path: &Path) -> anyhow::Result { + let lock_path = socket_path.with_file_name("auth-callback.lock"); + let lock_file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .open(lock_path)?; + lock_file.set_permissions(fs::Permissions::from_mode(0o600))?; + + match lock_file.try_lock() { + Ok(()) => Ok(lock_file), + Err(TryLockError::WouldBlock) => bail!("Another external-browser authentication is already in progress"), + Err(TryLockError::Error(err)) => Err(err.into()), + } +} + +fn remove_stale_socket(socket_path: &Path) -> anyhow::Result<()> { + let metadata = fs::symlink_metadata(socket_path)?; + if !metadata.file_type().is_socket() || metadata.uid() != uzers::get_current_uid() { + bail!("Authentication callback socket is not owned by the current user"); + } + + fs::remove_file(socket_path)?; + Ok(()) +} + +fn validate_callback(callback: &str) -> anyhow::Result<()> { + if callback.len() > MAX_CALLBACK_SIZE { + bail!("Authentication callback exceeds the maximum supported size"); + } + + let Some((scheme, data)) = callback.split_once(':') else { + bail!("Authentication callback URL is invalid"); + }; + if scheme != CALLBACK_SCHEME || data.is_empty() { + bail!("Authentication callback URL is invalid"); + } + + Ok(()) +} + +enum CallbackReadError { + UnsupportedVersion, + Invalid, + Io, +} + +async fn read_callback(stream: &mut UnixStream) -> Result { + let mut magic = [0_u8; 4]; + stream.read_exact(&mut magic).await.map_err(|_| CallbackReadError::Io)?; + if &magic != PROTOCOL_MAGIC { + return Err(CallbackReadError::Invalid); + } + + let version = stream.read_u8().await.map_err(|_| CallbackReadError::Io)?; + if version != PROTOCOL_VERSION { + return Err(CallbackReadError::UnsupportedVersion); + } + + let length = stream.read_u32().await.map_err(|_| CallbackReadError::Io)? as usize; + if length == 0 || length > MAX_CALLBACK_SIZE { + return Err(CallbackReadError::Invalid); + } + + let mut payload = vec![0; length]; + stream + .read_exact(&mut payload) + .await + .map_err(|_| CallbackReadError::Io)?; + let callback = String::from_utf8(payload).map_err(|_| CallbackReadError::Invalid)?; + validate_callback(&callback).map_err(|_| CallbackReadError::Invalid)?; + Ok(callback) +} + +async fn write_response(stream: &mut UnixStream, status: u8) -> anyhow::Result<()> { + stream.write_u8(PROTOCOL_VERSION).await?; + stream.write_u8(status).await?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use tempfile::tempdir; + + use super::*; + + const VALID_CALLBACK: &str = "globalprotectcallback:cas-as=1&un=alice@example.com&token=very_long_string"; + + #[test] + fn validates_supported_callback_scheme() { + assert!(validate_callback(VALID_CALLBACK).is_ok()); + assert!(validate_callback("https://example.com").is_err()); + assert!(validate_callback("globalprotectcallback:").is_err()); + assert!(validate_callback(&format!("globalprotectcallback:{}", "x".repeat(MAX_CALLBACK_SIZE))).is_err()); + } + + #[test] + fn preserves_unrelated_callback_handler() { + assert!(!should_register_handler("gpauth.desktop").unwrap()); + assert!(should_register_handler("").unwrap()); + assert!(should_register_handler("gpgui.desktop").unwrap()); + assert!(should_register_handler("other-vpn.desktop").is_err()); + } + + #[tokio::test] + async fn forwards_callback_to_waiting_receiver() { + let directory = tempdir().unwrap(); + let socket_path = directory.path().join("callback.sock"); + let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap(); + assert_eq!( + fs::symlink_metadata(&socket_path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + + let sender = tokio::spawn(async move { forward_auth_callback_to(VALID_CALLBACK, &socket_path).await }); + let auth_data = receiver.receive().await.unwrap(); + + sender.await.unwrap().unwrap(); + assert_eq!(auth_data.username(), "alice@example.com"); + assert_eq!(auth_data.token(), Some("very_long_string")); + let socket_path = receiver.socket_path.clone(); + drop(receiver); + assert!(!socket_path.exists()); + } + + #[tokio::test] + async fn rejects_bad_requests_and_keeps_waiting() { + let directory = tempdir().unwrap(); + let socket_path = directory.path().join("callback.sock"); + let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap(); + + let sender = tokio::spawn(async move { + assert_eq!( + send_raw_callback(&socket_path, PROTOCOL_VERSION, "https://example.com").await, + STATUS_INVALID_CALLBACK + ); + assert_eq!( + send_raw_callback(&socket_path, PROTOCOL_VERSION + 1, VALID_CALLBACK).await, + STATUS_UNSUPPORTED_VERSION + ); + forward_auth_callback_to(VALID_CALLBACK, &socket_path).await + }); + let auth_data = receiver.receive().await.unwrap(); + + sender.await.unwrap().unwrap(); + assert_eq!(auth_data.username(), "alice@example.com"); + } + + #[tokio::test] + async fn ignores_sender_that_disconnects_before_sending() { + let directory = tempdir().unwrap(); + let socket_path = directory.path().join("callback.sock"); + let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap(); + + drop(UnixStream::connect(&socket_path).await.unwrap()); + let sender = tokio::spawn(async move { forward_auth_callback_to(VALID_CALLBACK, &socket_path).await }); + let auth_data = receiver.receive().await.unwrap(); + + sender.await.unwrap().unwrap(); + assert_eq!(auth_data.username(), "alice@example.com"); + } + + #[tokio::test] + async fn replaces_owned_stale_socket() { + let directory = tempdir().unwrap(); + let socket_path = directory.path().join("callback.sock"); + drop(std::os::unix::net::UnixListener::bind(&socket_path).unwrap()); + + let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap(); + assert!(socket_path.exists()); + drop(receiver); + assert!(!socket_path.exists()); + } + + #[tokio::test] + async fn reports_when_no_receiver_is_active() { + let directory = tempdir().unwrap(); + let socket_path = directory.path().join("missing.sock"); + + let err = forward_auth_callback_to(VALID_CALLBACK, &socket_path) + .await + .unwrap_err(); + assert!(err.to_string().contains("No external-browser authentication")); + } + + #[test] + fn rejects_runtime_directory_with_broad_permissions() { + let directory = tempdir().unwrap(); + let runtime_dir = directory.path().join("runtime"); + fs::create_dir(&runtime_dir).unwrap(); + fs::set_permissions(&runtime_dir, fs::Permissions::from_mode(0o755)).unwrap(); + + let err = prepare_socket_directory(&runtime_dir.join("callback.sock")).unwrap_err(); + assert!(err.to_string().contains("permissions are too broad")); + } + + #[tokio::test] + async fn rejects_second_active_receiver() { + let directory = tempdir().unwrap(); + let socket_path = directory.path().join("callback.sock"); + let _receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap(); + + let err = AuthCallbackReceiver::bind_at(socket_path).err().unwrap(); + assert!(err.to_string().contains("already in progress")); + } + + async fn send_raw_callback(socket_path: &Path, version: u8, callback: &str) -> u8 { + let mut stream = UnixStream::connect(socket_path).await.unwrap(); + stream.write_all(PROTOCOL_MAGIC).await.unwrap(); + stream.write_u8(version).await.unwrap(); + stream.write_u32(callback.len() as u32).await.unwrap(); + stream.write_all(callback.as_bytes()).await.unwrap(); + assert_eq!(stream.read_u8().await.unwrap(), PROTOCOL_VERSION); + stream.read_u8().await.unwrap() + } +} diff --git a/crates/auth/src/lib.rs b/crates/auth/src/lib.rs index d1cd1e1..6c9d01b 100644 --- a/crates/auth/src/lib.rs +++ b/crates/auth/src/lib.rs @@ -7,9 +7,15 @@ use gpapi::{ #[cfg(feature = "browser-auth")] mod browser; +#[cfg(feature = "browser-auth")] +mod callback; + #[cfg(feature = "browser-auth")] pub use browser::*; +#[cfg(feature = "browser-auth")] +pub use callback::*; + #[cfg(feature = "webview-auth")] mod webview; #[cfg(feature = "webview-auth")] diff --git a/crates/gpapi/src/auth.rs b/crates/gpapi/src/auth.rs index 094b5f2..b889889 100644 --- a/crates/gpapi/src/auth.rs +++ b/crates/gpapi/src/auth.rs @@ -154,7 +154,6 @@ impl SamlAuthData { let auth_data: SamlAuthData = serde_urlencoded::from_str(auth_data.borrow()).map_err(|e| { warn!("Failed to parse token auth data: {}", e); - warn!("Auth data: {}", auth_data); AuthDataParseError::Invalid(anyhow::anyhow!(e)) })?; @@ -163,7 +162,7 @@ impl SamlAuthData { } let auth_data = decode_to_string(auth_data).map_err(|e| { - warn!("Failed to decode SAML auth data: {}, data: {}", e, data); + warn!("Failed to decode SAML auth data: {}", e); AuthDataParseError::Invalid(anyhow::anyhow!(e)) })?; let auth_data = Self::from_html(&auth_data)?; diff --git a/docs/bsd-source-build.md b/docs/bsd-source-build.md index 558f648..1629409 100644 --- a/docs/bsd-source-build.md +++ b/docs/bsd-source-build.md @@ -19,7 +19,7 @@ Install build and runtime dependencies: ```sh sudo pkg install git rust libiconv gettext-tools autoconf automake libtool patch \ gmake pkgconf libxml2 gnutls p11-kit nettle gmp gnome-keyring \ - libayatana-appindicator polkit webkit2-gtk_41 + libayatana-appindicator polkit webkit2-gtk_41 xdg-utils ``` Build and install: @@ -45,7 +45,7 @@ Install build and runtime dependencies: ```sh doas pkg_add git rust libiconv gettext-tools autoconf-2.72 automake-1.17 \ libtool patch gmake pkgconf libxml gnutls p11-kit nettle gmp \ - gnome-keyring polkit webkitgtk41 + gnome-keyring polkit webkitgtk41 xdg-utils ``` Use the installed Autoconf and Automake versions: diff --git a/flake.nix b/flake.nix index cc7674b..4d1fe57 100644 --- a/flake.nix +++ b/flake.nix @@ -65,6 +65,7 @@ linuxRuntimeDependencies = with pkgs; [ glib-networking libayatana-appindicator + xdg-utils ]; linuxBuildInputs = @@ -95,10 +96,10 @@ '' + lib.optionalString pkgs.stdenv.isLinux '' substituteInPlace $out/share/applications/gpgui.desktop \ - --replace-fail /usr/bin/gpclient /run/current-system/sw/bin/gpclient + --replace-fail /usr/bin/gpclient $out/bin/gpclient substituteInPlace $out/share/applications/gpauth.desktop \ - --replace-fail /usr/bin/gpauth /run/current-system/sw/bin/gpauth + --replace-fail /usr/bin/gpauth $out/bin/gpauth substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \ --replace-fail /usr/bin/gpservice $out/bin/gpservice \ @@ -112,10 +113,10 @@ rewriteHostInstallPaths = '' substituteInPlace $out/share/applications/gpgui.desktop \ - --replace-fail /usr/bin/gpclient /run/current-system/sw/bin/gpclient + --replace-fail /usr/bin/gpclient $out/bin/gpclient substituteInPlace $out/share/applications/gpauth.desktop \ - --replace-fail /usr/bin/gpauth /run/current-system/sw/bin/gpauth + --replace-fail /usr/bin/gpauth $out/bin/gpauth substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \ --replace-fail /usr/bin/gpservice $out/bin/gpservice \ @@ -177,6 +178,10 @@ runtimeDependencies = lib.optionals pkgs.stdenv.isLinux linuxRuntimeDependencies; + preFixup = lib.optionalString pkgs.stdenv.isLinux '' + gappsWrapperArgs+=(--prefix PATH : ${lib.makeBinPath [ pkgs.xdg-utils ]}) + ''; + overrideMain = { ... }: { @@ -341,56 +346,50 @@ if [ "''${1:-}" = "launch-gui" ]; then shift - auth_data= minimized= for arg in "$@"; do case "$arg" in --minimized) minimized=--minimized ;; - --*) - ;; *) - auth_data=$arg + echo "Unsupported launch-gui argument: $arg" >&2 + exit 2 ;; esac done - if [ -z "$auth_data" ]; then - if [ -n "''${XDG_DATA_HOME:-}" ]; then - data_home=$XDG_DATA_HOME - elif [ -n "''${HOME:-}" ]; then - data_home=$HOME/.local/share - else - data_home=/tmp - fi - - log_dir="$data_home/gpclient" - mkdir -p "$log_dir" - log_file="$log_dir/gpclient.log" - env_file=$(mktemp) - - env > "$env_file" - printf 'GP_LOG_FILE=%s\n' "$log_file" >> "$env_file" - - pkexec_bin=/run/wrappers/bin/pkexec - if [ ! -x "$pkexec_bin" ]; then - pkexec_bin=pkexec - fi - - set +e - if [ -n "$minimized" ]; then - "$pkexec_bin" --user root "$gpservice_public" --minimized --env-file "$env_file" 2>"$log_file" - else - "$pkexec_bin" --user root "$gpservice_public" --env-file "$env_file" 2>"$log_file" - fi - status=$? - set -e - rm -f "$env_file" - exit "$status" + if [ -n "''${XDG_DATA_HOME:-}" ]; then + data_home=$XDG_DATA_HOME + elif [ -n "''${HOME:-}" ]; then + data_home=$HOME/.local/share + else + data_home=/tmp fi - set -- launch-gui "$@" + log_dir="$data_home/gpclient" + mkdir -p "$log_dir" + log_file="$log_dir/gpclient.log" + env_file=$(mktemp) + + env > "$env_file" + printf 'GP_LOG_FILE=%s\n' "$log_file" >> "$env_file" + + pkexec_bin=/run/wrappers/bin/pkexec + if [ ! -x "$pkexec_bin" ]; then + pkexec_bin=pkexec + fi + + set +e + if [ -n "$minimized" ]; then + "$pkexec_bin" --user root "$gpservice_public" --minimized --env-file "$env_file" 2>"$log_file" + else + "$pkexec_bin" --user root "$gpservice_public" --env-file "$env_file" 2>"$log_file" + fi + status=$? + set -e + rm -f "$env_file" + exit "$status" fi exec "$gpclient_fhs" "$@" diff --git a/packaging/aur/globalprotect-openconnect-git/.SRCINFO b/packaging/aur/globalprotect-openconnect-git/.SRCINFO index 5f0dea5..54c5d0e 100644 --- a/packaging/aur/globalprotect-openconnect-git/.SRCINFO +++ b/packaging/aur/globalprotect-openconnect-git/.SRCINFO @@ -28,6 +28,7 @@ pkgbase = globalprotect-openconnect-git depends = libxml2 depends = shared-mime-info depends = desktop-file-utils + depends = xdg-utils optdepends = wmctrl: for window management provides = globalprotect-openconnect provides = gpclient diff --git a/packaging/aur/globalprotect-openconnect-git/PKGBUILD b/packaging/aur/globalprotect-openconnect-git/PKGBUILD index 7e85f3e..9c06fac 100644 --- a/packaging/aur/globalprotect-openconnect-git/PKGBUILD +++ b/packaging/aur/globalprotect-openconnect-git/PKGBUILD @@ -10,7 +10,7 @@ url="https://github.com/yuezk/GlobalProtect-openconnect" license=('GPL3') makedepends=(git pkg-config 'openconnect>=8.20' webkit2gtk-4.1 curl wget file openssl appmenu-gtk-module libappindicator-gtk3 librsvg libsecret cargo) -depends=(vpnc openssl webkit2gtk-4.1 libappindicator-gtk3 libsecret libxml2 shared-mime-info desktop-file-utils) +depends=(vpnc openssl webkit2gtk-4.1 libappindicator-gtk3 libsecret libxml2 shared-mime-info desktop-file-utils xdg-utils) optdepends=('wmctrl: for window management') conflicts=('globalprotect-openconnect') diff --git a/packaging/bsd/freebsd/MANIFEST.in b/packaging/bsd/freebsd/MANIFEST.in index aff1919..c2a5d6d 100644 --- a/packaging/bsd/freebsd/MANIFEST.in +++ b/packaging/bsd/freebsd/MANIFEST.in @@ -47,6 +47,10 @@ deps: { origin: "www/webkit2-gtk" version: "*" } + "xdg-utils": { + origin: "devel/xdg-utils" + version: "*" + } } desc: <