feat: add standalone auth callback transport

This commit is contained in:
Kevin Yue committed 2026-08-05 20:07:28 +08:00
1 parent 812965f020
commit 918abeb9bc
21 files changed
+581 -148

No files matched your search

Generated
+2 -1
View File
@@ -219,7 +219,6 @@ dependencies = [
"anyhow", "anyhow",
"block2", "block2",
"browser-launcher", "browser-launcher",
"common",
"gpapi", "gpapi",
"html-escape", "html-escape",
"log", "log",
@@ -228,10 +227,12 @@ dependencies = [
"objc2-web-kit", "objc2-web-kit",
"regex", "regex",
"tauri", "tauri",
"tempfile",
"tiny_http", "tiny_http",
"tokio", "tokio",
"tokio-util", "tokio-util",
"uuid", "uuid",
"uzers",
"webkit2gtk", "webkit2gtk",
] ]
+3
View File
@@ -195,6 +195,7 @@ install-bsd:
install -d $(DESTDIR)$(PREFIX)/share/applications install -d $(DESTDIR)$(PREFIX)/share/applications
install -m 644 packaging/bsd/gpgui.desktop $(DESTDIR)$(PREFIX)/share/applications/gpgui.desktop 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/scalable/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/32x32/apps install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/32x32/apps
install -d $(DESTDIR)$(PREFIX)/share/icons/hicolor/128x128/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); \ 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); \ polkit_pkg=$$(pkg_info -e 'polkit-*' | sed 's/^inst://' | head -n 1); \
webkitgtk_pkg=$$(pkg_info -e 'webkitgtk41-*' | 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 \ pkg_create \
-B .build/openbsd/pkgroot \ -B .build/openbsd/pkgroot \
-D COMMENT="$$comment" \ -D COMMENT="$$comment" \
@@ -269,6 +271,7 @@ package-openbsd: clean-bsd-package
-P x11/gnome/keyring:gnome-keyring-*:$$gnome_keyring_pkg \ -P x11/gnome/keyring:gnome-keyring-*:$$gnome_keyring_pkg \
-P sysutils/polkit:polkit-*:$$polkit_pkg \ -P sysutils/polkit:polkit-*:$$polkit_pkg \
-P www/webkitgtk4,webkitgtk41:webkitgtk41-*:$$webkitgtk_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 .build/openbsd/artifacts/$(PKG_NAME)-$(VERSION)-openbsd-$$openbsd_arch.tgz
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=openbsd GPGUI_BINARY="$(GPGUI_BINARY)" $(MAKE) bsd-gpgui-tarball BSD_FLAVOR=openbsd GPGUI_BINARY="$(GPGUI_BINARY)"
+43 -5
View File
@@ -1,5 +1,5 @@
use auth::{BrowserAuthenticator, auth_prelogin}; use auth::{BrowserAuthenticator, auth_prelogin, forward_auth_callback};
use clap::Parser; use clap::{Parser, Subcommand};
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
use gpapi::auth::AuthWindowTheme; use gpapi::auth::AuthWindowTheme;
use gpapi::{ use gpapi::{
@@ -27,6 +27,8 @@ const VERSION: &str = concat!(
version = VERSION, version = VERSION,
author, author,
about = "The authentication component for the GlobalProtect VPN client, supports the SSO authentication method.", 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 = "\ help_template = "\
{before-help}{name} {version} {before-help}{name} {version}
{author} {author}
@@ -41,8 +43,11 @@ See 'gpauth -h' for more information.
" "
)] )]
struct Cli { struct Cli {
#[arg(help = "The portal server to authenticate")] #[command(subcommand)]
server: String, command: Option<CliCommand>,
#[arg(required = true, help = "The portal server to authenticate")]
server: Option<String>,
#[arg(long, help = "Treating the server as a gateway")] #[arg(long, help = "Treating the server as a gateway")]
gateway: bool, gateway: bool,
@@ -110,6 +115,15 @@ struct Cli {
verbose: InfoLevelVerbosity, verbose: InfoLevelVerbosity,
} }
#[derive(Subcommand)]
enum CliCommand {
#[command(hide = true)]
AuthCallback {
#[arg(help = "The globalprotectcallback URL to forward")]
callback: String,
},
}
impl Args for Cli { impl Args for Cli {
fn fix_openssl(&self) -> bool { fn fix_openssl(&self) -> bool {
self.fix_openssl self.fix_openssl
@@ -142,7 +156,7 @@ impl Cli {
let openssl_conf = self.prepare_env()?; 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(); let gp_params = self.build_gp_params();
info!( info!(
"gpauth auth host-id: {}", "gpauth auth host-id: {}",
@@ -235,6 +249,14 @@ fn init_logger(cli: &Cli) {
pub async fn run() { pub async fn run() {
let cli = Cli::parse(); 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); init_logger(&cli);
info!("gpauth started: {}", VERSION); info!("gpauth started: {}", VERSION);
@@ -271,6 +293,22 @@ mod tests {
assert_eq!(cli.os, Os::default()); 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&[email protected]&token=token",
])
.unwrap();
assert!(matches!(
cli.command,
Some(CliCommand::AuthCallback { callback }) if callback.starts_with("globalprotectcallback:")
));
assert!(cli.server.is_none());
}
#[test] #[test]
fn host_id_arg_sets_profile_host_id_seed() { fn host_id_arg_sets_profile_host_id_seed() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--host-id", "host-seed"]) let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--host-id", "host-seed"])
-13
View File
@@ -1,6 +1,4 @@
use std::{ use std::{
env::temp_dir,
fs::File,
path::{Path, PathBuf}, path::{Path, PathBuf},
str::FromStr, str::FromStr,
}; };
@@ -165,17 +163,6 @@ fn init_logger(cli: &Cli) {
let mut builder = env_logger::builder(); let mut builder = env_logger::builder();
builder.filter_level(cli.verbose.log_level_filter()); 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(); builder.init();
} }
+1 -35
View File
@@ -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 clap::Args;
use common::constants::GP_CALLBACK_PORT_FILENAME;
use directories::ProjectDirs; use directories::ProjectDirs;
use gpapi::{ use gpapi::{
process::service_launcher::ServiceLauncher, process::service_launcher::ServiceLauncher,
utils::{endpoint::http_endpoint, env_utils, shutdown_signal}, utils::{endpoint::http_endpoint, env_utils, shutdown_signal},
}; };
use log::info; use log::info;
use tokio::io::AsyncWriteExt;
#[derive(Args)] #[derive(Args)]
pub(crate) struct LaunchGuiArgs { pub(crate) struct LaunchGuiArgs {
#[arg(
required = false,
help = "The authentication data, used for the default browser authentication"
)]
pub auth_data: Option<String>,
#[arg(long, help = "Launch the GUI minimized")] #[arg(long, help = "Launch the GUI minimized")]
minimized: bool, minimized: bool,
} }
@@ -37,13 +30,6 @@ impl<'a> LaunchGuiHandler<'a> {
anyhow::bail!("`launch-gui` cannot be run as root"); 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:<data>`
return feed_auth_data(auth_data).await;
}
if try_active_gui().await.is_ok() { if try_active_gui().await.is_ok() {
info!("The GUI is already running"); info!("The GUI is already running");
return Ok(()); 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<()> { async fn try_active_gui() -> anyhow::Result<()> {
let service_endpoint = http_endpoint().await?; let service_endpoint = http_endpoint().await?;
+6 -2
View File
@@ -8,18 +8,18 @@ edition.workspace = true
license.workspace = true license.workspace = true
[dependencies] [dependencies]
common = { path = "../common" }
gpapi = { path = "../gpapi" } gpapi = { path = "../gpapi" }
# Shared dependencies # Shared dependencies
anyhow.workspace = true anyhow.workspace = true
log.workspace = true log.workspace = true
tokio.workspace = true tokio = { workspace = true, features = ["io-util", "net", "time"] }
# Browser auth dependencies # Browser auth dependencies
browser-launcher = { path = "../browser-launcher", default-features = false, features = ["launcher"], optional = true } browser-launcher = { path = "../browser-launcher", default-features = false, features = ["launcher"], optional = true }
tiny_http = { version = "0.12", optional = true } tiny_http = { version = "0.12", optional = true }
uuid = { version = "1", optional = true, features = ["v4"] } uuid = { version = "1", optional = true, features = ["v4"] }
uzers = { workspace = true, optional = true }
# Webview auth dependencies # Webview auth dependencies
tauri = { workspace = true, optional = true } tauri = { workspace = true, optional = true }
@@ -41,6 +41,7 @@ browser-auth = [
"dep:browser-launcher", "dep:browser-launcher",
"dep:tiny_http", "dep:tiny_http",
"dep:uuid", "dep:uuid",
"dep:uzers",
] ]
webview-auth = [ webview-auth = [
"gpapi/tauri", "gpapi/tauri",
@@ -55,3 +56,6 @@ webview-auth = [
"dep:objc2-web-kit", "dep:objc2-web-kit",
] ]
release-devtools = ["webview-auth", "tauri/devtools"] release-devtools = ["webview-auth", "tauri/devtools"]
[dev-dependencies]
tempfile.workspace = true
+9 -41
View File
@@ -1,15 +1,9 @@
use std::{env::temp_dir, fs, os::unix::fs::PermissionsExt};
use browser_launcher::Browser as LaunchBrowser; use browser_launcher::Browser as LaunchBrowser;
use common::constants::GP_CALLBACK_PORT_FILENAME;
use gpapi::auth::SamlAuthData; use gpapi::auth::SamlAuthData;
use log::info; use log::info;
use tokio::{ use tokio::net::UdpSocket;
io::AsyncReadExt,
net::{TcpListener, UdpSocket},
};
use crate::browser::auth_server::AuthServer; use crate::{AuthCallbackReceiver, browser::auth_server::AuthServer, ensure_auth_callback_handler};
pub struct BrowserAuthenticator<'a> { pub struct BrowserAuthenticator<'a> {
auth_request: &'a str, auth_request: &'a str,
@@ -22,6 +16,12 @@ impl<'a> BrowserAuthenticator<'a> {
} }
pub async fn authenticate(&self) -> anyhow::Result<SamlAuthData> { pub async fn authenticate(&self) -> anyhow::Result<SamlAuthData> {
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 addr = self.determine_addr().await?;
let auth_server = AuthServer::new(&addr)?; let auth_server = AuthServer::new(&addr)?;
let auth_url = auth_server.auth_url(); 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))?; browser_launcher::open_url(&auth_url, LaunchBrowser::from_name(self.browser))?;
info!("Please continue the authentication process in the default 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<String> { async fn determine_addr(&self) -> anyhow::Result<String> {
@@ -84,38 +84,6 @@ async fn detect_local_ip() -> anyhow::Result<String> {
Ok(ip.to_string()) Ok(ip.to_string())
} }
async fn wait_auth_data() -> anyhow::Result<SamlAuthData> {
// 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<SamlAuthData> { fn read_auth_data_from_stdin() -> anyhow::Result<SamlAuthData> {
let mut data = String::new(); let mut data = String::new();
std::io::stdin().read_line(&mut data)?; std::io::stdin().read_line(&mut data)?;
+445
View File
@@ -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<Self> {
let socket_path = callback_socket_path();
prepare_socket_directory(&socket_path)?;
Self::bind_at(socket_path)
}
fn bind_at(socket_path: PathBuf) -> anyhow::Result<Self> {
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<SamlAuthData> {
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(&current_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<String> {
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<bool> {
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<AuthCallbackReceiver> {
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<fs::File> {
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<String, CallbackReadError> {
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&[email protected]&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(), "[email protected]");
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(), "[email protected]");
}
#[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(), "[email protected]");
}
#[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()
}
}
+6
View File
@@ -7,9 +7,15 @@ use gpapi::{
#[cfg(feature = "browser-auth")] #[cfg(feature = "browser-auth")]
mod browser; mod browser;
#[cfg(feature = "browser-auth")]
mod callback;
#[cfg(feature = "browser-auth")] #[cfg(feature = "browser-auth")]
pub use browser::*; pub use browser::*;
#[cfg(feature = "browser-auth")]
pub use callback::*;
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
mod webview; mod webview;
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
+1 -2
View File
@@ -154,7 +154,6 @@ impl SamlAuthData {
let auth_data: SamlAuthData = serde_urlencoded::from_str(auth_data.borrow()).map_err(|e| { let auth_data: SamlAuthData = serde_urlencoded::from_str(auth_data.borrow()).map_err(|e| {
warn!("Failed to parse token auth data: {}", e); warn!("Failed to parse token auth data: {}", e);
warn!("Auth data: {}", auth_data);
AuthDataParseError::Invalid(anyhow::anyhow!(e)) AuthDataParseError::Invalid(anyhow::anyhow!(e))
})?; })?;
@@ -163,7 +162,7 @@ impl SamlAuthData {
} }
let auth_data = decode_to_string(auth_data).map_err(|e| { 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)) AuthDataParseError::Invalid(anyhow::anyhow!(e))
})?; })?;
let auth_data = Self::from_html(&auth_data)?; let auth_data = Self::from_html(&auth_data)?;
+2 -2
View File
@@ -19,7 +19,7 @@ Install build and runtime dependencies:
```sh ```sh
sudo pkg install git rust libiconv gettext-tools autoconf automake libtool patch \ sudo pkg install git rust libiconv gettext-tools autoconf automake libtool patch \
gmake pkgconf libxml2 gnutls p11-kit nettle gmp gnome-keyring \ 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: Build and install:
@@ -45,7 +45,7 @@ Install build and runtime dependencies:
```sh ```sh
doas pkg_add git rust libiconv gettext-tools autoconf-2.72 automake-1.17 \ doas pkg_add git rust libiconv gettext-tools autoconf-2.72 automake-1.17 \
libtool patch gmake pkgconf libxml gnutls p11-kit nettle gmp \ 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: Use the installed Autoconf and Automake versions:
+40 -41
View File
@@ -65,6 +65,7 @@
linuxRuntimeDependencies = with pkgs; [ linuxRuntimeDependencies = with pkgs; [
glib-networking glib-networking
libayatana-appindicator libayatana-appindicator
xdg-utils
]; ];
linuxBuildInputs = linuxBuildInputs =
@@ -95,10 +96,10 @@
'' ''
+ lib.optionalString pkgs.stdenv.isLinux '' + lib.optionalString pkgs.stdenv.isLinux ''
substituteInPlace $out/share/applications/gpgui.desktop \ 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 \ 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 \ substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \
--replace-fail /usr/bin/gpservice $out/bin/gpservice \ --replace-fail /usr/bin/gpservice $out/bin/gpservice \
@@ -112,10 +113,10 @@
rewriteHostInstallPaths = '' rewriteHostInstallPaths = ''
substituteInPlace $out/share/applications/gpgui.desktop \ 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 \ 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 \ substituteInPlace $out/share/polkit-1/actions/com.yuezk.gpgui.policy \
--replace-fail /usr/bin/gpservice $out/bin/gpservice \ --replace-fail /usr/bin/gpservice $out/bin/gpservice \
@@ -177,6 +178,10 @@
runtimeDependencies = lib.optionals pkgs.stdenv.isLinux linuxRuntimeDependencies; runtimeDependencies = lib.optionals pkgs.stdenv.isLinux linuxRuntimeDependencies;
preFixup = lib.optionalString pkgs.stdenv.isLinux ''
gappsWrapperArgs+=(--prefix PATH : ${lib.makeBinPath [ pkgs.xdg-utils ]})
'';
overrideMain = overrideMain =
{ ... }: { ... }:
{ {
@@ -341,56 +346,50 @@
if [ "''${1:-}" = "launch-gui" ]; then if [ "''${1:-}" = "launch-gui" ]; then
shift shift
auth_data=
minimized= minimized=
for arg in "$@"; do for arg in "$@"; do
case "$arg" in case "$arg" in
--minimized) --minimized)
minimized=--minimized minimized=--minimized
;; ;;
--*)
;;
*) *)
auth_data=$arg echo "Unsupported launch-gui argument: $arg" >&2
exit 2
;; ;;
esac esac
done done
if [ -z "$auth_data" ]; then if [ -n "''${XDG_DATA_HOME:-}" ]; then
if [ -n "''${XDG_DATA_HOME:-}" ]; then data_home=$XDG_DATA_HOME
data_home=$XDG_DATA_HOME elif [ -n "''${HOME:-}" ]; then
elif [ -n "''${HOME:-}" ]; then data_home=$HOME/.local/share
data_home=$HOME/.local/share else
else data_home=/tmp
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"
fi 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 fi
exec "$gpclient_fhs" "$@" exec "$gpclient_fhs" "$@"
@@ -28,6 +28,7 @@ pkgbase = globalprotect-openconnect-git
depends = libxml2 depends = libxml2
depends = shared-mime-info depends = shared-mime-info
depends = desktop-file-utils depends = desktop-file-utils
depends = xdg-utils
optdepends = wmctrl: for window management optdepends = wmctrl: for window management
provides = globalprotect-openconnect provides = globalprotect-openconnect
provides = gpclient provides = gpclient
@@ -10,7 +10,7 @@ url="https://github.com/yuezk/GlobalProtect-openconnect"
license=('GPL3') license=('GPL3')
makedepends=(git pkg-config 'openconnect>=8.20' webkit2gtk-4.1 curl wget file openssl appmenu-gtk-module libappindicator-gtk3 librsvg libsecret cargo) 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') optdepends=('wmctrl: for window management')
conflicts=('globalprotect-openconnect') conflicts=('globalprotect-openconnect')
+4
View File
@@ -47,6 +47,10 @@ deps: {
origin: "www/webkit2-gtk" origin: "www/webkit2-gtk"
version: "*" version: "*"
} }
"xdg-utils": {
origin: "devel/xdg-utils"
version: "*"
}
} }
desc: <<EOD desc: <<EOD
A GlobalProtect VPN client based on OpenConnect. A GlobalProtect VPN client based on OpenConnect.
+11
View File
@@ -0,0 +1,11 @@
[Desktop Entry]
Type=Application
Name=GP Connect Login
Comment=Authenticate GP Connect VPN connections
NoDisplay=true
Terminal=false
TryExec=/usr/local/bin/gpauth
Exec=/usr/local/bin/gpauth auth-callback %u
MimeType=x-scheme-handler/globalprotectcallback;
Icon=gpgui
Categories=Network;
+1 -2
View File
@@ -4,7 +4,6 @@ Name=GP Connect
Comment=A GUI client for GlobalProtect VPN Comment=A GUI client for GlobalProtect VPN
GenericName=GlobalProtect VPN Client GenericName=GlobalProtect VPN Client
Categories=Network;Dialup; Categories=Network;Dialup;
Exec=/usr/local/bin/gpclient launch-gui %u Exec=/usr/local/bin/gpclient launch-gui
MimeType=x-scheme-handler/globalprotectcallback;
Icon=gpgui Icon=gpgui
Keywords=GlobalProtect;Openconnect;SAML;connection;VPN; Keywords=GlobalProtect;Openconnect;SAML;connection;VPN;
+1
View File
@@ -36,5 +36,6 @@ Depends:
libsecret-1-0, libsecret-1-0,
libayatana-appindicator3-1, libayatana-appindicator3-1,
gnome-keyring, gnome-keyring,
xdg-utils,
Description: A GUI client for GlobalProtect VPN Description: A GUI client for GlobalProtect VPN
A GUI client for GlobalProtect VPN, based on OpenConnect, supports the SSO authentication method. A GUI client for GlobalProtect VPN, based on OpenConnect, supports the SSO authentication method.
@@ -5,6 +5,7 @@ Comment=Authenticate GP Connect VPN connections
NoDisplay=true NoDisplay=true
Terminal=false Terminal=false
TryExec=/usr/bin/gpauth TryExec=/usr/bin/gpauth
Exec=/usr/bin/gpauth Exec=/usr/bin/gpauth auth-callback %u
MimeType=x-scheme-handler/globalprotectcallback;
Icon=gpgui Icon=gpgui
Categories=Network; Categories=Network;
@@ -5,7 +5,6 @@ Name=GP Connect
Comment=A GUI client for GlobalProtect VPN Comment=A GUI client for GlobalProtect VPN
GenericName=GlobalProtect VPN Client GenericName=GlobalProtect VPN Client
Categories=Network;Dialup; Categories=Network;Dialup;
Exec=/usr/bin/gpclient launch-gui %u Exec=/usr/bin/gpclient launch-gui
MimeType=x-scheme-handler/globalprotectcallback;
Icon=gpgui Icon=gpgui
Keywords=GlobalProtect;Openconnect;SAML;connection;VPN; Keywords=GlobalProtect;Openconnect;SAML;connection;VPN;
@@ -38,6 +38,7 @@ Requires: (libappindicator3-1 or libayatana-appindicator3-1)
%else %else
Requires: (libappindicator-gtk3 or libayatana-appindicator-gtk3) Requires: (libappindicator-gtk3 or libayatana-appindicator-gtk3)
%endif %endif
Requires: xdg-utils
Conflicts: globalprotect-openconnect-snapshot Conflicts: globalprotect-openconnect-snapshot
%global debug_package %{nil} %global debug_package %{nil}