Compare commits

..

9 Commits

Author SHA1 Message Date
Kevin Yue
fe3d3df662
ci: upload offline tarball 2025-01-23 21:59:59 +08:00
Kevin Yue
2f90b73683
fix: check the cli running state 2025-01-22 21:30:42 +08:00
Kevin Yue
5186e80c6f
doc: update installation for Ubuntu 18.04 2025-01-21 23:00:32 +08:00
Kevin Yue
4ff1c1dc1f
Release 2.4.3 2025-01-21 00:16:00 +08:00
Kevin Yue
c1427040f6
fix: do not use default value for os_version 2025-01-21 00:14:13 +08:00
Kevin Yue
a7ad02acb6
Release 2.4.2 2025-01-20 20:57:57 +08:00
Kevin Yue
b188d61be1
fix: disconnect VPN when sleep 2025-01-20 19:29:22 +08:00
Kevin Yue
ec85e857bc
Release 2.4.1 2025-01-09 23:53:03 +08:00
Kevin Yue
d37ccafdc2
feat: gpauth support macos 2025-01-09 21:22:41 +08:00
71 changed files with 2015 additions and 1247 deletions

View File

@ -14,6 +14,11 @@ on:
- release/*
tags:
- v*.*.*
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
# Include arm64 if ref is a tag
setup-matrix:
@ -39,7 +44,8 @@ jobs:
with:
version: 9
- name: Prepare workspace
run: rm -rf source && mkdir source
run: rm -rf source && mkdir -p source/artifacts
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v4
with:
@ -47,6 +53,7 @@ jobs:
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.ref }}
path: source/gp
- name: Create tarball
run: |
cd source/gp
@ -55,13 +62,69 @@ jobs:
touch SNAPSHOT
fi
make tarball
mv -v .build/tarball/*.tar.gz ../artifacts/
- name: Generate RPM spec file
env:
RELEASE_TAG: ${{ github.ref == 'refs/heads/dev' && 'snapshot' || github.ref_name }}
run: |
cd source/gp
make init-rpm \
REVISION='1%{?dist}' \
RPM_SOURCE=https://github.com/yuezk/GlobalProtect-openconnect/releases/download/${RELEASE_TAG}/%{name}-%{version}.tar.gz
mv -v .build/rpm/*.spec ../artifacts/
- name: Upload tarball
uses: actions/upload-artifact@v4
with:
name: artifact-source
if-no-files-found: error
path: |
source/gp/.build/tarball/*.tar.gz
source/artifacts/*
tarball-offline:
if: ${{ github.ref == 'refs/heads/dev' || startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest
needs:
- tarball
steps:
- uses: pnpm/action-setup@v4
with:
version: 9
- name: Prepare workspace
run: rm -rf source-offline && mkdir source-offline
- name: Download tarball
uses: actions/download-artifact@v4
with:
name: artifact-source
path: source-offline
- name: Create offline tarball
run: |
cd source-offline
offline_tarball=$(basename *.tar.gz .tar.gz).offline.tar.gz
# Extract the tarball
tar -xzf *.tar.gz
cd */
make tarball OFFLINE=1
# Rename the tarball to .offline.tar.gz
mv -v .build/tarball/*.tar.gz ../$offline_tarball
- name: Upload offline tarball
uses: actions/upload-artifact@v4
with:
path: source-offline/*.offline.tar.gz
name: artifact-source-offline
if-no-files-found: error
build-gp:
needs:
@ -163,6 +226,7 @@ jobs:
runs-on: ubuntu-latest
needs:
- tarball
- tarball-offline
- build-gp
- build-gpgui

View File

@ -52,22 +52,26 @@ jobs:
version: 9
- name: Prepare workspace
run: rm -rf publish-ppa && mkdir publish-ppa
- name: Download ${{ inputs.tag }} source code
uses: robinraju/release-downloader@v1.9
with:
token: ${{ secrets.GH_PAT }}
tag: ${{ inputs.tag }}
fileName: globalprotect-openconnect-*.tar.gz
tarBall: false
zipBall: false
out-file-path: publish-ppa
- name: Make the offline tarball
- name: Download ${{ inputs.tag }} offline source code
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
gh -R yuezk/GlobalProtect-openconnect \
release download ${{ inputs.tag }} \
--pattern '*.offline.tar.gz' \
--dir publish-ppa
- name: Patch the source code
run: |
cd publish-ppa
tar -xf globalprotect-openconnect-*.tar.gz
cd globalprotect-openconnect-*/
make tarball OFFLINE=1
# Rename the source tarball without the offline suffix
mv -v *.tar.gz $(basename *.tar.gz .offline.tar.gz).tar.gz
# Extract the source tarball
tar -xzf *.tar.gz
# Prepare the debian directory with custom files
cd globalprotect-openconnect-*/
# Prepare the debian directory with custom files
mkdir -p .build/debian
@ -78,7 +82,6 @@ jobs:
cp -v packaging/deb/postrm .build/debian/postrm
sed -i "s/@RUST@/cargo-1.80/g" .build/debian/control
sed -i "s/@OFFLINE@/1/g" .build/debian/rules
sed -i "s/@BUILD_GUI@/1/g" .build/debian/rules
sed -i "s/@RUST_VERSION@/1.80/g" .build/debian/rules
@ -89,7 +92,7 @@ jobs:
repository: "yuezk/globalprotect-openconnect"
gpg_private_key: ${{ secrets.PPA_GPG_PRIVATE_KEY }}
gpg_passphrase: ${{ secrets.PPA_GPG_PASSPHRASE }}
tarball: publish-ppa/globalprotect-openconnect-*/.build/tarball/*.tar.gz
tarball: publish-ppa/globalprotect-openconnect-*.tar.gz
debian_dir: publish-ppa/globalprotect-openconnect-*/.build/debian
deb_email: "k3vinyue@gmail.com"
deb_fullname: "Kevin Yue"

View File

@ -96,15 +96,16 @@ jobs:
steps:
- name: Prepare workspace
run: rm -rf build-${{ matrix.package }} && mkdir -p build-${{ matrix.package }}
- name: Download ${{ inputs.tag }} source code
uses: robinraju/release-downloader@v1.9
with:
token: ${{ secrets.GH_PAT }}
tag: ${{ inputs.tag }}
fileName: globalprotect-openconnect-*.tar.gz
tarBall: false
zipBall: false
out-file-path: build-${{ matrix.package }}
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
gh -R yuezk/GlobalProtect-openconnect \
release download ${{ inputs.tag }} \
--pattern '*[^offline].tar.gz' \
--dir build-${{ matrix.package }}
- name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build ${{ matrix.package }} package in Docker

14
.vscode/c_cpp_properties.json vendored Normal file
View File

@ -0,0 +1,14 @@
{
"configurations": [
{
"name": "Mac",
"includePath": ["/opt/homebrew/include"],
"macFrameworkPath": ["/System/Library/Frameworks", "/Library/Frameworks"],
"intelliSenseMode": "macos-clang-x64",
"compilerPath": "/usr/bin/clang",
"cStandard": "c17",
"cppStandard": "c++17"
}
],
"version": 4
}

11
.vscode/settings.json vendored
View File

@ -23,8 +23,12 @@
"gpgui",
"gpservice",
"hidpi",
"Ivars",
"jnlp",
"LOGNAME",
"NSHTTPURL",
"NSURL",
"objc",
"oneshot",
"openconnect",
"pkcs",
@ -55,9 +59,16 @@
"Vite",
"vpnc",
"vpninfo",
"webbrowser",
"wmctrl",
"XAUTHORITY",
"yuezk"
],
"rust-analyzer.cargo.features": "all",
"files.associations": {
"unistd.h": "c",
"utsname.h": "c",
"vpn.h": "c",
"openconnect.h": "c"
},
}

666
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,17 @@
[workspace]
resolver = "2"
members = ["crates/*", "apps/gpclient", "apps/gpservice", "apps/gpauth", "apps/gpgui-helper/src-tauri"]
members = [
"crates/*",
"apps/gpclient",
"apps/gpservice",
"apps/gpauth",
"apps/gpgui-helper/src-tauri",
]
[workspace.package]
rust-version = "1.80"
version = "2.4.0"
version = "2.4.3"
authors = ["Kevin Yue <k3vinyue@gmail.com>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2021"
@ -15,6 +21,7 @@ license = "GPL-3.0"
anyhow = "1.0"
base64 = "0.22"
clap = { version = "4", features = ["derive"] }
clap-verbosity-flag = "3"
ctrlc = "3.4"
directories = "5.0"
dns-lookup = "2.0.4"
@ -30,11 +37,11 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sysinfo = "0.33"
tempfile = "3.8"
tokio = { version = "1", features = ["full"] }
tokio = { version = "1" }
tokio-util = "0.7"
url = "2.4"
urlencoding = "2.1.3"
axum = "0.7"
axum = "0.8"
futures = "0.3"
futures-util = "0.3"
uzers = "0.12"

View File

@ -8,6 +8,8 @@ RUST_VERSION = 1.80
VERSION = $(shell $(CARGO) metadata --no-deps --format-version 1 | jq -r '.packages[0].version')
REVISION ?= 1
RPM_SOURCE ?= %{name}.tar.gz
PPA_REVISION ?= 1
PKG_NAME = globalprotect-openconnect
PKG = $(PKG_NAME)-$(VERSION)
@ -130,6 +132,10 @@ install:
install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/bin/gpgui; \
fi
# Install the disconnect hooks
install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
install -Dm644 packaging/files/usr/share/applications/gpgui.desktop $(DESTDIR)/usr/share/applications/gpgui.desktop
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
install -Dm644 packaging/files/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
@ -146,6 +152,9 @@ uninstall:
rm -f $(DESTDIR)/usr/bin/gpgui-helper
rm -f $(DESTDIR)/usr/bin/gpgui
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
rm -f $(DESTDIR)/usr/share/applications/gpgui.desktop
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
rm -f $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
@ -227,6 +236,7 @@ init-rpm: clean-rpm
sed -i "s/@VERSION@/$(VERSION)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@REVISION@/$(REVISION)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s|@SOURCE@|$(RPM_SOURCE)|g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@DATE@/$(shell LC_ALL=en.US date "+%a %b %d %Y")/g" .build/rpm/globalprotect-openconnect.spec

View File

@ -70,7 +70,7 @@ The GUI version is also available after you installed it. You can launch it from
### Debian/Ubuntu based distributions
#### Install from PPA (Ubuntu > 18.04)
#### Install from PPA
```
sudo add-apt-repository ppa:yuezk/globalprotect-openconnect
@ -81,10 +81,6 @@ sudo apt-get install globalprotect-openconnect
>
> For Linux Mint, you might need to import the GPG key with: `sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7937C393082992E5D6E4A60453FC26B43838D761` if you encountered an error `gpg: keyserver receive failed: General error`.
#### **Ubuntu 18.04**
The latest package is not available in the PPA, but you still needs to add the `ppa:yuezk/globalprotect-openconnect` repo beforehand to use the required `openconnect` package. Then you can follow the [Install from deb package](#install-from-deb-package) section to install the latest package.
#### Install from deb package
Download the latest deb package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Then install it with `apt`:

View File

@ -24,6 +24,9 @@ tokio.workspace = true
tempfile.workspace = true
compile-time.workspace = true
# Pin the version of home because the latest version requires Rust 1.81
home = "=0.5.9"
# webview auth dependencies
tauri = { workspace = true, optional = true }

View File

@ -1,21 +1,19 @@
use std::borrow::Cow;
use auth::{auth_prelogin, Authenticator, BrowserAuthenticator};
use auth::{auth_prelogin, BrowserAuthenticator};
use clap::Parser;
use gpapi::{
auth::{SamlAuthData, SamlAuthResult},
clap::{args::Os, handle_error, Args},
clap::{args::Os, handle_error, Args, InfoLevelVerbosity},
gp_params::{ClientOs, GpParams},
utils::{normalize_server, openssl},
GP_USER_AGENT,
};
use log::{info, LevelFilter};
use log::info;
use serde_json::json;
use tempfile::NamedTempFile;
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
#[derive(Parser, Clone)]
#[derive(Parser)]
#[command(
version = VERSION,
author,
@ -33,7 +31,7 @@ const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::dat
See 'gpauth -h' for more information.
"
)]
pub(crate) struct Cli {
struct Cli {
#[arg(help = "The portal server to authenticate")]
server: String,
@ -75,6 +73,9 @@ pub(crate) struct Cli {
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Clean the cache of the embedded browser")]
pub clean: bool,
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
impl Args for Cli {
@ -110,28 +111,26 @@ impl Cli {
let openssl_conf = self.prepare_env()?;
let server = normalize_server(&self.server)?;
let server: &'static str = Box::leak(server.into_boxed_str());
let gp_params: &'static GpParams = Box::leak(Box::new(self.build_gp_params()));
let gp_params = self.build_gp_params();
let auth_request = match self.saml_request.as_deref() {
Some(auth_request) => Cow::Borrowed(auth_request),
None => Cow::Owned(auth_prelogin(server, gp_params).await?),
Some(auth_request) => auth_request.to_string(),
None => auth_prelogin(&server, &gp_params).await?,
};
let auth_request: &'static str = Box::leak(auth_request.into_owned().into_boxed_str());
let authenticator = Authenticator::new(&server, gp_params).with_auth_request(&auth_request);
#[cfg(feature = "webview-auth")]
let browser = self
.browser
.as_deref()
.or_else(|| self.default_browser.then_some("default"));
.or_else(|| self.default_browser.then(|| "default"));
#[cfg(not(feature = "webview-auth"))]
let browser = self.browser.as_deref().or(Some("default"));
if browser.is_some() {
let auth_result = authenticator.browser_authenticate(browser).await;
if let Some(browser) = browser {
let authenticator = BrowserAuthenticator::new(&auth_request, browser);
let auth_result = authenticator.authenticate().await;
print_auth_result(auth_result);
// explicitly drop openssl_conf to avoid the unused variable warning
@ -140,7 +139,7 @@ impl Cli {
}
#[cfg(feature = "webview-auth")]
crate::webview_auth::authenticate(&self, authenticator, openssl_conf)?;
crate::webview_auth::authenticate(server, gp_params, auth_request, self.clean, openssl_conf).await?;
Ok(())
}
@ -158,14 +157,16 @@ impl Cli {
}
}
fn init_logger() {
env_logger::builder().filter_level(LevelFilter::Info).init();
fn init_logger(cli: &Cli) {
env_logger::builder()
.filter_level(cli.verbose.log_level_filter())
.init();
}
pub async fn run() {
let cli = Cli::parse();
init_logger();
init_logger(&cli);
info!("gpauth started: {}", VERSION);
if let Err(err) = cli.run().await {

View File

@ -1,6 +1,7 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod cli;
#[cfg(feature = "webview-auth")]
mod webview_auth;

View File

@ -1,23 +1,28 @@
use auth::{Authenticator, WebviewAuthenticator};
use auth::WebviewAuthenticator;
use gpapi::gp_params::GpParams;
use log::info;
use tauri::RunEvent;
use tempfile::NamedTempFile;
use crate::cli::{print_auth_result, Cli};
use crate::cli::print_auth_result;
pub fn authenticate(
cli: &Cli,
authenticator: Authenticator<'static>,
pub async fn authenticate(
server: String,
gp_params: GpParams,
auth_request: String,
clean: bool,
mut openssl_conf: Option<NamedTempFile>,
) -> anyhow::Result<()> {
let authenticator = authenticator.with_clean(cli.clean);
tauri::Builder::default()
.setup(move |app| {
let app_handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
let auth_result = authenticator.webview_authenticate(&app_handle).await;
let authenticator = WebviewAuthenticator::new(&server, &gp_params)
.with_auth_request(&auth_request)
.with_clean(clean);
let auth_result = authenticator.authenticate(&app_handle).await;
print_auth_result(auth_result);
// Ensure the app exits after the authentication process

View File

@ -16,13 +16,13 @@ clap.workspace = true
env_logger.workspace = true
inquire = "0.7"
log.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
sysinfo.workspace = true
serde_json.workspace = true
whoami.workspace = true
tempfile.workspace = true
reqwest.workspace = true
directories = "5.0"
directories.workspace = true
compile-time.workspace = true
[features]

View File

@ -1,24 +1,29 @@
use std::{env::temp_dir, fs::File};
use std::{env::temp_dir, fs::File, str::FromStr};
use anyhow::bail;
use clap::{Parser, Subcommand};
use gpapi::{
clap::{handle_error, Args},
clap::{handle_error, Args, InfoLevelVerbosity},
utils::openssl,
};
use log::{info, LevelFilter};
use log::info;
use sysinfo::{Pid, System};
use tempfile::NamedTempFile;
use tokio::fs;
use crate::{
connect::{ConnectArgs, ConnectHandler},
disconnect::DisconnectHandler,
disconnect::{DisconnectArgs, DisconnectHandler},
launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
GP_CLIENT_LOCK_FILE,
};
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
pub(crate) struct SharedArgs {
pub(crate) struct SharedArgs<'a> {
pub(crate) fix_openssl: bool,
pub(crate) ignore_tls_errors: bool,
pub(crate) verbose: &'a InfoLevelVerbosity,
}
#[derive(Subcommand)]
@ -26,7 +31,7 @@ enum CliCommand {
#[command(about = "Connect to a portal server")]
Connect(Box<ConnectArgs>),
#[command(about = "Disconnect from the server")]
Disconnect,
Disconnect(DisconnectArgs),
#[command(about = "Launch the GUI")]
LaunchGui(LaunchGuiArgs),
}
@ -60,6 +65,9 @@ struct Cli {
fix_openssl: bool,
#[arg(long, help = "Ignore the TLS errors")]
ignore_tls_errors: bool,
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
impl Args for Cli {
@ -73,6 +81,25 @@ impl Args for Cli {
}
impl Cli {
async fn is_running(&self) -> bool {
let Ok(c) = fs::read_to_string(GP_CLIENT_LOCK_FILE).await else {
return false;
};
let Ok(pid) = Pid::from_str(c.trim()) else {
return false;
};
let s = System::new_all();
let Some(p) = s.process(pid) else {
return false;
};
p.exe()
.map(|exe| exe.to_string_lossy().contains("gpclient"))
.unwrap_or(false)
}
fn fix_openssl(&self) -> anyhow::Result<Option<NamedTempFile>> {
if self.fix_openssl {
let file = openssl::fix_openssl_env()?;
@ -83,12 +110,18 @@ impl Cli {
}
async fn run(&self) -> anyhow::Result<()> {
// check if an instance is running
if self.is_running().await {
bail!("Another instance of the client is already running");
}
// The temp file will be dropped automatically when the file handle is dropped
// So, declare it here to ensure it's not dropped
let _file = self.fix_openssl()?;
let shared_args = SharedArgs {
fix_openssl: self.fix_openssl,
ignore_tls_errors: self.ignore_tls_errors,
verbose: &self.verbose,
};
if self.ignore_tls_errors {
@ -97,18 +130,18 @@ impl Cli {
match &self.command {
CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await,
CliCommand::Disconnect => DisconnectHandler::new().handle(),
CliCommand::Disconnect(args) => DisconnectHandler::new(args).handle().await,
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
}
}
}
fn init_logger(command: &CliCommand) {
fn init_logger(cli: &Cli) {
let mut builder = env_logger::builder();
builder.filter_level(LevelFilter::Info);
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) = command {
if let CliCommand::LaunchGui(args) = &cli.command {
let auth_data = args.auth_data.as_deref().unwrap_or_default();
if !auth_data.is_empty() {
if let Ok(log_file) = File::create(temp_dir().join("gpcallback.log")) {
@ -124,7 +157,7 @@ fn init_logger(command: &CliCommand) {
pub(crate) async fn run() {
let cli = Cli::parse();
init_logger(&cli.command);
init_logger(&cli);
info!("gpclient started: {}", VERSION);

View File

@ -5,7 +5,7 @@ use clap::Args;
use common::vpn_utils::find_csd_wrapper;
use gpapi::{
auth::SamlAuthResult,
clap::args::Os,
clap::{args::Os, ToVerboseArg},
credential::{Credential, PasswordCredential},
error::PortalError,
gateway::{gateway_login, GatewayLogin},
@ -19,7 +19,7 @@ use gpapi::{
GP_USER_AGENT,
};
use inquire::{Password, PasswordDisplayMode, Select, Text};
use log::info;
use log::{info, warn};
use openconnect::Vpn;
use crate::{cli::SharedArgs, GP_CLIENT_LOCK_FILE};
@ -84,10 +84,10 @@ pub(crate) struct ConnectArgs {
#[arg(long, default_value = GP_USER_AGENT, help = "The user agent to use")]
user_agent: String,
#[arg(long, default_value = "Linux")]
#[arg(long, value_enum, default_value_t = ConnectArgs::default_os())]
os: Os,
#[arg(long)]
#[arg(long, help = "If not specified, it will be computed based on the --os option")]
os_version: Option<String>,
#[arg(long, help = "Disable DTLS and ESP")]
@ -113,9 +113,17 @@ pub(crate) struct ConnectArgs {
}
impl ConnectArgs {
fn default_os() -> Os {
if cfg!(target_os = "macos") {
Os::Mac
} else {
Os::Linux
}
}
fn os_version(&self) -> String {
if let Some(os_version) = &self.os_version {
return os_version.to_owned();
if let Some(os_version) = self.os_version.as_deref() {
return os_version.to_string();
}
match self.os {
@ -128,7 +136,7 @@ impl ConnectArgs {
pub(crate) struct ConnectHandler<'a> {
args: &'a ConnectArgs,
shared_args: &'a SharedArgs,
shared_args: &'a SharedArgs<'a>,
latest_key_password: RefCell<Option<String>>,
}
@ -203,7 +211,7 @@ impl<'a> ConnectHandler<'a> {
return Ok(());
};
info!("Failed to connect portal with prelogin: {}", err);
warn!("Failed to connect portal with prelogin: {}", err);
if err.root_cause().downcast_ref::<PortalError>().is_some() {
info!("Trying the gateway authentication workflow...");
self.connect_gateway_with_prelogin(server).await?;
@ -356,6 +364,7 @@ impl<'a> ConnectHandler<'a> {
};
let os_version = self.args.os_version();
let verbose = self.shared_args.verbose.to_verbose_arg();
let auth_launcher = SamlAuthLauncher::new(&self.args.server)
.gateway(is_gateway)
.saml_request(prelogin.saml_request())
@ -364,7 +373,8 @@ impl<'a> ConnectHandler<'a> {
.os_version(Some(&os_version))
.fix_openssl(self.shared_args.fix_openssl)
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.browser(browser);
.browser(browser)
.verbose(verbose);
#[cfg(feature = "webview-auth")]
let use_default_browser = prelogin.support_default_browser() && self.args.default_browser;

View File

@ -1,31 +1,63 @@
use crate::GP_CLIENT_LOCK_FILE;
use clap::Args;
use gpapi::utils::lock_file::gpservice_lock_info;
use log::{info, warn};
use std::fs;
use std::{fs, str::FromStr, thread, time::Duration};
use sysinfo::{Pid, Signal, System};
pub(crate) struct DisconnectHandler;
impl DisconnectHandler {
pub(crate) fn new() -> Self {
Self
#[derive(Args)]
pub struct DisconnectArgs {
#[arg(
long,
required = false,
help = "The time in seconds to wait for the VPN connection to disconnect"
)]
wait: Option<u64>,
}
pub(crate) fn handle(&self) -> anyhow::Result<()> {
if fs::metadata(GP_CLIENT_LOCK_FILE).is_err() {
warn!("PID file not found, maybe the client is not running");
return Ok(());
pub struct DisconnectHandler<'a> {
args: &'a DisconnectArgs,
}
let pid = fs::read_to_string(GP_CLIENT_LOCK_FILE)?;
let pid = pid.trim().parse::<usize>()?;
impl<'a> DisconnectHandler<'a> {
pub fn new(args: &'a DisconnectArgs) -> Self {
Self { args }
}
pub async fn handle(&self) -> anyhow::Result<()> {
// Try to disconnect the CLI client
if let Ok(c) = fs::read_to_string(GP_CLIENT_LOCK_FILE) {
send_signal(c.trim(), Signal::Interrupt).unwrap_or_else(|err| {
warn!("Failed to send signal to client: {}", err);
});
};
// Try to disconnect the GUI service
if let Ok(c) = gpservice_lock_info().await {
send_signal(&c.pid.to_string(), Signal::User1).unwrap_or_else(|err| {
warn!("Failed to send signal to service: {}", err);
});
};
// sleep, to give the client and service time to disconnect
if let Some(wait) = self.args.wait {
thread::sleep(Duration::from_secs(wait));
}
Ok(())
}
}
fn send_signal(pid: &str, signal: Signal) -> anyhow::Result<()> {
let s = System::new_all();
let pid = Pid::from_str(pid)?;
if let Some(process) = s.process(Pid::from(pid)) {
info!("Found process {}, killing...", pid);
if process.kill_with(Signal::Interrupt).is_none() {
if let Some(process) = s.process(pid) {
info!("Found process {}, sending signal...", pid);
if process.kill_with(signal).is_none() {
warn!("Failed to kill process {}", pid);
}
}
Ok(())
}
}

View File

@ -10,7 +10,7 @@ license.workspace = true
tauri-build = { version = "2", features = [] }
[dependencies]
gpapi = { path = "../../../crates/gpapi", features = ["tauri"] }
gpapi = { path = "../../../crates/gpapi", features = ["tauri", "clap"] }
tauri.workspace = true
tokio.workspace = true

View File

@ -1,6 +1,9 @@
use clap::Parser;
use gpapi::utils::{base64, env_utils};
use log::{info, LevelFilter};
use gpapi::{
clap::InfoLevelVerbosity,
utils::{base64, env_utils},
};
use log::info;
use crate::app::App;
@ -15,6 +18,9 @@ struct Cli {
#[arg(long, default_value = env!("CARGO_PKG_VERSION"), help = "The version of the GUI")]
gui_version: String,
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
impl Cli {
@ -41,14 +47,16 @@ impl Cli {
}
}
fn init_logger() {
env_logger::builder().filter_level(LevelFilter::Info).init();
fn init_logger(cli: &Cli) {
env_logger::builder()
.filter_level(cli.verbose.log_level_filter())
.init();
}
pub fn run() {
let cli = Cli::parse();
init_logger();
init_logger(&cli);
info!("gpgui-helper started: {}", VERSION);
if let Err(e) = cli.run() {

View File

@ -5,11 +5,11 @@ edition.workspace = true
license.workspace = true
[dependencies]
gpapi = { path = "../../crates/gpapi" }
gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
openconnect = { path = "../../crates/openconnect" }
clap.workspace = true
anyhow.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
tokio-util.workspace = true
axum = { workspace = true, features = ["ws"] }
futures.workspace = true

View File

@ -3,13 +3,15 @@ use std::{collections::HashMap, io::Write};
use anyhow::bail;
use clap::Parser;
use gpapi::clap::InfoLevelVerbosity;
use gpapi::logger;
use gpapi::{
process::gui_launcher::GuiLauncher,
service::{request::WsRequest, vpn_state::VpnState},
utils::{crypto::generate_key, env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal},
GP_SERVICE_LOCK_FILE,
};
use log::{info, warn, LevelFilter};
use log::{info, warn};
use tokio::sync::{mpsc, watch};
use crate::{vpn_task::VpnTask, ws_server::WsServer};
@ -26,11 +28,18 @@ struct Cli {
#[cfg(debug_assertions)]
#[clap(long)]
no_gui: bool,
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
impl Cli {
async fn run(&mut self, redaction: Arc<Redaction>) -> anyhow::Result<()> {
let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE));
async fn run(&mut self) -> anyhow::Result<()> {
let redaction = self.init_logger();
info!("gpservice started: {}", VERSION);
let pid = std::process::id();
let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE, pid));
if lock_file.check_health().await {
bail!("Another instance of the service is already running");
@ -48,9 +57,17 @@ impl Cli {
let (shutdown_tx, mut shutdown_rx) = mpsc::channel::<()>(4);
let shutdown_tx_clone = shutdown_tx.clone();
let vpn_task_token = vpn_task.cancel_token();
let vpn_task_cancel_token = vpn_task.cancel_token();
let server_token = ws_server.cancel_token();
#[cfg(unix)]
{
let vpn_ctx = vpn_task.context();
let ws_ctx = ws_server.context();
tokio::spawn(async move { signals::handle_signals(vpn_ctx, ws_ctx).await });
}
let vpn_task_handle = tokio::spawn(async move { vpn_task.start(server_token).await });
let ws_server_handle = tokio::spawn(async move { ws_server.start(shutdown_tx_clone).await });
@ -82,7 +99,7 @@ impl Cli {
}
}
vpn_task_token.cancel();
vpn_task_cancel_token.cancel();
let _ = tokio::join!(vpn_task_handle, ws_server_handle);
lock_file.unlock()?;
@ -92,6 +109,33 @@ impl Cli {
Ok(())
}
fn init_logger(&self) -> Arc<Redaction> {
let redaction = Arc::new(Redaction::new());
let redaction_clone = Arc::clone(&redaction);
let inner_logger = env_logger::builder()
// Set the log level to the Trace level, the logs will be filtered
.filter_level(log::LevelFilter::Trace)
.format(move |buf, record| {
let timestamp = buf.timestamp();
writeln!(
buf,
"[{} {} {}] {}",
timestamp,
record.level(),
record.module_path().unwrap_or_default(),
redaction_clone.redact_str(&record.args().to_string())
)
})
.build();
let level = self.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info);
logger::init_with_logger(level, inner_logger);
redaction
}
fn prepare_api_key(&self) -> Vec<u8> {
#[cfg(debug_assertions)]
if self.no_gui {
@ -102,27 +146,52 @@ impl Cli {
}
}
fn init_logger() -> Arc<Redaction> {
let redaction = Arc::new(Redaction::new());
let redaction_clone = Arc::clone(&redaction);
// let target = Box::new(File::create("log.txt").expect("Can't create file"));
env_logger::builder()
.filter_level(LevelFilter::Info)
.format(move |buf, record| {
let timestamp = buf.timestamp();
writeln!(
buf,
"[{} {} {}] {}",
timestamp,
record.level(),
record.module_path().unwrap_or_default(),
redaction_clone.redact_str(&record.args().to_string())
)
})
// .target(env_logger::Target::Pipe(target))
.init();
#[cfg(unix)]
mod signals {
use std::sync::Arc;
redaction
use log::{info, warn};
use crate::vpn_task::VpnTaskContext;
use crate::ws_server::WsServerContext;
const DISCONNECTED_PID_FILE: &str = "/tmp/gpservice_disconnected.pid";
pub async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) {
use gpapi::service::event::WsEvent;
use tokio::signal::unix::{signal, Signal, SignalKind};
let (mut user_sig1, mut user_sig2) = match || -> anyhow::Result<(Signal, Signal)> {
let user_sig1 = signal(SignalKind::user_defined1())?;
let user_sig2 = signal(SignalKind::user_defined2())?;
Ok((user_sig1, user_sig2))
}() {
Ok(signals) => signals,
Err(err) => {
warn!("Failed to create signal: {}", err);
return;
}
};
loop {
tokio::select! {
_ = user_sig1.recv() => {
info!("Received SIGUSR1 signal");
if vpn_ctx.disconnect().await {
// Write the PID to a dedicated file to indicate that the VPN task is disconnected via SIGUSR1
let pid = std::process::id();
if let Err(err) = tokio::fs::write(DISCONNECTED_PID_FILE, pid.to_string()).await {
warn!("Failed to write PID to file: {}", err);
}
}
}
_ = user_sig2.recv() => {
info!("Received SIGUSR2 signal");
ws_ctx.send_event(WsEvent::ResumeConnection).await;
}
}
}
}
}
async fn launch_gui(envs: Option<HashMap<String, String>>, api_key: Vec<u8>, mut minimized: bool) {
@ -153,10 +222,7 @@ async fn launch_gui(envs: Option<HashMap<String, String>>, api_key: Vec<u8>, mut
pub async fn run() {
let mut cli = Cli::parse();
let redaction = init_logger();
info!("gpservice started: {}", VERSION);
if let Err(e) = cli.run(redaction).await {
if let Err(e) = cli.run().await {
eprintln!("Error: {}", e);
std::process::exit(1);
}

View File

@ -1,5 +1,4 @@
use std::{
borrow::Cow,
fs::{File, Permissions},
io::BufReader,
ops::ControlFlow,
@ -12,7 +11,7 @@ use anyhow::bail;
use axum::{
body::Bytes,
extract::{
ws::{self, CloseFrame, Message, WebSocket},
ws::{self, CloseFrame, Message, Utf8Bytes, WebSocket},
State, WebSocketUpgrade,
},
http::StatusCode,
@ -133,7 +132,7 @@ async fn handle_socket(mut socket: WebSocket, ctx: Arc<WsServerContext>) {
let close_msg = Message::Close(Some(CloseFrame {
code: ws::close_code::NORMAL,
reason: Cow::from("Goodbye"),
reason: Utf8Bytes::from("Goodbye"),
}));
if let Err(err) = sender.send(close_msg).await {

View File

@ -1,8 +1,11 @@
use std::{sync::Arc, thread};
use gpapi::service::{
request::{ConnectRequest, WsRequest},
use gpapi::{
logger,
service::{
request::{ConnectRequest, UpdateLogLevelRequest, WsRequest},
vpn_state::VpnState,
},
};
use log::{info, warn};
use openconnect::Vpn;
@ -87,7 +90,7 @@ impl VpnTaskContext {
});
}
pub async fn disconnect(&self) {
pub async fn disconnect(&self) -> bool {
if let Some(disconnect_rx) = self.disconnect_rx.write().await.take() {
info!("Disconnecting VPN...");
if let Some(vpn) = self.vpn_handle.read().await.as_ref() {
@ -98,9 +101,13 @@ impl VpnTaskContext {
// Wait for the VPN to be disconnected
disconnect_rx.await.ok();
info!("VPN disconnected");
true
} else {
info!("VPN is not connected, skip disconnect");
self.vpn_state_tx.send(VpnState::Disconnected).ok();
false
}
}
}
@ -143,6 +150,10 @@ impl VpnTask {
server_cancel_token.cancel();
}
pub fn context(&self) -> Arc<VpnTaskContext> {
return Arc::clone(&self.ctx);
}
async fn recv(&mut self) {
while let Some(req) = self.ws_req_rx.recv().await {
tokio::spawn(process_ws_req(req, self.ctx.clone()));
@ -158,5 +169,12 @@ async fn process_ws_req(req: WsRequest, ctx: Arc<VpnTaskContext>) {
WsRequest::Disconnect(_) => {
ctx.disconnect().await;
}
WsRequest::UpdateLogLevel(UpdateLogLevelRequest(level)) => {
let level = level.parse().unwrap_or_else(|_| log::Level::Info);
info!("Updating log level to: {}", level);
if let Err(err) = logger::set_max_level(level) {
warn!("Failed to update log level: {}", err);
}
}
}
}

View File

@ -20,7 +20,7 @@ impl WsConnection {
pub async fn send_event(&self, event: &WsEvent) -> anyhow::Result<()> {
let encrypted = self.crypto.encrypt(event)?;
let msg = Message::Binary(encrypted);
let msg = Message::Binary(encrypted.into());
self.tx.send(msg).await?;
@ -29,7 +29,7 @@ impl WsConnection {
pub fn recv_msg(&self, msg: Message) -> ControlFlow<(), WsRequest> {
match msg {
Message::Binary(data) => match self.crypto.decrypt(data) {
Message::Binary(data) => match self.crypto.decrypt(data.into()) {
Ok(ws_req) => ControlFlow::Continue(ws_req),
Err(err) => {
info!("Failed to decrypt message: {}", err);

View File

@ -113,6 +113,10 @@ impl WsServer {
}
}
pub fn context(&self) -> Arc<WsServerContext> {
Arc::clone(&self.ctx)
}
pub fn cancel_token(&self) -> CancellationToken {
self.cancel_token.clone()
}
@ -124,7 +128,7 @@ impl WsServer {
warn!("Failed to start WS server: {}", err);
let _ = shutdown_tx.send(()).await;
return;
},
}
};
tokio::select! {
@ -149,7 +153,7 @@ impl WsServer {
info!("WS server listening on port: {}", port);
self.lock_file.lock(port.to_string())?;
self.lock_file.lock(&port.to_string())?;
Ok(listener)
}

View File

@ -1,5 +1,20 @@
# Changelog
## 2.4.3 - 2025-01-21
- Do not use static default value for `--os-version` option.
## 2.4.2 - 2025-01-20
- Disconnect the VPN when sleep (fix [#166](https://github.com/yuezk/GlobalProtect-openconnect/issues/166), [#267](https://github.com/yuezk/GlobalProtect-openconnect/issues/267))
## 2.4.1 - 2025-01-09
- Fix the network issue with OpenSSL < 3.0.4
- GUI: fix the Wayland compatibility issue
- Support configure the log level
- Log the detailed error message when network error occurs
## 2.4.0 - 2024-12-26
- Upgrade to Tauri 2.0

View File

@ -31,6 +31,12 @@ html-escape = { version = "0.2.13", optional = true }
[target.'cfg(not(target_os = "macos"))'.dependencies]
webkit2gtk = { version = "2", optional = true }
[target.'cfg(target_os = "macos")'.dependencies]
block2 = { version = "0.5", optional = true }
objc2 = { version = "0.5", optional = true }
objc2-foundation = { version = "0.2", optional = true }
objc2-web-kit = { version = "0.2", optional = true }
[features]
browser-auth = [
"dep:webbrowser",
@ -40,10 +46,14 @@ browser-auth = [
"dep:uuid",
]
webview-auth = [
"gpapi/tauri",
"dep:tauri",
"dep:regex",
"dep:tokio-util",
"dep:html-escape",
"dep:webkit2gtk",
"gpapi/tauri",
"dep:block2",
"dep:objc2",
"dep:objc2-foundation",
"dep:objc2-web-kit",
]

View File

@ -1,60 +0,0 @@
use std::borrow::Cow;
use anyhow::bail;
use gpapi::{
gp_params::GpParams,
portal::{prelogin, Prelogin},
};
pub struct Authenticator<'a> {
server: &'a str,
auth_request: Option<&'a str>,
pub(crate) gp_params: &'a GpParams,
#[cfg(feature = "webview-auth")]
pub(crate) clean: bool,
#[cfg(feature = "webview-auth")]
pub(crate) is_retrying: tokio::sync::RwLock<bool>,
}
impl<'a> Authenticator<'a> {
pub fn new(server: &'a str, gp_params: &'a GpParams) -> Self {
Self {
server,
gp_params,
auth_request: None,
#[cfg(feature = "webview-auth")]
clean: false,
#[cfg(feature = "webview-auth")]
is_retrying: Default::default(),
}
}
pub fn with_auth_request(mut self, auth_request: &'a str) -> Self {
if !auth_request.is_empty() {
self.auth_request = Some(auth_request);
}
self
}
pub(crate) async fn initial_auth_request(&self) -> anyhow::Result<Cow<'a, str>> {
if let Some(auth_request) = self.auth_request {
return Ok(Cow::Borrowed(auth_request));
}
let auth_request = self.portal_prelogin().await?;
Ok(Cow::Owned(auth_request))
}
pub(crate) async fn portal_prelogin(&self) -> anyhow::Result<String> {
auth_prelogin(self.server, self.gp_params).await
}
}
pub async fn auth_prelogin(server: &str, gp_params: &GpParams) -> anyhow::Result<String> {
match prelogin(server, gp_params).await? {
Prelogin::Saml(prelogin) => Ok(prelogin.saml_request().to_string()),
Prelogin::Standard(_) => bail!("Received non-SAML prelogin response"),
}
}

View File

@ -0,0 +1,4 @@
mod auth_server;
mod browser_auth;
pub use browser_auth::BrowserAuthenticator;

View File

@ -4,30 +4,45 @@ use gpapi::{auth::SamlAuthData, GP_CALLBACK_PORT_FILENAME};
use log::info;
use tokio::{io::AsyncReadExt, net::TcpListener};
use super::auth_server::AuthServer;
use crate::browser::auth_server::AuthServer;
pub(super) struct BrowserAuthenticatorImpl<'a> {
pub enum Browser<'a> {
Default,
Chrome,
Firefox,
Other(&'a str),
}
impl<'a> Browser<'a> {
pub fn from_str(browser: &'a str) -> Self {
match browser.to_lowercase().as_str() {
"default" => Browser::Default,
"chrome" => Browser::Chrome,
"firefox" => Browser::Firefox,
_ => Browser::Other(browser),
}
}
fn as_str(&self) -> &str {
match self {
Browser::Default => "default",
Browser::Chrome => "chrome",
Browser::Firefox => "firefox",
Browser::Other(browser) => browser,
}
}
}
pub struct BrowserAuthenticator<'a> {
auth_request: &'a str,
browser: Option<&'a str>,
browser: Browser<'a>,
}
impl BrowserAuthenticatorImpl<'_> {
pub fn new(auth_request: &str) -> BrowserAuthenticatorImpl {
BrowserAuthenticatorImpl {
impl<'a> BrowserAuthenticator<'a> {
pub fn new(auth_request: &'a str, browser: &'a str) -> Self {
Self {
auth_request,
browser: None,
}
}
pub fn new_with_browser<'a>(auth_request: &'a str, browser: &'a str) -> BrowserAuthenticatorImpl<'a> {
let browser = browser.trim();
BrowserAuthenticatorImpl {
auth_request,
browser: if browser.is_empty() || browser == "default" {
None
} else {
Some(browser)
},
browser: Browser::from_str(browser),
}
}
@ -40,14 +55,17 @@ impl BrowserAuthenticatorImpl<'_> {
auth_server.serve_request(&auth_request);
});
if let Some(browser) = self.browser {
let app = find_browser_path(browser);
match self.browser {
Browser::Default => {
info!("Launching the default browser...");
webbrowser::open(&auth_url)?;
}
_ => {
let app = find_browser_path(&self.browser);
info!("Launching browser: {}", app);
open::with_detached(auth_url, app)?;
} else {
info!("Launching the default browser...");
webbrowser::open(&auth_url)?;
}
}
info!("Please continue the authentication process in the default browser");
@ -55,15 +73,18 @@ impl BrowserAuthenticatorImpl<'_> {
}
}
fn find_browser_path(browser: &str) -> String {
if browser == "chrome" {
which::which("google-chrome-stable")
.or_else(|_| which::which("google-chrome"))
.or_else(|_| which::which("chromium"))
fn find_browser_path(browser: &Browser) -> String {
match browser {
Browser::Chrome => {
const CHROME_VARIANTS: &[&str] = &["google-chrome-stable", "google-chrome", "chromium"];
CHROME_VARIANTS
.iter()
.find_map(|&browser_name| which::which(browser_name).ok())
.map(|path| path.to_string_lossy().to_string())
.unwrap_or_else(|_| browser.to_string())
} else {
browser.into()
.unwrap_or_else(|| browser.as_str().to_string())
}
_ => browser.as_str().to_string(),
}
}

View File

@ -1,5 +0,0 @@
mod auth_server;
mod browser_auth_ext;
mod browser_auth_impl;
pub use browser_auth_ext::BrowserAuthenticator;

View File

@ -1,22 +0,0 @@
use std::future::Future;
use gpapi::auth::SamlAuthData;
use crate::{browser_auth::browser_auth_impl::BrowserAuthenticatorImpl, Authenticator};
pub trait BrowserAuthenticator {
fn browser_authenticate(&self, browser: Option<&str>) -> impl Future<Output = anyhow::Result<SamlAuthData>> + Send;
}
impl BrowserAuthenticator for Authenticator<'_> {
async fn browser_authenticate(&self, browser: Option<&str>) -> anyhow::Result<SamlAuthData> {
let auth_request = self.initial_auth_request().await?;
let browser_auth = if let Some(browser) = browser {
BrowserAuthenticatorImpl::new_with_browser(&auth_request, browser)
} else {
BrowserAuthenticatorImpl::new(&auth_request)
};
browser_auth.authenticate().await
}
}

View File

@ -1,13 +1,23 @@
mod authenticator;
pub use authenticator::auth_prelogin;
pub use authenticator::Authenticator;
use anyhow::bail;
use gpapi::{
gp_params::GpParams,
portal::{prelogin, Prelogin},
};
#[cfg(feature = "browser-auth")]
mod browser_auth;
mod browser;
#[cfg(feature = "browser-auth")]
pub use browser_auth::BrowserAuthenticator;
pub use browser::*;
#[cfg(feature = "webview-auth")]
mod webview_auth;
mod webview;
#[cfg(feature = "webview-auth")]
pub use webview_auth::WebviewAuthenticator;
pub use webview::*;
pub async fn auth_prelogin(server: &str, gp_params: &GpParams) -> anyhow::Result<String> {
match prelogin(server, gp_params).await? {
Prelogin::Saml(prelogin) => Ok(prelogin.saml_request().to_string()),
Prelogin::Standard(_) => bail!("Received non-SAML prelogin response"),
}
}

View File

@ -0,0 +1,8 @@
mod auth_messenger;
mod webview_auth;
#[cfg_attr(not(target_os = "macos"), path = "webview/unix.rs")]
#[cfg_attr(target_os = "macos", path = "webview/macos.rs")]
mod platform_impl;
pub use webview_auth::WebviewAuthenticator;

View File

@ -0,0 +1,229 @@
use anyhow::bail;
use gpapi::{auth::SamlAuthData, error::AuthDataParseError};
use log::{error, info};
use regex::Regex;
use tokio::sync::{mpsc, RwLock};
use tokio_util::sync::CancellationToken;
#[derive(Debug)]
pub(crate) enum AuthDataLocation {
#[cfg(not(target_os = "macos"))]
Headers,
Body,
}
#[derive(Debug)]
pub(crate) enum AuthError {
/// Failed to load page due to TLS error
#[cfg(not(target_os = "macos"))]
TlsError,
/// 1. Found auth data in headers/body but it's invalid
/// 2. Loaded an empty page, failed to load page. etc.
Invalid(anyhow::Error, AuthDataLocation),
/// No auth data found in headers/body
NotFound(AuthDataLocation),
}
impl AuthError {
pub fn invalid_from_body(err: anyhow::Error) -> Self {
Self::Invalid(err, AuthDataLocation::Body)
}
pub fn not_found_in_body() -> Self {
Self::NotFound(AuthDataLocation::Body)
}
}
#[cfg(not(target_os = "macos"))]
impl AuthError {
pub fn not_found_in_headers() -> Self {
Self::NotFound(AuthDataLocation::Headers)
}
}
pub(crate) enum AuthEvent {
Data(SamlAuthData, AuthDataLocation),
Error(AuthError),
RaiseWindow,
Close,
}
pub struct AuthMessenger {
tx: mpsc::UnboundedSender<AuthEvent>,
rx: RwLock<mpsc::UnboundedReceiver<AuthEvent>>,
raise_window_cancel_token: RwLock<Option<CancellationToken>>,
}
impl AuthMessenger {
pub fn new() -> Self {
let (tx, rx) = mpsc::unbounded_channel();
Self {
tx,
rx: RwLock::new(rx),
raise_window_cancel_token: Default::default(),
}
}
pub async fn subscribe(&self) -> anyhow::Result<AuthEvent> {
let mut rx = self.rx.write().await;
if let Some(event) = rx.recv().await {
return Ok(event);
}
bail!("Failed to receive auth event");
}
pub fn send_auth_event(&self, event: AuthEvent) {
if let Err(event) = self.tx.send(event) {
error!("Failed to send auth event: {}", event);
}
}
pub fn send_auth_error(&self, err: AuthError) {
self.send_auth_event(AuthEvent::Error(err));
}
fn send_auth_data(&self, data: SamlAuthData, location: AuthDataLocation) {
self.send_auth_event(AuthEvent::Data(data, location));
}
pub fn schedule_raise_window(&self, delay: u64) {
let Ok(mut guard) = self.raise_window_cancel_token.try_write() else {
return;
};
// Return if the previous raise window task is still running
if let Some(token) = guard.as_ref() {
if !token.is_cancelled() {
info!("Raise window task is still running, skipping...");
return;
}
}
let cancel_token = CancellationToken::new();
let cancel_token_clone = cancel_token.clone();
*guard = Some(cancel_token_clone);
let tx = self.tx.clone();
tokio::spawn(async move {
info!("Displaying the window in {} second(s)...", delay);
tokio::select! {
_ = tokio::time::sleep(tokio::time::Duration::from_secs(delay)) => {
cancel_token.cancel();
if let Err(err) = tx.send(AuthEvent::RaiseWindow) {
error!("Failed to send raise window event: {}", err);
}
}
_ = cancel_token.cancelled() => {
info!("Cancelled raise window task");
}
}
});
}
pub fn cancel_raise_window(&self) {
if let Ok(mut cancel_token) = self.raise_window_cancel_token.try_write() {
if let Some(token) = cancel_token.take() {
token.cancel();
}
}
}
pub fn read_from_html(&self, html: &str) {
if html.contains("Temporarily Unavailable") {
return self.send_auth_error(AuthError::invalid_from_body(anyhow::anyhow!("Temporarily Unavailable")));
}
let auth_result = SamlAuthData::from_html(html).or_else(|err| {
info!("Read auth data from html failed: {}, extracting gpcallback...", err);
if let Some(gpcallback) = extract_gpcallback(html) {
info!("Found gpcallback from html...");
SamlAuthData::from_gpcallback(&gpcallback)
} else {
Err(err)
}
});
match auth_result {
Ok(data) => self.send_auth_data(data, AuthDataLocation::Body),
Err(AuthDataParseError::Invalid(err)) => self.send_auth_error(AuthError::invalid_from_body(err)),
Err(AuthDataParseError::NotFound) => self.send_auth_error(AuthError::not_found_in_body()),
}
}
#[cfg(not(target_os = "macos"))]
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader) {
use log::warn;
let Some(status) = auth_response.get_header("saml-auth-status") else {
return self.send_auth_error(AuthError::not_found_in_headers());
};
// Do not send auth error when reading from headers, as the html body may contain the auth data
if status != "1" {
warn!("Found invalid saml-auth-status in headers: {}", status);
return;
}
let username = auth_response.get_header("saml-username");
let prelogin_cookie = auth_response.get_header("prelogin-cookie");
let portal_userauthcookie = auth_response.get_header("portal-userauthcookie");
match SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie) {
Ok(auth_data) => self.send_auth_data(auth_data, AuthDataLocation::Headers),
Err(err) => {
warn!("Failed to read auth data from headers: {}", err);
}
}
}
}
fn extract_gpcallback(html: &str) -> Option<String> {
let re = Regex::new(r#"globalprotectcallback:[^"]+"#).unwrap();
re.captures(html)
.and_then(|captures| captures.get(0))
.map(|m| html_escape::decode_html_entities(m.as_str()).to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extract_gpcallback_some() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:PGh0bWw+PCEtLSA8c">
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:PGh0bWw+PCEtLSA8c">
"#;
assert_eq!(
extract_gpcallback(html).as_deref(),
Some("globalprotectcallback:PGh0bWw+PCEtLSA8c")
);
}
#[test]
fn extract_gpcallback_cas() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:cas-as=1&amp;un=xyz@email.com&amp;token=very_long_string">
"#;
assert_eq!(
extract_gpcallback(html).as_deref(),
Some("globalprotectcallback:cas-as=1&un=xyz@email.com&token=very_long_string")
);
}
#[test]
fn extract_gpcallback_none() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=PGh0bWw+PCEtLSA8c">
"#;
assert_eq!(extract_gpcallback(html), None);
}
}

View File

@ -0,0 +1,58 @@
use block2::RcBlock;
use log::warn;
use objc2::runtime::AnyObject;
use objc2_foundation::{NSError, NSString, NSURLRequest, NSURL};
use objc2_web_kit::WKWebView;
use tauri::webview::PlatformWebview;
use super::webview_auth::PlatformWebviewExt;
impl PlatformWebviewExt for PlatformWebview {
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
warn!("Ignoring TLS errors is not supported on macOS");
Ok(())
}
fn load_url(&self, url: &str) -> anyhow::Result<()> {
unsafe {
let wv: &WKWebView = &*self.inner().cast();
let url = NSURL::URLWithString(&NSString::from_str(url)).ok_or_else(|| anyhow::anyhow!("Invalid URL"))?;
let request = NSURLRequest::requestWithURL(&url);
wv.loadRequest(&request);
}
Ok(())
}
fn load_html(&self, html: &str) -> anyhow::Result<()> {
unsafe {
let wv: &WKWebView = &*self.inner().cast();
wv.loadHTMLString_baseURL(&NSString::from_str(html), None);
}
Ok(())
}
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>) {
unsafe {
let wv: &WKWebView = &*self.inner().cast();
let js_callback = RcBlock::new(move |body: *mut AnyObject, err: *mut NSError| {
if let Some(err) = err.as_ref() {
let code = err.code();
let message = err.localizedDescription();
callback(Err(anyhow::anyhow!("Error {}: {}", code, message)));
} else {
let body: &NSString = &*body.cast();
callback(Ok(body.to_string()));
}
});
wv.evaluateJavaScript_completionHandler(
&NSString::from_str("document.documentElement.outerHTML"),
Some(&js_callback),
);
}
}
}

View File

@ -0,0 +1,105 @@
use std::sync::Arc;
use anyhow::bail;
use gpapi::utils::redact::redact_uri;
use log::warn;
use tauri::webview::PlatformWebview;
use webkit2gtk::{
gio::Cancellable, glib::GString, LoadEvent, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt,
WebsiteDataManagerExt,
};
use super::{
auth_messenger::AuthError,
webview_auth::{GetHeader, PlatformWebviewExt},
};
impl GetHeader for WebResource {
fn get_header(&self, key: &str) -> Option<String> {
self
.response()
.and_then(|response| response.http_headers())
.and_then(|headers| headers.one(key))
.map(GString::into)
}
}
impl PlatformWebviewExt for PlatformWebview {
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
if let Some(manager) = self.inner().website_data_manager() {
manager.set_tls_errors_policy(TLSErrorsPolicy::Ignore);
return Ok(());
}
bail!("Failed to get website data manager");
}
fn load_url(&self, url: &str) -> anyhow::Result<()> {
self.inner().load_uri(url);
Ok(())
}
fn load_html(&self, html: &str) -> anyhow::Result<()> {
self.inner().load_html(html, None);
Ok(())
}
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>) {
let script = "document.documentElement.outerHTML";
self
.inner()
.evaluate_javascript(script, None, None, Cancellable::NONE, move |result| match result {
Ok(value) => callback(Ok(value.to_string())),
Err(err) => callback(Err(anyhow::anyhow!(err))),
});
}
}
pub trait PlatformWebviewOnResponse {
fn on_response(&self, callback: Box<dyn Fn(anyhow::Result<WebResource, AuthError>) + 'static>);
}
impl PlatformWebviewOnResponse for PlatformWebview {
fn on_response(&self, callback: Box<dyn Fn(anyhow::Result<WebResource, AuthError>) + 'static>) {
let wv = self.inner();
let callback = Arc::new(callback);
let callback_clone = Arc::clone(&callback);
wv.connect_load_changed(move |wv, event| {
if event != LoadEvent::Finished {
return;
}
let Some(web_resource) = wv.main_resource() else {
return;
};
let uri = web_resource.uri().unwrap_or("".into());
if uri.is_empty() {
callback_clone(Err(AuthError::invalid_from_body(anyhow::anyhow!("Empty URI"))));
} else {
callback_clone(Ok(web_resource));
}
});
wv.connect_load_failed_with_tls_errors(move |_wv, uri, cert, err| {
let redacted_uri = redact_uri(uri);
warn!(
"Failed to load uri: {} with error: {}, cert: {}",
redacted_uri, err, cert
);
callback(Err(AuthError::TlsError));
true
});
wv.connect_load_failed(move |_wv, _event, uri, err| {
let redacted_uri = redact_uri(uri);
if !uri.starts_with("globalprotectcallback:") {
warn!("Failed to load uri: {} with error: {}", redacted_uri, err);
}
// NOTE: Don't send error here, since load_changed event will be triggered after this
// true to stop other handlers from being invoked for the event. false to propagate the event further.
true
});
}
}

View File

@ -0,0 +1,277 @@
use std::{sync::Arc, time::Duration};
use anyhow::bail;
use gpapi::{auth::SamlAuthData, gp_params::GpParams, utils::redact::redact_uri};
use log::{info, warn};
use tauri::{
webview::{PageLoadEvent, PageLoadPayload},
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
};
use tokio::{sync::oneshot, time};
use crate::auth_prelogin;
use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger};
pub trait PlatformWebviewExt {
fn ignore_tls_errors(&self) -> anyhow::Result<()>;
fn load_url(&self, url: &str) -> anyhow::Result<()>;
fn load_html(&self, html: &str) -> anyhow::Result<()>;
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>);
fn load_auth_request(&self, auth_request: &str) -> anyhow::Result<()> {
if auth_request.starts_with("http") {
info!("Loading auth request as URL: {}", redact_uri(auth_request));
self.load_url(auth_request)
} else {
info!("Loading auth request as HTML...");
self.load_html(auth_request)
}
}
}
#[cfg(not(target_os = "macos"))]
pub trait GetHeader {
fn get_header(&self, key: &str) -> Option<String>;
}
pub struct WebviewAuthenticator<'a> {
server: &'a str,
gp_params: &'a GpParams,
auth_request: Option<&'a str>,
clean: bool,
is_retrying: tokio::sync::RwLock<bool>,
}
impl<'a> WebviewAuthenticator<'a> {
pub fn new(server: &'a str, gp_params: &'a GpParams) -> Self {
Self {
server,
gp_params,
auth_request: None,
clean: false,
is_retrying: Default::default(),
}
}
pub fn with_auth_request(mut self, auth_request: &'a str) -> Self {
self.auth_request = Some(auth_request);
self
}
pub fn with_clean(mut self, clean: bool) -> Self {
self.clean = clean;
self
}
pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result<SamlAuthData> {
let auth_messenger = Arc::new(AuthMessenger::new());
let auth_messenger_clone = Arc::clone(&auth_messenger);
let on_page_load = move |auth_window: WebviewWindow, event: PageLoadPayload<'_>| {
let auth_messenger_clone = Arc::clone(&auth_messenger_clone);
let redacted_url = redact_uri(event.url().as_str());
match event.event() {
PageLoadEvent::Started => {
info!("Started loading page: {}", redacted_url);
auth_messenger_clone.cancel_raise_window();
}
PageLoadEvent::Finished => {
info!("Finished loading page: {}", redacted_url);
}
}
// Read auth data from the page no matter whether it's finished loading or not
// Because we found that the finished event may not be triggered in some cases (e.g., on macOS)
let _ = auth_window.with_webview(move |wv| {
wv.get_html(Box::new(move |html| match html {
Ok(html) => auth_messenger_clone.read_from_html(&html),
Err(err) => warn!("Failed to get html: {}", err),
}));
});
};
let title_bar_height = if cfg!(target_os = "macos") { 28.0 } else { 0.0 };
let auth_window = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
.on_page_load(on_page_load)
.title("GlobalProtect Login")
.inner_size(900.0, 650.0 + title_bar_height)
.focused(true)
.visible(false)
.center()
.build()?;
self
.setup_auth_window(&auth_window, Arc::clone(&auth_messenger))
.await?;
loop {
match auth_messenger.subscribe().await? {
AuthEvent::Close => bail!("Authentication cancelled"),
AuthEvent::RaiseWindow => self.raise_window(&auth_window),
#[cfg(not(target_os = "macos"))]
AuthEvent::Error(AuthError::TlsError) => bail!(gpapi::error::PortalError::TlsError),
AuthEvent::Error(AuthError::NotFound(location)) => {
info!(
"No auth data found in {:?}, it may not be the /SAML20/SP/ACS endpoint",
location
);
self.handle_not_found(&auth_window, &auth_messenger);
}
AuthEvent::Error(AuthError::Invalid(err, location)) => {
warn!("Got invalid auth data in {:?}: {}", location, err);
self.retry_auth(&auth_window).await;
}
AuthEvent::Data(auth_data, location) => {
info!("Got auth data from {:?}", location);
auth_window.close()?;
return Ok(auth_data);
}
}
}
}
async fn setup_auth_window(
&self,
auth_window: &WebviewWindow,
auth_messenger: Arc<AuthMessenger>,
) -> anyhow::Result<()> {
info!("Setting up auth window...");
if self.clean {
info!("Clearing all browsing data...");
auth_window.clear_all_browsing_data()?;
}
// Handle window close event
let auth_messenger_clone = Arc::clone(&auth_messenger);
auth_window.on_window_event(move |event| {
if let WindowEvent::CloseRequested { .. } = event {
auth_messenger_clone.send_auth_event(AuthEvent::Close);
}
});
// Show the window after 10 seconds, so that the user can see the window if the auth process is stuck
let auth_messenger_clone = Arc::clone(&auth_messenger);
tokio::spawn(async move {
time::sleep(Duration::from_secs(10)).await;
auth_messenger_clone.send_auth_event(AuthEvent::RaiseWindow);
});
let auth_request = match self.auth_request {
Some(auth_request) => auth_request.to_string(),
None => auth_prelogin(&self.server, &self.gp_params).await?,
};
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
let ignore_tls_errors = self.gp_params.ignore_tls_errors();
// Set up webview
auth_window.with_webview(move |wv| {
#[cfg(not(target_os = "macos"))]
{
use super::platform_impl::PlatformWebviewOnResponse;
wv.on_response(Box::new(move |response| match response {
Ok(response) => auth_messenger.read_from_response(&response),
Err(err) => auth_messenger.send_auth_error(err),
}));
}
let result = || -> anyhow::Result<()> {
if ignore_tls_errors {
wv.ignore_tls_errors()?;
}
wv.load_auth_request(&auth_request)
}();
if let Err(result) = tx.send(result) {
warn!("Failed to send setup auth window result: {:?}", result);
}
})?;
rx.await??;
info!("Auth window setup completed");
Ok(())
}
fn handle_not_found(&self, auth_window: &WebviewWindow, auth_messenger: &Arc<AuthMessenger>) {
let visible = auth_window.is_visible().unwrap_or(false);
if visible {
return;
}
auth_messenger.schedule_raise_window(2);
}
async fn retry_auth(&self, auth_window: &WebviewWindow) {
let mut is_retrying = self.is_retrying.write().await;
if *is_retrying {
info!("Already retrying authentication, skipping...");
return;
}
*is_retrying = true;
drop(is_retrying);
if let Err(err) = self.retry_auth_impl(auth_window).await {
warn!("Failed to retry authentication: {}", err);
}
*self.is_retrying.write().await = false;
}
async fn retry_auth_impl(&self, auth_window: &WebviewWindow) -> anyhow::Result<()> {
info!("Retrying authentication...");
auth_window.eval( r#"
var loading = document.createElement("div");
loading.innerHTML = '<div style="position: absolute; width: 100%; text-align: center; font-size: 20px; font-weight: bold; top: 50%; left: 50%; transform: translate(-50%, -50%);">Got invalid token, retrying...</div>';
loading.style = "position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.85); z-index: 99999;";
document.body.appendChild(loading);
"#)?;
let auth_request = auth_prelogin(&self.server, &self.gp_params).await?;
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
auth_window.with_webview(move |wv| {
let result = wv.load_auth_request(&auth_request);
if let Err(result) = tx.send(result) {
warn!("Failed to send retry auth result: {:?}", result);
}
})?;
rx.await??;
Ok(())
}
fn raise_window(&self, auth_window: &WebviewWindow) {
let visible = auth_window.is_visible().unwrap_or(false);
if visible {
return;
}
info!("Raising auth window...");
#[cfg(target_os = "macos")]
let result = auth_window.show();
#[cfg(not(target_os = "macos"))]
let result = {
use gpapi::utils::window::WindowExt;
auth_window.raise()
};
if let Err(err) = result {
warn!("Failed to raise window: {}", err);
}
}
}

View File

@ -1,9 +0,0 @@
mod auth_messenger;
mod auth_response;
mod auth_settings;
mod webview_auth_ext;
#[cfg_attr(not(target_os = "macos"), path = "webview_auth/unix.rs")]
mod platform_impl;
pub use webview_auth_ext::WebviewAuthenticator;

View File

@ -1,108 +0,0 @@
use anyhow::bail;
use gpapi::auth::SamlAuthData;
use log::{error, info};
use tokio::sync::{mpsc, RwLock};
use tokio_util::sync::CancellationToken;
pub enum AuthError {
/// Failed to load page due to TLS error
TlsError,
/// 1. Found auth data in headers/body but it's invalid
/// 2. Loaded an empty page, failed to load page. etc.
Invalid,
/// No auth data found in headers/body
NotFound,
}
pub type AuthResult = anyhow::Result<SamlAuthData, AuthError>;
pub enum AuthEvent {
Data(SamlAuthData),
Error(AuthError),
RaiseWindow,
Close,
}
pub struct AuthMessenger {
tx: mpsc::UnboundedSender<AuthEvent>,
rx: RwLock<mpsc::UnboundedReceiver<AuthEvent>>,
raise_window_cancel_token: RwLock<Option<CancellationToken>>,
}
impl AuthMessenger {
pub fn new() -> Self {
let (tx, rx) = mpsc::unbounded_channel();
Self {
tx,
rx: RwLock::new(rx),
raise_window_cancel_token: Default::default(),
}
}
pub async fn subscribe(&self) -> anyhow::Result<AuthEvent> {
let mut rx = self.rx.write().await;
if let Some(event) = rx.recv().await {
return Ok(event);
}
bail!("Failed to receive auth event");
}
pub fn send_auth_event(&self, event: AuthEvent) {
if let Err(event) = self.tx.send(event) {
error!("Failed to send auth event: {}", event);
}
}
pub fn send_auth_result(&self, result: AuthResult) {
match result {
Ok(data) => self.send_auth_data(data),
Err(err) => self.send_auth_error(err),
}
}
pub fn send_auth_error(&self, err: AuthError) {
self.send_auth_event(AuthEvent::Error(err));
}
pub fn send_auth_data(&self, data: SamlAuthData) {
self.send_auth_event(AuthEvent::Data(data));
}
pub fn schedule_raise_window(&self, delay: u64) {
let cancel_token = CancellationToken::new();
let cancel_token_clone = cancel_token.clone();
if let Ok(mut guard) = self.raise_window_cancel_token.try_write() {
// Cancel the previous raise window task if it exists
if let Some(token) = guard.take() {
token.cancel();
}
*guard = Some(cancel_token_clone);
}
let tx = self.tx.clone();
tokio::spawn(async move {
info!("Displaying the window in {} second(s)...", delay);
tokio::select! {
_ = tokio::time::sleep(tokio::time::Duration::from_secs(delay)) => {
if let Err(err) = tx.send(AuthEvent::RaiseWindow) {
error!("Failed to send raise window event: {}", err);
}
}
_ = cancel_token.cancelled() => {
info!("Cancelled raise window task");
}
}
});
}
pub fn cancel_raise_window(&self) {
if let Ok(mut cancel_token) = self.raise_window_cancel_token.try_write() {
if let Some(token) = cancel_token.take() {
token.cancel();
}
}
}
}

View File

@ -1,152 +0,0 @@
use std::sync::Arc;
use gpapi::{
auth::{AuthDataParseResult, SamlAuthData},
error::AuthDataParseError,
};
use log::{info, warn};
use regex::Regex;
use crate::webview_auth::auth_messenger::{AuthError, AuthMessenger};
/// Trait for handling authentication response
pub trait AuthResponse {
fn get_header(&self, key: &str) -> Option<String>;
fn get_body<F>(&self, cb: F)
where
F: FnOnce(anyhow::Result<Vec<u8>>) + 'static;
fn url(&self) -> Option<String>;
fn is_acs_endpoint(&self) -> bool {
self.url().map_or(false, |url| url.ends_with("/SAML20/SP/ACS"))
}
}
pub fn read_auth_data(auth_response: &impl AuthResponse, auth_messenger: &Arc<AuthMessenger>) {
let auth_messenger = Arc::clone(auth_messenger);
match read_from_headers(auth_response) {
Ok(auth_data) => {
info!("Found auth data in headers");
auth_messenger.send_auth_data(auth_data);
}
Err(header_err) => {
info!("Failed to read auth data from headers: {}", header_err);
let is_acs_endpoint = auth_response.is_acs_endpoint();
read_from_body(auth_response, move |auth_result| {
// If the endpoint is `/SAML20/SP/ACS` and no auth data found in body, it should be considered as invalid
let auth_result = auth_result.map_err(move |e| {
info!("Failed to read auth data from body: {}", e);
if is_acs_endpoint || e.is_invalid() || header_err.is_invalid() {
AuthError::Invalid
} else {
AuthError::NotFound
}
});
auth_messenger.send_auth_result(auth_result);
});
}
}
}
fn read_from_headers(auth_response: &impl AuthResponse) -> AuthDataParseResult {
let Some(status) = auth_response.get_header("saml-auth-status") else {
info!("No SAML auth status found in headers");
return Err(AuthDataParseError::NotFound);
};
if status != "1" {
info!("Found invalid auth status: {}", status);
return Err(AuthDataParseError::Invalid);
}
let username = auth_response.get_header("saml-username");
let prelogin_cookie = auth_response.get_header("prelogin-cookie");
let portal_userauthcookie = auth_response.get_header("portal-userauthcookie");
SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(|e| {
warn!("Found invalid auth data: {}", e);
AuthDataParseError::Invalid
})
}
fn read_from_body<F>(auth_response: &impl AuthResponse, cb: F)
where
F: FnOnce(AuthDataParseResult) + 'static,
{
auth_response.get_body(|body| match body {
Ok(body) => {
let html = String::from_utf8_lossy(&body);
cb(read_from_html(&html))
}
Err(err) => {
info!("Failed to read body: {}", err);
cb(Err(AuthDataParseError::Invalid))
}
});
}
fn read_from_html(html: &str) -> AuthDataParseResult {
if html.contains("Temporarily Unavailable") {
info!("Found 'Temporarily Unavailable' in HTML, auth failed");
return Err(AuthDataParseError::Invalid);
}
SamlAuthData::from_html(html).or_else(|err| {
if let Some(gpcallback) = extract_gpcallback(html) {
info!("Found gpcallback from html...");
SamlAuthData::from_gpcallback(&gpcallback)
} else {
Err(err)
}
})
}
fn extract_gpcallback(html: &str) -> Option<String> {
let re = Regex::new(r#"globalprotectcallback:[^"]+"#).unwrap();
re.captures(html)
.and_then(|captures| captures.get(0))
.map(|m| html_escape::decode_html_entities(m.as_str()).to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extract_gpcallback_some() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:PGh0bWw+PCEtLSA8c">
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:PGh0bWw+PCEtLSA8c">
"#;
assert_eq!(
extract_gpcallback(html).as_deref(),
Some("globalprotectcallback:PGh0bWw+PCEtLSA8c")
);
}
#[test]
fn extract_gpcallback_cas() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:cas-as=1&amp;un=xyz@email.com&amp;token=very_long_string">
"#;
assert_eq!(
extract_gpcallback(html).as_deref(),
Some("globalprotectcallback:cas-as=1&un=xyz@email.com&token=very_long_string")
);
}
#[test]
fn extract_gpcallback_none() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=PGh0bWw+PCEtLSA8c">
"#;
assert_eq!(extract_gpcallback(html), None);
}
}

View File

@ -1,25 +0,0 @@
use std::sync::Arc;
use super::auth_messenger::AuthMessenger;
pub struct AuthRequest<'a>(&'a str);
impl<'a> AuthRequest<'a> {
pub fn new(auth_request: &'a str) -> Self {
Self(auth_request)
}
pub fn is_url(&self) -> bool {
self.0.starts_with("http")
}
pub fn as_str(&self) -> &str {
self.0
}
}
pub struct AuthSettings<'a> {
pub auth_request: AuthRequest<'a>,
pub auth_messenger: Arc<AuthMessenger>,
pub ignore_tls_errors: bool,
}

View File

@ -1,136 +0,0 @@
use std::sync::Arc;
use anyhow::bail;
use gpapi::utils::redact::redact_uri;
use log::{info, warn};
use webkit2gtk::{
gio::Cancellable,
glib::{GString, TimeSpan},
LoadEvent, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebView, WebViewExt, WebsiteDataManagerExt,
WebsiteDataManagerExtManual, WebsiteDataTypes,
};
use crate::webview_auth::{
auth_messenger::AuthError,
auth_response::read_auth_data,
auth_settings::{AuthRequest, AuthSettings},
};
use super::auth_response::AuthResponse;
impl AuthResponse for WebResource {
fn get_header(&self, key: &str) -> Option<String> {
self
.response()
.and_then(|response| response.http_headers())
.and_then(|headers| headers.one(key))
.map(GString::into)
}
fn get_body<F>(&self, cb: F)
where
F: FnOnce(anyhow::Result<Vec<u8>>) + 'static,
{
let cancellable = Cancellable::NONE;
self.data(cancellable, |data| cb(data.map_err(|e| anyhow::anyhow!(e))));
}
fn url(&self) -> Option<String> {
self.uri().map(GString::into)
}
}
pub fn clear_data<F>(wv: &WebView, cb: F)
where
F: FnOnce(anyhow::Result<()>) + Send + 'static,
{
let Some(data_manager) = wv.website_data_manager() else {
cb(Err(anyhow::anyhow!("Failed to get website data manager")));
return;
};
data_manager.clear(
WebsiteDataTypes::COOKIES,
TimeSpan(0),
Cancellable::NONE,
move |result| {
cb(result.map_err(|e| anyhow::anyhow!(e)));
},
);
}
pub fn setup_webview(wv: &WebView, auth_settings: AuthSettings) -> anyhow::Result<()> {
let AuthSettings {
auth_request,
auth_messenger,
ignore_tls_errors,
} = auth_settings;
let auth_messenger_clone = Arc::clone(&auth_messenger);
let Some(data_manager) = wv.website_data_manager() else {
bail!("Failed to get website data manager");
};
if ignore_tls_errors {
data_manager.set_tls_errors_policy(TLSErrorsPolicy::Ignore);
}
wv.connect_load_changed(move |wv, event| {
if event == LoadEvent::Started {
auth_messenger_clone.cancel_raise_window();
return;
}
if event != LoadEvent::Finished {
return;
}
let Some(main_resource) = wv.main_resource() else {
return;
};
let uri = main_resource.uri().unwrap_or("".into());
if uri.is_empty() {
warn!("Loaded an empty URI");
auth_messenger_clone.send_auth_error(AuthError::Invalid);
return;
}
read_auth_data(&main_resource, &auth_messenger_clone);
});
wv.connect_load_failed_with_tls_errors(move |_wv, uri, cert, err| {
let redacted_uri = redact_uri(uri);
warn!(
"Failed to load uri: {} with error: {}, cert: {}",
redacted_uri, err, cert
);
auth_messenger.send_auth_error(AuthError::TlsError);
true
});
wv.connect_load_failed(move |_wv, _event, uri, err| {
let redacted_uri = redact_uri(uri);
if !uri.starts_with("globalprotectcallback:") {
warn!("Failed to load uri: {} with error: {}", redacted_uri, err);
}
// NOTE: Don't send error here, since load_changed event will be triggered after this
// true to stop other handlers from being invoked for the event. false to propagate the event further.
true
});
load_auth_request(wv, &auth_request);
Ok(())
}
pub fn load_auth_request(wv: &WebView, auth_request: &AuthRequest) {
if auth_request.is_url() {
info!("Loading auth request as URI...");
wv.load_uri(auth_request.as_str());
} else {
info!("Loading auth request as HTML...");
wv.load_html(auth_request.as_str(), None);
}
}

View File

@ -1,194 +0,0 @@
use std::{
future::Future,
sync::Arc,
time::{Duration, Instant},
};
use anyhow::bail;
use gpapi::{auth::SamlAuthData, error::PortalError, utils::window::WindowExt};
use log::{info, warn};
use tauri::{AppHandle, WebviewUrl, WebviewWindow, WindowEvent};
use tokio::{sync::oneshot, time};
use crate::{
webview_auth::{
auth_messenger::{AuthError, AuthEvent, AuthMessenger},
auth_settings::{AuthRequest, AuthSettings},
platform_impl,
},
Authenticator,
};
pub trait WebviewAuthenticator {
fn with_clean(self, clean: bool) -> Self;
fn webview_authenticate(&self, app_handle: &AppHandle) -> impl Future<Output = anyhow::Result<SamlAuthData>> + Send;
}
impl WebviewAuthenticator for Authenticator<'_> {
fn with_clean(mut self, clean: bool) -> Self {
self.clean = clean;
self
}
async fn webview_authenticate(&self, app_handle: &AppHandle) -> anyhow::Result<SamlAuthData> {
let auth_window = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
.title("GlobalProtect Login")
.focused(true)
.visible(false)
.center()
.build()?;
self.auth_loop(&auth_window).await
}
}
impl Authenticator<'_> {
async fn auth_loop(&self, auth_window: &WebviewWindow) -> anyhow::Result<SamlAuthData> {
if self.clean {
self.clear_webview_data(&auth_window).await?;
}
let auth_messenger = self.setup_auth_window(&auth_window).await?;
loop {
match auth_messenger.subscribe().await? {
AuthEvent::Close => bail!("Authentication cancelled"),
AuthEvent::RaiseWindow => self.raise_window(auth_window),
AuthEvent::Error(AuthError::TlsError) => bail!(PortalError::TlsError),
AuthEvent::Error(AuthError::NotFound) => self.handle_not_found(auth_window, &auth_messenger),
AuthEvent::Error(AuthError::Invalid) => self.retry_auth(auth_window).await,
AuthEvent::Data(auth_data) => {
auth_window.close()?;
return Ok(auth_data);
}
}
}
}
async fn clear_webview_data(&self, auth_window: &WebviewWindow) -> anyhow::Result<()> {
info!("Clearing webview data...");
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
let now = Instant::now();
auth_window.with_webview(|webview| {
platform_impl::clear_data(&webview.inner(), |result| {
if let Err(result) = tx.send(result) {
warn!("Failed to send clear data result: {:?}", result);
}
})
})?;
rx.await??;
info!("Webview data cleared in {:?}", now.elapsed());
Ok(())
}
async fn setup_auth_window(&self, auth_window: &WebviewWindow) -> anyhow::Result<Arc<AuthMessenger>> {
info!("Setting up auth window...");
let auth_messenger = Arc::new(AuthMessenger::new());
let auth_request = self.initial_auth_request().await?.into_owned();
let ignore_tls_errors = self.gp_params.ignore_tls_errors();
// Handle window close event
let auth_messenger_clone = Arc::clone(&auth_messenger);
auth_window.on_window_event(move |event| {
if let WindowEvent::CloseRequested { .. } = event {
auth_messenger_clone.send_auth_event(AuthEvent::Close);
}
});
// Show the window after 10 seconds, so that the user can see the window if the auth process is stuck
let auth_messenger_clone = Arc::clone(&auth_messenger);
tokio::spawn(async move {
time::sleep(Duration::from_secs(10)).await;
auth_messenger_clone.send_auth_event(AuthEvent::RaiseWindow);
});
// setup webview
let auth_messenger_clone = Arc::clone(&auth_messenger);
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
auth_window.with_webview(move |webview| {
let auth_settings = AuthSettings {
auth_request: AuthRequest::new(&auth_request),
auth_messenger: auth_messenger_clone,
ignore_tls_errors,
};
let result = platform_impl::setup_webview(&webview.inner(), auth_settings);
if let Err(result) = tx.send(result) {
warn!("Failed to send setup auth window result: {:?}", result);
}
})?;
rx.await??;
info!("Auth window setup completed");
Ok(auth_messenger)
}
fn handle_not_found(&self, auth_window: &WebviewWindow, auth_messenger: &Arc<AuthMessenger>) {
info!("No auth data found, it may not be the /SAML20/SP/ACS endpoint");
let visible = auth_window.is_visible().unwrap_or(false);
if visible {
return;
}
auth_messenger.schedule_raise_window(1);
}
async fn retry_auth(&self, auth_window: &WebviewWindow) {
let mut is_retrying = self.is_retrying.write().await;
if *is_retrying {
info!("Already retrying authentication, skipping...");
return;
}
*is_retrying = true;
drop(is_retrying);
if let Err(err) = self.retry_auth_impl(auth_window).await {
warn!("Failed to retry authentication: {}", err);
}
*self.is_retrying.write().await = false;
}
async fn retry_auth_impl(&self, auth_window: &WebviewWindow) -> anyhow::Result<()> {
info!("Retrying authentication...");
auth_window.eval( r#"
var loading = document.createElement("div");
loading.innerHTML = '<div style="position: absolute; width: 100%; text-align: center; font-size: 20px; font-weight: bold; top: 50%; left: 50%; transform: translate(-50%, -50%);">Got invalid token, retrying...</div>';
loading.style = "position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.85); z-index: 99999;";
document.body.appendChild(loading);
"#)?;
let auth_request = self.portal_prelogin().await?;
let (tx, rx) = oneshot::channel::<()>();
auth_window.with_webview(move |webview| {
let auth_request = AuthRequest::new(&auth_request);
platform_impl::load_auth_request(&webview.inner(), &auth_request);
tx.send(()).expect("Failed to send message to the channel")
})?;
rx.await?;
Ok(())
}
fn raise_window(&self, auth_window: &WebviewWindow) {
let visible = auth_window.is_visible().unwrap_or(false);
if visible {
return;
}
info!("Raising auth window...");
if let Err(err) = auth_window.raise() {
warn!("Failed to raise window: {}", err);
}
}
}

View File

@ -2,22 +2,26 @@ use std::{io, path::Path};
use is_executable::IsExecutable;
const VPNC_SCRIPT_LOCATIONS: [&str; 6] = [
const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
"/usr/local/share/vpnc-scripts/vpnc-script",
"/usr/local/sbin/vpnc-script",
"/usr/share/vpnc-scripts/vpnc-script",
"/usr/sbin/vpnc-script",
"/etc/vpnc/vpnc-script",
"/etc/openconnect/vpnc-script",
#[cfg(target_os = "macos")]
"/opt/homebrew/etc/vpnc/vpnc-script",
];
const CSD_WRAPPER_LOCATIONS: [&str; 3] = [
const CSD_WRAPPER_LOCATIONS: &[&str] = &[
#[cfg(target_arch = "x86_64")]
"/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh",
#[cfg(target_arch = "aarch64")]
"/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh",
"/usr/lib/openconnect/hipreport.sh",
"/usr/libexec/openconnect/hipreport.sh",
#[cfg(target_os = "macos")]
"/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh",
];
fn find_executable(locations: &[&str]) -> Option<String> {

View File

@ -12,12 +12,13 @@ dns-lookup.workspace = true
log.workspace = true
reqwest.workspace = true
openssl.workspace = true
version-compare = "0.2"
pem.workspace = true
roxmltree.workspace = true
serde.workspace = true
specta = { workspace = true, features = ["derive"] }
urlencoding.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["process", "signal", "macros"] }
serde_json.workspace = true
whoami.workspace = true
tempfile.workspace = true
@ -33,8 +34,13 @@ sha256.workspace = true
tauri = { workspace = true, optional = true }
clap = { workspace = true, optional = true }
clap-verbosity-flag = { workspace = true, optional = true }
env_logger = { workspace = true, optional = true }
log-reload = { version = "0.1", optional = true }
[features]
tauri = ["dep:tauri"]
clap = ["dep:clap"]
clap = ["dep:clap", "dep:clap-verbosity-flag"]
webview-auth = []
logger = ["dep:env_logger", "dep:log-reload"]

View File

@ -72,15 +72,12 @@ impl SamlAuthData {
let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie");
let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie");
SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(|e| {
warn!("Failed to parse auth data: {}", e);
AuthDataParseError::Invalid
})
}
Some(status) => {
warn!("Found invalid auth status: {}", status);
Err(AuthDataParseError::Invalid)
SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid)
}
Some(status) => Err(AuthDataParseError::Invalid(anyhow::anyhow!(
"SAML auth status: {}",
status
))),
None => Err(AuthDataParseError::NotFound),
}
}
@ -100,7 +97,7 @@ 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
AuthDataParseError::Invalid(anyhow::anyhow!(e))
})?;
return Ok(auth_data);
@ -108,7 +105,7 @@ impl SamlAuthData {
let auth_data = decode_to_string(auth_data).map_err(|e| {
warn!("Failed to decode SAML auth data: {}", e);
AuthDataParseError::Invalid
AuthDataParseError::Invalid(anyhow::anyhow!(e))
})?;
let auth_data = Self::from_html(&auth_data)?;
@ -128,7 +125,7 @@ impl SamlAuthData {
}
}
pub fn parse_xml_tag(html: &str, tag: &str) -> Option<String> {
fn parse_xml_tag(html: &str, tag: &str) -> Option<String> {
let re = Regex::new(&format!("<{}>(.*)</{}>", tag, tag)).unwrap();
re.captures(html)
.and_then(|captures| captures.get(1))

View File

@ -1,3 +1,6 @@
use clap_verbosity_flag::{LogLevel, Verbosity, VerbosityFilter};
use log::Level;
use crate::error::PortalError;
pub mod args;
@ -8,7 +11,7 @@ pub trait Args {
}
pub fn handle_error(err: anyhow::Error, args: &impl Args) {
eprintln!("\nError: {}", err);
eprintln!("\nError: {:?}", err);
let Some(err) = err.downcast_ref::<PortalError>() else {
return;
@ -26,3 +29,53 @@ pub fn handle_error(err: anyhow::Error, args: &impl Args) {
eprintln!("{} --ignore-tls-errors {}\n", args[0], args[1..].join(" "));
}
}
#[derive(Debug)]
pub struct InfoLevel;
pub type InfoLevelVerbosity = Verbosity<InfoLevel>;
impl LogLevel for InfoLevel {
fn default_filter() -> VerbosityFilter {
VerbosityFilter::Info
}
fn verbose_help() -> Option<&'static str> {
Some("Enable verbose output, -v for debug, -vv for trace")
}
fn quiet_help() -> Option<&'static str> {
Some("Decrease logging verbosity, -q for warnings, -qq for errors")
}
}
pub trait ToVerboseArg {
fn to_verbose_arg(&self) -> Option<&'static str>;
}
/// Convert the verbosity to the CLI argument value
/// The default verbosity is `Info`, which means no argument is needed
impl ToVerboseArg for InfoLevelVerbosity {
fn to_verbose_arg(&self) -> Option<&'static str> {
match self.filter() {
VerbosityFilter::Off => Some("-qqq"),
VerbosityFilter::Error => Some("-qq"),
VerbosityFilter::Warn => Some("-q"),
VerbosityFilter::Info => None,
VerbosityFilter::Debug => Some("-v"),
VerbosityFilter::Trace => Some("-vv"),
}
}
}
impl ToVerboseArg for Level {
fn to_verbose_arg(&self) -> Option<&'static str> {
match self {
Level::Error => Some("-qq"),
Level::Warn => Some("-q"),
Level::Info => None,
Level::Debug => Some("-v"),
Level::Trace => Some("-vv"),
}
}
}

View File

@ -4,10 +4,13 @@ use thiserror::Error;
pub enum PortalError {
#[error("Prelogin error: {0}")]
PreloginError(String),
#[error("Portal config error: {0}")]
ConfigError(String),
#[error("Network error: {0}")]
#[error(transparent)]
NetworkError(#[from] reqwest::Error),
#[error("TLS error")]
TlsError,
}
@ -26,12 +29,12 @@ impl PortalError {
pub enum AuthDataParseError {
#[error("No auth data found")]
NotFound,
#[error("Invalid auth data")]
Invalid,
#[error(transparent)]
Invalid(#[from] anyhow::Error),
}
impl AuthDataParseError {
pub fn is_invalid(&self) -> bool {
matches!(self, AuthDataParseError::Invalid)
matches!(self, AuthDataParseError::Invalid(_))
}
}

View File

@ -31,12 +31,10 @@ pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParam
info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
let res = client
.post(&login_url)
.form(&params)
.send()
.await
.map_err(|e| anyhow::anyhow!(PortalError::NetworkError(e)))?;
let res = client.post(&login_url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
let res = parse_gp_response(res).await.map_err(|err| {
warn!("{err}");

View File

@ -9,9 +9,10 @@ use crate::{utils::request::create_identity, GP_USER_AGENT};
#[derive(Debug, Serialize, Deserialize, Clone, Type, Default)]
pub enum ClientOs {
#[default]
#[cfg_attr(not(target_os = "macos"), default)]
Linux,
Windows,
#[cfg_attr(target_os = "macos", default)]
Mac,
}

View File

@ -8,6 +8,9 @@ pub mod process;
pub mod service;
pub mod utils;
#[cfg(feature = "logger")]
pub mod logger;
#[cfg(feature = "clap")]
pub mod clap;

View File

@ -0,0 +1,44 @@
use std::sync::OnceLock;
use anyhow::bail;
use env_logger::Logger;
use log::{warn, Level};
use log_reload::{ReloadHandle, ReloadLog};
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<Logger>>> = OnceLock::new();
pub fn init(level: Level) {
// Initialize the env_logger and global max level to trace, the logs will be
// filtered by the outer logger
let logger = env_logger::builder().filter_level(log::LevelFilter::Trace).build();
init_with_logger(level, logger);
}
pub fn init_with_logger(level: Level, logger: Logger) {
if let Some(_) = LOG_HANDLE.get() {
warn!("Logger already initialized");
return;
}
log::set_max_level(log::LevelFilter::Trace);
// Create a new logger that will filter the logs based on the max level
let level_filter_logger = log_reload::LevelFilter::new(level, logger);
let reload_log = ReloadLog::new(level_filter_logger);
let handle = reload_log.handle();
// Register the logger to be used by the log crate
let _ = log::set_boxed_logger(Box::new(reload_log));
let _ = LOG_HANDLE.set(handle);
}
pub fn set_max_level(level: Level) -> anyhow::Result<()> {
let Some(handle) = LOG_HANDLE.get() else {
bail!("Logger not initialized")
};
handle
.modify(|logger| logger.set_level(level))
.map_err(|e| anyhow::anyhow!(e))
}

View File

@ -1,6 +1,6 @@
use anyhow::bail;
use dns_lookup::lookup_addr;
use log::{debug, info, warn};
use log::{info, warn};
use reqwest::{Client, StatusCode};
use roxmltree::{Document, Node};
use serde::Serialize;
@ -111,12 +111,10 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent());
let res = client
.post(&url)
.form(&params)
.send()
.await
.map_err(|e| anyhow::anyhow!(PortalError::NetworkError(e)))?;
let res = client.post(&url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
let res_xml = parse_gp_response(res).await.or_else(|err| {
if err.status == StatusCode::NOT_FOUND {
@ -135,8 +133,6 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
bail!(PortalError::ConfigError("Empty portal config response".to_string()))
}
debug!("Portal config response: {}", res_xml);
let doc = Document::parse(&res_xml).map_err(|e| PortalError::ConfigError(e.to_string()))?;
let root = doc.root();

View File

@ -116,12 +116,10 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prel
let client = Client::try_from(gp_params)?;
let res = client
.post(&prelogin_url)
.form(&params)
.send()
.await
.map_err(|e| anyhow::anyhow!(PortalError::NetworkError(e)))?;
let res = client.post(&prelogin_url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
let res_xml = parse_gp_response(res).await.or_else(|err| {
if err.status == StatusCode::NOT_FOUND {

View File

@ -23,6 +23,7 @@ pub struct SamlAuthLauncher<'a> {
#[cfg(feature = "webview-auth")]
default_browser: bool,
browser: Option<&'a str>,
verbose: Option<&'a str>,
}
impl<'a> SamlAuthLauncher<'a> {
@ -43,6 +44,7 @@ impl<'a> SamlAuthLauncher<'a> {
#[cfg(feature = "webview-auth")]
default_browser: false,
browser: None,
verbose: None,
}
}
@ -104,6 +106,11 @@ impl<'a> SamlAuthLauncher<'a> {
self
}
pub fn verbose(mut self, verbose: Option<&'a str>) -> Self {
self.verbose = verbose;
self
}
/// Launch the authenticator binary as the current user or SUDO_USER if available.
pub async fn launch(self) -> anyhow::Result<Credential> {
let mut auth_cmd = Command::new(GP_AUTH_BINARY);
@ -156,6 +163,10 @@ impl<'a> SamlAuthLauncher<'a> {
auth_cmd.arg("--browser").arg(browser);
}
if let Some(verbose) = self.verbose {
auth_cmd.arg(verbose);
}
let mut non_root_cmd = auth_cmd.into_non_root()?;
let output = non_root_cmd
.kill_on_drop(true)

View File

@ -10,26 +10,28 @@ use crate::GP_SERVICE_BINARY;
use super::command_traits::CommandExt;
pub struct ServiceLauncher {
pub struct ServiceLauncher<'a> {
program: PathBuf,
minimized: bool,
env_file: Option<String>,
log_file: Option<String>,
verbose: Option<&'a str>
}
impl Default for ServiceLauncher {
impl Default for ServiceLauncher<'_> {
fn default() -> Self {
Self::new()
}
}
impl ServiceLauncher {
impl<'a> ServiceLauncher<'a> {
pub fn new() -> Self {
Self {
program: GP_SERVICE_BINARY.into(),
minimized: false,
env_file: None,
log_file: None,
verbose: None
}
}
@ -48,6 +50,11 @@ impl ServiceLauncher {
self
}
pub fn verbose(mut self, verbose: Option<&'a str>) -> Self {
self.verbose = verbose;
self
}
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
let mut cmd = Command::new_pkexec(&self.program);
@ -59,6 +66,10 @@ impl ServiceLauncher {
cmd.arg("--env-file").arg(env_file);
}
if let Some(verbose) = self.verbose {
cmd.arg(verbose);
}
if let Some(log_file) = &self.log_file {
let log_file = File::create(log_file)?;
let stdio = Stdio::from(log_file);

View File

@ -7,4 +7,5 @@ use super::vpn_state::VpnState;
pub enum WsEvent {
VpnState(VpnState),
ActiveGui,
ResumeConnection,
}

View File

@ -206,11 +206,15 @@ impl ConnectRequest {
#[derive(Debug, Deserialize, Serialize, Type)]
pub struct DisconnectRequest;
#[derive(Debug, Deserialize, Serialize)]
pub struct UpdateLogLevelRequest(pub String);
/// Requests that can be sent to the service
#[derive(Debug, Deserialize, Serialize)]
pub enum WsRequest {
Connect(Box<ConnectRequest>),
Disconnect(DisconnectRequest),
UpdateLogLevel(UpdateLogLevelRequest),
}
#[derive(Debug, Deserialize, Serialize)]

View File

@ -1,10 +1,9 @@
use tokio::fs;
use crate::GP_SERVICE_LOCK_FILE;
use super::lock_file::gpservice_lock_info;
async fn read_port() -> anyhow::Result<String> {
let port = fs::read_to_string(GP_SERVICE_LOCK_FILE).await?;
Ok(port.trim().to_string())
let lock_info = gpservice_lock_info().await?;
Ok(lock_info.port.to_string())
}
pub async fn http_endpoint() -> anyhow::Result<String> {

View File

@ -42,8 +42,8 @@ pub fn patch_gui_runtime_env(hidpi: bool) {
std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1");
// Workaround for https://github.com/tauri-apps/tao/issues/929
let desktop = env::var("XDG_CURRENT_DESKTOP").unwrap_or_default().to_lowercase();
if desktop.contains("gnome") {
let is_wayland = std::env::var("XDG_SESSION_TYPE").unwrap_or_default() == "wayland";
if is_wayland {
env::set_var("GDK_BACKEND", "x11");
}

View File

@ -1,19 +1,24 @@
use std::path::PathBuf;
use thiserror::Error;
use tokio::fs;
pub struct LockFile {
path: PathBuf,
pid: u32,
}
impl LockFile {
pub fn new<P: Into<PathBuf>>(path: P) -> Self {
Self { path: path.into() }
pub fn new<P: Into<PathBuf>>(path: P, pid: u32) -> Self {
Self { path: path.into(), pid }
}
pub fn exists(&self) -> bool {
self.path.exists()
}
pub fn lock(&self, content: impl AsRef<[u8]>) -> anyhow::Result<()> {
pub fn lock(&self, content: &str) -> anyhow::Result<()> {
let content = format!("{}:{}", self.pid, content);
std::fs::write(&self.path, content)?;
Ok(())
}
@ -37,3 +42,87 @@ impl LockFile {
}
}
}
#[derive(Error, Debug)]
pub enum LockFileError {
#[error("Failed to read lock file: {0}")]
IoError(#[from] std::io::Error),
#[error("Invalid lock file format: expected 'pid:port'")]
InvalidFormat,
#[error("Invalid PID value: {0}")]
InvalidPid(std::num::ParseIntError),
#[error("Invalid port value: {0}")]
InvalidPort(std::num::ParseIntError),
}
pub struct LockInfo {
pub pid: u32,
pub port: u32,
}
impl LockInfo {
async fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self, LockFileError> {
let content = fs::read_to_string(path).await?;
Self::parse(&content)
}
fn parse(content: &str) -> Result<Self, LockFileError> {
let mut parts = content.trim().split(':');
let pid = parts
.next()
.ok_or(LockFileError::InvalidFormat)?
.parse()
.map_err(LockFileError::InvalidPid)?;
let port = parts
.next()
.ok_or(LockFileError::InvalidFormat)?
.parse()
.map_err(LockFileError::InvalidPort)?;
// Ensure there are no extra parts after pid:port
if parts.next().is_some() {
return Err(LockFileError::InvalidFormat);
}
Ok(Self { pid, port })
}
}
pub async fn gpservice_lock_info() -> Result<LockInfo, LockFileError> {
LockInfo::from_file(crate::GP_SERVICE_LOCK_FILE).await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_valid_input() {
let info = LockInfo::parse("1234:8080").unwrap();
assert_eq!(info.pid, 1234);
assert_eq!(info.port, 8080);
}
#[test]
fn test_parse_invalid_format() {
assert!(matches!(
LockInfo::parse("123:456:789"),
Err(LockFileError::InvalidFormat)
));
}
#[test]
fn test_parse_invalid_numbers() {
assert!(matches!(LockInfo::parse("abc:8080"), Err(LockFileError::InvalidPid(_))));
assert!(matches!(
LockInfo::parse("1234:abc"),
Err(LockFileError::InvalidPort(_))
));
}
}

View File

@ -1,9 +1,12 @@
use std::path::Path;
use log::{info, warn};
use regex::Regex;
use tempfile::NamedTempFile;
use version_compare::{compare_to, Cmp};
pub fn openssl_conf() -> String {
let option = "UnsafeLegacyServerConnect";
let option = get_openssl_option();
format!(
"openssl_conf = openssl_init
@ -47,3 +50,58 @@ pub fn fix_openssl_env() -> anyhow::Result<NamedTempFile> {
Ok(openssl_conf)
}
// See: https://stackoverflow.com/questions/75763525/curl-35-error0a000152ssl-routinesunsafe-legacy-renegotiation-disabled
fn get_openssl_option() -> &'static str {
let version_str = openssl::version::version();
let default_option = "UnsafeLegacyServerConnect";
let Some(version) = extract_openssl_version(version_str) else {
warn!("Failed to extract OpenSSL version from '{}'", version_str);
return default_option;
};
let older_than_3_0_4 = match compare_to(version, "3.0.4", Cmp::Lt) {
Ok(result) => result,
Err(_) => {
warn!("Failed to compare OpenSSL version: {}", version);
return default_option;
}
};
if older_than_3_0_4 {
info!("Using 'UnsafeLegacyRenegotiation' option");
"UnsafeLegacyRenegotiation"
} else {
info!("Using 'UnsafeLegacyServerConnect' option");
default_option
}
}
fn extract_openssl_version(version: &str) -> Option<&str> {
let re = Regex::new(r"OpenSSL (\d+\.\d+\.\d+[^\s]*)").unwrap();
re.captures(version).and_then(|caps| caps.get(1)).map(|m| m.as_str())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_extract_version() {
let input = "OpenSSL 3.4.0 22 Oct 2024 (Library: OpenSSL 3.4.0 22 Oct 2024)";
assert_eq!(extract_openssl_version(input), Some("3.4.0"));
}
#[test]
fn test_different_format() {
let input = "OpenSSL 1.1.1t 7 Feb 2023";
assert_eq!(extract_openssl_version(input), Some("1.1.1t"));
}
#[test]
fn test_invalid_input() {
let input = "Invalid string without version";
assert_eq!(extract_openssl_version(input), None);
}
}

View File

@ -1,9 +1,14 @@
fn main() {
// Link to the native openconnect library
println!("cargo:rustc-link-lib=openconnect");
println!("cargo:rustc-link-search=/opt/homebrew/lib"); // Homebrew path
println!("cargo:rerun-if-changed=src/ffi/vpn.c");
println!("cargo:rerun-if-changed=src/ffi/vpn.h");
// Compile the vpn.c file
cc::Build::new().file("src/ffi/vpn.c").include("src/ffi").compile("vpn");
cc::Build::new()
.file("src/ffi/vpn.c")
.include("src/ffi")
.include("/opt/homebrew/include") // Homebrew path
.compile("vpn");
}

View File

@ -10,6 +10,10 @@ install:
install -Dm755 artifacts/usr/bin/gpgui $(DESTDIR)/usr/bin/gpgui; \
fi
# Install the disconnect hooks
install -Dm755 artifacts/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
install -Dm755 artifacts/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
install -Dm644 artifacts/usr/share/applications/gpgui.desktop $(DESTDIR)/usr/share/applications/gpgui.desktop
install -Dm644 artifacts/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
install -Dm644 artifacts/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
@ -26,6 +30,9 @@ uninstall:
rm -f $(DESTDIR)/usr/bin/gpgui-helper
rm -f $(DESTDIR)/usr/bin/gpgui
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
rm -f $(DESTDIR)/usr/share/applications/gpgui.desktop
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
rm -f $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png

View File

@ -0,0 +1,26 @@
#!/bin/sh
# Resume the VPN connection if the network comes back up
set -e
PIDFILE=/tmp/gpservice_disconnected.pid
resume_vpn() {
if [ -f $PIDFILE ]; then
PID=$(cat $PIDFILE)
# Always remove the PID file
rm $PIDFILE
# Ensure the PID is a gpservice process
if ps -p $PID -o comm= | grep -q gpservice; then
# Send a USR2 signal to the gpclient process to resume the VPN connection
kill -USR2 $PID
fi
fi
}
if [ "$2" = "up" ]; then
resume_vpn
fi

View File

@ -0,0 +1,6 @@
#!/bin/sh
set -e
# Disconnect the VPN connection before the network goes down
/usr/bin/gpclient disconnect --wait 3

View File

@ -6,7 +6,7 @@ Group: Productivity/Networking/PPP
License: GPL-3.0
URL: https://github.com/yuezk/GlobalProtect-openconnect
Source: %{name}.tar.gz
Source: @SOURCE@
BuildRequires: make
BuildRequires: rust
@ -14,12 +14,17 @@ BuildRequires: cargo
BuildRequires: jq
BuildRequires: pkg-config
BuildRequires: openconnect-devel
BuildRequires: openssl-devel
BuildRequires: (openssl-devel or libopenssl-devel)
BuildRequires: wget
BuildRequires: file
BuildRequires: perl
BuildRequires: (webkit2gtk4.1-devel or webkit2gtk3-soup2-devel)
%if 0%{?suse_version}
BuildRequires: webkit2gtk3-devel
%else
BuildRequires: webkit2gtk4.1-devel
%endif
BuildRequires: (libappindicator-gtk3-devel or libappindicator3-1)
BuildRequires: (librsvg2-devel or librsvg-devel)
@ -55,6 +60,13 @@ make build OFFLINE=@OFFLINE@ BUILD_FE=0
%{_datadir}/icons/hicolor/scalable/apps/gpgui.svg
%{_datadir}/polkit-1/actions/com.yuezk.gpgui.policy
%dir /usr/lib/NetworkManager
%dir /usr/lib/NetworkManager/dispatcher.d
%dir /usr/lib/NetworkManager/dispatcher.d/pre-down.d
/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
%dir %{_datadir}/icons/hicolor
%dir %{_datadir}/icons/hicolor/32x32
%dir %{_datadir}/icons/hicolor/32x32/apps

2
rust-toolchain.toml Normal file
View File

@ -0,0 +1,2 @@
[toolchain]
channel = "1.80.1"

View File

@ -28,7 +28,7 @@ release_snapshot() {
echo "Uploading new assets..."
gh -R "$REPO" release upload "$TAG" \
"$PROJECT_DIR"/.build/artifacts/artifact-source/* \
"$PROJECT_DIR"/.build/artifacts/artifact-source*/* \
"$PROJECT_DIR"/.build/artifacts/artifact-gpgui-*/*
}
@ -40,7 +40,7 @@ release_tag() {
gh -R "$REPO" release create $TAG \
--title "$TAG" \
--notes "$RELEASE_NOTES" \
"$PROJECT_DIR"/.build/artifacts/artifact-source/* \
"$PROJECT_DIR"/.build/artifacts/artifact-source*/* \
"$PROJECT_DIR"/.build/artifacts/artifact-gpgui-*/*
}