Compare commits

..
Author SHA1 Message Date
Kevin Yue 10a0d9db15 feat: add split-DNS support to VPN connection options 2026-04-06 11:05:19 +08:00
Kevin Yue 70354748e8 fix: continue deb build when mk-build-deps fails 2026-04-06 11:04:29 +08:00
Kevin Yue 33a3c2de11 fix: update Rust version handling in PPA build scripts 2026-04-06 11:04:18 +08:00
Kevin Yue c27ab657c0 chore: upgrade to vite 8 2026-03-20 14:47:09 +08:00
Kevin Yue b0eccfad2e fix: add excluded series input to PPA publish workflow 2026-03-20 14:30:08 +08:00
Kevin Yue 1a81a304d7 chore: bump Rust version to 1.89 2026-03-20 14:16:21 +08:00
Kevin Yue 2fc936c901 Merge branch 'main' into dev 2026-03-20 13:31:44 +08:00
Kevin Yue 8bb65cc9c7 fix: log empty gateway login response headers and handle accordingly 2026-02-13 19:52:05 +08:00
Kevin Yue c83dfa8b24 fix: trim leading slash from auth callback data 2026-02-09 22:37:39 +08:00
Kevin Yue 61b05051f1 fix: include SAML auth data in decode warning 2026-02-09 20:33:58 +08:00
Kevin Yue 6b0316c3e7 refactor: add cookie handling from standard input in ConnectHandler 2026-01-14 23:43:48 +08:00
Kevin Yue 9b4d3b171a refactor: improve error handling and update deprecation warnings in ConnectHandler 2026-01-14 22:31:57 +08:00
Kevin Yue 3238613c76 refactor: update ConnectArgs to replace deprecated options and add HIP support 2025-12-25 08:57:13 +08:00
Kevin Yue 7f7b73612a fix: remove rust build requirement and clarify openconnect dependency 2025-12-24 12:10:28 +08:00
Kevin Yue 4bf351cbfa refactor: replace BUILD_GUI with BUILD_GUI_HELPER and simplify build options 2025-12-23 23:52:49 +08:00
64 changed files with 1783 additions and 4273 deletions

No files matched your search

+14 -14
View File
@@ -41,14 +41,14 @@ jobs:
runs-on: ubuntu-latest
needs: [setup-matrix]
steps:
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@v4
with:
version: 9
- name: Prepare workspace
run: rm -rf source && mkdir -p source/artifacts
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
@@ -80,7 +80,7 @@ jobs:
mv -v .build/rpm/*.spec ../artifacts/
- name: Upload tarball
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: artifact-source
if-no-files-found: error
@@ -93,7 +93,7 @@ jobs:
needs:
- tarball
steps:
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@v4
with:
version: 9
@@ -101,7 +101,7 @@ jobs:
run: rm -rf source-offline && mkdir source-offline
- name: Download tarball
uses: actions/download-artifact@v8
uses: actions/download-artifact@v4
with:
name: artifact-source
path: source-offline
@@ -122,7 +122,7 @@ jobs:
mv -v .build/tarball/*.tar.gz ../$offline_tarball
- name: Upload offline tarball
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
path: source-offline/*.offline.tar.gz
name: artifact-source-offline
@@ -144,7 +144,7 @@ jobs:
rm -rf build-gp-${{ matrix.package }}
mkdir -p build-gp-${{ matrix.package }}
- name: Download tarball
uses: actions/download-artifact@v8
uses: actions/download-artifact@v4
with:
name: artifact-source
path: build-gp-${{ matrix.package }}
@@ -169,7 +169,7 @@ jobs:
# Don't upload package for ubuntu-rolling because it's duplicate of deb package
- name: Upload ${{ matrix.package }} package
if: ${{ matrix.package != 'ubuntu-rolling' }}
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: artifact-gp-${{ matrix.package }}-${{ matrix.os.arch }}
if-no-files-found: error
@@ -185,13 +185,13 @@ jobs:
runs-on: ${{ matrix.os.runner }}
name: build-gpgui (${{ matrix.os.arch }})
steps:
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@v4
with:
version: 9
- name: Prepare workspace
run: rm -rf gpgui-source && mkdir gpgui-source
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
@@ -199,7 +199,7 @@ jobs:
path: gpgui-source/gp
submodules: recursive
- name: Checkout gpgui@${{ github.ref_name }}
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui
@@ -225,7 +225,7 @@ jobs:
-v $(pwd):/workspace yuezk/gpdev:gpgui-builder-tauri2 \
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
- name: Upload gpgui
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: artifact-gpgui-${{ matrix.os.arch }}
if-no-files-found: error
@@ -247,7 +247,7 @@ jobs:
run: rm -rf gh-release && mkdir gh-release
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
@@ -256,7 +256,7 @@ jobs:
submodules: recursive
- name: Download all artifacts
uses: actions/download-artifact@v8
uses: actions/download-artifact@v4
with:
path: gh-release/gp/.build/artifacts
+1 -1
View File
@@ -45,7 +45,7 @@ jobs:
needs: check
runs-on: ubuntu-latest
steps:
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@v4
with:
version: 9
- name: Prepare workspace
+3 -2
View File
@@ -127,7 +127,7 @@ jobs:
bash install.sh
- name: Upload ${{ matrix.package }} package
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: artifact-${{ matrix.os }}-${{ matrix.package }}
if-no-files-found: error
@@ -143,7 +143,7 @@ jobs:
- name: Prepare workspace
run: rm -rf gh-release && mkdir gh-release
- name: Download artifact
uses: actions/download-artifact@v8
uses: actions/download-artifact@v4
with:
path: gh-release
- name: Update release
@@ -155,3 +155,4 @@ jobs:
tag_name: ${{ inputs.tag }}
files: |
gh-release/artifact-*/*
Generated
+792 -412
View File
File diff suppressed because it is too large. Load diff
+1 -2
View File
@@ -11,7 +11,7 @@ members = [
[workspace.package]
rust-version = "1.89"
version = "2.5.2"
version = "2.5.1"
authors = ["Kevin Yue <[email protected]>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2024"
@@ -59,7 +59,6 @@ which = "8"
uuid = "1"
netdev = "0.40"
machine-uid = "0.5"
humantime = "2"
# Tauri dependencies
tauri = { version = "2" }
+2 -3
View File
@@ -100,7 +100,7 @@ build-rs:
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth -p gpgui-helper; \
else \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth --no-default-features; \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth; \
fi
clean:
@@ -125,7 +125,7 @@ install:
install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/bin/gpgui; \
fi
install -Dm755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)/usr/libexec/gpclient/vpnc-script
# Install the HIP report script
install -Dm755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
# Install the disconnect hooks
@@ -148,7 +148,6 @@ uninstall:
rm -f $(DESTDIR)/usr/bin/gpgui-helper
rm -f $(DESTDIR)/usr/bin/gpgui
rm -f $(DESTDIR)/usr/libexec/gpclient/vpnc-script
rm -f $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
+4 -19
View File
@@ -96,10 +96,6 @@ gpclient launch-gui
## Installation
> [!Note]
>
> For older Linux distributions, use [v2.3.13](https://github.com/yuezk/GlobalProtect-openconnect/releases/tag/v2.3.13) instead of the latest release. It provides release assets for common distro families, including Debian/Ubuntu (`.deb`), Arch Linux / Manjaro (`.pkg.tar.zst`), RPM-based distros such as Fedora / RHEL / Rocky / AlmaLinux / CentOS (`.rpm`), and generic Linux tarballs (`.bin.tar.xz`).
### Debian / Ubuntu
#### Option 1: Install from PPA (Recommended)
@@ -200,14 +196,6 @@ sudo emerge --ask --verbose net-vpn/GlobalProtect-openconnect
This repository includes a flake for NixOS integration.
If you want a quick user-level install, you can install it directly from the flake:
```bash
nix profile add github:yuezk/GlobalProtect-openconnect
```
If you want it managed as part of your NixOS system configuration, use the steps below.
#### Installation Steps
1. Add the flake to your `flake.nix`:
@@ -300,16 +288,13 @@ This project includes a DevContainer configuration that provides a consistent, r
```
3. **Build the project:**
To build everything including the GUI helper run this command:
```bash
docker run --privileged --cap-add=NET_ADMIN --device=/dev/net/tun \
--tty -v "$(pwd)":/workspace -w /workspace gpoc-devcontainer \
-v "$(pwd)":/workspace -w /workspace gpoc-devcontainer \
bash -c "export PATH=/usr/local/cargo/bin:\$PATH && make build"
```
To build without the GUI helper run the same command as above, but with `BUILD_GUI=0` passed as an argument to `make`.
5. **Locate build artifacts:**
4. **Locate build artifacts:**
The compiled binaries will be available in `target/release/`:
- `gpclient` – CLI client
@@ -332,7 +317,7 @@ This project includes a DevContainer configuration that provides a consistent, r
- [Rust 1.89 or later](https://www.rust-lang.org/tools/install)
- [Tauri dependencies](https://tauri.app/start/prerequisites/)
- OpenConnect source-build dependencies: `autoconf`, `automake`, `autopoint`/`gettext`, `libtool`, `patch`, `pkg-config`, `libxml2`, `zlib`, `lz4`, `gnutls`, `p11-kit`, `nettle`, and `gmp` development packages
- `libopenconnect-dev` (or `openconnect-devel` on RPM-based systems)
- `pkexec` and `gnome-keyring` (or `pam_kwallet` on KDE)
- `nodejs` and `pnpm` (optional)
@@ -394,7 +379,7 @@ See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/iss
### Trial and Pricing
The **CLI version** is completely free and open source.
The **GUI version** is a paid application with a **7-day trial period** after installation.
The **GUI version** is a paid application with a **10-day trial period** after installation.
### Open Source Licenses
+2 -2
View File
@@ -1,9 +1,9 @@
use auth::{BrowserAuthenticator, auth_prelogin};
use auth::{auth_prelogin, BrowserAuthenticator};
use clap::Parser;
use common::constants::GP_USER_AGENT;
use gpapi::{
auth::{SamlAuthData, SamlAuthResult},
clap::{Args, InfoLevelVerbosity, args::Os, handle_error},
clap::{args::Os, handle_error, Args, InfoLevelVerbosity},
gp_params::{ClientOs, GpParams},
utils::{normalize_server, openssl},
};
+95 -138
View File
@@ -1,9 +1,4 @@
use std::{
borrow::Cow,
cell::RefCell,
fs,
sync::{Arc, Mutex},
};
use std::{borrow::Cow, cell::RefCell, fs, sync::Arc};
use anyhow::{Context, bail};
use clap::Args;
@@ -13,7 +8,7 @@ use gpapi::{
clap::{ToVerboseArg, args::Os},
credential::{Credential, PasswordCredential},
error::PortalError,
gateway::{GatewayLogin, SessionExtensionAuth, gateway_login},
gateway::{GatewayLogin, gateway_login},
gp_params::{ClientOs, GpParams},
portal::{Prelogin, StandardPrelogin, prelogin, retrieve_config},
process::{
@@ -25,18 +20,8 @@ use gpapi::{
use inquire::{Password, PasswordDisplayMode, Select, Text};
use log::{info, warn};
use openconnect::Vpn;
use tokio::{runtime::Handle, task::JoinHandle};
use crate::{
GP_CLIENT_LOCK_FILE,
cli::SharedArgs,
session::{SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info},
};
struct GatewayLoginSession {
cookie: String,
extension_auth: SessionExtensionAuth,
}
use crate::{GP_CLIENT_LOCK_FILE, cli::SharedArgs};
#[derive(Args)]
pub(crate) struct ConnectArgs {
@@ -124,11 +109,8 @@ pub(crate) struct ConnectArgs {
#[arg(long, help = "Disable DTLS and ESP")]
no_dtls: bool,
#[arg(
long = "local-hostname",
help = "Same as the '--local-hostname' option in the openconnect command"
)]
local_hostname: Option<String>,
#[arg(long, help = "Comma-separated split-DNS domains to pass to the VPNC script")]
split_dns: Option<String>,
#[arg(
long = "force-dpd",
@@ -136,12 +118,6 @@ pub(crate) struct ConnectArgs {
)]
dpd_interval: Option<u32>,
#[arg(
long = "no-xmlpost",
help = "Same as the '--no-xmlpost' option in the openconnect command"
)]
no_xmlpost: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
hidpi: bool,
@@ -185,6 +161,24 @@ impl ConnectArgs {
Os::Mac => host_utils::get_macos_os_string(),
}
}
fn normalized_split_dns(&self) -> anyhow::Result<Option<String>> {
let Some(split_dns) = self.split_dns.as_deref() else {
return Ok(None);
};
let domains = split_dns
.split(',')
.map(str::trim)
.map(str::to_owned)
.collect::<Vec<_>>();
if domains.iter().any(|domain| domain.is_empty()) {
bail!("The '--split-dns' option must contain a comma-separated list of non-empty domains");
}
Ok(Some(domains.join(",")))
}
}
pub(crate) struct ConnectHandler<'a> {
@@ -221,21 +215,15 @@ impl<'a> ConnectHandler<'a> {
}
fn build_gp_params(&self) -> GpParams {
let mut builder = GpParams::builder();
builder
GpParams::builder()
.user_agent(&self.user_agent())
.client_os(ClientOs::from(&self.args.os))
.os_version(self.args.os_version().to_owned())
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone());
if let Some(local_hostname) = self.args.local_hostname.as_deref() {
builder.computer(local_hostname);
}
builder.build()
.key_password(self.latest_key_password.borrow().clone())
.build()
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
@@ -289,14 +277,14 @@ impl<'a> ConnectHandler<'a> {
}
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
self.args.normalized_split_dns()?;
let server = self.args.server.as_str();
let as_gateway = self.args.as_gateway;
if as_gateway {
info!("Treating the server as a gateway");
return self
.connect_gateway_with_prelogin(server, server, self.args.client_version.as_deref(), false)
.await;
return self.connect_gateway_with_prelogin(server).await;
}
let Err(err) = self.connect_portal_with_prelogin(server).await else {
@@ -306,9 +294,7 @@ impl<'a> ConnectHandler<'a> {
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, server, self.args.client_version.as_deref(), false)
.await?;
self.connect_gateway_with_prelogin(server).await?;
eprintln!("\nNOTE: the server may be a gateway, not a portal.");
eprintln!("NOTE: try to use the `--as-gateway` option if you were authenticated twice.");
@@ -351,42 +337,22 @@ impl<'a> ConnectHandler<'a> {
let gateway = selected_gateway.server();
let cred = portal_config.auth_cookie().into();
let login_session = match self.login_gateway(gateway, &cred, &gp_params).await {
Ok(login_session) => login_session,
let cookie = match self.login_gateway(gateway, &cred, &gp_params).await {
Ok(cookie) => cookie,
Err(err) => {
info!("Gateway login failed: {}", err);
let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version());
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
return self
.connect_gateway_with_prelogin(portal, gateway, client_version, allow_extend_session)
.await;
return self.connect_gateway_with_prelogin(gateway).await;
}
};
// Use the client version from the command line argument if specified, otherwise
// use the version from the portal config if available
let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version());
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
client_version,
allow_extend_session,
login_session.extension_auth,
)
.await
self.connect_gateway(gateway, &cookie, client_version).await
}
async fn connect_gateway_with_prelogin(
&self,
portal: &str,
gateway: &str,
client_version: Option<&str>,
allow_extend_session: bool,
) -> anyhow::Result<()> {
async fn connect_gateway_with_prelogin(&self, gateway: &str) -> anyhow::Result<()> {
info!("Performing the gateway authentication...");
let mut gp_params = self.build_gp_params();
@@ -395,36 +361,20 @@ impl<'a> ConnectHandler<'a> {
let prelogin = prelogin(gateway, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, gateway).await?;
let login_session = self.login_gateway(gateway, &cred, &gp_params).await?;
let cookie = self.login_gateway(gateway, &cred, &gp_params).await?;
self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
client_version,
allow_extend_session,
login_session.extension_auth,
)
.await
// When logging in to a gateway directly, there is no portal config to get the client version from
let client_version = self.args.client_version.as_deref();
self.connect_gateway(gateway, &cookie, client_version).await
}
async fn login_gateway(
&self,
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLoginSession> {
async fn login_gateway(&self, gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<String> {
let mut gp_params = gp_params.clone();
loop {
match gateway_login(gateway, cred, &gp_params).await? {
GatewayLogin::Cookie(cookie) => {
return Ok(GatewayLoginSession {
cookie,
extension_auth: SessionExtensionAuth::new(cred.clone(), gp_params),
});
}
GatewayLogin::Cookie(cookie) => return Ok(cookie),
GatewayLogin::Mfa(message, input_str) => {
let otp = Text::new(&message).prompt()?;
gp_params.set_input_str(&input_str);
@@ -436,16 +386,9 @@ impl<'a> ConnectHandler<'a> {
}
}
async fn connect_gateway(
&self,
portal: &str,
gateway: &str,
cookie: &str,
client_version: Option<&str>,
allow_extend_session: bool,
extension_auth: SessionExtensionAuth,
) -> anyhow::Result<()> {
async fn connect_gateway(&self, gateway: &str, cookie: &str, client_version: Option<&str>) -> anyhow::Result<()> {
let mtu = self.args.mtu.unwrap_or(0);
let split_dns = self.args.normalized_split_dns()?;
let (hip, csd_wrapper) = self.determine_hip_script();
let hip_user = self.determine_hip_user();
let csd_uid = get_uid(&hip_user)?;
@@ -453,20 +396,6 @@ impl<'a> ConnectHandler<'a> {
let os = ClientOs::from(&self.args.os).to_openconnect_os().to_owned();
let os_version = self.args.os_version().to_owned();
let client_version = client_version.map(|s| s.to_owned());
let session_ctx = build_session_context(SessionContextInput {
portal: portal.to_string(),
gateway: gateway.to_string(),
cookie: cookie.to_string(),
user_agent: self.user_agent().into_owned(),
os: ClientOs::from(&self.args.os),
os_version: os_version.clone(),
client_version: client_version.clone(),
certificate: self.args.certificate.clone(),
sslkey: self.args.sslkey.clone(),
key_password: self.latest_key_password.borrow().clone(),
disable_ipv6: self.args.disable_ipv6,
extension_auth: Some(extension_auth),
});
let vpn = Vpn::builder(gateway, cookie)
.script(self.args.script.clone())
.interface(self.args.interface.clone())
@@ -475,6 +404,7 @@ impl<'a> ConnectHandler<'a> {
.os(Some(os))
.os_version(Some(os_version))
.client_version(client_version)
.split_dns(split_dns)
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone())
@@ -485,18 +415,11 @@ impl<'a> ConnectHandler<'a> {
.mtu(mtu)
.disable_ipv6(self.args.disable_ipv6)
.no_dtls(self.args.no_dtls)
.local_hostname(self.args.local_hostname.clone())
.dpd_interval(self.args.dpd_interval.unwrap_or(0))
.no_xmlpost(self.args.no_xmlpost)
.build()?;
let vpn = Arc::new(vpn);
let vpn_clone = vpn.clone();
let runtime_handle = Handle::current();
let session_ctx = Arc::new(Mutex::new(Some(session_ctx)));
let session_task: Arc<Mutex<Option<JoinHandle<()>>>> = Arc::new(Mutex::new(None));
let session_task_on_connect = Arc::clone(&session_task);
let session_ctx_on_connect = Arc::clone(&session_ctx);
// Listen for the interrupt signal in the background
tokio::spawn(async move {
@@ -505,22 +428,7 @@ impl<'a> ConnectHandler<'a> {
vpn_clone.disconnect();
});
vpn.connect(move |vpn_session_info| {
write_pid_file();
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
return;
};
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
info!("VPN session info: {}", session_info.log_summary());
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info);
session_task_on_connect.lock().unwrap().replace(task);
});
if let Some(task) = session_task.lock().unwrap().take() {
task.abort();
}
vpn.connect(write_pid_file);
if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() {
info!("Removing PID file");
@@ -679,3 +587,52 @@ fn get_uid(user: &Option<String>) -> anyhow::Result<u32> {
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
}
}
#[cfg(test)]
mod tests {
use clap::Parser;
use super::ConnectArgs;
#[derive(Parser)]
struct TestCli {
#[command(flatten)]
args: ConnectArgs,
}
fn parse_connect_args(args: &[&str]) -> ConnectArgs {
TestCli::parse_from(args).args
}
#[test]
fn parses_split_dns_domains() {
let args = parse_connect_args(&["gpclient", "example.com", "--split-dns", "corp.local,svc.local"]);
assert_eq!(
args.normalized_split_dns().unwrap(),
Some("corp.local,svc.local".to_string())
);
}
#[test]
fn normalizes_split_dns_whitespace() {
let args = parse_connect_args(&["gpclient", "example.com", "--split-dns", " corp.local , svc.local "]);
assert_eq!(
args.normalized_split_dns().unwrap(),
Some("corp.local,svc.local".to_string())
);
}
#[test]
fn rejects_empty_split_dns_domains() {
let args = parse_connect_args(&["gpclient", "example.com", "--split-dns", "corp.local,,svc.local"]);
let err = args.normalized_split_dns().unwrap_err();
assert_eq!(
err.to_string(),
"The '--split-dns' option must contain a comma-separated list of non-empty domains"
);
}
}
-1
View File
@@ -3,7 +3,6 @@ mod connect;
mod disconnect;
mod hip;
mod launch_gui;
mod session;
pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock";
-252
View File
@@ -1,252 +0,0 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use common::constants::GP_CLIENT_VERSION;
use gpapi::{
gateway::{SessionContext, SessionExtensionAuth, extend_session},
gp_params::ClientOs,
session::{SessionInfo, SessionRequestArgs, SessionWarning},
};
use log::{info, warn};
use openconnect::VpnSessionInfo;
use tokio::{runtime::Handle, task::JoinHandle};
#[derive(Debug, PartialEq, Eq)]
struct SessionWarningSchedule {
delay: Duration,
message: String,
should_auto_extend: bool,
}
pub(crate) struct SessionContextInput {
pub(crate) portal: String,
pub(crate) gateway: String,
pub(crate) cookie: String,
pub(crate) user_agent: String,
pub(crate) os: ClientOs,
pub(crate) os_version: String,
pub(crate) client_version: Option<String>,
pub(crate) certificate: Option<String>,
pub(crate) sslkey: Option<String>,
pub(crate) key_password: Option<String>,
pub(crate) disable_ipv6: bool,
pub(crate) extension_auth: Option<SessionExtensionAuth>,
}
pub(crate) fn build_session_context(input: SessionContextInput) -> SessionContext {
let session_args = SessionRequestArgs::new(input.cookie)
.with_user_agent(Some(input.user_agent))
.with_os(Some(input.os))
.with_os_version(Some(input.os_version))
.with_client_version(Some(
input.client_version.unwrap_or_else(|| GP_CLIENT_VERSION.to_string()),
))
.with_certificate(input.certificate)
.with_sslkey(input.sslkey)
.with_key_password(input.key_password)
.with_disable_ipv6(input.disable_ipv6);
let ctx = SessionContext::new(input.gateway, input.portal, session_args);
match input.extension_auth {
Some(extension_auth) => ctx.with_extension_auth(extension_auth),
None => ctx,
}
}
pub(crate) fn session_info_from_vpn(vpn_session_info: VpnSessionInfo, allow_extend_session: bool) -> SessionInfo {
SessionInfo::from_vpn_session_fields(
vpn_session_info.lifetime_secs,
vpn_session_info.user_expires,
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
prior_secs: warning.prior_secs,
message: warning.message,
}),
allow_extend_session,
)
}
pub(crate) fn spawn_session_runtime_with_info(
handle: &Handle,
session_ctx: SessionContext,
session_info: SessionInfo,
) -> JoinHandle<()> {
handle.spawn(run_session_runtime(session_ctx, session_info))
}
async fn run_session_runtime(session_ctx: SessionContext, mut session_info: SessionInfo) {
loop {
let Some(schedule) = build_session_warning_schedule(&session_info) else {
info!("No session warning schedule provided by the gateway");
return;
};
tokio::time::sleep(schedule.delay).await;
eprintln!("\nWARNING: {}", schedule.message);
if !schedule.should_auto_extend {
info!("Session extension is not allowed by the gateway");
return;
}
info!("Attempting to extend the session");
match extend_session(&session_ctx).await {
Ok(()) => {
let Some(next_session_info) = session_info.rescheduled_after_extension() else {
info!("Session extended, but no lifetime is available to schedule another warning");
return;
};
eprintln!("Session extended.");
session_info = next_session_info;
}
Err(err) => {
warn!("Failed to extend session: {}", err);
eprintln!("WARNING: Failed to extend session: {}", err);
return;
}
}
}
}
fn build_session_warning_schedule(session_info: &SessionInfo) -> Option<SessionWarningSchedule> {
let warning = session_info.lifetime_warning.as_ref()?;
let warning_secs = if let Some(user_expires) = session_info.user_expires {
let now = unix_timestamp();
user_expires.saturating_sub(warning.prior_secs).saturating_sub(now)
} else if let Some(lifetime_secs) = session_info.lifetime_secs {
lifetime_secs.saturating_sub(warning.prior_secs)
} else {
return None;
};
Some(SessionWarningSchedule {
delay: Duration::from_secs(warning_secs as u64),
message: warning.message.clone(),
should_auto_extend: session_info.allow_extend_session,
})
}
fn unix_timestamp() -> u32 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as u32
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_session_info(user_expires: Option<u32>, allow_extend_session: bool) -> SessionInfo {
SessionInfo {
user_expires,
lifetime_warning: Some(SessionWarning {
prior_secs: 1800,
message: "Session expires soon".to_string(),
}),
allow_extend_session,
..Default::default()
}
}
#[test]
fn builds_warning_schedule_for_auto_extend() {
let session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
let schedule = build_session_warning_schedule(&session_info).unwrap();
assert_eq!(schedule.message, "Session expires soon");
assert!(schedule.delay <= Duration::from_secs(30));
assert!(schedule.should_auto_extend);
}
#[test]
fn builds_warning_schedule_without_auto_extend() {
let session_info = sample_session_info(Some(unix_timestamp() + 1830), false);
let schedule = build_session_warning_schedule(&session_info).unwrap();
assert!(!schedule.should_auto_extend);
}
#[test]
fn schedules_next_warning_after_extension_from_lifetime() {
let mut session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
session_info.lifetime_secs = Some(7200);
let next_session_info = session_info.rescheduled_after_extension().unwrap();
let schedule = build_session_warning_schedule(&next_session_info).unwrap();
assert!(schedule.delay <= Duration::from_secs(5400));
}
#[test]
fn builds_session_context_from_cli_runtime_values() {
let ctx = build_session_context(SessionContextInput {
portal: "portal.example.com".to_string(),
gateway: "vpn.example.com".to_string(),
cookie: "authcookie=AUTH".to_string(),
user_agent: "UA".to_string(),
os: ClientOs::Mac,
os_version: "macOS 15.0".to_string(),
client_version: Some("6.3.1-12".to_string()),
certificate: Some("/tmp/client.pem".to_string()),
sslkey: Some("/tmp/client.key".to_string()),
key_password: Some("secret".to_string()),
disable_ipv6: true,
extension_auth: None,
});
assert_eq!(ctx.portal(), "portal.example.com");
assert_eq!(ctx.server(), "vpn.example.com");
assert_eq!(ctx.session_args().cookie(), "authcookie=AUTH");
assert_eq!(ctx.session_args().user_agent().as_deref(), Some("UA"));
assert!(matches!(ctx.session_args().os(), Some(ClientOs::Mac)));
assert_eq!(ctx.session_args().os_version().as_deref(), Some("macOS 15.0"));
assert_eq!(ctx.session_args().client_version().as_deref(), Some("6.3.1-12"));
assert_eq!(ctx.session_args().certificate().as_deref(), Some("/tmp/client.pem"));
assert_eq!(ctx.session_args().sslkey().as_deref(), Some("/tmp/client.key"));
assert_eq!(ctx.session_args().key_password().as_deref(), Some("secret"));
assert!(ctx.session_args().disable_ipv6());
}
#[test]
fn maps_openconnect_session_metadata_to_runtime_session_info() {
let info = session_info_from_vpn(
VpnSessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(1_776_828_409),
lifetime_warning: Some(openconnect::VpnSessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
},
true,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(info.allow_extend_session);
}
#[test]
fn direct_gateway_session_info_does_not_allow_extension_without_portal_policy() {
let info = session_info_from_vpn(
VpnSessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(1_776_828_409),
lifetime_warning: Some(openconnect::VpnSessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
},
false,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(!info.allow_extend_session);
}
}
+15 -15
View File
@@ -11,27 +11,27 @@
"dependencies": {
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.3.10",
"@mui/material": "^7.3.10",
"@tauri-apps/api": "^2.11.0",
"react": "^19.2.5",
"react-dom": "^19.2.5"
"@mui/icons-material": "^7.3.6",
"@mui/material": "^7.3.6",
"@tauri-apps/api": "^2.9.1",
"react": "^19.2.3",
"react-dom": "^19.2.3"
},
"devDependencies": {
"@tauri-apps/cli": "^2.11.1",
"@types/node": "^25.6.0",
"@types/react": "^19.2.14",
"@tauri-apps/cli": "^2.9.6",
"@types/node": "^22.19.3",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@typescript-eslint/eslint-plugin": "^8.59.2",
"@typescript-eslint/parser": "^8.59.2",
"@typescript-eslint/eslint-plugin": "^8.50.0",
"@typescript-eslint/parser": "^8.50.0",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4",
"eslint": "^9.39.2",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.1.1",
"prettier": "3.8.3",
"typescript": "^6.0.3",
"vite": "^8.0.10"
"eslint-plugin-react-hooks": "^7.0.1",
"prettier": "3.4.2",
"typescript": "^5.9.3",
"vite": "^8.0.1"
},
"packageManager": "[email protected]"
}
+685 -729
View File
File diff suppressed because it is too large. Load diff
+4 -9
View File
@@ -88,10 +88,6 @@ impl GuiUpdater {
}
pub async fn update(&self) {
if !cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) {
info!("GUI version is not supported on this architecture.");
return;
}
info!("Update GUI, version: {}", self.version);
#[cfg(debug_assertions)]
@@ -103,11 +99,10 @@ impl GuiUpdater {
format!("v{}", self.version)
};
let arch = if cfg!(target_arch = "x86_64") {
"x86_64"
} else {
"aarch64"
};
#[cfg(target_arch = "x86_64")]
let arch = "x86_64";
#[cfg(target_arch = "aarch64")]
let arch = "aarch64";
let file_url = format!(
"https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{}/gpgui_{}.bin.tar.xz",
+1 -1
View File
@@ -159,7 +159,7 @@ mod signals {
pub async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) {
use gpapi::service::event::WsEvent;
use tokio::signal::unix::{Signal, SignalKind, signal};
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())?;
+1 -1
View File
@@ -11,8 +11,8 @@ use anyhow::bail;
use axum::{
body::Bytes,
extract::{
State, WebSocketUpgrade,
ws::{self, CloseFrame, Message, Utf8Bytes, WebSocket},
State, WebSocketUpgrade,
},
http::StatusCode,
response::IntoResponse,
+1 -1
View File
@@ -1,8 +1,8 @@
use std::sync::Arc;
use axum::{
Router,
routing::{get, post},
Router,
};
use crate::{handlers, ws_server::WsServerContext};
+6 -59
View File
@@ -4,13 +4,12 @@ use gpapi::{
logger,
service::{
request::{ConnectRequest, UpdateLogLevelRequest, WsRequest},
vpn_state::{ConnectedInfo, VpnState},
vpn_state::VpnState,
},
session::{SessionInfo, SessionWarning},
};
use log::{info, warn};
use openconnect::Vpn;
use tokio::sync::{RwLock, mpsc, oneshot, watch};
use tokio::sync::{mpsc, oneshot, watch, RwLock};
use tokio_util::sync::CancellationToken;
pub(crate) struct VpnTaskContext {
@@ -39,7 +38,6 @@ impl VpnTaskContext {
let info = req.info().clone();
let vpn_handle = Arc::clone(&self.vpn_handle);
let args = req.args();
let allow_extend_session = args.allow_extend_session();
let vpn = match Vpn::builder(req.gateway().server(), args.cookie())
.script(args.vpnc_script())
.user_agent(args.user_agent())
@@ -56,9 +54,6 @@ impl VpnTaskContext {
.mtu(args.mtu())
.disable_ipv6(args.disable_ipv6())
.no_dtls(args.no_dtls())
.local_hostname(args.local_hostname())
.dpd_interval(args.force_dpd())
.no_xmlpost(args.no_xmlpost())
.build()
{
Ok(vpn) => vpn,
@@ -83,19 +78,9 @@ impl VpnTaskContext {
let vpn_state_tx_clone = vpn_state_tx.clone();
vpn_handle.blocking_read().as_ref().map(|vpn| {
vpn.connect(move |vpn_session_info| {
let session_info = SessionInfo::from_vpn_session_fields(
vpn_session_info.lifetime_secs,
vpn_session_info.user_expires,
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
prior_secs: warning.prior_secs,
message: warning.message,
}),
allow_extend_session,
);
info!("VPN session info: {}", session_info.log_summary());
let connected_info = Box::new(ConnectedInfo::new(info.clone(), Some(session_info)));
vpn_state_tx.send(VpnState::Connected(connected_info)).ok();
vpn.connect(move || {
let connect_info = Box::new(info.clone());
vpn_state_tx.send(VpnState::Connected(connect_info)).ok();
})
});
@@ -124,6 +109,7 @@ impl VpnTaskContext {
} else {
info!("VPN is not connected, skip disconnect");
self.vpn_state_tx.send(VpnState::Disconnected).ok();
false
}
}
@@ -195,42 +181,3 @@ async fn process_ws_req(req: WsRequest, ctx: Arc<VpnTaskContext>) {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_openconnect_session_metadata_to_service_session_info() {
let info = SessionInfo::from_vpn_session_fields(
Some(43_200),
None,
Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
true,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.expires_in_human.as_deref(), Some("12h"));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(info.allow_extend_session);
}
#[test]
fn direct_request_session_metadata_keeps_extension_disabled() {
let info = SessionInfo::from_vpn_session_fields(
Some(43_200),
None,
Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
false,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert!(!info.allow_extend_session);
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ use openconnect::{find_csd_wrapper, find_vpnc_script};
use serde::de::DeserializeOwned;
use tokio::{
net::TcpListener,
sync::{RwLock, mpsc, watch},
sync::{mpsc, watch, RwLock},
};
use tokio_util::sync::CancellationToken;
-11
View File
@@ -1,16 +1,5 @@
# Changelog
## 2.5.2 - 2026-05-06
- Experimental: GUI/CLI add session expiry warnings and support automatic session extension when allowed by the portal.
- GUI/CLI: expose additional OpenConnect connection options.
- Fix Linux packages to vendor the `vpnc-script`.
- Remove OpenConnect from the packaging dependency.
- Fix reconnect handling by preserving GlobalProtect cookie fields.
- Fix auth callback data parsing
- Improve NixOS packaging and user-level installation docs.
- Upgrade Rust, Tauri, Vite, frontend, and Rust dependencies.
## 2.5.1 - 2025-12-22
- Fix the `.deb` package installation issue (fix [#563](https://github.com/yuezk/GlobalProtect-openconnect/issues/563))
+1 -1
View File
@@ -1,7 +1,7 @@
use anyhow::bail;
use gpapi::{
gp_params::GpParams,
portal::{Prelogin, prelogin},
portal::{prelogin, Prelogin},
};
#[cfg(feature = "browser-auth")]
+1 -1
View File
@@ -2,7 +2,7 @@ use anyhow::bail;
use gpapi::{auth::SamlAuthData, error::AuthDataParseError};
use log::{error, info};
use regex::Regex;
use tokio::sync::{RwLock, mpsc};
use tokio::sync::{mpsc, RwLock};
use tokio_util::sync::CancellationToken;
#[derive(Debug)]
+1 -1
View File
@@ -1,7 +1,7 @@
use block2::RcBlock;
use log::warn;
use objc2::runtime::AnyObject;
use objc2_foundation::{NSError, NSString, NSURL, NSURLRequest};
use objc2_foundation::{NSError, NSString, NSURLRequest, NSURL};
use objc2_web_kit::WKWebView;
use tauri::webview::PlatformWebview;
+2 -2
View File
@@ -5,8 +5,8 @@ use gpapi::utils::redact::redact_uri;
use log::warn;
use tauri::webview::PlatformWebview;
use webkit2gtk::{
LoadEvent, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt, WebsiteDataManagerExt,
gio::Cancellable, glib::GString,
gio::Cancellable, glib::GString, LoadEvent, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt,
WebsiteDataManagerExt,
};
use super::{
+1 -1
View File
@@ -4,8 +4,8 @@ use anyhow::bail;
use gpapi::{auth::SamlAuthData, gp_params::GpParams, utils::redact::redact_uri};
use log::{info, warn};
use tauri::{
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
webview::{PageLoadEvent, PageLoadPayload},
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
};
use tokio::{sync::oneshot, time};
+5 -17
View File
@@ -4,29 +4,17 @@ pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
pub const GP_CALLBACK_PORT_FILENAME: &str = "gpcallback.port";
// Release binaries - macOS (Apple Silicon Homebrew)
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
#[cfg(all(not(debug_assertions), target_os = "macos"))]
pub const GP_CLIENT_BINARY: &str = "/opt/homebrew/bin/gpclient";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
#[cfg(all(not(debug_assertions), target_os = "macos"))]
pub const GP_SERVICE_BINARY: &str = "/opt/homebrew/bin/gpservice";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
#[cfg(all(not(debug_assertions), target_os = "macos"))]
pub const GP_GUI_BINARY: &str = "/opt/homebrew/bin/gpgui";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
#[cfg(all(not(debug_assertions), target_os = "macos"))]
pub const GP_GUI_HELPER_BINARY: &str = "/opt/homebrew/bin/gpgui-helper";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
#[cfg(all(not(debug_assertions), target_os = "macos"))]
pub const GP_AUTH_BINARY: &str = "/opt/homebrew/bin/gpauth";
// Release binaries - macOS (Intel Homebrew)
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_CLIENT_BINARY: &str = "/usr/local/bin/gpclient";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_SERVICE_BINARY: &str = "/usr/local/bin/gpservice";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_GUI_BINARY: &str = "/usr/local/bin/gpgui";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_GUI_HELPER_BINARY: &str = "/usr/local/bin/gpgui-helper";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_AUTH_BINARY: &str = "/usr/local/bin/gpauth";
// Release binaries - Linux
#[cfg(all(not(debug_assertions), not(target_os = "macos")))]
pub const GP_CLIENT_BINARY: &str = "/usr/bin/gpclient";
-2
View File
@@ -34,8 +34,6 @@ md5.workspace = true
sha256.workspace = true
machine-uid.workspace = true
uuid = { workspace = true, features = ["v5"] }
chrono.workspace = true
humantime.workspace = true
# Optional dependencies for features
tauri = { workspace = true, optional = true }
+1 -1
View File
@@ -1,4 +1,4 @@
use clap::{ValueEnum, builder::PossibleValue};
use clap::{builder::PossibleValue, ValueEnum};
use crate::gp_params::ClientOs;
+21 -192
View File
@@ -1,9 +1,9 @@
use std::{borrow::Cow, collections::HashMap};
use std::borrow::Cow;
use anyhow::bail;
use log::{debug, info, warn};
use reqwest::Client;
use urlencoding::{decode, encode};
use urlencoding::encode;
use xmltree::Element;
use crate::{
@@ -19,30 +19,17 @@ pub enum GatewayLogin {
}
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, false).await
}
pub async fn gateway_login_with_extend_lifetime(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, true).await
}
async fn gateway_login_with_options(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
extend_lifetime: bool,
) -> anyhow::Result<GatewayLogin> {
let url = normalize_server(gateway)?;
let gateway = remove_url_scheme(&url);
let login_url = format!("{}/ssl-vpn/login.esp", url);
let client = Client::try_from(gp_params)?;
let params = build_gateway_login_params(&gateway, cred, gp_params, extend_lifetime);
let mut params = cred.to_params();
let extra_params = gp_params.to_params();
params.extend(extra_params);
params.insert("server", &gateway);
info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
@@ -58,7 +45,7 @@ async fn gateway_login_with_options(
// It's possible to get an empty response, log the response headers for debugging
if res.trim().is_empty() {
info!("Empty gateway login response headers: {:?}", res);
debug!("Empty gateway login response headers: {:?}", res);
bail!("Got empty gateway login response");
}
@@ -80,33 +67,6 @@ async fn gateway_login_with_options(
Ok(GatewayLogin::Cookie(cookie))
}
fn build_gateway_login_params(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
extend_lifetime: bool,
) -> HashMap<String, String> {
let mut params = cred
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect::<HashMap<_, _>>();
params.extend(
gp_params
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string())),
);
params.insert("server".to_string(), gateway.to_string());
if extend_lifetime {
params.insert("extend-lifetime".to_string(), "true".to_string());
}
params
}
fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
let args = element
.descendants("argument")
@@ -114,19 +74,14 @@ fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<Stri
.map(|e| e.get_text().unwrap_or_default())
.collect::<Vec<_>>();
let mut params = vec![
read_required_arg(&args, 1, "authcookie")?,
read_optional_arg(&args, 2, "persistent-cookie")?,
read_optional_arg(&args, 3, "portal")?,
read_required_arg(&args, 4, "user")?,
read_optional_arg(&args, 7, "domain")?,
read_optional_arg(&args, 15, "preferred-ip")?,
read_optional_arg(&args, 18, "preferred-ipv6")?,
]
.into_iter()
.flatten()
.collect::<Vec<_>>();
params.push(("computer", computer.to_string()));
let params = [
read_args(&args, 1, "authcookie")?,
read_args(&args, 3, "portal")?,
read_args(&args, 4, "user")?,
read_args(&args, 7, "domain")?,
read_args(&args, 15, "preferred-ip")?,
("computer", computer),
];
let token = params
.iter()
@@ -137,43 +92,11 @@ fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<Stri
Ok(token)
}
fn read_required_arg(
args: &[Cow<'_, str>],
index: usize,
key: &'static str,
) -> anyhow::Result<Option<(&'static str, String)>> {
let Some(value) = read_arg_value(args, index)? else {
bail!("Failed to read {key} from args");
};
Ok(Some((key, value)))
}
fn read_optional_arg(
args: &[Cow<'_, str>],
index: usize,
key: &'static str,
) -> anyhow::Result<Option<(&'static str, String)>> {
Ok(read_arg_value(args, index)?.map(|value| (key, value)))
}
fn read_arg_value(args: &[Cow<'_, str>], index: usize) -> anyhow::Result<Option<String>> {
Ok(
args
.get(index)
.map(|s| normalize_arg_value(s.as_ref()))
.transpose()
.map_err(|err| anyhow::anyhow!("Failed to decode gateway login argument {index}: {err}"))?
.flatten(),
)
}
fn normalize_arg_value(value: &str) -> anyhow::Result<Option<String>> {
if value.is_empty() || value == "(null)" || value == "-1" {
return Ok(None);
}
Ok(Some(decode(value)?.into_owned()))
fn read_args<'a>(args: &'a [Cow<'_, str>], index: usize, key: &'a str) -> anyhow::Result<(&'a str, &'a str)> {
args
.get(index)
.ok_or_else(|| anyhow::anyhow!("Failed to read {key} from args"))
.map(|s| (key, s.as_ref()))
}
fn parse_mfa(res: &str) -> Option<(String, String)> {
@@ -204,98 +127,4 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
assert_eq!(message, "MFA message");
assert_eq!(input_str, "5ef64e83000119ed");
}
#[test]
fn normal_gateway_login_params_do_not_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, false);
assert!(!params.contains_key("extend-lifetime"));
}
#[test]
fn extension_gateway_login_params_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, true);
assert_eq!(params.get("extend-lifetime").map(String::as_str), Some("true"));
}
#[test]
fn gateway_token_keeps_upstream_cookie_fields() {
let res = r#"
<jnlp>
<application-desc>
<argument></argument>
<argument>AUTHCOOKIE</argument>
<argument>PERSISTENTCOOKIE</argument>
<argument>vpn.example.com</argument>
<argument>alice</argument>
<argument>LDAP-auth</argument>
<argument>vsys1</argument>
<argument>%28empty_domain%29</argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument>tunnel</argument>
<argument>-1</argument>
<argument>4100</argument>
<argument>10.0.0.10</argument>
<argument>unused-user-cookie</argument>
<argument>unused-prelogon-cookie</argument>
<argument>2001:db8::10</argument>
</application-desc>
</jnlp>
"#;
let root = Element::parse(res.as_bytes()).unwrap();
let token = build_gateway_token(&root, "metalklesk").unwrap();
assert_eq!(
token,
"authcookie=AUTHCOOKIE&persistent-cookie=PERSISTENTCOOKIE&portal=vpn.example.com&user=alice&domain=%28empty_domain%29&preferred-ip=10.0.0.10&preferred-ipv6=2001%3Adb8%3A%3A10&computer=metalklesk"
);
}
#[test]
fn gateway_token_omits_empty_optional_fields() {
let res = r#"
<jnlp>
<application-desc>
<argument></argument>
<argument>AUTHCOOKIE</argument>
<argument></argument>
<argument>vpn.example.com</argument>
<argument>alice</argument>
<argument>LDAP-auth</argument>
<argument>vsys1</argument>
<argument>-1</argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument>tunnel</argument>
<argument>-1</argument>
<argument>4100</argument>
<argument></argument>
<argument>unused-user-cookie</argument>
<argument>unused-prelogon-cookie</argument>
<argument>(null)</argument>
</application-desc>
</jnlp>
"#;
let root = Element::parse(res.as_bytes()).unwrap();
let token = build_gateway_token(&root, "metalklesk").unwrap();
assert_eq!(
token,
"authcookie=AUTHCOOKIE&portal=vpn.example.com&user=alice&computer=metalklesk"
);
}
}
+1 -3
View File
@@ -1,11 +1,9 @@
pub mod hip;
mod login;
mod parse_gateways;
pub mod session;
pub mod hip;
pub use login::*;
pub(crate) use parse_gateways::*;
pub use session::*;
use serde::{Deserialize, Serialize};
use specta::Type;
-246
View File
@@ -1,246 +0,0 @@
use std::{
collections::HashMap,
time::{SystemTime, UNIX_EPOCH},
};
use anyhow::bail;
use log::{info, warn};
use reqwest::Client;
use xmltree::Element;
use crate::{
credential::Credential,
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
gp_params::GpParams,
session::SessionRequestArgs,
utils::{normalize_server, parse_gp_response, xml::ElementExt},
};
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime";
#[derive(Clone)]
pub struct SessionExtensionAuth {
credential: Credential,
gp_params: GpParams,
}
impl SessionExtensionAuth {
pub fn new(credential: Credential, gp_params: GpParams) -> Self {
Self { credential, gp_params }
}
}
impl std::fmt::Debug for SessionExtensionAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionExtensionAuth")
.field("username", &self.credential.username())
.field("gp_params", &"<redacted>")
.finish()
}
}
#[derive(Debug, Clone)]
pub struct SessionContext {
server: String,
portal: String,
session_args: SessionRequestArgs,
extension_auth: Option<SessionExtensionAuth>,
}
impl SessionContext {
pub fn new(server: String, portal: String, session_args: SessionRequestArgs) -> Self {
Self {
server,
portal,
session_args,
extension_auth: None,
}
}
pub fn with_extension_auth(mut self, extension_auth: SessionExtensionAuth) -> Self {
self.extension_auth = Some(extension_auth);
self
}
pub fn server(&self) -> &str {
&self.server
}
pub fn portal(&self) -> &str {
&self.portal
}
pub fn session_args(&self) -> &SessionRequestArgs {
&self.session_args
}
fn extension_auth(&self) -> Option<&SessionExtensionAuth> {
self.extension_auth.as_ref()
}
}
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
extend_session_lifetime(ctx).await?;
let base_url = normalize_server(ctx.server())?;
let client = build_session_client(ctx.session_args())?;
let form = build_extend_session_form(ctx)?;
let url = format!("{base_url}/ssl-vpn/agentmessage.esp");
info!("Sending extend-session request");
let response = client.post(&url).form(&form).send().await?;
let response = parse_gp_response(response).await?;
let root = Element::parse(response.as_bytes())?;
let status = parse_extend_session_status(&root, &response)?;
info!("Extend-session gateway response status: {}", status);
match status.as_str() {
"success" => Ok(()),
status => bail!("Extend session rejected: {status}"),
}
}
async fn extend_session_lifetime(ctx: &SessionContext) -> anyhow::Result<()> {
let auth = ctx
.extension_auth()
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
let login = gateway_login_with_extend_lifetime(ctx.server(), &auth.credential, &auth.gp_params).await?;
validate_extension_login(login)
}
fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
match login {
GatewayLogin::Cookie(_) => Ok(()),
GatewayLogin::Mfa(_, _) => bail!("Session extension requires an interactive gateway challenge"),
}
}
fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
let mut builder = GpParams::builder();
builder.user_agent(args.user_agent().as_deref().unwrap_or_default());
builder.client_os(args.os().unwrap_or_default());
builder.os_version(args.os_version());
builder.client_version(args.client_version());
builder.certificate(args.certificate());
builder.sslkey(args.sslkey());
builder.key_password(args.key_password());
Client::try_from(&builder.build())
}
fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
Ok(serde_urlencoded::from_str(args.cookie())?)
}
fn build_extend_session_form(ctx: &SessionContext) -> anyhow::Result<HashMap<String, String>> {
let mut form = parse_cookie_form(ctx.session_args())?;
form.insert("portal".to_string(), ctx.portal().to_string());
form.insert("timestamp".to_string(), unix_timestamp().to_string());
form.insert("message".to_string(), EXTEND_SESSION_MESSAGE.to_string());
form.insert("comment".to_string(), EXTEND_SESSION_COMMENT.to_string());
Ok(form)
}
fn parse_extend_session_status(root: &Element, response: &str) -> anyhow::Result<String> {
match root.attr("status") {
Some(status) => Ok(status.to_string()),
None => {
warn!("Malformed extend-session response body: {}", response.trim());
bail!("Malformed extend session response")
}
}
}
fn unix_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
#[cfg(test)]
mod tests {
use crate::{gp_params::ClientOs, session::SessionRequestArgs};
use super::*;
fn build_session_args() -> SessionRequestArgs {
SessionRequestArgs::new("authcookie=AUTH&portal=vpn.example.com&user=alice&preferred-ip=10.0.0.10".to_string())
.with_os(Some(ClientOs::Mac))
.with_os_version(Some("macOS 15.0".to_string()))
.with_client_version(Some("6.3.1-12".to_string()))
.with_disable_ipv6(true)
}
#[test]
fn active_session_context_preserves_connect_args_for_extension() {
let session_args = build_session_args();
let ctx = SessionContext::new(
"vpn.example.com".to_string(),
"portal.example.com".to_string(),
session_args,
);
let form = parse_cookie_form(ctx.session_args()).unwrap();
assert_eq!(form.get("authcookie").map(String::as_str), Some("AUTH"));
assert_eq!(form.get("portal").map(String::as_str), Some("vpn.example.com"));
assert_eq!(form.get("user").map(String::as_str), Some("alice"));
assert_eq!(form.get("preferred-ip").map(String::as_str), Some("10.0.0.10"));
}
#[test]
fn builds_extend_session_form() {
let session_args = build_session_args();
let ctx = SessionContext::new(
"vpn.example.com".to_string(),
"portal.example.com".to_string(),
session_args,
);
let form = build_extend_session_form(&ctx).unwrap();
assert_eq!(form.get("authcookie").map(String::as_str), Some("AUTH"));
assert_eq!(form.get("portal").map(String::as_str), Some("portal.example.com"));
assert_eq!(form.get("message").map(String::as_str), Some(EXTEND_SESSION_MESSAGE));
assert_eq!(form.get("comment").map(String::as_str), Some(EXTEND_SESSION_COMMENT));
assert!(form.contains_key("timestamp"));
}
#[test]
fn parses_extend_session_status_attribute() {
let root = Element::parse(r#"<response status="success"></response>"#.as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root, r#"<response status="success"></response>"#).unwrap(),
"success"
);
}
#[test]
fn rejects_extend_session_response_without_status() {
let root = Element::parse("<response><result>ok</result></response>".as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root, "<response><result>ok</result></response>")
.unwrap_err()
.to_string(),
"Malformed extend session response"
);
}
#[test]
fn rejects_extension_login_mfa_challenge() {
assert_eq!(
validate_extension_login(GatewayLogin::Mfa("MFA required".to_string(), "input".to_string()))
.unwrap_err()
.to_string(),
"Session extension requires an interactive gateway challenge"
);
}
}
-1
View File
@@ -6,7 +6,6 @@ pub mod gp_params;
pub mod portal;
pub mod process;
pub mod service;
pub mod session;
pub mod utils;
#[cfg(feature = "logger")]
+1 -1
View File
@@ -2,7 +2,7 @@ use std::sync::OnceLock;
use anyhow::bail;
use env_logger::Logger;
use log::{Level, warn};
use log::{warn, Level};
use log_reload::{ReloadHandle, ReloadLog};
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<Logger>>> = OnceLock::new();
-55
View File
@@ -33,10 +33,6 @@ pub struct PortalConfig {
* The version returned by the portal config, if any
*/
version: Option<String>,
/**
* Whether the portal policy allows extending the gateway session.
*/
allow_extend_session: Option<bool>,
}
impl PortalConfig {
@@ -64,10 +60,6 @@ impl PortalConfig {
self.version.as_deref()
}
pub fn allow_extend_session(&self) -> Option<bool> {
self.allow_extend_session
}
/// In-place sort the gateways by region
pub fn sort_gateways(&mut self, region: &str) {
let preferred_gateway = self.find_preferred_gateway(region);
@@ -176,7 +168,6 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
let version = root.descendant_text("version").map(|s| s.to_string());
info!("Detected portal version: {:?}", version);
let allow_extend_session = parse_allow_extend_session(&root);
Ok(PortalConfig {
portal: server.to_string(),
@@ -186,18 +177,9 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
config_digest: config_digest.map(|s| s.to_string()),
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
version,
allow_extend_session,
})
}
fn parse_allow_extend_session(root: &Element) -> Option<bool> {
match root.descendant_text("allow-extend-session")?.trim() {
"yes" => Some(true),
"no" => Some(false),
_ => None,
}
}
// Perform DNS lookup and compare the result with the expected hostname
fn internal_host_detect(element: &Element) -> bool {
let ip_info = [
@@ -231,40 +213,3 @@ fn internal_host_detect(element: &Element) -> bool {
false
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_xml(xml: &str) -> Element {
Element::parse(xml.as_bytes()).unwrap()
}
#[test]
fn parses_allow_extend_session_yes() {
let root = parse_xml("<response><allow-extend-session>yes</allow-extend-session></response>");
assert_eq!(parse_allow_extend_session(&root), Some(true));
}
#[test]
fn parses_allow_extend_session_no() {
let root = parse_xml("<response><allow-extend-session>no</allow-extend-session></response>");
assert_eq!(parse_allow_extend_session(&root), Some(false));
}
#[test]
fn leaves_absent_allow_extend_session_unknown() {
let root = parse_xml("<response></response>");
assert_eq!(parse_allow_extend_session(&root), None);
}
#[test]
fn ignores_non_official_allow_extend_session_values() {
let root = parse_xml("<response><allow-extend-session>true</allow-extend-session></response>");
assert_eq!(parse_allow_extend_session(&root), None);
}
}
+6 -10
View File
@@ -177,16 +177,12 @@ impl<'a> SamlAuthLauncher<'a> {
}
let mut non_root_cmd = auth_cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn();
let child = match child {
Ok(child) => child,
Err(err) => {
bail!("Failed to spawn {}: {}", program, err);
}
};
let output = child.wait_with_output().await?;
let output = non_root_cmd
.kill_on_drop(true)
.stdout(Stdio::piped())
.spawn()?
.wait_with_output()
.await?;
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
bail!("Failed to parse auth data")
@@ -50,12 +50,7 @@ impl<'a> GuiHelperLauncher<'a> {
info!("Launching gpgui-helper");
let mut non_root_cmd = cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
let mut child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
};
let mut child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn()?;
let Some(mut stdin) = child.stdin.take() else {
bail!("Failed to open stdin");
};
+1 -6
View File
@@ -69,12 +69,7 @@ impl<'a> GuiLauncher<'a> {
info!("Launching gpgui");
let mut non_root_cmd = cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
let mut child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
};
let mut child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn()?;
let Some(mut stdin) = child.stdin.take() else {
bail!("Failed to open stdin");
};
+6 -8
View File
@@ -72,14 +72,12 @@ impl<'a> HipLauncher<'a> {
cmd.env("APP_VERSION", client_version);
}
let child = cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn();
let child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", self.program, err),
};
let output = child.wait_with_output().await?;
let output = cmd
.kill_on_drop(true)
.stdout(Stdio::piped())
.spawn()?
.wait_with_output()
.await?;
if let Some(exit_status) = output.status.code() {
if exit_status != 0 {
+2 -68
View File
@@ -27,7 +27,7 @@ impl LaunchGuiRequest {
}
}
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
#[derive(Debug, Deserialize, Serialize, Type)]
pub struct ConnectArgs {
cookie: String,
vpnc_script: Option<String>,
@@ -49,11 +49,6 @@ pub struct ConnectArgs {
mtu: u32,
disable_ipv6: bool,
no_dtls: bool,
local_hostname: Option<String>,
force_dpd: u32,
no_xmlpost: bool,
#[serde(rename = "allowExtendSession")]
allow_extend_session: bool,
}
impl ConnectArgs {
@@ -75,10 +70,6 @@ impl ConnectArgs {
mtu: 0,
disable_ipv6: false,
no_dtls: false,
local_hostname: None,
force_dpd: 0,
no_xmlpost: false,
allow_extend_session: false,
}
}
@@ -98,10 +89,6 @@ impl ConnectArgs {
self.os.as_ref().map(|os| os.to_openconnect_os().to_string())
}
pub fn os(&self) -> Option<ClientOs> {
self.os.clone()
}
pub fn os_version(&self) -> Option<String> {
self.os_version.clone()
}
@@ -149,25 +136,9 @@ impl ConnectArgs {
pub fn no_dtls(&self) -> bool {
self.no_dtls
}
pub fn local_hostname(&self) -> Option<String> {
self.local_hostname.clone()
}
pub fn force_dpd(&self) -> u32 {
self.force_dpd
}
pub fn no_xmlpost(&self) -> bool {
self.no_xmlpost
}
pub fn allow_extend_session(&self) -> bool {
self.allow_extend_session
}
}
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
#[derive(Debug, Deserialize, Serialize, Type)]
pub struct ConnectRequest {
info: ConnectInfo,
args: ConnectArgs,
@@ -256,26 +227,6 @@ impl ConnectRequest {
self
}
pub fn with_local_hostname<T: Into<Option<String>>>(mut self, local_hostname: T) -> Self {
self.args.local_hostname = local_hostname.into();
self
}
pub fn with_force_dpd(mut self, force_dpd: u32) -> Self {
self.args.force_dpd = force_dpd;
self
}
pub fn with_no_xmlpost(mut self, no_xmlpost: bool) -> Self {
self.args.no_xmlpost = no_xmlpost;
self
}
pub fn with_allow_extend_session(mut self, allow_extend_session: bool) -> Self {
self.args.allow_extend_session = allow_extend_session;
self
}
pub fn gateway(&self) -> &Gateway {
self.info.gateway()
}
@@ -308,20 +259,3 @@ pub struct UpdateGuiRequest {
pub path: String,
pub checksum: String,
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn connect_request_serializes_allow_extend_session() {
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
let req = ConnectRequest::new(info, "authcookie=AUTH".to_string()).with_allow_extend_session(true);
let value = serde_json::to_value(req).unwrap();
assert_eq!(value["args"]["allowExtendSession"], json!(true));
}
}
+2 -51
View File
@@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::{gateway::Gateway, session::SessionInfo};
use crate::gateway::Gateway;
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectInfo {
@@ -10,30 +10,6 @@ pub struct ConnectInfo {
gateways: Vec<Gateway>,
}
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ConnectedInfo {
info: Box<ConnectInfo>,
session_info: Option<SessionInfo>,
}
impl ConnectedInfo {
pub fn new(info: ConnectInfo, session_info: Option<SessionInfo>) -> Self {
Self {
info: Box::new(info),
session_info,
}
}
pub fn info(&self) -> &ConnectInfo {
&self.info
}
pub fn session_info(&self) -> Option<&SessionInfo> {
self.session_info.as_ref()
}
}
impl ConnectInfo {
pub fn new(portal: String, gateway: Gateway, gateways: Vec<Gateway>) -> Self {
Self {
@@ -53,31 +29,6 @@ impl ConnectInfo {
pub enum VpnState {
Disconnected,
Connecting(Box<ConnectInfo>),
Connected(Box<ConnectedInfo>),
Connected(Box<ConnectInfo>),
Disconnecting,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn connected_state_serializes_session_info() {
let gateway = Gateway::new("vpn".to_string(), "vpn.example.com".to_string());
let connect_info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
let session_info = SessionInfo {
lifetime_secs: Some(43_200),
allow_extend_session: true,
..Default::default()
};
let value = serde_json::to_value(VpnState::Connected(Box::new(ConnectedInfo::new(
connect_info,
Some(session_info),
))))
.unwrap();
assert_eq!(value["connected"]["sessionInfo"]["lifetimeSecs"], 43_200);
assert_eq!(value["connected"]["sessionInfo"]["allowExtendSession"], true);
}
}
-302
View File
@@ -1,302 +0,0 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use chrono::{Local, TimeZone};
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::gp_params::ClientOs;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct SessionWarning {
pub prior_secs: u32,
pub message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct SessionRequestArgs {
cookie: String,
user_agent: Option<String>,
os: Option<ClientOs>,
os_version: Option<String>,
client_version: Option<String>,
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
disable_ipv6: bool,
}
impl SessionRequestArgs {
pub fn new(cookie: String) -> Self {
Self {
cookie,
user_agent: None,
os: None,
os_version: None,
client_version: None,
certificate: None,
sslkey: None,
key_password: None,
disable_ipv6: false,
}
}
pub fn with_user_agent<T: Into<Option<String>>>(mut self, user_agent: T) -> Self {
self.user_agent = user_agent.into();
self
}
pub fn with_os<T: Into<Option<ClientOs>>>(mut self, os: T) -> Self {
self.os = os.into();
self
}
pub fn with_os_version<T: Into<Option<String>>>(mut self, os_version: T) -> Self {
self.os_version = os_version.into();
self
}
pub fn with_client_version<T: Into<Option<String>>>(mut self, client_version: T) -> Self {
self.client_version = client_version.into();
self
}
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
self.certificate = certificate.into();
self
}
pub fn with_sslkey<T: Into<Option<String>>>(mut self, sslkey: T) -> Self {
self.sslkey = sslkey.into();
self
}
pub fn with_key_password<T: Into<Option<String>>>(mut self, key_password: T) -> Self {
self.key_password = key_password.into();
self
}
pub fn with_disable_ipv6(mut self, disable_ipv6: bool) -> Self {
self.disable_ipv6 = disable_ipv6;
self
}
pub fn cookie(&self) -> &str {
&self.cookie
}
pub fn user_agent(&self) -> Option<String> {
self.user_agent.clone()
}
pub fn os(&self) -> Option<ClientOs> {
self.os.clone()
}
pub fn os_version(&self) -> Option<String> {
self.os_version.clone()
}
pub fn client_version(&self) -> Option<String> {
self.client_version.clone()
}
pub fn certificate(&self) -> Option<String> {
self.certificate.clone()
}
pub fn sslkey(&self) -> Option<String> {
self.sslkey.clone()
}
pub fn key_password(&self) -> Option<String> {
self.key_password.clone()
}
pub fn disable_ipv6(&self) -> bool {
self.disable_ipv6
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SessionInfo {
pub lifetime_secs: Option<u32>,
pub user_expires: Option<u32>,
pub expires_in_human: Option<String>,
pub lifetime_warning: Option<SessionWarning>,
pub inactivity_warning: Option<SessionWarning>,
pub admin_logout_message: Option<String>,
pub allow_extend_session: bool,
}
impl SessionInfo {
pub fn with_computed_human_times(mut self) -> Self {
self.expires_in_human = build_human_readable_expiry(self.user_expires, self.lifetime_secs);
self
}
pub fn from_vpn_session_fields(
lifetime_secs: Option<u32>,
user_expires: Option<u32>,
lifetime_warning: Option<SessionWarning>,
allow_extend_session: bool,
) -> Self {
Self {
lifetime_secs,
user_expires,
expires_in_human: None,
lifetime_warning,
inactivity_warning: None,
admin_logout_message: None,
allow_extend_session,
}
.with_computed_human_times()
}
pub fn rescheduled_after_extension(&self) -> Option<Self> {
let lifetime_secs = self.lifetime_secs?;
let mut session_info = self.clone();
session_info.user_expires = Some(unix_timestamp().saturating_add(lifetime_secs));
Some(session_info.with_computed_human_times())
}
pub fn log_summary(&self) -> String {
let lifetime_secs = self
.lifetime_secs
.map(format_secs_with_duration)
.unwrap_or_else(|| "none".to_string());
let user_expires = self
.user_expires
.map(format_epoch_with_local_time)
.unwrap_or_else(|| "none".to_string());
let lifetime_warning_prior = self
.lifetime_warning
.as_ref()
.map(|warning| format_secs_with_duration(warning.prior_secs))
.unwrap_or_else(|| "none".to_string());
format!(
"lifetime_secs={lifetime_secs}, user_expires={user_expires}, lifetime_warning_prior={lifetime_warning_prior}, allow_extend_session={}",
self.allow_extend_session
)
}
}
pub fn format_duration_secs(total_secs: u32) -> String {
humantime::format_duration(Duration::from_secs(total_secs as u64)).to_string()
}
fn format_secs_with_duration(secs: u32) -> String {
format!("{secs} ({})", format_duration_secs(secs))
}
fn format_epoch_with_local_time(epoch: u32) -> String {
let local_time = Local
.timestamp_opt(epoch as i64, 0)
.single()
.map(|time| time.format("%Y-%m-%d %H:%M:%S").to_string())
.unwrap_or_else(|| "invalid time".to_string());
let now = unix_timestamp();
let relative = if epoch >= now {
format!("in {}", format_duration_secs(epoch.saturating_sub(now)))
} else {
format!("{} ago", format_duration_secs(now.saturating_sub(epoch)))
};
format!("{epoch} ({local_time}, {relative})")
}
fn build_human_readable_expiry(user_expires: Option<u32>, lifetime_secs: Option<u32>) -> Option<String> {
if let Some(user_expires) = user_expires {
let now = unix_timestamp();
return Some(format_duration_secs(user_expires.saturating_sub(now)));
}
lifetime_secs.map(format_duration_secs)
}
fn unix_timestamp() -> u32 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as u32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_duration_secs() {
assert_eq!(format_duration_secs(43_200), "12h");
assert_eq!(format_duration_secs(1_830), "30m 30s");
}
#[test]
fn logs_session_info_with_human_readable_times() {
let info = SessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(unix_timestamp().saturating_add(43_200)),
lifetime_warning: Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
allow_extend_session: true,
..Default::default()
};
let summary = info.log_summary();
assert!(summary.contains("lifetime_secs=43200 (12h)"));
assert!(summary.contains("user_expires="));
assert!(summary.contains(", in "));
assert!(summary.contains("lifetime_warning_prior=1800 (30m)"));
assert!(summary.contains("allow_extend_session=true"));
}
#[test]
fn computes_expires_in_human_from_lifetime_or_epoch() {
let from_lifetime = SessionInfo {
lifetime_secs: Some(43_200),
..Default::default()
}
.with_computed_human_times();
assert_eq!(from_lifetime.expires_in_human.as_deref(), Some("12h"));
let from_epoch = SessionInfo {
user_expires: Some(unix_timestamp().saturating_add(1_830)),
..Default::default()
}
.with_computed_human_times();
assert!(
from_epoch
.expires_in_human
.as_deref()
.is_some_and(|value| value.starts_with("30m"))
);
}
#[test]
fn reschedules_after_extension_from_lifetime() {
let now = unix_timestamp();
let info = SessionInfo {
lifetime_secs: Some(7_200),
user_expires: Some(now.saturating_add(1_830)),
..Default::default()
};
let next = info.rescheduled_after_extension().unwrap();
assert!(
next
.user_expires
.is_some_and(|expires| expires >= now.saturating_add(7_200))
);
assert!(next.expires_in_human.is_some());
}
#[test]
fn reschedule_after_extension_requires_lifetime() {
assert!(SessionInfo::default().rescheduled_after_extension().is_none());
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
use base64::{Engine, engine::general_purpose};
use base64::{engine::general_purpose, Engine};
pub fn encode(data: &[u8]) -> String {
let engine = general_purpose::STANDARD;
+2 -2
View File
@@ -1,8 +1,8 @@
use chacha20poly1305::{
AeadCore, ChaCha20Poly1305, Key, KeyInit,
aead::{Aead, OsRng},
AeadCore, ChaCha20Poly1305, Key, KeyInit,
};
use serde::{Serialize, de::DeserializeOwned};
use serde::{de::DeserializeOwned, Serialize};
pub fn generate_key() -> Key {
ChaCha20Poly1305::generate_key(&mut OsRng)
-51
View File
@@ -1,6 +1,5 @@
use std::collections::HashMap;
use std::env;
use std::ffi::OsStr;
use std::io::Write;
use std::path::Path;
@@ -42,15 +41,6 @@ pub fn patch_gui_runtime_env(hidpi: bool) {
// This is to avoid blank screen on some systems
unsafe { std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1") };
if is_wayland_session(
env::var_os("WAYLAND_DISPLAY").as_deref(),
env::var("XDG_SESSION_TYPE").ok().as_deref(),
) {
info!("Wayland session detected, enabling Linux WebKit rendering fallbacks");
set_env_if_missing("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
set_env_if_missing("LIBGL_ALWAYS_SOFTWARE", "1");
}
if hidpi {
info!("Setting GDK_SCALE=2 and GDK_DPI_SCALE=0.5");
unsafe {
@@ -59,44 +49,3 @@ pub fn patch_gui_runtime_env(hidpi: bool) {
};
}
}
fn is_wayland_session(wayland_display: Option<&OsStr>, xdg_session_type: Option<&str>) -> bool {
if wayland_display.is_some() {
return true;
}
matches!(xdg_session_type, Some("wayland"))
}
fn set_env_if_missing(key: &str, value: &str) {
if env::var_os(key).is_some() {
return;
}
info!("Setting {}={}", key, value);
unsafe { env::set_var(key, value) };
}
#[cfg(test)]
mod tests {
use std::ffi::OsStr;
use super::is_wayland_session;
#[test]
fn detects_wayland_from_wayland_display() {
assert!(is_wayland_session(Some(OsStr::new("wayland-1")), None));
}
#[test]
fn detects_wayland_from_session_type() {
assert!(is_wayland_session(None, Some("wayland")));
}
#[test]
fn ignores_non_wayland_sessions() {
assert!(!is_wayland_session(None, None));
assert!(!is_wayland_session(None, Some("x11")));
assert!(!is_wayland_session(None, Some("tty")));
}
}
+3 -3
View File
@@ -1,4 +1,4 @@
pub mod xml;
pub(crate) mod xml;
pub mod base64;
pub mod checksum;
@@ -48,7 +48,7 @@ pub fn remove_url_scheme(s: &str) -> String {
#[derive(Error, Debug)]
#[error("GP response error: reason={reason}, status={status}, body={body}")]
pub struct GpError {
pub(crate) struct GpError {
pub status: StatusCode,
pub reason: String,
body: String,
@@ -60,7 +60,7 @@ impl GpError {
}
}
pub async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError> {
pub(crate) async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError> {
let status = res.status();
if status.is_client_error() || status.is_server_error() {
+1 -1
View File
@@ -3,7 +3,7 @@ use std::path::Path;
use log::{info, warn};
use regex::Regex;
use tempfile::NamedTempFile;
use version_compare::{Cmp, compare_to};
use version_compare::{compare_to, Cmp};
pub fn openssl_conf() -> String {
let option = get_openssl_option();
+1 -1
View File
@@ -2,7 +2,7 @@ use std::sync::RwLock;
use redact_engine::{Pattern, Redaction as RedactEngine};
use regex::Regex;
use url::{Url, form_urlencoded};
use url::{form_urlencoded, Url};
pub struct Redaction {
redact_engine: RwLock<Option<RedactEngine>>,
+1 -1
View File
@@ -23,9 +23,9 @@ mod unix {
use anyhow::bail;
use gtk::{
EventBox,
glib::Cast,
traits::{EventBoxExt, GtkWindowExt, WidgetExt},
EventBox,
};
use log::info;
use tauri::WebviewWindow;
+1 -1
View File
@@ -1,6 +1,6 @@
use xmltree::Element;
pub trait ElementExt {
pub(crate) trait ElementExt {
/// Recursively find all descendants with the given name
fn descendants(&self, name: &str) -> Vec<&Element>;
+3 -11
View File
@@ -121,8 +121,7 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
// We explicitly enable static and disable shared to ensure we get a .a file.
// .reconf("-ivf") is CRITICAL for git submodules because 'configure'
// usually doesn't exist yet and needs to be generated.
let mut config = autotools::Config::new(&build_src);
config
let dst = autotools::Config::new(&build_src)
.reconf("-ivf")
.enable_static()
.disable_shared()
@@ -135,15 +134,8 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
.without("libpskc", None)
.without("gssapi", None)
.with("gnutls-tss2", Some("no"))
.with("vpnc-script", Some("/etc/vpnc/vpnc-script")); // Specify vpnc-script, otherwise it will fail on macOS
#[cfg(target_os = "macos")]
{
config.ldflag("-liconv");
config.env("LIBS", "-liconv");
}
let dst = config.build();
.with("vpnc-script", Some("/etc/vpnc/vpnc-script")) // Specify vpnc-script, otherwise it will fail on macOS
.build();
let lib_dir = dst.join("lib");
let include_dir = dst.join("include");
@@ -1,124 +0,0 @@
diff --git a/gpst.c b/gpst.c
index 244aaf04..78c16d1c 100644
--- a/gpst.c
+++ b/gpst.c
@@ -438,8 +438,19 @@ static int gpst_parse_config_xml(struct openconnect_info *vpninfo, xmlNode *xml_
new_ip_info.netmask = add_option_steal(&new_opts, "netmask", &s);
} else if (!xmlnode_get_val(xml_node, "mtu", &s))
new_ip_info.mtu = atoi(s);
- else if (!xmlnode_get_val(xml_node, "lifetime", &s))
+ else if (!xmlnode_get_val(xml_node, "lifetime", &s)) {
+ vpninfo->gp_session_lifetime = atoi(s);
vpninfo->auth_expiration = time(NULL) + atol(s);
+ } else if (!xmlnode_get_val(xml_node, "user-expires", &s) ||
+ !xmlnode_get_val(xml_node, "user_expires", &s)) {
+ vpninfo->gp_user_expires = atol(s);
+ } else if (!xmlnode_get_val(xml_node, "lifetime-notify-prior", &s)) {
+ vpninfo->gp_lifetime_notify_prior = atoi(s);
+ } else if (!xmlnode_get_val(xml_node, "lifetime-notify-message", &s)) {
+ free(vpninfo->gp_lifetime_notify_message);
+ vpninfo->gp_lifetime_notify_message = s;
+ s = NULL;
+ }
else if (!xmlnode_get_val(xml_node, "quarantine", &s)) {
if (strcmp(s, "no"))
vpn_progress(vpninfo, PRG_DEBUG,
diff --git a/libopenconnect.map.in b/libopenconnect.map.in
index f036c071..44110486 100644
--- a/libopenconnect.map.in
+++ b/libopenconnect.map.in
@@ -113,6 +113,10 @@ OPENCONNECT_5_7 {
openconnect_set_cookie;
openconnect_set_allow_insecure_crypto;
openconnect_get_auth_expiration;
+ openconnect_get_gp_session_lifetime;
+ openconnect_get_gp_user_expires;
+ openconnect_get_gp_lifetime_notify_prior;
+ openconnect_get_gp_lifetime_notify_message;
openconnect_disable_dtls;
openconnect_get_connect_url;
openconnect_set_webview_callback;
diff --git a/libopenconnect5.symbols b/libopenconnect5.symbols
index 7cb04d05..2c7af781 100644
--- a/libopenconnect5.symbols
+++ b/libopenconnect5.symbols
@@ -94,6 +94,10 @@ libopenconnect.so.5 libopenconnect5 #MINVER#
openconnect_set_cookie@OPENCONNECT_5_7 8.20
openconnect_set_allow_insecure_crypto@OPENCONNECT_5_7 8.20
openconnect_get_auth_expiration@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_session_lifetime@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_user_expires@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_lifetime_notify_prior@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_lifetime_notify_message@OPENCONNECT_5_7 8.20
openconnect_disable_dtls@OPENCONNECT_5_7 8.20
openconnect_get_connect_url@OPENCONNECT_5_7 8.20
openconnect_set_webview_callback@OPENCONNECT_5_7 8.20
diff --git a/library.c b/library.c
index b5e74e9b..03f47004 100644
--- a/library.c
+++ b/library.c
@@ -838,6 +838,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
free(vpninfo->dtls_cipher);
free(vpninfo->peer_cert_hash);
free(vpninfo->ciphersuite_config);
+ free(vpninfo->gp_lifetime_notify_message);
#if defined(OPENCONNECT_OPENSSL)
free(vpninfo->cstp_cipher);
#if defined(HAVE_BIO_METH_FREE)
@@ -1137,6 +1138,26 @@ time_t openconnect_get_auth_expiration(struct openconnect_info *vpninfo)
return vpninfo->auth_expiration;
}
+int openconnect_get_gp_session_lifetime(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_session_lifetime;
+}
+
+time_t openconnect_get_gp_user_expires(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_user_expires;
+}
+
+int openconnect_get_gp_lifetime_notify_prior(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_lifetime_notify_prior;
+}
+
+const char *openconnect_get_gp_lifetime_notify_message(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_lifetime_notify_message;
+}
+
int openconnect_get_ip_info(struct openconnect_info *vpninfo,
const struct oc_ip_info **info,
const struct oc_vpn_option **cstp_options,
diff --git a/openconnect-internal.h b/openconnect-internal.h
index abf45bbd..dd5507ca 100644
--- a/openconnect-internal.h
+++ b/openconnect-internal.h
@@ -647,6 +647,10 @@ struct openconnect_info {
int dtls_attempt_period;
int udp_probes_sent;
time_t auth_expiration;
+ int gp_session_lifetime;
+ time_t gp_user_expires;
+ int gp_lifetime_notify_prior;
+ char *gp_lifetime_notify_message;
time_t new_dtls_started;
#if defined(OPENCONNECT_OPENSSL)
SSL_CTX *dtls_ctx;
diff --git a/openconnect.h b/openconnect.h
index 136f181a..febf15cc 100644
--- a/openconnect.h
+++ b/openconnect.h
@@ -655,6 +655,10 @@ void openconnect_set_dpd(struct openconnect_info *, int min_seconds);
void openconnect_set_trojan_interval(struct openconnect_info *, int seconds);
int openconnect_get_idle_timeout(struct openconnect_info *);
time_t openconnect_get_auth_expiration(struct openconnect_info *);
+int openconnect_get_gp_session_lifetime(struct openconnect_info *);
+time_t openconnect_get_gp_user_expires(struct openconnect_info *);
+int openconnect_get_gp_lifetime_notify_prior(struct openconnect_info *);
+const char *openconnect_get_gp_lifetime_notify_message(struct openconnect_info *);
/* The returned structures are owned by the library and may be freed/replaced
due to rekey or reconnect. Assume that once the mainloop starts, the
@@ -1,15 +0,0 @@
diff --git a/gpst.c b/gpst.c
index 244aaf04..fb8d945d 100644
--- a/gpst.c
+++ b/gpst.c
@@ -669,6 +669,10 @@ static int gpst_get_config(struct openconnect_info *vpninfo)
result = do_https_request(vpninfo, "POST", "application/x-www-form-urlencoded", request_body, &xml_buf, NULL, HTTP_NO_FLAGS);
free(vpninfo->urlpath);
vpninfo->urlpath = orig_path;
+ if (result >= 0 && xml_buf)
+ vpn_progress(vpninfo, PRG_DEBUG,
+ "GlobalProtect getconfig.esp response:\n%s\n",
+ xml_buf);
/* parse getconfig result */
if (result >= 0)
+5 -19
View File
@@ -1,6 +1,6 @@
use crate::Vpn;
use log::{debug, info, trace, warn};
use std::ffi::{c_char, c_int, c_long, c_void};
use std::ffi::{c_char, c_int, c_void};
/// ConnectOptions struct for FFI, the field names and order must match the C definition.
#[repr(C)]
@@ -15,7 +15,7 @@ pub(crate) struct ConnectOptions {
pub os: *const c_char,
pub os_version: *const c_char,
pub client_version: *const c_char,
pub local_hostname: *const c_char,
pub split_dns: *const c_char,
pub script: *const c_char,
pub interface: *const c_char,
@@ -35,26 +35,12 @@ pub(crate) struct ConnectOptions {
pub no_dtls: u32,
pub dpd_interval: u32,
pub no_xmlpost: u32,
}
#[repr(C)]
#[derive(Debug)]
pub(crate) struct VpnSessionInfoRaw {
pub auth_expiration: c_long,
pub lifetime_secs: c_int,
pub user_expires: c_long,
pub lifetime_warning_prior: c_int,
pub lifetime_warning_message: *const c_char,
}
#[link(name = "vpn")]
unsafe extern "C" {
#[link_name = "vpn_connect"]
fn vpn_connect(
options: *const ConnectOptions,
callback: extern "C" fn(i32, *const VpnSessionInfoRaw, *mut c_void),
) -> c_int;
fn vpn_connect(options: *const ConnectOptions, callback: extern "C" fn(i32, *mut c_void)) -> c_int;
#[link_name = "vpn_disconnect"]
fn vpn_disconnect();
@@ -69,9 +55,9 @@ pub(crate) fn disconnect() {
}
#[unsafe(no_mangle)]
extern "C" fn on_vpn_connected(pipe_fd: i32, session_info: *const VpnSessionInfoRaw, vpn: *mut c_void) {
extern "C" fn on_vpn_connected(pipe_fd: i32, vpn: *mut c_void) {
let vpn = unsafe { &*(vpn as *const Vpn) };
vpn.on_connected(pipe_fd, crate::vpn::session_info_from_raw(session_info));
vpn.on_connected(pipe_fd);
}
// Logger used in the C code.
+18 -27
View File
@@ -12,6 +12,7 @@ void *g_user_data;
static int g_cmd_pipe_fd;
static const char *g_vpnc_script;
static const char *g_vpnc_interface;
static const char *g_split_dns;
static int g_script_tun;
static vpn_connected_callback on_vpn_connected;
@@ -40,9 +41,19 @@ static void print_progress(__attribute__((unused)) void *_vpninfo, int level,
}
}
static void sync_split_dns_env()
{
if (g_split_dns && *g_split_dns) {
setenv("CISCO_SPLIT_DNS", g_split_dns, 1);
} else {
unsetenv("CISCO_SPLIT_DNS");
}
}
static void setup_tun_handler(void *_vpninfo)
{
int ret;
sync_split_dns_env();
if (g_script_tun) {
ret = openconnect_setup_tun_script(_vpninfo, g_vpnc_script);
} else {
@@ -51,16 +62,7 @@ static void setup_tun_handler(void *_vpninfo)
}
if (!ret) {
vpn_session_info session_info = {
.auth_expiration = (long)openconnect_get_auth_expiration(_vpninfo),
.lifetime_secs = openconnect_get_gp_session_lifetime(_vpninfo),
.user_expires = (long)openconnect_get_gp_user_expires(_vpninfo),
.lifetime_warning_prior =
openconnect_get_gp_lifetime_notify_prior(_vpninfo),
.lifetime_warning_message =
openconnect_get_gp_lifetime_notify_message(_vpninfo),
};
on_vpn_connected(g_cmd_pipe_fd, &session_info, g_user_data);
on_vpn_connected(g_cmd_pipe_fd, g_user_data);
}
}
@@ -69,11 +71,11 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
{
struct openconnect_info *vpninfo;
struct utsname utsbuf;
const char *effective_local_hostname = NULL;
g_user_data = options->user_data;
g_vpnc_script = options->script;
g_vpnc_interface = options->interface;
g_split_dns = options->split_dns;
g_script_tun = options->script_tun;
on_vpn_connected = callback;
@@ -89,7 +91,6 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
INFO("DISABLE_IPV6: %d", options->disable_ipv6);
INFO("NO_DTLS: %d", options->no_dtls);
INFO("DPD_INTERVAL: %d", options->dpd_interval);
INFO("NO_XMLPOST: %d", options->no_xmlpost);
vpninfo =
openconnect_vpninfo_new(options->user_agent, validate_peer_cert,
@@ -120,17 +121,6 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
options->client_version);
}
effective_local_hostname = options->local_hostname;
if (!effective_local_hostname && !uname(&utsbuf)) {
effective_local_hostname = utsbuf.nodename;
}
if (effective_local_hostname) {
openconnect_set_localname(vpninfo, effective_local_hostname);
}
INFO("LOCAL_HOSTNAME: %s",
effective_local_hostname ? effective_local_hostname : "(not set)");
if (options->certificate) {
INFO("Setting client certificate: %s", options->certificate);
openconnect_set_client_cert(vpninfo, options->certificate,
@@ -141,10 +131,6 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
openconnect_set_key_password(vpninfo, options->key_password);
}
if (options->no_xmlpost) {
openconnect_set_xmlpost(vpninfo, 0);
}
if (options->csd_wrapper) {
openconnect_setup_csd(vpninfo, options->csd_uid, 1,
options->csd_wrapper);
@@ -169,6 +155,10 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
return 1;
}
if (!uname(&utsbuf)) {
openconnect_set_localname(vpninfo, utsbuf.nodename);
}
// Essential step
if (openconnect_make_cstp_connection(vpninfo) != 0) {
ERROR("openconnect_make_cstp_connection failed");
@@ -188,6 +178,7 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
if (ret) {
INFO("openconnect_mainloop returned %d, exiting", ret);
unsetenv("CISCO_SPLIT_DNS");
openconnect_vpninfo_free(vpninfo);
return ret;
}
+2 -13
View File
@@ -3,17 +3,7 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct vpn_session_info {
long auth_expiration;
int lifetime_secs;
long user_expires;
int lifetime_warning_prior;
const char *lifetime_warning_message;
} vpn_session_info;
typedef void (*vpn_connected_callback)(int cmd_pipe_fd,
const vpn_session_info *session_info,
void *user_data);
typedef void (*vpn_connected_callback)(int cmd_pipe_fd, void *user_data);
typedef struct vpn_options {
void *user_data;
@@ -25,7 +15,7 @@ typedef struct vpn_options {
const char *os;
const char *os_version;
const char *client_version;
const char *local_hostname;
const char *split_dns;
const char *script;
const char *interface;
@@ -45,7 +35,6 @@ typedef struct vpn_options {
const int no_dtls;
const int dpd_interval;
const int no_xmlpost;
} vpn_options;
int vpn_connect(const vpn_options *options, vpn_connected_callback callback);
+45 -101
View File
@@ -1,5 +1,5 @@
use std::{
ffi::{CStr, CString, c_char},
ffi::{CString, c_char},
fmt,
sync::{Arc, RwLock},
};
@@ -9,52 +9,7 @@ use log::info;
use crate::ffi;
use crate::vpn_utils::{check_executable, find_csd_wrapper, find_vpnc_script};
type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce(VpnSessionInfo) + 'static + Send + Sync>>>>;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct VpnSessionInfo {
pub lifetime_secs: Option<u32>,
pub user_expires: Option<u32>,
pub lifetime_warning: Option<VpnSessionWarning>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VpnSessionWarning {
pub prior_secs: u32,
pub message: String,
}
pub(crate) fn session_info_from_raw(raw: *const ffi::VpnSessionInfoRaw) -> VpnSessionInfo {
if raw.is_null() {
return VpnSessionInfo::default();
}
let raw = unsafe { &*raw };
let warning_message =
unsafe { optional_c_string(raw.lifetime_warning_message) }.filter(|message| !message.is_empty());
let user_expires = positive_i64_to_u32(raw.user_expires).or_else(|| positive_i64_to_u32(raw.auth_expiration));
VpnSessionInfo {
lifetime_secs: positive_i64_to_u32(raw.lifetime_secs as i64),
user_expires,
lifetime_warning: match (positive_i64_to_u32(raw.lifetime_warning_prior as i64), warning_message) {
(Some(prior_secs), Some(message)) => Some(VpnSessionWarning { prior_secs, message }),
_ => None,
},
}
}
unsafe fn optional_c_string(value: *const c_char) -> Option<String> {
if value.is_null() {
return None;
}
unsafe { CStr::from_ptr(value) }.to_str().ok().map(ToOwned::to_owned)
}
fn positive_i64_to_u32(value: i64) -> Option<u32> {
u32::try_from(value).ok().filter(|value| *value > 0)
}
type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce() + 'static + Send + Sync>>>>;
pub struct Vpn {
server: CString,
@@ -64,7 +19,7 @@ pub struct Vpn {
os: CString,
os_version: Option<CString>,
client_version: Option<CString>,
local_hostname: Option<CString>,
split_dns: Option<CString>,
script: CString,
interface: Option<CString>,
@@ -84,7 +39,6 @@ pub struct Vpn {
no_dtls: bool,
dpd_interval: u32,
no_xmlpost: bool,
callback: OnConnectedCallback,
}
@@ -94,18 +48,18 @@ impl Vpn {
VpnBuilder::new(server, cookie)
}
pub fn connect(&self, on_connected: impl FnOnce(VpnSessionInfo) + 'static + Send + Sync) -> i32 {
pub fn connect(&self, on_connected: impl FnOnce() + 'static + Send + Sync) -> i32 {
self.callback.write().unwrap().replace(Box::new(on_connected));
let options = self.build_connect_options();
ffi::connect(&options)
}
pub(crate) fn on_connected(&self, pipe_fd: i32, session_info: VpnSessionInfo) {
pub(crate) fn on_connected(&self, pipe_fd: i32) {
info!("Connected to VPN, pipe_fd: {}", pipe_fd);
if let Some(callback) = self.callback.write().unwrap().take() {
callback(session_info);
callback();
}
}
@@ -124,7 +78,7 @@ impl Vpn {
os: self.os.as_ptr(),
os_version: Self::option_to_ptr(&self.os_version),
client_version: Self::option_to_ptr(&self.client_version),
local_hostname: Self::option_to_ptr(&self.local_hostname),
split_dns: Self::option_to_ptr(&self.split_dns),
script: self.script.as_ptr(),
interface: Self::option_to_ptr(&self.interface),
@@ -143,7 +97,6 @@ impl Vpn {
disable_ipv6: self.disable_ipv6 as u32,
no_dtls: self.no_dtls as u32,
dpd_interval: self.dpd_interval,
no_xmlpost: self.no_xmlpost as u32,
}
}
@@ -185,7 +138,7 @@ pub struct VpnBuilder {
os: Option<String>,
os_version: Option<String>,
client_version: Option<String>,
local_hostname: Option<String>,
split_dns: Option<String>,
certificate: Option<String>,
sslkey: Option<String>,
@@ -201,7 +154,6 @@ pub struct VpnBuilder {
no_dtls: bool,
dpd_interval: u32,
no_xmlpost: bool,
}
impl VpnBuilder {
@@ -217,7 +169,7 @@ impl VpnBuilder {
os: None,
os_version: None,
client_version: None,
local_hostname: None,
split_dns: None,
certificate: None,
sslkey: None,
@@ -232,7 +184,6 @@ impl VpnBuilder {
disable_ipv6: false,
no_dtls: false,
dpd_interval: 0,
no_xmlpost: false,
}
}
@@ -271,8 +222,8 @@ impl VpnBuilder {
self
}
pub fn local_hostname<T: Into<Option<String>>>(mut self, local_hostname: T) -> Self {
self.local_hostname = local_hostname.into();
pub fn split_dns<T: Into<Option<String>>>(mut self, split_dns: T) -> Self {
self.split_dns = split_dns.into();
self
}
@@ -331,11 +282,6 @@ impl VpnBuilder {
self
}
pub fn no_xmlpost(mut self, no_xmlpost: bool) -> Self {
self.no_xmlpost = no_xmlpost;
self
}
fn determine_script(&self) -> Result<&str, VpnError> {
match &self.script {
Some(script) => {
@@ -378,7 +324,7 @@ impl VpnBuilder {
os: Self::to_cstring(&os),
os_version: self.os_version.as_deref().map(Self::to_cstring),
client_version: self.client_version.as_deref().map(Self::to_cstring),
local_hostname: self.local_hostname.as_deref().map(Self::to_cstring),
split_dns: self.split_dns.as_deref().map(Self::to_cstring),
script: Self::to_cstring(&script),
interface: self.interface.as_deref().map(Self::to_cstring),
@@ -397,7 +343,6 @@ impl VpnBuilder {
disable_ipv6: self.disable_ipv6,
no_dtls: self.no_dtls,
dpd_interval: self.dpd_interval,
no_xmlpost: self.no_xmlpost,
callback: Default::default(),
})
@@ -410,47 +355,46 @@ impl VpnBuilder {
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::CString;
use std::{
ffi::CStr,
fs,
time::{SystemTime, UNIX_EPOCH},
};
#[test]
fn maps_session_info_from_callback_payload() {
let message = CString::new("Session expires soon").unwrap();
let raw = ffi::VpnSessionInfoRaw {
auth_expiration: 0,
lifetime_secs: 43_200,
user_expires: 1_776_828_409,
lifetime_warning_prior: 1_800,
lifetime_warning_message: message.as_ptr(),
};
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
let info = session_info_from_raw(&raw);
use super::Vpn;
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(
info.lifetime_warning,
Some(VpnSessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
})
);
#[cfg(unix)]
fn create_executable_script() -> String {
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
let path = std::env::temp_dir().join(format!("gp-openconnect-test-{nanos}.sh"));
fs::write(&path, "#!/bin/sh\nexit 0\n").unwrap();
let mut permissions = fs::metadata(&path).unwrap().permissions();
permissions.set_mode(0o755);
fs::set_permissions(&path, permissions).unwrap();
path.to_string_lossy().into_owned()
}
#[cfg(unix)]
#[test]
fn falls_back_to_auth_expiration_when_user_expires_is_absent() {
let raw = ffi::VpnSessionInfoRaw {
auth_expiration: 1_776_828_409,
lifetime_secs: 0,
user_expires: 0,
lifetime_warning_prior: 0,
lifetime_warning_message: std::ptr::null(),
};
fn split_dns_survives_into_connect_options() {
let script = create_executable_script();
let vpn = Vpn::builder("https://vpn.example.com", "cookie")
.script(Some(script.clone()))
.split_dns(Some("corp.local,svc.local".to_string()))
.build()
.unwrap();
let info = session_info_from_raw(&raw);
let options = vpn.build_connect_options();
let split_dns = unsafe { CStr::from_ptr(options.split_dns) }.to_str().unwrap();
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(info.lifetime_secs, None);
assert_eq!(info.lifetime_warning, None);
assert_eq!(split_dns, "corp.local,svc.local");
fs::remove_file(script).unwrap();
}
}
+2 -8
View File
@@ -3,8 +3,6 @@ use std::{io, path::Path};
use is_executable::IsExecutable;
const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
"/usr/libexec/gpclient/vpnc-script",
"/usr/lib/gpclient/vpnc-script",
"/usr/local/share/vpnc-scripts/vpnc-script",
"/usr/local/sbin/vpnc-script",
"/usr/share/vpnc-scripts/vpnc-script",
@@ -12,10 +10,8 @@ const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
"/etc/vpnc/vpnc-script",
"/etc/openconnect/vpnc-script",
"/usr/libexec/vpnc-scripts/vpnc-script",
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
#[cfg(target_os = "macos")]
"/opt/homebrew/etc/vpnc/vpnc-script",
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
"/usr/local/etc/vpnc/vpnc-script",
];
const CSD_WRAPPER_LOCATIONS: &[&str] = &[
@@ -26,10 +22,8 @@ const CSD_WRAPPER_LOCATIONS: &[&str] = &[
"/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh",
"/usr/lib/openconnect/hipreport.sh",
"/usr/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
#[cfg(target_os = "macos")]
"/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
"/usr/local/opt/openconnect/libexec/openconnect/hipreport.sh",
];
fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
+4 -2
View File
@@ -59,6 +59,7 @@
buildInputs =
with pkgs;
[
vpnc-scripts
libxml2
zlib
lz4
@@ -102,8 +103,9 @@
{
postPatch = ''
substituteInPlace crates/openconnect/src/vpn_utils.rs \
--replace-fail /usr/libexec/gpclient/vpnc-script $out/libexec/gpclient/vpnc-script \
--replace-fail /usr/libexec/gpclient/hipreport.sh $out/libexec/gpclient/hipreport.sh
--replace-fail /etc/vpnc/vpnc-script ${pkgs.vpnc-scripts}/bin/vpnc-script \
--replace-fail /usr/libexec/gpclient/hipreport.sh $out/libexec/gpclient/hipreport.sh \
--replace-fail /usr/lib/openconnect/hipreport.sh ${pkgs.openconnect}/libexec/openconnect/hipreport.sh
substituteInPlace crates/common/src/constants.rs \
--replace-fail /usr/bin/gpclient $out/bin/gpclient \
+1 -2
View File
@@ -10,7 +10,7 @@ install:
install -Dm755 artifacts/usr/bin/gpgui $(DESTDIR)/usr/bin/gpgui; \
fi
install -Dm755 artifacts/usr/libexec/gpclient/vpnc-script $(DESTDIR)/usr/libexec/gpclient/vpnc-script
# Install the HIP report script
install -Dm755 artifacts/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
# Install the disconnect hooks
@@ -33,7 +33,6 @@ uninstall:
rm -f $(DESTDIR)/usr/bin/gpgui-helper
rm -f $(DESTDIR)/usr/bin/gpgui
rm -f $(DESTDIR)/usr/libexec/gpclient/vpnc-script
rm -f $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
+2 -12
View File
@@ -4,25 +4,14 @@ Priority: optional
Maintainer: Kevin Yue <[email protected]>
Standards-Version: 4.1.4
Build-Depends: debhelper (>= 9),
autoconf,
automake,
autopoint,
libtool,
patch,
pkg-config,
make (>= 4),
libssl-dev,
libxml2-dev,
zlib1g-dev,
liblz4-dev,
libgnutls28-dev,
libp11-kit-dev,
nettle-dev,
libgmp-dev,
libsecret-1-0,
libayatana-appindicator3-1,
gnome-keyring,
libwebkit2gtk-4.1-dev,
libopenconnect-dev (>= 8.20),
rust-@RUST_VERSION@-all
Homepage: https://github.com/yuezk/GlobalProtect-openconnect
@@ -32,6 +21,7 @@ Multi-Arch: foreign
Depends:
${misc:Depends},
${shlibs:Depends},
vpnc-scripts,
libsecret-1-0,
libayatana-appindicator3-1,
gnome-keyring,
@@ -4,16 +4,13 @@
LOGFILE="/tmp/gpclient-hipreport.log"
LINUX_GPCLIENT_BIN="/usr/bin/gpclient"
ARM64_HOMEBREW_GPCLIENT_BIN="/opt/homebrew/bin/gpclient"
X86_64_HOMEBREW_GPCLIENT_BIN="/usr/local/bin/gpclient"
HOMEBREW_GPCLIENT_BIN="/opt/homebrew/bin/gpclient"
GPCLIENT_BIN=""
if [ -x "$LINUX_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$LINUX_GPCLIENT_BIN"
elif [ -x "$ARM64_HOMEBREW_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$ARM64_HOMEBREW_GPCLIENT_BIN"
elif [ -x "$X86_64_HOMEBREW_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$X86_64_HOMEBREW_GPCLIENT_BIN"
elif [ -x "$HOMEBREW_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$HOMEBREW_GPCLIENT_BIN"
else
echo "Error: gpclient binary not found." > "$LOGFILE"
exit 1
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -8,9 +8,10 @@ pkgdesc="A GUI client for GlobalProtect VPN, based on OpenConnect, supports the
arch=('x86_64' 'aarch64')
url="https://github.com/yuezk/GlobalProtect-openconnect"
license=('GPL3')
makedepends=('make' 'pkg-config' 'cargo' 'file' 'autoconf' 'automake' 'gettext' 'libtool' 'patch')
makedepends=('make' 'pkg-config' 'cargo' 'file')
depends=('webkit2gtk-4.1' 'libappindicator-gtk3' 'librsvg' 'libsecret' 'openssl' 'appmenu-gtk-module'
'gnutls' 'libxml2' 'zlib' 'lz4' 'libp11-kit' 'nettle' 'gmp' 'xdg-utils')
'gnutls' 'libxml2' 'vpnc' 'lz4' 'libp11-kit' 'nettle' 'xdg-utils'
'openconnect>=8.20')
optdepends=('wmctrl: for window management')
provides=('globalprotect-openconnect' 'gpclient' 'gpservice' 'gpauth' 'gpgui')
@@ -12,18 +12,11 @@ BuildRequires: make
BuildRequires: libtool
BuildRequires: autoconf
BuildRequires: automake
BuildRequires: gettext
BuildRequires: gcc-c++
BuildRequires: cargo
BuildRequires: pkg-config
BuildRequires: openconnect-devel
BuildRequires: (openssl-devel or libopenssl-devel)
BuildRequires: libxml2-devel
BuildRequires: zlib-devel
BuildRequires: (lz4-devel or liblz4-devel)
BuildRequires: gnutls-devel
BuildRequires: p11-kit-devel
BuildRequires: (nettle-devel or libnettle-devel)
BuildRequires: gmp-devel
BuildRequires: wget
BuildRequires: file
BuildRequires: perl
@@ -37,6 +30,9 @@ BuildRequires: webkit2gtk4.1-devel
BuildRequires: (libappindicator-gtk3-devel or libappindicator3-1)
BuildRequires: (librsvg2-devel or librsvg-devel)
# Still requires openconnect because of the latest vpnc-script it provides on
# some distros (e.g., opensuse)
Requires: openconnect >= 8.20
Requires: (libappindicator-gtk3 or libayatana-appindicator)
Conflicts: globalprotect-openconnect-snapshot
@@ -62,7 +58,6 @@ make build
%files
%defattr(-,root,root)
%{_bindir}/*
%{_libexecdir}/gpclient/vpnc-script
%{_libexecdir}/gpclient/hipreport.sh
%{_datadir}/applications/gpgui.desktop
%{_datadir}/icons/hicolor/32x32/apps/gpgui.png