Compare commits

...
Author SHA1 Message Date
Kevin Yue fcff1155b3 docs: clarify source build prerequisites 2026-04-19 12:27:44 +08:00
Kevin Yue 2bce296f05 chore: cut 2.3.13 2026-04-19 11:03:27 +08:00
Kevin Yue 0e32dab997 fix: update 2.3.x package and release flow 2026-04-19 10:58:39 +08:00
Kevin Yue 6db0ed726a ci: rename publish to publish-ppa 2026-04-19 09:43:54 +08:00
Kevin Yue 2a089f69d1 ci: align release workflow matrix with build 2026-04-19 09:24:55 +08:00
Kevin Yue ef4770c0dd Release 2.3.12 2026-04-19 09:00:50 +08:00
Kevin Yue 21822074a8 fix: support custom VPN ports on 2.3.x 2026-04-19 08:37:05 +08:00
Kevin Yue e0db4631ca chore: pin vendored openssl in lockfile 2026-04-19 00:46:43 +08:00
Kevin Yue e733b38ab7 refactor: backport xmltree parser migration to 2.3.x 2026-04-19 00:40:00 +08:00
Kevin Yue c206e72885 docs: note epel and restore rpm appindicator deps 2026-04-19 00:24:59 +08:00
Kevin Yue c1f00aca82 chore: refresh lockfile deps for Rust 1.71 2026-04-19 00:13:18 +08:00
Kevin Yue d28c567e95 chore: add ayatana appindicator rpm runtime dep 2026-04-19 00:00:27 +08:00
Kevin Yue e305af607b chore: add ayatana appindicator rpm build dep 2026-04-18 23:53:31 +08:00
Kevin Yue af903f5d5b ci: run build-gp on arm64 2026-04-18 23:28:54 +08:00
Kevin Yue 745e72892d ci: always include arm64 in build matrix 2026-04-18 23:25:01 +08:00
Kevin Yue ce7df6ea5c ci: add 2.3.x branch to workflow triggers 2026-04-18 23:18:09 +08:00
Kevin Yue a269a60e93 Merge pull request #593 from yuezk/codex/backport-openconnect-2.3 2026-04-18 11:16:11 -04:00
Kevin Yue 3bb27f0193 ci: use GitHub hosted arm action runner 2026-04-18 23:05:38 +08:00
Kevin Yue 3028224bd2 backport browser flag default value support 2026-04-18 23:01:26 +08:00
Kevin Yue 2576b08a89 backport remote browser and arm64 runner updates 2026-04-18 22:54:25 +08:00
Kevin Yue 19106150dd fix: bump wry to 0.24.12 2026-04-18 22:26:37 +08:00
Kevin Yue 11c4a16f73 fix: fall back to direct gmp linking 2026-04-18 22:05:59 +08:00
Kevin Yue 90d3f409d6 fix: force utf-8 locale for debmake 2026-04-18 21:55:36 +08:00
Kevin Yue 56835a5c4d ci: add 2.3.x pull request builds 2026-04-18 21:42:12 +08:00
Kevin Yue 46564ed65d ci: only run 2.3.x builds for pull requests 2026-04-18 21:40:52 +08:00
Kevin Yue 06a25354a7 Revert "ci: use tauri2 builders for 2.3.x pushes"
This reverts commit 7e4f65b1c8.
2026-04-18 21:39:14 +08:00
Kevin Yue 7e4f65b1c8 ci: use tauri2 builders for 2.3.x pushes 2026-04-18 21:37:29 +08:00
Kevin Yue fd4702c2f4 ci: use artifact actions v4 2026-04-18 21:28:38 +08:00
Kevin Yue 8785f7308a ci: use artifact actions v4 2026-04-18 21:28:22 +08:00
Kevin Yue e18d6d3ed0 ci: trigger 2.3.x pull request builds 2026-04-18 21:26:49 +08:00
Kevin Yue f754a7f3c7 Backport vendored openconnect and HIP flow 2026-04-18 20:21:10 +08:00
Kevin Yue 51c55376e8 ci: use gh to download release asset 2025-01-21 22:48:40 +08:00
Kevin Yue 26d5d5bcf0 Release 2.3.11 2025-01-21 21:37:56 +08:00
Kevin Yue b99053718a ci: upload offline tarball 2025-01-21 21:11:03 +08:00
Kevin Yue 6e603c84b3 chore: pin rust version 1.71.1 2025-01-21 20:18:06 +08:00
Kevin Yue eeb60125e6 ci: update publish PPA action 2025-01-21 00:54:43 +08:00
Kevin Yue 875c463bc2 ci: update publish PPA action 2025-01-21 00:46:03 +08:00
Kevin Yue 8cc73df3d6 Release 2.3.10 2025-01-21 00:06:02 +08:00
Kevin Yue fd3ff7b0de Do not use default value for os version 2025-01-21 00:05:46 +08:00
Kevin Yue 72a83f12d0 fix: disconnect VPN when sleep 2025-01-20 20:17:18 +08:00
58 changed files with 5111 additions and 1254 deletions

No files matched your search

+76 -18
View File
@@ -9,13 +9,31 @@ on:
branches:
- main
- dev
- 2.3.x
- hotfix/*
- feature/*
- release/*
tags:
- v*.*.*
pull_request:
paths-ignore:
- LICENSE
- "*.md"
- .vscode
- .devcontainer
branches:
- 2.3.x
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
GP_REF: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.ref }}
GPGUI_REF: ${{ github.event_name == 'pull_request' && github.base_ref || github.ref_name }}
jobs:
# Include arm64 if ref is a tag
# Always include arm64
setup-matrix:
runs-on: ubuntu-latest
outputs:
@@ -24,11 +42,7 @@ jobs:
- name: Set up matrix
id: set-matrix
run: |
if [[ "${{ github.ref }}" == "refs/tags/"* ]]; then
echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}, {"runner": "arm64", "arch": "arm64"}]' >> $GITHUB_OUTPUT
else
echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}]' >> $GITHUB_OUTPUT
fi
echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}, {"runner": "ubuntu-24.04-arm", "arch": "ubuntu-24.04-arm"}]' >> $GITHUB_OUTPUT
tarball:
runs-on: ubuntu-latest
@@ -44,8 +58,9 @@ jobs:
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.ref }}
ref: ${{ env.GP_REF }}
path: source/gp
submodules: recursive
- name: Create tarball
run: |
cd source/gp
@@ -55,21 +70,61 @@ jobs:
fi
make tarball
- name: Upload tarball
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: artifact-source
if-no-files-found: error
path: |
source/gp/.build/tarball/*.tar.gz
tarball-offline:
if: ${{ startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest
needs:
- tarball
steps:
- uses: pnpm/action-setup@v2
with:
version: 8
- name: Prepare workspace
run: rm -rf source-offline && mkdir source-offline
- name: Download tarball
uses: actions/download-artifact@v4
with:
name: artifact-source
path: source-offline
- name: Create offline tarball
run: |
cd source-offline
offline_tarball=$(basename *.tar.gz .tar.gz).offline.tar.gz
# Extract the tarball
tar -xzf *.tar.gz
cd */
make tarball OFFLINE=1
# Rename the tarball to .offline.tar.gz
mv -v .build/tarball/*.tar.gz ../$offline_tarball
- name: Upload offline tarball
uses: actions/upload-artifact@v4
with:
path: source-offline/*.offline.tar.gz
name: artifact-source-offline
if-no-files-found: error
build-gp:
needs:
- setup-matrix
- tarball
strategy:
matrix:
# Only build gp on amd64, as the arm64 package will be built in release.yaml
os: [{runner: ubuntu-latest, arch: amd64}]
os: ${{fromJson(needs.setup-matrix.outputs.matrix)}}
package: [deb, rpm, pkg, binary]
runs-on: ${{ matrix.os.runner }}
name: build-gp (${{ matrix.package }}, ${{ matrix.os.arch }})
@@ -79,7 +134,7 @@ jobs:
rm -rf build-gp-${{ matrix.package }}
mkdir -p build-gp-${{ matrix.package }}
- name: Download tarball
uses: actions/download-artifact@v3
uses: actions/download-artifact@v4
with:
name: artifact-source
path: build-gp-${{ matrix.package }}
@@ -88,6 +143,7 @@ jobs:
- name: Build ${{ matrix.package }} package in Docker
run: |
docker run --rm \
-e LIBXML2_STATIC=1 \
-v $(pwd)/build-gp-${{ matrix.package }}:/${{ matrix.package }} \
yuezk/gpdev:${{ matrix.package }}-builder
- name: Install ${{ matrix.package }} package in Docker
@@ -98,7 +154,7 @@ jobs:
yuezk/gpdev:${{ matrix.package }}-builder \
bash install.sh
- name: Upload ${{ matrix.package }} package
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: artifact-gp-${{ matrix.package }}-${{ matrix.os.arch }}
if-no-files-found: error
@@ -124,14 +180,15 @@ jobs:
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.ref }}
ref: ${{ env.GP_REF }}
path: gpgui-source/gp
- name: Checkout gpgui@${{ github.ref_name }}
submodules: recursive
- name: Checkout gpgui@${{ env.GPGUI_REF }}
uses: actions/checkout@v3
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui
ref: ${{ github.ref_name }}
ref: ${{ env.GPGUI_REF }}
path: gpgui-source/gpgui
- name: Tarball
run: |
@@ -141,7 +198,7 @@ jobs:
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build gpgui in Docker
run: |
docker run --rm -v $(pwd)/gpgui-source:/gpgui yuezk/gpdev:gpgui-builder
docker run --rm -e LIBXML2_STATIC=1 -v $(pwd)/gpgui-source:/gpgui yuezk/gpdev:gpgui-builder
- name: Install gpgui in Docker
run: |
cd gpgui-source
@@ -149,7 +206,7 @@ jobs:
docker run --rm -v $(pwd):/gpgui yuezk/gpdev:gpgui-builder \
bash -c "cd /gpgui/gpgui_*/ && ./gpgui --version"
- name: Upload gpgui
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: artifact-gpgui-${{ matrix.os.arch }}
if-no-files-found: error
@@ -162,6 +219,7 @@ jobs:
runs-on: ubuntu-latest
needs:
- tarball
- tarball-offline
- build-gp
- build-gpgui
@@ -178,7 +236,7 @@ jobs:
path: gh-release/gp
- name: Download all artifacts
uses: actions/download-artifact@v3
uses: actions/download-artifact@v4
with:
path: gh-release/gp/.build/artifacts
@@ -1,4 +1,4 @@
name: Publish Packages
name: Publish PPA
on:
workflow_dispatch:
@@ -52,38 +52,43 @@ jobs:
version: 8
- name: Prepare workspace
run: rm -rf publish-ppa && mkdir publish-ppa
- name: Download ${{ inputs.tag }} source code
- name: Download ${{ inputs.tag }} offline source code
uses: robinraju/[email protected]
with:
token: ${{ secrets.GH_PAT }}
tag: ${{ inputs.tag }}
fileName: globalprotect-openconnect-*.tar.gz
fileName: globalprotect-openconnect-*.offline.tar.gz
tarBall: false
zipBall: false
out-file-path: publish-ppa
- name: Make the offline tarball
- name: Patch the source code
run: |
cd publish-ppa
tar -xf globalprotect-openconnect-*.tar.gz
cd globalprotect-openconnect-*/
make tarball OFFLINE=1
# Rename the source tarball without the offline suffix
mv *.tar.gz $(basename *.tar.gz .offline.tar.gz).tar.gz
# Extract the source tarball
tar -xzf *.tar.gz
# Prepare the debian directory with custom files
cd globalprotect-openconnect-*/
mkdir -p .build/debian
sed 's/@RUST@/rust-all(>=1.70)/g' packaging/deb/control.in > .build/debian/control
sed 's/@RUST@/rust-all(>=1.71)/g' packaging/deb/control.in > .build/debian/control
sed 's/@OFFLINE@/1/g' packaging/deb/rules.in > .build/debian/rules
cp packaging/deb/postrm .build/debian/postrm
- name: Publish to PPA
uses: yuezk/publish-ppa-package@v2
uses: yuezk/publish-ppa-package@gp_2.3.x
with:
repository: "yuezk/globalprotect-openconnect"
gpg_private_key: ${{ secrets.PPA_GPG_PRIVATE_KEY }}
gpg_passphrase: ${{ secrets.PPA_GPG_PASSPHRASE }}
tarball: publish-ppa/globalprotect-openconnect-*/.build/tarball/*.tar.gz
tarball: publish-ppa/globalprotect-openconnect-*.tar.gz
debian_dir: publish-ppa/globalprotect-openconnect-*/.build/debian
deb_email: "[email protected]"
deb_fullname: "Kevin Yue"
extra_ppa: "yuezk/globalprotect-openconnect liushuyu-011/rust-bpo-1.75"
series: "bionic focal"
revision: ${{ inputs.revision }}
+21 -16
View File
@@ -73,9 +73,12 @@ jobs:
const inputs = ${{ toJson(inputs) }}
const { arch } = inputs
const osMap = {
"all": ["ubuntu-latest", "arm64"],
"x86_64": ["ubuntu-latest"],
"arm64": ["arm64"]
"all": [
{ runner: "ubuntu-latest", arch: "amd64" },
{ runner: "ubuntu-24.04-arm", arch: "ubuntu-24.04-arm" },
],
"x86_64": [{ runner: "ubuntu-latest", arch: "amd64" }],
"arm64": [{ runner: "ubuntu-24.04-arm", arch: "ubuntu-24.04-arm" }],
}
const package = Object.entries(inputs)
@@ -92,24 +95,27 @@ jobs:
- setup-matrix
strategy:
matrix: ${{ fromJson(needs.setup-matrix.outputs.matrix) }}
runs-on: ${{ matrix.os }}
runs-on: ${{ matrix.os.runner }}
name: build (${{ matrix.package }}, ${{ matrix.os.arch }})
steps:
- name: Prepare workspace
run: rm -rf build-${{ matrix.package }} && mkdir -p build-${{ matrix.package }}
- name: Download ${{ inputs.tag }} source code
uses: robinraju/[email protected]
with:
token: ${{ secrets.GH_PAT }}
tag: ${{ inputs.tag }}
fileName: globalprotect-openconnect-*.tar.gz
tarBall: false
zipBall: false
out-file-path: build-${{ matrix.package }}
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
gh -R yuezk/GlobalProtect-openconnect \
release download ${{ inputs.tag }} \
--pattern '*[^offline].tar.gz' \
--dir build-${{ matrix.package }}
- name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build ${{ matrix.package }} package in Docker
run: |
docker run --rm \
-e LIBXML2_STATIC=1 \
-v $(pwd)/build-${{ matrix.package }}:/${{ matrix.package }} \
-e INCLUDE_GUI=1 \
yuezk/gpdev:${{ matrix.package }}-builder
@@ -122,9 +128,9 @@ jobs:
bash install.sh
- name: Upload ${{ matrix.package }} package
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: artifact-${{ matrix.os }}-${{ matrix.package }}
name: artifact-${{ matrix.os.arch }}-${{ matrix.package }}
if-no-files-found: error
path: |
build-${{ matrix.package }}/artifacts/*
@@ -138,7 +144,7 @@ jobs:
- name: Prepare workspace
run: rm -rf gh-release && mkdir gh-release
- name: Download artifact
uses: actions/download-artifact@v3
uses: actions/download-artifact@v4
with:
path: gh-release
- name: Update release
@@ -150,4 +156,3 @@ jobs:
tag_name: ${{ inputs.tag }}
files: |
gh-release/artifact-*/*
+6
View File
@@ -0,0 +1,6 @@
[submodule "crates/openconnect/deps/openconnect"]
path = crates/openconnect/deps/openconnect
url = https://gitlab.com/openconnect/openconnect.git
[submodule "crates/openconnect/deps/libxml2"]
path = crates/openconnect/deps/libxml2
url = https://gitlab.gnome.org/GNOME/libxml2.git
Generated
+1823 -1001
View File
File diff suppressed because it is too large. Load diff
+22 -16
View File
@@ -1,11 +1,17 @@
[workspace]
resolver = "2"
members = ["crates/*", "apps/gpclient", "apps/gpservice", "apps/gpauth", "apps/gpgui-helper/src-tauri"]
members = [
"crates/*",
"apps/gpclient",
"apps/gpservice",
"apps/gpauth",
"apps/gpgui-helper/src-tauri",
]
[workspace.package]
rust-version = "1.70"
version = "2.3.9"
rust-version = "1.71.1"
version = "2.3.13"
authors = ["Kevin Yue <[email protected]>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2021"
@@ -13,43 +19,43 @@ license = "GPL-3.0"
[workspace.dependencies]
anyhow = "1.0"
base64 = "0.21"
clap = { version = "4.4.2", features = ["derive"] }
base64 = "0.22"
clap = { version = "~4.4.2", features = ["derive"] }
ctrlc = "3.4"
directories = "5.0"
dns-lookup = "2.0.4"
env_logger = "0.10"
env_logger = "0.11"
is_executable = "1.0"
log = "0.4"
regex = "1"
reqwest = { version = "0.11", features = ["native-tls-vendored", "json"] }
openssl = "0.10"
pem = "3"
roxmltree = "0.18"
xmltree = "0.11"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sysinfo = "0.29"
sysinfo = "0.30"
tempfile = "3.8"
tokio = { version = "1", features = ["full"] }
tokio = { version = "1" }
tokio-util = "0.7"
url = "2.4"
urlencoding = "2.1.3"
axum = "0.7"
futures = "0.3"
futures-util = "0.3"
tokio-tungstenite = "0.20.1"
uzers = "0.11"
tokio-tungstenite = "0.26.1"
uzers = "0.12"
whoami = "1"
thiserror = "1"
thiserror = "2"
redact-engine = "0.1"
compile-time = "0.2"
serde_urlencoded = "0.7"
md5="0.7"
sha256="1"
which="6"
md5 = "0.7"
sha256 = "1"
which = "7"
# Tauri dependencies
tauri = { version = "1.5" }
tauri = { version = "1" }
specta = "=2.0.0-rc.1"
specta-macros = "=2.0.0-rc.1"
rspc = { version = "1.0.0-rc.5", features = ["tauri"] }
+14 -1
View File
@@ -117,6 +117,13 @@ 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 -Dm755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
# Install the disconnect hooks
install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
install -Dm644 packaging/files/usr/share/applications/gpgui.desktop $(DESTDIR)/usr/share/applications/gpgui.desktop
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
install -Dm644 packaging/files/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
@@ -133,6 +140,12 @@ 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
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
rm -f $(DESTDIR)/usr/share/applications/gpgui.desktop
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
rm -f $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
@@ -149,7 +162,7 @@ init-debian: clean-debian tarball
cp .build/tarball/${PKG}.tar.gz .build/deb
tar -xzf .build/deb/${PKG}.tar.gz -C .build/deb
cd .build/deb/${PKG} && debmake
cd .build/deb/${PKG} && LC_ALL=C.UTF-8 LANG=C.UTF-8 PYTHONUTF8=1 debmake
cp -f packaging/deb/control.in .build/deb/$(PKG)/debian/control
cp -f packaging/deb/rules.in .build/deb/$(PKG)/debian/rules
+82 -8
View File
@@ -145,6 +145,12 @@ The package is also available on [OBS](https://build.opensuse.org/package/show/h
Download the latest RPM package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
On RHEL / Rocky Linux / AlmaLinux / CentOS, enable EPEL first:
```bash
sudo dnf install epel-release
```
```bash
sudo rpm -i globalprotect-openconnect-*.rpm
```
@@ -168,23 +174,91 @@ sudo emerge -av net-vpn/globalprotect-openconnect
## Build from source
You can also build the client from source, steps are as follows:
The source build now vendors OpenConnect in `crates/openconnect/deps/openconnect`.
It can also build libxml2 from `crates/openconnect/deps/libxml2` when needed.
You do not need to install `openconnect` or `libopenconnect-dev` to build from source.
If you build from a git checkout, make sure the vendored sources are present:
```bash
git clone --recursive https://github.com/yuezk/GlobalProtect-openconnect.git
```
Or, if you already cloned the repo without submodules:
```bash
git submodule update --init --recursive
```
If you build from the release source tarball (`globalprotect-openconnect-${version}.tar.gz`), the vendored sources are already included, so you do not need the submodule step.
### Prerequisites
- [Install Rust 1.75 or later](https://www.rust-lang.org/tools/install)
- Install Tauri dependencies: https://tauri.app/v1/guides/getting-started/prerequisites/#setting-up-linux
- Install `perl` and `jq`
- Install `openconnect >= 8.20` and `libopenconnect-dev` (or `openconnect-devel` on RPM-based distributions)
- Install `make`, `pkg-config`, `autoconf`, `automake`, `libtool`, `patch`, `perl`, and `jq`
- Install development libraries for `gnutls`, `zlib`, `lz4`, `p11-kit`, `nettle`, `gmp`, and `openssl`
- Install `pkexec`, `gnome-keyring` (or `pam_kwallet` on KDE)
- Install `nodejs` and `pnpm` (optional only if you downloaded the source tarball from the release page and run with the `BUILD_FE=0` flag, see below)
- Install `nodejs` and `pnpm` if you are building from a git checkout
- Install `libxml2` development headers if you want to link against the system libxml2
On Debian/Ubuntu, that usually means:
```bash
sudo apt-get install \
autoconf automake libtool patch pkg-config jq make perl \
zlib1g-dev liblz4-dev libp11-kit-dev nettle-dev libgnutls28-dev libgmp-dev libssl-dev libxml2-dev \
libsecret-1-dev libayatana-appindicator3-dev libwebkit2gtk-4.0-dev \
gnome-keyring
```
On RHEL 9 / Rocky Linux 9 / AlmaLinux 9 / CentOS Stream 9, that usually means:
```bash
sudo dnf install \
autoconf automake libtool patch pkgconf-pkg-config jq make perl gcc-c++ \
zlib-devel lz4-devel p11-kit-devel nettle-devel gnutls-devel gmp-devel openssl-devel libxml2-devel \
libsecret libappindicator-gtk3 webkit2gtk4.0-devel
```
If your distro uses different package names, check `packaging/deb/control.in` and `packaging/rpm/globalprotect-openconnect.spec.in` for the dependency lists used by the project packaging.
### Build
1. Download the source code tarball from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Choose `globalprotect-openconnect-${version}.tar.gz`.
2. Extract the tarball with `tar -xzf globalprotect-openconnect-${version}.tar.gz`.
3. Enter the source directory and run `make build BUILD_FE=0` to build the client.
3. Run `sudo make install` to install the client. (Note, `DESTDIR` is not supported)
#### From a git checkout
Use the default build if you have `nodejs` and `pnpm` installed:
```bash
make build
sudo make install
```
#### From the release source tarball
The release source tarball already includes the generated frontend assets, so you can skip the frontend build:
```bash
tar -xzf globalprotect-openconnect-${version}.tar.gz
cd globalprotect-openconnect-${version}
make build BUILD_FE=0
sudo make install
```
#### Build with vendored libxml2
By default, the build links against the system `libxml2`.
If you also want to build libxml2 from the vendored source, use:
```bash
make build LIBXML2_STATIC=1
```
Or, when building from the release tarball:
```bash
make build BUILD_FE=0 LIBXML2_STATIC=1
```
## FAQ
+9 -2
View File
@@ -73,7 +73,9 @@ struct Cli {
#[arg(
long,
help = "The browser to use for authentication, e.g., `default`, `firefox`, `chrome`, `chromium`, or the path to the browser executable"
help = "The browser to use for authentication, e.g., `default`, `firefox`, `chrome`, `chromium`, `remote`, or the path to the browser executable. Use `remote` for headless servers",
default_missing_value = "default",
num_args=0..=1
)]
browser: Option<String>,
}
@@ -104,7 +106,12 @@ impl Cli {
};
if let Some(browser_auth) = browser_auth {
browser_auth.authenticate()?;
if let Some(auth_data) = browser_auth.authenticate()? {
info!("Authentication completed");
println!("{}", json!(SamlAuthResult::Success(auth_data)));
return Ok(());
}
info!("Please continue the authentication process in the default browser");
+5 -1
View File
@@ -10,15 +10,19 @@ common = { path = "../../crates/common" }
gpapi = { path = "../../crates/gpapi", features = ["clap"] }
openconnect = { path = "../../crates/openconnect" }
anyhow.workspace = true
askama = "0.12"
chrono = "0.4"
clap.workspace = true
env_logger.workspace = true
inquire = "0.6.2"
log.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
sysinfo.workspace = true
serde_json.workspace = true
serde_urlencoded.workspace = true
whoami.workspace = true
tempfile.workspace = true
reqwest.workspace = true
directories = "5.0"
compile-time.workspace = true
xmltree = "0.11"
+11 -4
View File
@@ -7,7 +7,8 @@ use tempfile::NamedTempFile;
use crate::{
connect::{ConnectArgs, ConnectHandler},
disconnect::DisconnectHandler,
disconnect::{DisconnectArgs, DisconnectHandler},
hip::{HipArgs, HipHandler},
launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
};
@@ -23,9 +24,11 @@ enum CliCommand {
#[command(about = "Connect to a portal server")]
Connect(Box<ConnectArgs>),
#[command(about = "Disconnect from the server")]
Disconnect,
Disconnect(DisconnectArgs),
#[command(about = "Launch the GUI")]
LaunchGui(LaunchGuiArgs),
#[command(about = "Generate HIP report")]
Hip(HipArgs),
}
#[derive(Parser)]
@@ -50,7 +53,10 @@ struct Cli {
#[command(subcommand)]
command: CliCommand,
#[arg(long, help = "Uses extended compatibility mode for OpenSSL operations to support a broader range of systems and formats.")]
#[arg(
long,
help = "Uses extended compatibility mode for OpenSSL operations to support a broader range of systems and formats."
)]
fix_openssl: bool,
#[arg(long, help = "Ignore the TLS errors")]
ignore_tls_errors: bool,
@@ -81,8 +87,9 @@ impl Cli {
match &self.command {
CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await,
CliCommand::Disconnect => DisconnectHandler::new().handle(),
CliCommand::Disconnect(args) => DisconnectHandler::new(args).handle().await,
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
CliCommand::Hip(args) => HipHandler::new(args).handle().await,
}
}
}
+15 -5
View File
@@ -84,10 +84,10 @@ pub(crate) struct ConnectArgs {
#[arg(long, default_value = GP_USER_AGENT, help = "The user agent to use")]
user_agent: String,
#[arg(long, default_value = "Linux")]
#[arg(long, value_enum, default_value_t = ConnectArgs::default_os())]
os: Os,
#[arg(long)]
#[arg(long, help = "If not specified, it will be computed based on the --os option")]
os_version: Option<String>,
#[arg(long, help = "Disable DTLS and ESP")]
@@ -104,15 +104,25 @@ pub(crate) struct ConnectArgs {
#[arg(
long,
help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, or the path to the browser executable"
help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, `remote`, or the path to the browser executable. Use `remote` for headless servers",
default_missing_value = "default",
num_args=0..=1
)]
browser: Option<String>,
}
impl ConnectArgs {
fn default_os() -> Os {
if cfg!(target_os = "macos") {
Os::Mac
} else {
Os::Linux
}
}
fn os_version(&self) -> String {
if let Some(os_version) = &self.os_version {
return os_version.to_owned();
if let Some(os_version) = self.os_version.as_deref() {
return os_version.to_string();
}
match self.os {
+52 -20
View File
@@ -1,31 +1,63 @@
use crate::GP_CLIENT_LOCK_FILE;
use clap::Args;
use gpapi::utils::lock_file::gpservice_lock_info;
use log::{info, warn};
use std::fs;
use sysinfo::{Pid, ProcessExt, Signal, System, SystemExt};
use std::{fs, str::FromStr, thread, time::Duration};
use sysinfo::{Pid, Signal, System};
pub(crate) struct DisconnectHandler;
#[derive(Args)]
pub struct DisconnectArgs {
#[arg(
long,
required = false,
help = "The time in seconds to wait for the VPN connection to disconnect"
)]
wait: Option<u64>,
}
impl DisconnectHandler {
pub(crate) fn new() -> Self {
Self
pub struct DisconnectHandler<'a> {
args: &'a DisconnectArgs,
}
impl<'a> DisconnectHandler<'a> {
pub fn new(args: &'a DisconnectArgs) -> Self {
Self { args }
}
pub(crate) fn handle(&self) -> anyhow::Result<()> {
if fs::metadata(GP_CLIENT_LOCK_FILE).is_err() {
warn!("PID file not found, maybe the client is not running");
return Ok(());
pub async fn handle(&self) -> anyhow::Result<()> {
// Try to disconnect the CLI client
if let Ok(c) = fs::read_to_string(GP_CLIENT_LOCK_FILE) {
send_signal(c.trim(), Signal::Interrupt).unwrap_or_else(|err| {
warn!("Failed to send signal to client: {}", err);
});
};
// Try to disconnect the GUI service
if let Ok(c) = gpservice_lock_info().await {
send_signal(&c.pid.to_string(), Signal::User1).unwrap_or_else(|err| {
warn!("Failed to send signal to service: {}", err);
});
};
// sleep, to give the client and service time to disconnect
if let Some(wait) = self.args.wait {
thread::sleep(Duration::from_secs(wait));
}
let pid = fs::read_to_string(GP_CLIENT_LOCK_FILE)?;
let pid = pid.trim().parse::<usize>()?;
let s = System::new_all();
if let Some(process) = s.process(Pid::from(pid)) {
info!("Found process {}, killing...", pid);
if process.kill_with(Signal::Interrupt).is_none() {
warn!("Failed to kill process {}", pid);
}
}
Ok(())
}
}
fn send_signal(pid: &str, signal: Signal) -> anyhow::Result<()> {
let s = System::new_all();
let pid = Pid::from_str(pid)?;
if let Some(process) = s.process(pid) {
info!("Found process {}, sending signal...", pid);
if process.kill_with(signal).is_none() {
warn!("Failed to kill process {}", pid);
}
}
Ok(())
}
+258
View File
@@ -0,0 +1,258 @@
use askama::Template;
use clap::Args;
use gpapi::{clap::args::Os, utils::host_utils};
use log::debug;
use std::{collections::HashMap, env};
use xmltree::Element;
#[derive(Template)]
#[template(path = "hip_report.xml")]
struct HipReportTemplate<'a> {
client_version: &'a str,
generate_time: String,
day: String,
month: String,
year: String,
user_name: &'a str,
host_info: HostInfo<'a>,
md5: &'a str,
}
struct HostInfo<'a> {
os_vendor: &'a str,
os_version: &'a str,
host_id: String,
host_name: String,
software_version: &'a str,
domain: String,
network_interfaces: Vec<NetworkInterface>,
}
impl<'a> HostInfo<'a> {
fn default_ipv4(&self) -> &str {
self
.network_interfaces
.first()
.and_then(|iface| iface.ipv4.as_deref())
.unwrap_or_default()
}
fn default_ipv6(&self) -> &str {
self
.network_interfaces
.first()
.and_then(|iface| iface.ipv6.as_deref())
.unwrap_or_default()
}
}
#[derive(Clone)]
struct NetworkInterface {
name: String,
description: String,
mac_address: Option<String>,
ipv4: Option<String>,
ipv6: Option<String>,
}
impl NetworkInterface {
fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
Self {
name: name.into(),
description: description.into(),
mac_address: None,
ipv4: None,
ipv6: None,
}
}
fn with_ipv4(mut self, ipv4: Option<String>) -> Self {
self.ipv4 = ipv4;
self
}
fn with_ipv6(mut self, ipv6: Option<String>) -> Self {
self.ipv6 = ipv6;
self
}
}
#[derive(Args)]
pub(crate) struct HipArgs {
#[arg(
long,
help = "The GP client version, defaults to APP_VERSION or the packaged version"
)]
client_version: Option<String>,
#[arg(long, value_enum, default_value_t = HipArgs::default_os(), help = "The client OS")]
client_os: Os,
#[arg(long, help = "The OS version string, defaults to a computed value for the target OS")]
os_version: Option<String>,
#[arg(long, help = "The authentication cookie")]
cookie: String,
#[arg(long, help = "The client IPv4 address")]
client_ip: Option<String>,
#[arg(long, help = "The client IPv6 address")]
client_ipv6: Option<String>,
#[arg(long, help = "The MD5 digest to encode into the HIP report")]
md5: String,
}
impl HipArgs {
fn default_os() -> Os {
if cfg!(target_os = "macos") {
Os::Mac
} else if cfg!(target_os = "windows") {
Os::Windows
} else {
Os::Linux
}
}
fn client_version(&self) -> String {
self
.client_version
.clone()
.or_else(|| env::var("APP_VERSION").ok())
.unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string())
}
fn os_version(&self) -> String {
self.os_version.clone().unwrap_or_else(|| match self.client_os {
Os::Linux => host_utils::get_linux_os_string().to_string(),
Os::Windows => host_utils::get_windows_os_string().to_string(),
Os::Mac => host_utils::get_macos_os_string().to_string(),
})
}
}
pub(crate) struct HipHandler<'a> {
args: &'a HipArgs,
}
impl<'a> HipHandler<'a> {
pub(crate) fn new(args: &'a HipArgs) -> Self {
Self { args }
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
let cookie_params = self.parse_cookie();
let report = self.generate_hip_report(&cookie_params)?;
debug!("Generated HIP report:\n{}", report);
println!("{}", report);
Ok(())
}
fn parse_cookie(&self) -> HashMap<String, String> {
serde_urlencoded::from_str(&self.args.cookie).unwrap_or_default()
}
fn generate_hip_report(&self, cookie_params: &HashMap<String, String>) -> anyhow::Result<String> {
let (generate_time, day, month, year) = get_current_time_components();
let client_version = self.args.client_version();
let os_version = self.args.os_version();
let user_name = cookie_params.get("user").map(|value| value.as_str()).unwrap_or("");
let host_info = self.collect_host_info(cookie_params, &os_version);
let template = HipReportTemplate {
client_version: &client_version,
generate_time,
day,
month,
year,
user_name,
host_info,
md5: &self.args.md5,
};
format_xml(&template.render()?)
}
fn collect_host_info<'b>(&'b self, cookie_params: &'b HashMap<String, String>, os_version: &'b str) -> HostInfo<'b> {
let domain = cookie_params.get("domain").cloned().unwrap_or_default();
let ipv4 = self
.args
.client_ip
.clone()
.or_else(|| cookie_params.get("preferred-ip").cloned());
let ipv6 = self
.args
.client_ipv6
.clone()
.or_else(|| cookie_params.get("preferred-ipv6").cloned());
match self.args.client_os {
Os::Linux => HostInfo {
os_vendor: "Linux",
os_version,
host_id: host_utils::derive_uuid(&["linux"]),
host_name: whoami::devicename(),
software_version: "",
domain,
network_interfaces: vec![NetworkInterface::new("enp1s0f0", "enp1s0f0")
.with_ipv4(ipv4)
.with_ipv6(ipv6)],
},
Os::Mac => HostInfo {
os_vendor: "Apple",
os_version,
host_id: host_utils::get_machine_id().to_string(),
host_name: whoami::devicename(),
software_version: host_utils::get_macos_version(),
domain,
network_interfaces: vec![NetworkInterface::new("en0", "en0").with_ipv4(ipv4).with_ipv6(ipv6)],
},
Os::Windows => {
let iface = NetworkInterface::new(
format!("{{{}}}", host_utils::derive_uuid(&["pangp"]).to_uppercase()),
"PANGP Virtual Ethernet Adapter Secure",
)
.with_ipv4(ipv4)
.with_ipv6(ipv6);
let loopback = NetworkInterface {
name: iface.name.clone(),
description: "Software Loopback Interface 1".to_string(),
mac_address: Some(String::new()),
ipv4: Some("127.0.0.1".to_string()),
ipv6: Some("::1".to_string()),
};
HostInfo {
os_vendor: "Microsoft",
os_version,
host_id: host_utils::get_machine_id().to_string(),
host_name: whoami::devicename(),
software_version: host_utils::get_windows_version(),
domain,
network_interfaces: vec![iface, loopback],
}
}
}
}
}
fn get_current_time_components() -> (String, String, String, String) {
let now = chrono::Local::now();
(
now.format("%m/%d/%Y %H:%M:%S").to_string(),
now.format("%d").to_string(),
now.format("%m").to_string(),
now.format("%Y").to_string(),
)
}
fn format_xml(xml_str: &str) -> anyhow::Result<String> {
let xml = Element::parse(xml_str.as_bytes())?;
let mut xml_buf = Vec::new();
xml.write_with_config(&mut xml_buf, xmltree::EmitterConfig::new().perform_indent(true))?;
Ok(String::from_utf8(xml_buf)?)
}
+1
View File
@@ -1,6 +1,7 @@
mod cli;
mod connect;
mod disconnect;
mod hip;
mod launch_gui;
pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock";
+275
View File
@@ -0,0 +1,275 @@
<?xml version="1.0" encoding="UTF-8"?>
<hip-report name="hip-report">
<md5-sum>{{ md5 }}</md5-sum>
<user-name>{{ user_name }}</user-name>
<domain>{{ host_info.domain }}.internal</domain>
<host-name>{{ host_info.host_name }}</host-name>
<host-id>{{ host_info.host_id }}</host-id>
<ip-address>{{ host_info.default_ipv4() }}</ip-address>
<ipv6-address>{{ host_info.default_ipv6() }}</ipv6-address>
<generate-time>{{ generate_time }}</generate-time>
<hip-report-version>4</hip-report-version>
<categories>
<entry name="host-info">
<client-version>{{ client_version }}</client-version>
<os>{{ host_info.os_version }}</os>
<os-vendor>{{ host_info.os_vendor }}</os-vendor>
<domain>{{ host_info.domain }}.internal</domain>
<host-name>{{ host_info.host_name }}</host-name>
<host-id>{{ host_info.host_id }}</host-id>
<network-interface>
{% for iface in host_info.network_interfaces.iter() -%}
<entry name="{{ iface.name }}">
<description>{{ iface.description }}</description>
{% if let Some(mac) = iface.mac_address -%}
<mac-address>{{ mac }}</mac-address>
{% endif -%}
{% if let Some(ipv4) = iface.ipv4 -%}
<ip-address>
<entry name="{{ ipv4 }}"/>
</ip-address>
{% endif -%}
{% if let Some(ipv6) = iface.ipv6 -%}
<ipv6-address>
<entry name="{{ ipv6 }}"/>
</ipv6-address>
{% endif -%}
</entry>
{% endfor -%}
</network-interface>
</entry>
{% if host_info.os_vendor == "Microsoft" -%}
<entry name="antivirus">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="1" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="1" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>no</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="anti-spyware">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="2" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="2" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>no</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-backup">
<list>
<entry>
<ProductInfo>
<Prod name="Windows Backup and Restore" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<last-backup-time>n/a</last-backup-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod name="Windows Drive Encryption" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<drives>
<entry>
<drive-name>C:\\</drive-name>
<enc-state>full</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
<entry>
<ProductInfo>
<Prod name="Microsoft Windows Firewall" version="10.0.22621.4830" vendor="Microsoft Corp.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee ePolicy Orchestrator Agent" version="5.0.5.658" vendor="McAfee, Inc.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Microsoft Windows Update Agent" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches/>
</entry>
{% else if host_info.os_vendor == "Apple" -%}
<entry name="anti-malware">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Xprotect" version="2167" defver="235000000000000" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Gatekeeper" version="{{ host_info.software_version }}" defver="" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-backup">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Time Machine" version="1.3"/>
<last-backup-time>n/a</last-backup-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="FileVault" version="{{ host_info.software_version }}"/>
<drives>
<entry>
<drive-name>Macintosh HD</drive-name>
<enc-state>encrypted</enc-state>
</entry>
<entry>
<drive-name>Data</drive-name>
<enc-state>encrypted</enc-state>
</entry>
<entry>
<drive-name>All</drive-name>
<enc-state>encrypted</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Mac OS X Builtin Firewall" version="{{ host_info.software_version }}"/>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod vendor="OpenBSD" name="Packet Filter" version="{{ host_info.software_version }}"/>
<is-enabled>no</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Software Update" version="3.0"/>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches>
</missing-patches>
</entry>
{% else if host_info.os_vendor == "Linux" -%}
<entry name="anti-malware">
<list/>
</entry>
<entry name="disk-backup">
<list/>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod name="cryptsetup" version="2.3.3" vendor="GitLab Inc.">
</Prod>
<drives>
<entry>
<drive-name>/</drive-name>
<enc-state>encrypted</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
<entry>
<ProductInfo>
<Prod name="IPTables" version="1.8.4" vendor="IPTables">
</Prod>
<is-enabled>no</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="nftables" version="0.9.3" vendor="The Netfilter Project">
</Prod>
<is-enabled>n/a</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod name="Apt" version="2.0.11" vendor="Canonical Ltd.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches>
</missing-patches>
</entry>
{% endif -%}
</categories>
</hip-report>
+1 -1
View File
@@ -9,7 +9,7 @@ gpapi = { path = "../../crates/gpapi" }
openconnect = { path = "../../crates/openconnect" }
clap.workspace = true
anyhow.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
tokio-util.workspace = true
axum = { workspace = true, features = ["ws"] }
futures.workspace = true
+66 -9
View File
@@ -30,7 +30,8 @@ struct Cli {
impl Cli {
async fn run(&mut self, redaction: Arc<Redaction>) -> anyhow::Result<()> {
let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE));
let pid = std::process::id();
let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE, pid));
if lock_file.check_health().await {
bail!("Another instance of the service is already running");
@@ -48,9 +49,17 @@ impl Cli {
let (shutdown_tx, mut shutdown_rx) = mpsc::channel::<()>(4);
let shutdown_tx_clone = shutdown_tx.clone();
let vpn_task_token = vpn_task.cancel_token();
let vpn_task_cancel_token = vpn_task.cancel_token();
let server_token = ws_server.cancel_token();
#[cfg(unix)]
{
let vpn_ctx = vpn_task.context();
let ws_ctx = ws_server.context();
tokio::spawn(async move { signals::handle_signals(vpn_ctx, ws_ctx).await });
}
let vpn_task_handle = tokio::spawn(async move { vpn_task.start(server_token).await });
let ws_server_handle = tokio::spawn(async move { ws_server.start(shutdown_tx_clone).await });
@@ -74,15 +83,15 @@ impl Cli {
}
tokio::select! {
_ = shutdown_signal() => {
info!("Shutdown signal received");
}
_ = shutdown_rx.recv() => {
info!("Shutdown request received, shutting down");
}
_ = shutdown_signal() => {
info!("Shutdown signal received");
}
_ = shutdown_rx.recv() => {
info!("Shutdown request received, shutting down");
}
}
vpn_task_token.cancel();
vpn_task_cancel_token.cancel();
let _ = tokio::join!(vpn_task_handle, ws_server_handle);
lock_file.unlock()?;
@@ -125,6 +134,54 @@ fn init_logger() -> Arc<Redaction> {
redaction
}
#[cfg(unix)]
mod signals {
use std::sync::Arc;
use log::{info, warn};
use crate::vpn_task::VpnTaskContext;
use crate::ws_server::WsServerContext;
const DISCONNECTED_PID_FILE: &str = "/tmp/gpservice_disconnected.pid";
pub(crate) async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) {
use gpapi::service::event::WsEvent;
use tokio::signal::unix::{signal, Signal, SignalKind};
let (mut user_sig1, mut user_sig2) = match || -> anyhow::Result<(Signal, Signal)> {
let user_sig1 = signal(SignalKind::user_defined1())?;
let user_sig2 = signal(SignalKind::user_defined2())?;
Ok((user_sig1, user_sig2))
}() {
Ok(signals) => signals,
Err(err) => {
warn!("Failed to create signal: {}", err);
return;
}
};
loop {
tokio::select! {
_ = user_sig1.recv() => {
info!("Received SIGUSR1 signal");
if vpn_ctx.disconnect().await {
// Write the PID to a dedicated file to indicate that the VPN task is disconnected via SIGUSR1
let pid = std::process::id();
if let Err(err) = tokio::fs::write(DISCONNECTED_PID_FILE, pid.to_string()).await {
warn!("Failed to write PID to file: {}", err);
}
}
}
_ = user_sig2.recv() => {
info!("Received SIGUSR2 signal");
ws_ctx.send_event(WsEvent::ResumeConnection).await;
}
}
}
}
}
async fn launch_gui(envs: Option<HashMap<String, String>>, api_key: Vec<u8>, mut minimized: bool) {
loop {
let gui_launcher = GuiLauncher::new(env!("CARGO_PKG_VERSION"), &api_key)
+1 -1
View File
@@ -43,7 +43,7 @@ pub(crate) async fn auth_data(State(ctx): State<Arc<WsServerContext>>, body: Str
ctx.send_event(WsEvent::AuthData(body)).await;
}
pub async fn update_gui(State(ctx): State<Arc<WsServerContext>>, body: Bytes) -> Result<(), StatusCode> {
pub(crate) async fn update_gui(State(ctx): State<Arc<WsServerContext>>, body: Bytes) -> Result<(), StatusCode> {
let payload = match ctx.decrypt::<UpdateGuiRequest>(body.to_vec()) {
Ok(payload) => payload,
Err(err) => {
+9 -1
View File
@@ -87,7 +87,7 @@ impl VpnTaskContext {
});
}
pub async fn disconnect(&self) {
pub async fn disconnect(&self) -> bool {
if let Some(disconnect_rx) = self.disconnect_rx.write().await.take() {
info!("Disconnecting VPN...");
if let Some(vpn) = self.vpn_handle.read().await.as_ref() {
@@ -98,9 +98,13 @@ impl VpnTaskContext {
// Wait for the VPN to be disconnected
disconnect_rx.await.ok();
info!("VPN disconnected");
true
} else {
info!("VPN is not connected, skip disconnect");
self.vpn_state_tx.send(VpnState::Disconnected).ok();
false
}
}
}
@@ -143,6 +147,10 @@ impl VpnTask {
server_cancel_token.cancel();
}
pub fn context(&self) -> Arc<VpnTaskContext> {
return Arc::clone(&self.ctx);
}
async fn recv(&mut self) {
while let Some(req) = self.ws_req_rx.recv().await {
tokio::spawn(process_ws_req(req, self.ctx.clone()));
+6 -2
View File
@@ -113,6 +113,10 @@ impl WsServer {
}
}
pub fn context(&self) -> Arc<WsServerContext> {
Arc::clone(&self.ctx)
}
pub fn cancel_token(&self) -> CancellationToken {
self.cancel_token.clone()
}
@@ -124,7 +128,7 @@ impl WsServer {
warn!("Failed to start WS server: {}", err);
let _ = shutdown_tx.send(()).await;
return;
},
}
};
tokio::select! {
@@ -149,7 +153,7 @@ impl WsServer {
info!("WS server listening on port: {}", port);
self.lock_file.lock(port.to_string())?;
self.lock_file.lock(&port.to_string())?;
Ok(listener)
}
+15
View File
@@ -1,5 +1,20 @@
# Changelog
## 2.3.13 - 2026-04-19
- Backport the vendored OpenConnect/libxml2 runtime from newer releases, including the updated HIP flow and bundled Linux helper scripts.
- CLI/browser authentication: support `--browser remote` for headless servers, restore the browser flag default behavior, and improve external browser auth handling.
- Support VPN portals and gateways running on custom ports (fix [#404](https://github.com/yuezk/GlobalProtect-openconnect/issues/404)).
- Improve `2.3.x` build and packaging compatibility on current Linux toolchains and Debian/Ubuntu builder environments.
## 2.3.11 - 2025-01-21
- Update minimal Rust version to 1.71.1, so that the PPA can be built on Ubuntu 18.04.
## 2.3.10 - 2025-01-20
- Disconnect the VPN when sleep (fix [#166](https://github.com/yuezk/GlobalProtect-openconnect/issues/166), [#267](https://github.com/yuezk/GlobalProtect-openconnect/issues/267))
## 2.3.9 - 2024-11-02
- Enhance the OpenSSL compatibility mode (fix [#437](https://github.com/yuezk/GlobalProtect-openconnect/issues/437))
+10 -2
View File
@@ -2,22 +2,30 @@ use std::{io, path::Path};
use is_executable::IsExecutable;
const VPNC_SCRIPT_LOCATIONS: [&str; 6] = [
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",
"/usr/sbin/vpnc-script",
"/etc/vpnc/vpnc-script",
"/etc/openconnect/vpnc-script",
#[cfg(target_os = "macos")]
"/opt/homebrew/etc/vpnc/vpnc-script",
];
const CSD_WRAPPER_LOCATIONS: [&str; 3] = [
const CSD_WRAPPER_LOCATIONS: &[&str] = &[
"/usr/libexec/gpclient/hipreport.sh",
"/usr/lib/gpclient/hipreport.sh",
#[cfg(target_arch = "x86_64")]
"/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh",
#[cfg(target_arch = "aarch64")]
"/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh",
"/usr/lib/openconnect/hipreport.sh",
"/usr/libexec/openconnect/hipreport.sh",
#[cfg(target_os = "macos")]
"/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh",
];
fn find_executable(locations: &[&str]) -> Option<String> {
+10 -2
View File
@@ -12,12 +12,12 @@ log.workspace = true
reqwest.workspace = true
openssl.workspace = true
pem.workspace = true
roxmltree.workspace = true
xmltree.workspace = true
serde.workspace = true
specta.workspace = true
specta-macros.workspace = true
urlencoding.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["process", "signal", "macros"] }
serde_json.workspace = true
whoami.workspace = true
tempfile.workspace = true
@@ -31,12 +31,20 @@ serde_urlencoded.workspace = true
md5.workspace = true
sha256.workspace = true
which.workspace = true
machine-uid = "0.5"
uuid = { version = "1", features = ["v5"] }
# Pin the version of home because the latest version requires Rust 1.81
home = "=0.5.9"
tauri = { workspace = true, optional = true }
clap = { workspace = true, optional = true }
open = { version = "5", optional = true }
webbrowser = { version = "1", optional = true }
[target.'cfg(any(target_os="macos", target_os="windows"))'.dependencies]
os_info = { version = "3", default-features = false }
[features]
tauri = ["dep:tauri"]
clap = ["dep:clap"]
+13 -16
View File
@@ -2,9 +2,13 @@ use std::collections::HashMap;
use log::{info, warn};
use reqwest::Client;
use roxmltree::Document;
use xmltree::Element;
use crate::{gp_params::GpParams, process::hip_launcher::HipLauncher, utils::normalize_server};
use crate::{
gp_params::GpParams,
process::hip_launcher::HipLauncher,
utils::{normalize_server, xml::ElementExt},
};
struct HipReporter<'a> {
server: String,
@@ -65,16 +69,12 @@ impl HipReporter<'_> {
let res = self.client.post(&config_url).form(&params).send().await?;
let res_xml = res.error_for_status()?.text().await?;
let doc = Document::parse(&res_xml)?;
// Get <ip-address>
let ip = doc
.descendants()
.find(|n| n.has_tag_name("ip-address"))
.and_then(|n| n.text())
let root = Element::parse(res_xml.as_bytes())?;
let ip = root
.descendant_text("ip-address")
.ok_or_else(|| anyhow::anyhow!("ip-address not found"))?;
Ok(ip.to_string())
Ok(ip)
}
async fn check_hip(&self, client_ip: &str) -> anyhow::Result<bool> {
@@ -122,12 +122,9 @@ impl HipReporter<'_> {
}
fn is_hip_needed(res_xml: &str) -> anyhow::Result<bool> {
let doc = Document::parse(res_xml)?;
let hip_needed = doc
.descendants()
.find(|n| n.has_tag_name("hip-report-needed"))
.and_then(|n| n.text())
let root = Element::parse(res_xml.as_bytes())?;
let hip_needed = root
.descendant_text("hip-report-needed")
.ok_or_else(|| anyhow::anyhow!("hip-report-needed not found"))?;
Ok(hip_needed == "yes")
+9 -10
View File
@@ -1,14 +1,14 @@
use anyhow::bail;
use log::{info, warn};
use reqwest::Client;
use roxmltree::Document;
use urlencoding::encode;
use xmltree::Element;
use crate::{
credential::Credential,
error::PortalError,
gp_params::GpParams,
utils::{normalize_server, parse_gp_response, remove_url_scheme},
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
};
pub enum GatewayLogin {
@@ -52,18 +52,17 @@ pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParam
return Ok(GatewayLogin::Mfa(message, input_str));
}
let doc = Document::parse(&res)?;
let cookie = build_gateway_token(&doc, gp_params.computer())?;
let root = Element::parse(res.as_bytes())?;
let cookie = build_gateway_token(&root, gp_params.computer())?;
Ok(GatewayLogin::Cookie(cookie))
}
fn build_gateway_token(doc: &Document, computer: &str) -> anyhow::Result<String> {
let args = doc
.descendants()
.filter(|n| n.has_tag_name("argument"))
.map(|n| n.text().unwrap_or("").to_string())
fn build_gateway_token(root: &Element, computer: &str) -> anyhow::Result<String> {
let args = root
.descendants("argument")
.iter()
.map(|element| element.get_text().unwrap_or_default().to_string())
.collect::<Vec<_>>();
let params = [
+22 -25
View File
@@ -1,62 +1,59 @@
use log::info;
use roxmltree::Node;
use xmltree::Element;
use crate::utils::xml::NodeExt;
use crate::utils::xml::ElementExt;
use super::{Gateway, PriorityRule};
pub(crate) fn parse_gateways(node: &Node, prefer_internal: bool) -> Option<Vec<Gateway>> {
let node_gateways = node.find_descendant("gateways")?;
pub(crate) fn parse_gateways(root: &Element, prefer_internal: bool) -> Option<Vec<Gateway>> {
let node_gateways = root.descendant("gateways")?;
let internal_gateway_list = if prefer_internal {
info!("Try to parse the internal gateways...");
node_gateways.find_descendant("internal").and_then(|n| n.find_child("list"))
node_gateways.descendant("internal").and_then(|node| node.child("list"))
} else {
None
};
let gateway_list = internal_gateway_list.or_else(|| {
info!("Try to parse the external gateways...");
node_gateways.find_descendant("external").and_then(|n| n.find_child("list"))
node_gateways.descendant("external").and_then(|node| node.child("list"))
})?;
let gateways = gateway_list
.children()
.filter_map(|gateway_item| {
if !gateway_item.has_tag_name("entry") {
return None;
}
let address = gateway_item.attribute("name").unwrap_or_default().to_string();
let name = gateway_item.child_text("description").unwrap_or_default().to_string();
.children("entry")
.iter()
.map(|gateway_item| {
let address = gateway_item.attr("name").unwrap_or_default().to_string();
let name = gateway_item.child_text("description").unwrap_or_default();
let priority = gateway_item
.child_text("priority")
.and_then(|s| s.parse().ok())
.unwrap_or(u32::MAX);
let priority_rules = gateway_item
.find_child("priority-rule")
.map(|n| {
n.children()
.filter_map(|n| {
if !n.has_tag_name("entry") {
return None;
}
let name = n.attribute("name").unwrap_or_default().to_string();
let priority: u32 = n
.child("priority-rule")
.map(|node| {
node
.children("entry")
.iter()
.map(|entry| {
let name = entry.attr("name").unwrap_or_default().to_string();
let priority: u32 = entry
.child_text("priority")
.and_then(|s| s.parse().ok())
.unwrap_or(u32::MAX);
Some(PriorityRule { name, priority })
PriorityRule { name, priority }
})
.collect()
})
.unwrap_or_default();
Some(Gateway {
Gateway {
name,
address,
priority,
priority_rules,
})
}
})
.collect();
+8 -9
View File
@@ -2,16 +2,16 @@ use anyhow::bail;
use dns_lookup::lookup_addr;
use log::{debug, info, warn};
use reqwest::{Client, StatusCode};
use roxmltree::{Document, Node};
use serde::Serialize;
use specta::Type;
use xmltree::Element;
use crate::{
credential::{AuthCookieCredential, Credential},
error::PortalError,
gateway::{parse_gateways, Gateway},
gp_params::GpParams,
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::NodeExt},
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
};
#[derive(Debug, Serialize, Type)]
@@ -137,14 +137,13 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
debug!("Portal config response: {}", res_xml);
let doc = Document::parse(&res_xml).map_err(|e| PortalError::ConfigError(e.to_string()))?;
let root = doc.root();
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
let mut ihd_enabled = false;
let mut prefer_internal = false;
if let Some(ihd_node) = root.find_descendant("internal-host-detection") {
if let Some(ihd_node) = root.descendant("internal-host-detection") {
ihd_enabled = true;
prefer_internal = internal_host_detect(&ihd_node)
prefer_internal = internal_host_detect(ihd_node)
}
let mut gateways = parse_gateways(&root, prefer_internal).unwrap_or_else(|| {
@@ -164,16 +163,16 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
Ok(PortalConfig {
portal: server.to_string(),
auth_cookie: AuthCookieCredential::new(cred.username(), user_auth_cookie, prelogon_user_auth_cookie),
auth_cookie: AuthCookieCredential::new(cred.username(), &user_auth_cookie, &prelogon_user_auth_cookie),
config_cred: cred.clone(),
gateways,
config_digest: config_digest.map(|s| s.to_string()),
config_digest,
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
})
}
// Perform DNS lookup and compare the result with the expected hostname
fn internal_host_detect(node: &Node) -> bool {
fn internal_host_detect(node: &Element) -> bool {
let ip_info = [
(node.child_text("ip-address"), node.child_text("host")),
(node.child_text("ipv6-address"), node.child_text("ipv6-host")),
+20 -29
View File
@@ -1,14 +1,14 @@
use anyhow::{anyhow, bail};
use log::{info, warn};
use reqwest::{Client, StatusCode};
use roxmltree::Document;
use serde::Serialize;
use specta::Type;
use xmltree::Element;
use crate::{
error::PortalError,
gp_params::GpParams,
utils::{base64, normalize_server, parse_gp_response, xml::NodeExt},
utils::{base64, normalize_server, parse_gp_response, xml::ElementExt},
};
const REQUIRED_PARAMS: [&str; 8] = [
@@ -147,32 +147,30 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prel
}
fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
let doc = Document::parse(res_xml)?;
let root = doc.root();
let root = Element::parse(res_xml.as_bytes())?;
let status = root
.descendant_text("status")
.ok_or_else(|| anyhow::anyhow!("Prelogin response does not contain status element"))?;
// Check the status of the prelogin response
if status.to_uppercase() != "SUCCESS" {
let msg = root.descendant_text("msg").unwrap_or("Unknown error");
let msg = root
.descendant_text("msg")
.unwrap_or_else(|| "Unknown error".to_string());
bail!("{}", msg)
}
let region = root
.descendant_text("region")
.unwrap_or_else(|| {
info!("Prelogin response does not contain region element");
"Unknown"
})
.to_string();
let region = root.descendant_text("region").unwrap_or_else(|| {
info!("Prelogin response does not contain region element");
"Unknown".to_string()
});
let saml_method = root.descendant_text("saml-auth-method");
let saml_request = root.descendant_text("saml-request");
let saml_default_browser = root.descendant_text("saml-default-browser");
// Check if the prelogin response is SAML
if saml_method.is_some() && saml_request.is_some() {
let saml_request = base64::decode_to_string(saml_request.unwrap())?;
let saml_request = base64::decode_to_string(&saml_request.unwrap())?;
let support_default_browser = saml_default_browser.map(|s| s.to_lowercase() == "yes").unwrap_or(false);
let saml_prelogin = SamlPrelogin {
@@ -185,25 +183,18 @@ fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
return Ok(Prelogin::Saml(saml_prelogin));
}
let label_username = root
.descendant_text("username-label")
.unwrap_or_else(|| {
info!("Username label has no value, using default");
"Username"
})
.to_string();
let label_password = root
.descendant_text("password-label")
.unwrap_or_else(|| {
info!("Password label has no value, using default");
"Password"
})
.to_string();
let label_username = root.descendant_text("username-label").unwrap_or_else(|| {
info!("Username label has no value, using default");
"Username".to_string()
});
let label_password = root.descendant_text("password-label").unwrap_or_else(|| {
info!("Password label has no value, using default");
"Password".to_string()
});
let auth_message = root
.descendant_text("authentication-message")
.unwrap_or("Please enter the login credentials")
.to_string();
.unwrap_or_else(|| "Please enter the login credentials".to_string());
let standard_prelogin = StandardPrelogin {
region,
is_gateway,
@@ -1,8 +1,20 @@
use std::{borrow::Cow, env::temp_dir, fs, io::Write, os::unix::fs::PermissionsExt};
use std::{
borrow::Cow,
env::temp_dir,
fs,
io::{Read, Write},
net::{TcpListener, UdpSocket},
os::unix::fs::PermissionsExt,
thread,
};
use anyhow::bail;
use log::{info, warn};
use crate::auth::SamlAuthData;
const REMOTE_AUTH_PATH: &str = "/auth";
pub struct BrowserAuthenticator<'a> {
auth_request: &'a str,
browser: Option<&'a str>,
@@ -28,7 +40,14 @@ impl BrowserAuthenticator<'_> {
}
}
pub fn authenticate(&self) -> anyhow::Result<()> {
pub fn authenticate(&self) -> anyhow::Result<Option<SamlAuthData>> {
if self
.browser
.is_some_and(|browser| browser.eq_ignore_ascii_case("remote"))
{
return self.authenticate_remote();
}
let path = if self.auth_request.starts_with("http") {
Cow::Borrowed(self.auth_request)
} else {
@@ -60,7 +79,36 @@ impl BrowserAuthenticator<'_> {
webbrowser::open(path.as_ref())?;
}
Ok(())
Ok(None)
}
fn authenticate_remote(&self) -> anyhow::Result<Option<SamlAuthData>> {
let local_ip = detect_local_ip()?;
let listener = TcpListener::bind((local_ip.as_str(), 0))?;
let auth_url = format!("http://{}{}", listener.local_addr()?, REMOTE_AUTH_PATH);
let auth_request = self.auth_request.to_string();
thread::spawn(move || serve_auth_request(listener, auth_request));
info!(
r#"
==== Manual Authentication Required ====
Please open the following URL in your browser:
{}
After completing the authentication, please paste the authentication data back to this terminal.
(The data should start with "globalprotectcallback:...")
"#,
auth_url
);
let mut data = String::new();
std::io::stdin().read_line(&mut data)?;
Ok(Some(SamlAuthData::from_gpcallback(data.trim())?))
}
}
@@ -75,3 +123,90 @@ fn find_browser_path(browser: &str) -> String {
browser.into()
}
}
fn detect_local_ip() -> anyhow::Result<String> {
let socket = UdpSocket::bind("0.0.0.0:0")?;
socket.connect("1.1.1.1:80")?;
let ip = socket.local_addr()?.ip().to_string();
info!("Determined local IP address: {}", ip);
Ok(ip)
}
fn serve_auth_request(listener: TcpListener, auth_request: String) {
let Ok(addr) = listener.local_addr() else {
warn!("Failed to determine auth server address");
return;
};
let auth_url = format!("http://{}{}", addr, REMOTE_AUTH_PATH);
info!("Auth server started at: {}", auth_url);
for incoming in listener.incoming() {
let mut stream = match incoming {
Ok(stream) => stream,
Err(err) => {
warn!("Failed to accept auth request: {}", err);
continue;
}
};
let mut request = [0_u8; 4096];
let size = match stream.read(&mut request) {
Ok(size) => size,
Err(err) => {
warn!("Failed to read auth request: {}", err);
continue;
}
};
let request = String::from_utf8_lossy(&request[..size]);
let path = request
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.unwrap_or("/");
if path != REMOTE_AUTH_PATH {
let _ = write_response(&mut stream, "404 Not Found", "text/plain", "not found", None);
continue;
}
let response = if auth_request.starts_with("http") {
write_response(
&mut stream,
"302 Found",
"text/plain",
"redirect",
Some(("Location", auth_request.as_str())),
)
} else {
write_response(&mut stream, "200 OK", "text/html; charset=utf-8", &auth_request, None)
};
if let Err(err) = response {
warn!("Failed to write auth response: {}", err);
}
break;
}
}
fn write_response(
stream: &mut std::net::TcpStream,
status: &str,
content_type: &str,
body: &str,
extra_header: Option<(&str, &str)>,
) -> std::io::Result<()> {
write!(stream, "HTTP/1.1 {}\r\n", status)?;
write!(stream, "Content-Type: {}\r\n", content_type)?;
if let Some((name, value)) = extra_header {
write!(stream, "{}: {}\r\n", name, value)?;
}
write!(stream, "Content-Length: {}\r\n", body.len())?;
write!(stream, "Connection: close\r\n\r\n")?;
stream.write_all(body.as_bytes())?;
stream.flush()
}
+1
View File
@@ -9,4 +9,5 @@ pub enum WsEvent {
ActiveGui,
/// External authentication data
AuthData(String),
ResumeConnection,
}
+4 -5
View File
@@ -1,10 +1,9 @@
use tokio::fs;
use crate::GP_SERVICE_LOCK_FILE;
use super::lock_file::gpservice_lock_info;
async fn read_port() -> anyhow::Result<String> {
let port = fs::read_to_string(GP_SERVICE_LOCK_FILE).await?;
Ok(port.trim().to_string())
let lock_info = gpservice_lock_info().await?;
Ok(lock_info.port.to_string())
}
pub async fn http_endpoint() -> anyhow::Result<String> {
+99
View File
@@ -0,0 +1,99 @@
use std::sync::OnceLock;
const DEFAULT_MACOS_VERSION: &str = "13.4.0";
#[cfg(not(target_os = "linux"))]
const DEFAULT_LINUX_DISTRO: &str = "Ubuntu 24.04.3 LTS";
#[cfg(not(target_os = "windows"))]
const DEFAULT_WINDOWS_DISTRO: &str = "Windows 11 Pro";
const DEFAULT_WINDOWS_VERSION: &str = "10.0.22631.0";
const DEFAULT_MACHINE_ID: &str = "DEADBEEF-DEAD-BEEF-DEAD-BEEFDEADBEEF";
static MACHINE_ID: OnceLock<&'static str> = OnceLock::new();
static MACOS_VERSION: OnceLock<&'static str> = OnceLock::new();
static MACOS_OS_STRING: OnceLock<String> = OnceLock::new();
static LINUX_OS_STRING: OnceLock<String> = OnceLock::new();
static WINDOWS_VERSION: OnceLock<&'static str> = OnceLock::new();
static WINDOWS_OS_STRING: OnceLock<String> = OnceLock::new();
pub fn get_macos_version() -> &'static str {
MACOS_VERSION.get_or_init(|| {
#[cfg(target_os = "macos")]
{
match os_info::get().version() {
os_info::Version::Unknown => DEFAULT_MACOS_VERSION,
version => Box::leak(version.to_string().into_boxed_str()),
}
}
#[cfg(not(target_os = "macos"))]
DEFAULT_MACOS_VERSION
})
}
pub fn get_macos_os_string() -> &'static str {
MACOS_OS_STRING.get_or_init(|| format!("Apple Mac OS X {}", get_macos_version()))
}
pub fn get_linux_os_string() -> &'static str {
LINUX_OS_STRING.get_or_init(|| {
#[cfg(target_os = "linux")]
{
format!("Linux {}", whoami::distro())
}
#[cfg(not(target_os = "linux"))]
{
format!("Linux {}", DEFAULT_LINUX_DISTRO)
}
})
}
pub fn get_windows_version() -> &'static str {
WINDOWS_VERSION.get_or_init(|| {
#[cfg(target_os = "windows")]
{
match os_info::get().version() {
os_info::Version::Unknown => DEFAULT_WINDOWS_VERSION,
version => Box::leak(format!("{}.0", version).into_boxed_str()),
}
}
#[cfg(not(target_os = "windows"))]
DEFAULT_WINDOWS_VERSION
})
}
pub fn get_windows_os_string() -> &'static str {
WINDOWS_OS_STRING.get_or_init(|| {
#[cfg(target_os = "windows")]
{
let edition = os_info::get()
.edition()
.map(|edition| edition.to_string())
.unwrap_or_else(|| whoami::distro());
format!("Microsoft {} , 64-bit", edition)
}
#[cfg(not(target_os = "windows"))]
{
format!("Microsoft {} , 64-bit", DEFAULT_WINDOWS_DISTRO)
}
})
}
pub fn get_machine_id() -> &'static str {
MACHINE_ID.get_or_init(|| {
machine_uid::get()
.map(|id| Box::leak(id.to_string().into_boxed_str()) as &'static str)
.unwrap_or(DEFAULT_MACHINE_ID)
})
}
pub fn derive_uuid(seeds: &[&str]) -> String {
use uuid::Uuid;
let namespace = Uuid::NAMESPACE_DNS;
let name = format!("{}-{}", get_machine_id(), seeds.join("-"));
Uuid::new_v5(&namespace, name.as_bytes()).hyphenated().to_string()
}
+92 -3
View File
@@ -1,19 +1,24 @@
use std::path::PathBuf;
use thiserror::Error;
use tokio::fs;
pub struct LockFile {
path: PathBuf,
pid: u32,
}
impl LockFile {
pub fn new<P: Into<PathBuf>>(path: P) -> Self {
Self { path: path.into() }
pub fn new<P: Into<PathBuf>>(path: P, pid: u32) -> Self {
Self { path: path.into(), pid }
}
pub fn exists(&self) -> bool {
self.path.exists()
}
pub fn lock(&self, content: impl AsRef<[u8]>) -> anyhow::Result<()> {
pub fn lock(&self, content: &str) -> anyhow::Result<()> {
let content = format!("{}:{}", self.pid, content);
std::fs::write(&self.path, content)?;
Ok(())
}
@@ -37,3 +42,87 @@ impl LockFile {
}
}
}
#[derive(Error, Debug)]
pub enum LockFileError {
#[error("Failed to read lock file: {0}")]
IoError(#[from] std::io::Error),
#[error("Invalid lock file format: expected 'pid:port'")]
InvalidFormat,
#[error("Invalid PID value: {0}")]
InvalidPid(std::num::ParseIntError),
#[error("Invalid port value: {0}")]
InvalidPort(std::num::ParseIntError),
}
pub struct LockInfo {
pub pid: u32,
pub port: u32,
}
impl LockInfo {
async fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self, LockFileError> {
let content = fs::read_to_string(path).await?;
Self::parse(&content)
}
fn parse(content: &str) -> Result<Self, LockFileError> {
let mut parts = content.trim().split(':');
let pid = parts
.next()
.ok_or(LockFileError::InvalidFormat)?
.parse()
.map_err(LockFileError::InvalidPid)?;
let port = parts
.next()
.ok_or(LockFileError::InvalidFormat)?
.parse()
.map_err(LockFileError::InvalidPort)?;
// Ensure there are no extra parts after pid:port
if parts.next().is_some() {
return Err(LockFileError::InvalidFormat);
}
Ok(Self { pid, port })
}
}
pub async fn gpservice_lock_info() -> Result<LockInfo, LockFileError> {
LockInfo::from_file(crate::GP_SERVICE_LOCK_FILE).await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_valid_input() {
let info = LockInfo::parse("1234:8080").unwrap();
assert_eq!(info.pid, 1234);
assert_eq!(info.port, 8080);
}
#[test]
fn test_parse_invalid_format() {
assert!(matches!(
LockInfo::parse("123:456:789"),
Err(LockFileError::InvalidFormat)
));
}
#[test]
fn test_parse_invalid_numbers() {
assert!(matches!(LockInfo::parse("abc:8080"), Err(LockFileError::InvalidPid(_))));
assert!(matches!(
LockInfo::parse("1234:abc"),
Err(LockFileError::InvalidPort(_))
));
}
}
+20
View File
@@ -5,6 +5,7 @@ pub mod checksum;
pub mod crypto;
pub mod endpoint;
pub mod env_file;
pub mod host_utils;
pub mod lock_file;
pub mod openssl;
pub mod redact;
@@ -93,3 +94,22 @@ async fn parse_gp_error(res: Response) -> (String, String) {
(reason, res)
}
#[cfg(test)]
mod tests {
use super::normalize_server;
#[test]
fn normalize_server_preserves_custom_port() {
let normalized = normalize_server("vpn.example.com:4443").unwrap();
assert_eq!(normalized, "https://vpn.example.com:4443");
}
#[test]
fn normalize_server_removes_path_but_keeps_custom_port() {
let normalized = normalize_server("https://vpn.example.com:4443/global-protect").unwrap();
assert_eq!(normalized, "https://vpn.example.com:4443");
}
}
+63 -16
View File
@@ -1,27 +1,74 @@
use roxmltree::Node;
use xmltree::Element;
pub(crate) trait NodeExt<'a> {
fn find_descendant(&self, name: &str) -> Option<Node<'a, 'a>>;
fn descendant_text(&self, name: &str) -> Option<&'a str>;
fn find_child(&self, name: &str) -> Option<Node<'a, 'a>>;
fn child_text(&self, name: &str) -> Option<&'a str>;
pub(crate) trait ElementExt {
fn descendants(&self, name: &str) -> Vec<&Element>;
fn descendant(&self, name: &str) -> Option<&Element>;
fn descendant_text(&self, name: &str) -> Option<String>;
fn child(&self, name: &str) -> Option<&Element>;
fn child_text(&self, name: &str) -> Option<String>;
fn children(&self, name: &str) -> Vec<&Element>;
fn attr(&self, name: &str) -> Option<&str>;
}
impl<'a> NodeExt<'a> for Node<'a, 'a> {
fn find_descendant(&self, name: &str) -> Option<Node<'a, 'a>> {
self.descendants().find(|n| n.has_tag_name(name))
impl ElementExt for Element {
fn descendants(&self, name: &str) -> Vec<&Element> {
let mut results = Vec::new();
if self.name == name {
results.push(self);
}
for child in &self.children {
if let Some(element) = child.as_element() {
results.extend(element.descendants(name));
}
}
results
}
fn descendant_text(&self, name: &str) -> Option<&'a str> {
self.find_descendant(name).and_then(|node| node.text())
fn descendant(&self, name: &str) -> Option<&Element> {
if self.name == name {
return Some(self);
}
for child in &self.children {
if let Some(element) = child.as_element() {
if let Some(found) = element.descendant(name) {
return Some(found);
}
}
}
None
}
fn find_child(&self, name: &str) -> Option<Node<'a, 'a>> {
self.children().find(|n| n.has_tag_name(name))
fn descendant_text(&self, name: &str) -> Option<String> {
self
.descendant(name)
.and_then(|element| element.get_text().map(|s| s.to_string()))
}
fn child_text(&self, name: &str) -> Option<&'a str> {
self.find_child(name).and_then(|node| node.text())
fn child(&self, name: &str) -> Option<&Element> {
self.get_child(name)
}
fn child_text(&self, name: &str) -> Option<String> {
self
.get_child(name)
.and_then(|element| element.get_text().map(|s| s.to_string()))
}
fn children(&self, name: &str) -> Vec<&Element> {
self
.children
.iter()
.filter_map(|child| child.as_element())
.filter(|element| element.name == name)
.collect()
}
fn attr(&self, name: &str) -> Option<&str> {
self.attributes.get(name).map(|s| s.as_str())
}
}
+3
View File
@@ -11,3 +11,6 @@ log.workspace = true
[build-dependencies]
cc = "1"
autotools = "0.2"
pkg-config = "0.3"
fs_extra = "1"
+151 -4
View File
@@ -1,9 +1,156 @@
use std::{env, path::PathBuf, process::Command};
fn apply_patches(patches_dir: &PathBuf, build_src: &PathBuf) {
let mut patches = std::fs::read_dir(patches_dir)
.expect("Failed to read patches directory")
.filter_map(|entry| entry.ok())
.filter(|entry| entry.path().extension().and_then(|s| s.to_str()) == Some("patch"))
.map(|entry| entry.path())
.collect::<Vec<_>>();
patches.sort();
for patch in patches {
println!("cargo:rerun-if-changed={}", patch.display());
let status = Command::new("patch")
.arg("-p1")
.arg("-i")
.arg(&patch)
.current_dir(build_src)
.status()
.expect("Failed to execute patch command");
if !status.success() {
panic!("Failed to apply patch file: {}", patch.display());
}
}
}
fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
let libxml2_dir = deps_dir.join("libxml2");
let build_src = out_dir.join("libxml2_build");
println!("cargo:rerun-if-changed={}", libxml2_dir.display());
if build_src.exists() {
std::fs::remove_dir_all(&build_src).unwrap();
}
std::fs::create_dir_all(&build_src).unwrap();
let mut options = fs_extra::dir::CopyOptions::new();
options.overwrite = true;
options.content_only = true;
fs_extra::dir::copy(&libxml2_dir, &build_src, &options).expect("Failed to copy libxml2 sources to OUT_DIR");
let dst = autotools::Config::new(&build_src)
.reconf("-ivf")
.enable_static()
.disable_shared()
.with("python", Some("no"))
.with("icu", Some("no"))
.with("http", Some("no"))
.with("ftp", Some("no"))
.with("catalog", Some("no"))
.with("docbook", Some("no"))
.with("legacy", Some("no"))
.with("threads", Some("no"))
.with("zlib", Some("no"))
.with("lzma", Some("no"))
.cflag("-fPIC")
.build();
let lib_dir = dst.join("lib");
let include_dir = dst.join("include/libxml2");
println!("cargo:rustc-link-search=native={}", lib_dir.display());
println!("cargo:rustc-link-lib=static=xml2");
println!("cargo:include={}", include_dir.display());
dst
}
fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
let openconnect_dir = deps_dir.join("openconnect");
let patches_dir = deps_dir.join("patches");
let build_src = out_dir.join("openconnect_build");
println!("cargo:rerun-if-changed={}", openconnect_dir.display());
if build_src.exists() {
std::fs::remove_dir_all(&build_src).unwrap();
}
std::fs::create_dir_all(&build_src).unwrap();
let mut options = fs_extra::dir::CopyOptions::new();
options.overwrite = true;
options.content_only = true;
fs_extra::dir::copy(&openconnect_dir, &build_src, &options).expect("Failed to copy openconnect sources to OUT_DIR");
apply_patches(&patches_dir, &build_src);
let dst = autotools::Config::new(&build_src)
.reconf("-ivf")
.enable_static()
.disable_shared()
.disable("nls", None)
.disable("docs", None)
.disable("dsa-tests", None)
.without("libproxy", None)
.without("stoken", None)
.without("libpcsclite", None)
.without("libpskc", None)
.without("gssapi", None)
.with("gnutls-tss2", Some("no"))
.with("vpnc-script", Some("/usr/libexec/gpclient/vpnc-script"))
.build();
let lib_dir = dst.join("lib");
let include_dir = dst.join("include");
println!("cargo:rustc-link-search=native={}", lib_dir.display());
println!("cargo:rustc-link-lib=static=openconnect");
println!("cargo:include={}", include_dir.display());
dst
}
fn main() {
// Link to the native openconnect library
println!("cargo:rustc-link-lib=openconnect");
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let deps_dir = PathBuf::from(manifest_dir).join("deps");
let oc_dst = build_openconnect(&deps_dir, &out_dir);
if env::var("LIBXML2_STATIC").is_ok() {
let _libxml2_dst = build_libxml2(&deps_dir, &out_dir);
} else {
pkg_config::probe_library("libxml-2.0").unwrap();
}
pkg_config::probe_library("zlib").unwrap();
pkg_config::probe_library("liblz4").unwrap();
pkg_config::probe_library("gnutls").unwrap();
pkg_config::probe_library("p11-kit-1").unwrap();
pkg_config::probe_library("hogweed").unwrap();
pkg_config::probe_library("nettle").unwrap();
if pkg_config::probe_library("gmp").is_err() {
println!("cargo:warning=Falling back to direct gmp linking because pkg-config metadata is unavailable");
println!("cargo:rustc-link-lib=gmp");
}
println!("cargo:rerun-if-changed=src/ffi/vpn.c");
println!("cargo:rerun-if-changed=src/ffi/vpn.h");
// Compile the vpn.c file
cc::Build::new().file("src/ffi/vpn.c").include("src/ffi").compile("vpn");
#[cfg(target_os = "linux")]
{
println!("cargo:rustc-link-arg=-Wl,-Bstatic");
println!("cargo:rustc-link-arg=-Wl,-Bdynamic");
}
cc::Build::new()
.file("src/ffi/vpn.c")
.include("src/ffi")
.include(&oc_dst.join("include"))
.compile("vpn");
}
@@ -0,0 +1,113 @@
From a8d5ec198ca9ae47a0e6b4f1ea244d2738acf055 Mon Sep 17 00:00:00 2001
From: Kevin Yue <[email protected]>
Date: Sun, 14 Dec 2025 17:10:02 +0800
Subject: [PATCH 1/4] Add support for GlobalProtect app version handling
- Introduced `gp_app_version` field in `openconnect_info` structure.
- Implemented `openconnect_set_gp_app_version` and `openconnect_get_gp_app_version` functions.
- Updated `gpst_get_config` to use the app version in requests.
- Free `gp_app_version` in `openconnect_vpninfo_free` to prevent memory leaks.
---
gpst.c | 8 +++++---
library.c | 15 +++++++++++++++
openconnect-internal.h | 4 ++++
openconnect.h | 2 ++
4 files changed, 26 insertions(+), 3 deletions(-)
diff --git a/gpst.c b/gpst.c
index 244aaf04..5c24bbd2 100644
--- a/gpst.c
+++ b/gpst.c
@@ -650,8 +650,11 @@ static int gpst_get_config(struct openconnect_info *vpninfo)
/* submit getconfig request */
+ const char *app_version = openconnect_get_gp_app_version(vpninfo);
+ vpn_progress(vpninfo, PRG_DEBUG, _("Using GlobalProtect app version: %s\n"), app_version);
+
buf_append(request_body, "client-type=1&protocol-version=p1&internal=no");
- append_opt(request_body, "app-version", vpninfo->csd_ticket ? : "6.3.0-33");
+ append_opt(request_body, "app-version", app_version);
append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes");
append_opt(request_body, "clientos", gpst_os_name(vpninfo));
append_opt(request_body, "os-version", vpninfo->platname);
@@ -1040,8 +1043,7 @@ static int run_hip_script(struct openconnect_info *vpninfo)
* accept new ones.
*/
unsetenv("APP_VERSION");
- if (vpninfo->csd_ticket)
- if (setenv("APP_VERSION", vpninfo->csd_ticket, 1))
+ if (setenv("APP_VERSION", openconnect_get_gp_app_version(vpninfo), 1))
goto out;
execv(hip_argv[0], (char **)hip_argv);
diff --git a/library.c b/library.c
index b5e74e9b..18334c76 100644
--- a/library.c
+++ b/library.c
@@ -896,6 +896,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
free(vpninfo->localname);
free(vpninfo->useragent);
+ free(vpninfo->gp_app_version);
free(vpninfo->authgroup);
#ifdef HAVE_LIBSTOKEN
if (vpninfo->stoken_pin)
@@ -1019,6 +1020,20 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo,
return 0;
}
+int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
+ const char *gp_app_version)
+{
+ UTF8CHECK(gp_app_version);
+
+ STRDUP(vpninfo->gp_app_version, gp_app_version);
+ return 0;
+}
+
+const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo)
+{
+ return vpninfo->csd_ticket ?: (vpninfo->gp_app_version ?: "6.3.0-33");
+}
+
int openconnect_set_urlpath(struct openconnect_info *vpninfo,
const char *urlpath)
{
diff --git a/openconnect-internal.h b/openconnect-internal.h
index abf45bbd..988f85f0 100644
--- a/openconnect-internal.h
+++ b/openconnect-internal.h
@@ -786,6 +786,7 @@ struct openconnect_info {
int is_dyndns; /* Attempt to redo DNS lookup on each CSTP reconnect */
char *useragent;
char *version_string;
+ char *gp_app_version;
const char *quit_reason;
const char *delay_tunnel_reason; /* If non-null, provides a reason why protocol is not yet ready for tunnel setup */
@@ -1677,6 +1678,9 @@ void openconnect_set_juniper(struct openconnect_info *vpninfo);
/* hpke.c */
int handle_external_browser(struct openconnect_info *vpninfo);
+/* Get the app version */
+const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo);
+
/* version.c */
extern const char openconnect_version_str[];
diff --git a/openconnect.h b/openconnect.h
index 136f181a..7d4f3399 100644
--- a/openconnect.h
+++ b/openconnect.h
@@ -470,6 +470,8 @@ int openconnect_set_http_proxy(struct openconnect_info *vpninfo,
int openconnect_set_useragent(struct openconnect_info *vpninfo,
const char *useragent);
+int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
+ const char *gp_app_version);
int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo);
int openconnect_obtain_cookie(struct openconnect_info *vpninfo);
int openconnect_init_ssl(void);
--
2.50.1 (Apple Git-155)
@@ -0,0 +1,31 @@
From 8591eba702f52dae335601c997271786be50dff7 Mon Sep 17 00:00:00 2001
From: Kevin Yue <[email protected]>
Date: Sun, 14 Dec 2025 17:10:52 +0800
Subject: [PATCH 2/4] Update user agent for common headers in GlobalProtect
authentication
---
auth-globalprotect.c | 7 -------
1 file changed, 7 deletions(-)
diff --git a/auth-globalprotect.c b/auth-globalprotect.c
index 8d094273..27e41c2b 100644
--- a/auth-globalprotect.c
+++ b/auth-globalprotect.c
@@ -34,14 +34,7 @@ struct login_context {
void gpst_common_headers(struct openconnect_info *vpninfo,
struct oc_text_buf *buf)
{
- char *orig_ua = vpninfo->useragent;
-
- /* XX: more recent servers don't appear to require this specific UA value,
- * but we don't have any good way to detect them.
- */
- vpninfo->useragent = (char *)"PAN GlobalProtect";
http_common_headers(vpninfo, buf);
- vpninfo->useragent = orig_ua;
}
/* Translate platform names (derived from AnyConnect) into the values
--
2.50.1 (Apple Git-155)
@@ -0,0 +1,120 @@
From dda2aceca7e614af65b968e632065ef223cb6612 Mon Sep 17 00:00:00 2001
From: Kevin Yue <[email protected]>
Date: Sun, 14 Dec 2025 17:14:08 +0800
Subject: [PATCH 3/4] Add support for OS version handling in GlobalProtect
authentication
---
auth-globalprotect.c | 2 +-
gpst.c | 4 ++--
library.c | 15 +++++++++++++++
openconnect-internal.h | 4 ++++
openconnect.h | 3 +++
5 files changed, 25 insertions(+), 3 deletions(-)
diff --git a/auth-globalprotect.c b/auth-globalprotect.c
index 27e41c2b..59d6de3b 100644
--- a/auth-globalprotect.c
+++ b/auth-globalprotect.c
@@ -731,7 +731,7 @@ static int gpst_login(struct openconnect_info *vpninfo, int portal, struct login
buf_append(request_body, "jnlpReady=jnlpReady&ok=Login&direct=yes&clientVer=4100&prot=https:&internal=no");
append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes");
append_opt(request_body, "clientos", gpst_os_name(vpninfo));
- append_opt(request_body, "os-version", vpninfo->platname);
+ append_opt(request_body, "os-version", openconnect_get_gp_os_version(vpninfo));
append_opt(request_body, "server", vpninfo->hostname);
append_opt(request_body, "computer", vpninfo->localname);
if (ctx->portal_userauthcookie)
diff --git a/gpst.c b/gpst.c
index 5c24bbd2..0373fce0 100644
--- a/gpst.c
+++ b/gpst.c
@@ -657,7 +657,7 @@ static int gpst_get_config(struct openconnect_info *vpninfo)
append_opt(request_body, "app-version", app_version);
append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes");
append_opt(request_body, "clientos", gpst_os_name(vpninfo));
- append_opt(request_body, "os-version", vpninfo->platname);
+ append_opt(request_body, "os-version", openconnect_get_gp_os_version(vpninfo));
append_opt(request_body, "hmac-algo", "sha1,md5,sha256");
append_opt(request_body, "enc-algo", "aes-128-cbc,aes-256-cbc");
if (old_addr || old_addr6) {
@@ -1044,7 +1044,7 @@ static int run_hip_script(struct openconnect_info *vpninfo)
*/
unsetenv("APP_VERSION");
if (setenv("APP_VERSION", openconnect_get_gp_app_version(vpninfo), 1))
- goto out;
+ goto out;
execv(hip_argv[0], (char **)hip_argv);
diff --git a/library.c b/library.c
index 18334c76..e2169054 100644
--- a/library.c
+++ b/library.c
@@ -897,6 +897,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
free(vpninfo->localname);
free(vpninfo->useragent);
free(vpninfo->gp_app_version);
+ free(vpninfo->gp_os_version);
free(vpninfo->authgroup);
#ifdef HAVE_LIBSTOKEN
if (vpninfo->stoken_pin)
@@ -1034,6 +1035,20 @@ const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo)
return vpninfo->csd_ticket ?: (vpninfo->gp_app_version ?: "6.3.0-33");
}
+int openconnect_set_gp_os_version(struct openconnect_info *vpninfo,
+ const char *gp_os_version)
+{
+ UTF8CHECK(gp_os_version);
+
+ STRDUP(vpninfo->gp_os_version, gp_os_version);
+ return 0;
+}
+
+const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_os_version ?: vpninfo->platname;
+}
+
int openconnect_set_urlpath(struct openconnect_info *vpninfo,
const char *urlpath)
{
diff --git a/openconnect-internal.h b/openconnect-internal.h
index 988f85f0..5c8d2909 100644
--- a/openconnect-internal.h
+++ b/openconnect-internal.h
@@ -787,6 +787,7 @@ struct openconnect_info {
char *useragent;
char *version_string;
char *gp_app_version;
+ char *gp_os_version;
const char *quit_reason;
const char *delay_tunnel_reason; /* If non-null, provides a reason why protocol is not yet ready for tunnel setup */
@@ -1681,6 +1682,9 @@ int handle_external_browser(struct openconnect_info *vpninfo);
/* Get the app version */
const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo);
+/* Get the OS version string for GP */
+const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo);
+
/* version.c */
extern const char openconnect_version_str[];
diff --git a/openconnect.h b/openconnect.h
index 7d4f3399..aa96a53b 100644
--- a/openconnect.h
+++ b/openconnect.h
@@ -472,6 +472,9 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo,
int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
const char *gp_app_version);
+int openconnect_set_gp_os_version(struct openconnect_info *vpninfo,
+ const char *gp_os_version);
+
int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo);
int openconnect_obtain_cookie(struct openconnect_info *vpninfo);
int openconnect_init_ssl(void);
--
2.50.1 (Apple Git-155)
@@ -0,0 +1,38 @@
From 3915a51c81831a1a9b087d82f0c760365682f23b Mon Sep 17 00:00:00 2001
From: Kevin Yue <[email protected]>
Date: Mon, 15 Dec 2025 19:20:44 +0800
Subject: [PATCH 4/4] Add client version and OS information to HIP script
arguments
---
gpst.c | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/gpst.c b/gpst.c
index 0373fce0..d04c42c2 100644
--- a/gpst.c
+++ b/gpst.c
@@ -1013,6 +1013,12 @@ static int run_hip_script(struct openconnect_info *vpninfo)
exit(1);
hip_argv[i++] = openconnect_utf8_to_legacy(vpninfo, vpninfo->csd_wrapper);
+ hip_argv[i++] = "--client-version";
+ hip_argv[i++] = openconnect_get_gp_app_version(vpninfo);
+ hip_argv[i++] = "--client-os";
+ hip_argv[i++] = gpst_os_name(vpninfo);
+ hip_argv[i++] = "--os-version";
+ hip_argv[i++] = openconnect_get_gp_os_version(vpninfo);
hip_argv[i++] = "--cookie";
hip_argv[i++] = vpninfo->cookie;
if (vpninfo->ip_info.addr) {
@@ -1025,8 +1031,6 @@ static int run_hip_script(struct openconnect_info *vpninfo)
}
hip_argv[i++] = "--md5";
hip_argv[i++] = vpninfo->csd_token;
- hip_argv[i++] = "--client-os";
- hip_argv[i++] = gpst_os_name(vpninfo);
hip_argv[i++] = NULL;
/* XX: Sending the above parameters as --long-options was a mistake that was
--
2.50.1 (Apple Git-155)
+1 -1
View File
@@ -75,7 +75,7 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
openconnect_set_loglevel(vpninfo, PRG_TRACE);
openconnect_init_ssl();
openconnect_set_protocol(vpninfo, "gp");
openconnect_set_hostname(vpninfo, options->server);
openconnect_parse_url(vpninfo, options->server);
openconnect_set_cookie(vpninfo, options->cookie);
if (options->os) {
+13
View File
@@ -258,3 +258,16 @@ impl VpnBuilder {
CString::new(value.to_string()).expect("Failed to convert to CString")
}
}
#[cfg(test)]
mod tests {
use super::Vpn;
#[test]
fn vpn_builder_preserves_raw_host_and_custom_port() {
let builder = Vpn::builder("vpn.example.com:4443", "cookie");
assert_eq!(builder.server, "vpn.example.com:4443");
assert_eq!(builder.cookie, "cookie");
}
}
+4 -2
View File
@@ -34,7 +34,9 @@
nativeBuildInputs = with pkgs; [
perl
jq
openconnect
autoconf
automake
libtool
libsoup
webkitgtk
pkg-config
@@ -43,7 +45,7 @@
overrideMain = {...}: {
postPatch = ''
substituteInPlace crates/common/src/vpn_utils.rs \
--replace-fail /etc/vpnc/vpnc-script ${pkgs.vpnc-scripts}/bin/vpnc-script
--replace-fail /usr/libexec/gpclient/vpnc-script ${pkgs.vpnc-scripts}/bin/vpnc-script
substituteInPlace crates/gpapi/src/lib.rs \
--replace-fail /usr/bin/gpclient $out/bin/gpclient \
--replace-fail /usr/bin/gpservice $out/bin/gpservice \
+13
View File
@@ -10,6 +10,13 @@ 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 -Dm755 artifacts/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
# Install the disconnect hooks
install -Dm755 artifacts/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
install -Dm755 artifacts/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
install -Dm644 artifacts/usr/share/applications/gpgui.desktop $(DESTDIR)/usr/share/applications/gpgui.desktop
install -Dm644 artifacts/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
install -Dm644 artifacts/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
@@ -26,6 +33,12 @@ 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
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
rm -f $(DESTDIR)/usr/share/applications/gpgui.desktop
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
rm -f $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
+12 -3
View File
@@ -4,20 +4,29 @@ Priority: optional
Maintainer: Kevin Yue <[email protected]>
Standards-Version: 4.1.4
Build-Depends: debhelper (>= 9),
autoconf,
automake,
libtool,
patch,
pkg-config,
jq (>= 1),
make (>= 4),
libxml2,
zlib1g-dev,
liblz4-dev,
libp11-kit-dev,
nettle-dev,
libgnutls28-dev,
libgmp-dev,
libsecret-1-0,
libayatana-appindicator3-1,
gnome-keyring,
libwebkit2gtk-4.0-dev,
libopenconnect-dev (>= 8.20),@RUST@
libssl-dev,@RUST@
Homepage: https://github.com/yuezk/GlobalProtect-openconnect
Package: globalprotect-openconnect
Architecture: any
Multi-Arch: foreign
Depends: ${misc:Depends}, ${shlibs:Depends}, openconnect (>=8.20), libxml2, libsecret-1-0, libayatana-appindicator3-1, gnome-keyring
Depends: ${misc:Depends}, ${shlibs:Depends}, libsecret-1-0, libayatana-appindicator3-1, gnome-keyring
Description: A GUI for GlobalProtect VPN
A GUI for GlobalProtect VPN, based on OpenConnect, supports the SSO authentication method.
+4
View File
@@ -2,6 +2,10 @@
export OFFLINE = @OFFLINE@
export BUILD_FE = 0
export LIBXML2_STATIC = 1
override_dh_auto_build:
$(MAKE) build
%:
dh $@ --no-parallel
@@ -0,0 +1,26 @@
#!/bin/sh
# Resume the VPN connection if the network comes back up
set -e
PIDFILE=/tmp/gpservice_disconnected.pid
resume_vpn() {
if [ -f $PIDFILE ]; then
PID=$(cat $PIDFILE)
# Always remove the PID file
rm $PIDFILE
# Ensure the PID is a gpservice process
if ps -p $PID -o comm= | grep -q gpservice; then
# Send a USR2 signal to the gpclient process to resume the VPN connection
kill -USR2 $PID
fi
fi
}
if [ "$2" = "up" ]; then
resume_vpn
fi
@@ -0,0 +1,6 @@
#!/bin/sh
set -e
# Disconnect the VPN connection before the network goes down
/usr/bin/gpclient disconnect --wait 3
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
# Wrapper for gpclient hip
LOGFILE="/tmp/gpclient-hipreport.log"
LINUX_GPCLIENT_BIN="/usr/bin/gpclient"
HOMEBREW_GPCLIENT_BIN="/opt/homebrew/bin/gpclient"
GPCLIENT_BIN="${GPCLIENT_BIN:-}"
if [ -n "$GPCLIENT_BIN" ] && [ -x "$GPCLIENT_BIN" ]; then
:
elif [ -x "$LINUX_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$LINUX_GPCLIENT_BIN"
elif [ -x "$HOMEBREW_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$HOMEBREW_GPCLIENT_BIN"
else
echo "Error: gpclient binary not found." > "$LOGFILE"
exit 1
fi
HIP_REPORT_OUTPUT=$("$GPCLIENT_BIN" hip "$@" 2> "$LOGFILE")
STATUS=$?
if [ $STATUS -ne 0 ]; then
exit $STATUS
fi
printf '%s\n' "$HIP_REPORT_OUTPUT"
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -8,8 +8,8 @@ pkgdesc="A GUI for GlobalProtect VPN, based on OpenConnect, supports the SSO aut
arch=('x86_64' 'aarch64')
url="https://github.com/yuezk/GlobalProtect-openconnect"
license=('GPL3')
makedepends=('make' 'pkg-config' 'rust' 'cargo' 'jq' 'webkit2gtk' 'curl' 'wget' 'file' 'openssl' 'appmenu-gtk-module' 'gtk3' 'libappindicator-gtk3' 'librsvg' 'libvips' 'libayatana-appindicator' 'openconnect' 'libsecret')
depends=('openconnect>=8.20' webkit2gtk libappindicator-gtk3 libayatana-appindicator libsecret libxml2)
makedepends=('make' 'pkg-config' 'rust' 'cargo' 'jq' 'webkit2gtk' 'curl' 'wget' 'file' 'openssl' 'appmenu-gtk-module' 'gtk3' 'libappindicator-gtk3' 'librsvg' 'libvips' 'libayatana-appindicator' 'libsecret' 'autoconf' 'automake' 'libtool')
depends=('webkit2gtk' 'libappindicator-gtk3' 'libayatana-appindicator' 'libsecret' 'gnutls' 'lz4' 'nettle' 'libp11-kit' 'gmp')
optdepends=('wmctrl: for window management')
provides=('globalprotect-openconnect' 'gpclient' 'gpservice' 'gpauth' 'gpgui')
@@ -25,7 +25,7 @@ build() {
# Must unset the CFLAGS, otherwise the build fails
unset CFLAGS
make build OFFLINE=@OFFLINE@ BUILD_FE=0
make build OFFLINE=@OFFLINE@ BUILD_FE=0 LIBXML2_STATIC=1
}
package() {
@@ -13,17 +13,26 @@ BuildRequires: rust
BuildRequires: cargo
BuildRequires: jq
BuildRequires: pkg-config
BuildRequires: openconnect-devel
BuildRequires: libtool
BuildRequires: autoconf
BuildRequires: automake
BuildRequires: gcc-c++
BuildRequires: openssl-devel
BuildRequires: zlib-devel
BuildRequires: lz4-devel
BuildRequires: p11-kit-devel
BuildRequires: nettle-devel
BuildRequires: gnutls-devel
BuildRequires: gmp-devel
BuildRequires: wget
BuildRequires: file
BuildRequires: perl
BuildRequires: (webkit2gtk4.0-devel or webkit2gtk3-soup2-devel)
BuildRequires: (webkit2gtk4.0-devel or webkit2gtk3-devel or webkit2gtk3-soup2-devel)
BuildRequires: (libappindicator-gtk3-devel or libappindicator3-1)
BuildRequires: (librsvg2-devel or librsvg-devel)
Requires: openconnect >= 8.20, (libayatana-appindicator or libappindicator-gtk3)
Requires: (libayatana-appindicator or libappindicator-gtk3)
Conflicts: globalprotect-openconnect-snapshot
%global debug_package %{nil}
@@ -40,7 +49,7 @@ rm -f %{_bindir}/gpgui
%build
# The injected RUSTFLAGS could fail the build
unset RUSTFLAGS
make build OFFLINE=@OFFLINE@ BUILD_FE=0
make build OFFLINE=@OFFLINE@ BUILD_FE=0 LIBXML2_STATIC=1
%install
%make_install
@@ -48,6 +57,8 @@ make build OFFLINE=@OFFLINE@ BUILD_FE=0
%files
%defattr(-,root,root)
%{_bindir}/*
%{_libexecdir}/gpclient/vpnc-script
%{_libexecdir}/gpclient/hipreport.sh
%{_datadir}/applications/gpgui.desktop
%{_datadir}/icons/hicolor/32x32/apps/gpgui.png
%{_datadir}/icons/hicolor/128x128/apps/gpgui.png
@@ -55,6 +66,15 @@ make build OFFLINE=@OFFLINE@ BUILD_FE=0
%{_datadir}/icons/hicolor/scalable/apps/gpgui.svg
%{_datadir}/polkit-1/actions/com.yuezk.gpgui.policy
%dir /usr/lib/NetworkManager
%dir /usr/lib/NetworkManager/dispatcher.d
%dir /usr/lib/NetworkManager/dispatcher.d/pre-down.d
/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
%dir %{_libexecdir}
%dir %{_libexecdir}/gpclient
%dir %{_datadir}/icons/hicolor
%dir %{_datadir}/icons/hicolor/32x32
%dir %{_datadir}/icons/hicolor/32x32/apps
+2
View File
@@ -0,0 +1,2 @@
[toolchain]
channel = "1.71.1"
+12 -1
View File
@@ -33,14 +33,25 @@ release_snapshot() {
}
release_tag() {
local release_args=()
if existing_notes=$(gh -R "$REPO" release view "$TAG" --json body --jq .body 2>/dev/null); then
RELEASE_NOTES="$existing_notes"
fi
if [[ $TAG == v2.3.* ]]; then
release_args+=(--latest=false)
fi
echo "Removing existing release..."
gh -R "$REPO" release delete $TAG --yes --cleanup-tag || true
echo "Creating release..."
gh -R "$REPO" release create $TAG \
"${release_args[@]}" \
--title "$TAG" \
--notes "$RELEASE_NOTES" \
"$PROJECT_DIR"/.build/artifacts/artifact-source/* \
"$PROJECT_DIR"/.build/artifacts/artifact-source*/* \
"$PROJECT_DIR"/.build/artifacts/artifact-gpgui-*/*
}