Compare commits

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

No files matched your search

-6
View File
@@ -1,6 +0,0 @@
.build
.git
.vendor
apps/gpgui-helper/node_modules
target
vendor.tar.xz
+51 -156
View File
@@ -1,15 +1,6 @@
name: Build name: Build
on: on:
workflow_dispatch: workflow_dispatch:
inputs:
gp_branch:
description: 'GlobalProtect-openconnect branch to use for the snapshot release'
required: true
default: dev
gpgui_branch:
description: 'gpgui branch to use for the snapshot release'
required: true
default: dev
push: push:
paths-ignore: paths-ignore:
- LICENSE - LICENSE
@@ -18,6 +9,7 @@ on:
- .devcontainer - .devcontainer
branches: branches:
- main - main
- dev
- hotfix/* - hotfix/*
- feature/* - feature/*
- release/* - release/*
@@ -29,21 +21,38 @@ concurrency:
cancel-in-progress: true cancel-in-progress: true
jobs: jobs:
# Include arm64 if ref is a tag
setup-matrix:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
- name: Set up matrix
id: set-matrix
run: |
# Set the matrix to include arm64 if the ref is a tag or is the dev branch
if [[ "${{ github.ref }}" == "refs/tags/"* || "${{ github.ref }}" == "refs/heads/dev" ]]; then
echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}, {"runner": "ubuntu-24.04-arm", "arch": "ubuntu-24.04-arm"}]' >> $GITHUB_OUTPUT
else
echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}]' >> $GITHUB_OUTPUT
fi
tarball: tarball:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: [setup-matrix]
steps: steps:
- uses: pnpm/action-setup@v5 - uses: pnpm/action-setup@v4
with: with:
version: 9 version: 9
- name: Prepare workspace - name: Prepare workspace
run: rm -rf source && mkdir -p source/artifacts run: rm -rf source && mkdir -p source/artifacts
- name: Checkout GlobalProtect-openconnect - name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6 uses: actions/checkout@v4
with: with:
token: ${{ secrets.GH_PAT }} token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }} ref: ${{ github.ref }}
path: source/gp path: source/gp
submodules: recursive submodules: recursive
@@ -60,7 +69,7 @@ jobs:
- name: Generate RPM spec file - name: Generate RPM spec file
env: env:
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }} RELEASE_TAG: ${{ github.ref == 'refs/heads/dev' && 'snapshot' || github.ref_name }}
run: | run: |
cd source/gp cd source/gp
@@ -71,7 +80,7 @@ jobs:
mv -v .build/rpm/*.spec ../artifacts/ mv -v .build/rpm/*.spec ../artifacts/
- name: Upload tarball - name: Upload tarball
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v4
with: with:
name: artifact-source name: artifact-source
if-no-files-found: error if-no-files-found: error
@@ -79,12 +88,12 @@ jobs:
source/artifacts/* source/artifacts/*
tarball-offline: tarball-offline:
if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/') }} if: ${{ github.ref == 'refs/heads/dev' || startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: needs:
- tarball - tarball
steps: steps:
- uses: pnpm/action-setup@v5 - uses: pnpm/action-setup@v4
with: with:
version: 9 version: 9
@@ -92,7 +101,7 @@ jobs:
run: rm -rf source-offline && mkdir source-offline run: rm -rf source-offline && mkdir source-offline
- name: Download tarball - name: Download tarball
uses: actions/download-artifact@v8 uses: actions/download-artifact@v4
with: with:
name: artifact-source name: artifact-source
path: source-offline path: source-offline
@@ -113,7 +122,7 @@ jobs:
mv -v .build/tarball/*.tar.gz ../$offline_tarball mv -v .build/tarball/*.tar.gz ../$offline_tarball
- name: Upload offline tarball - name: Upload offline tarball
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v4
with: with:
path: source-offline/*.offline.tar.gz path: source-offline/*.offline.tar.gz
name: artifact-source-offline name: artifact-source-offline
@@ -121,16 +130,12 @@ jobs:
build-gp: build-gp:
needs: needs:
- setup-matrix
- tarball - tarball
strategy: strategy:
fail-fast: false
matrix: matrix:
os: os: ${{fromJson(needs.setup-matrix.outputs.matrix)}}
- runner: ubuntu-latest package: [deb, rpm, pkg, binary, ubuntu-rolling]
arch: amd64
- runner: ubuntu-24.04-arm
arch: ubuntu-24.04-arm
package: [deb, rpm, pkg, apk, binary, ubuntu-rolling]
runs-on: ${{ matrix.os.runner }} runs-on: ${{ matrix.os.runner }}
name: build-gp (${{ matrix.package }}, ${{ matrix.os.arch }}) name: build-gp (${{ matrix.package }}, ${{ matrix.os.arch }})
steps: steps:
@@ -139,7 +144,7 @@ jobs:
rm -rf build-gp-${{ matrix.package }} rm -rf build-gp-${{ matrix.package }}
mkdir -p build-gp-${{ matrix.package }} mkdir -p build-gp-${{ matrix.package }}
- name: Download tarball - name: Download tarball
uses: actions/download-artifact@v8 uses: actions/download-artifact@v4
with: with:
name: artifact-source name: artifact-source
path: build-gp-${{ matrix.package }} path: build-gp-${{ matrix.package }}
@@ -164,109 +169,41 @@ jobs:
# Don't upload package for ubuntu-rolling because it's duplicate of deb package # Don't upload package for ubuntu-rolling because it's duplicate of deb package
- name: Upload ${{ matrix.package }} package - name: Upload ${{ matrix.package }} package
if: ${{ matrix.package != 'ubuntu-rolling' }} if: ${{ matrix.package != 'ubuntu-rolling' }}
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v4
with: with:
name: artifact-gp-${{ matrix.package }}-${{ matrix.os.arch }} name: artifact-gp-${{ matrix.package }}-${{ matrix.os.arch }}
if-no-files-found: error if-no-files-found: error
path: | path: |
build-gp-${{ matrix.package }}/artifacts/* build-gp-${{ matrix.package }}/artifacts/*
build-docker-image:
strategy:
fail-fast: false
matrix:
include:
- runner: ubuntu-latest
platform: linux/amd64
- runner: ubuntu-24.04-arm
platform: linux/arm64
runs-on: ${{ matrix.runner }}
steps:
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> "$GITHUB_ENV"
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }}
submodules: recursive
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Build and push by digest
id: build
uses: docker/build-push-action@v7
with:
context: .
file: packaging/docker/alpine/Dockerfile
platforms: ${{ matrix.platform }}
outputs: type=image,name=yuezk/globalprotect-openconnect,push-by-digest=true,name-canonical=true,push=true
- name: Verify CLI tools
env:
IMAGE: yuezk/globalprotect-openconnect
DIGEST: ${{ steps.build.outputs.digest }}
run: |
docker run --rm "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint gpauth "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v7
with:
name: digests-${{ env.PLATFORM_PAIR }}
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
build-gpgui: build-gpgui:
needs:
- setup-matrix
strategy: strategy:
fail-fast: false
matrix: matrix:
os: os: ${{fromJson(needs.setup-matrix.outputs.matrix)}}
- runner: ubuntu-latest
arch: amd64
- runner: ubuntu-24.04-arm
arch: ubuntu-24.04-arm
libc:
- name: glibc
builder: gpgui-builder-tauri2
artifact_suffix: ""
- name: musl
builder: gpgui-alpine-builder-tauri2
artifact_suffix: "-musl"
runs-on: ${{ matrix.os.runner }} runs-on: ${{ matrix.os.runner }}
name: build-gpgui (${{ matrix.libc.name }}, ${{ matrix.os.arch }}) name: build-gpgui (${{ matrix.os.arch }})
steps: steps:
- uses: pnpm/action-setup@v5 - uses: pnpm/action-setup@v4
with: with:
version: 9 version: 9
- name: Prepare workspace - name: Prepare workspace
run: rm -rf gpgui-source && mkdir gpgui-source run: rm -rf gpgui-source && mkdir gpgui-source
- name: Checkout GlobalProtect-openconnect - name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6 uses: actions/checkout@v4
with: with:
token: ${{ secrets.GH_PAT }} token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }} ref: ${{ github.ref }}
path: gpgui-source/gp path: gpgui-source/gp
submodules: recursive submodules: recursive
- name: Checkout gpgui - name: Checkout gpgui@${{ github.ref_name }}
uses: actions/checkout@v6 uses: actions/checkout@v4
with: with:
token: ${{ secrets.GH_PAT }} token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui repository: yuezk/gpgui
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gpgui_branch || github.ref_name }} ref: ${{ github.ref_name }}
path: gpgui-source/gpgui path: gpgui-source/gpgui
- name: Tarball - name: Tarball
run: | run: |
@@ -278,32 +215,31 @@ jobs:
run: | run: |
docker run --pull=always --rm \ docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \ -e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd)/gpgui-source:/workspace yuezk/gpdev:${{ matrix.libc.builder }} -v $(pwd)/gpgui-source:/workspace yuezk/gpdev:gpgui-builder-tauri2
- name: Install gpgui in Docker - name: Install gpgui in Docker
run: | run: |
cd gpgui-source cd gpgui-source
tar -xJf *.bin.tar.xz tar -xJf *.bin.tar.xz
docker run --pull=always --rm \ docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \ -e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd):/workspace yuezk/gpdev:${{ matrix.libc.builder }} \ -v $(pwd):/workspace yuezk/gpdev:gpgui-builder-tauri2 \
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version" bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
- name: Upload gpgui - name: Upload gpgui
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v4
with: with:
name: artifact-gpgui${{ matrix.libc.artifact_suffix }}-${{ matrix.os.arch }} name: artifact-gpgui-${{ matrix.os.arch }}
if-no-files-found: error if-no-files-found: error
path: | path: |
gpgui-source/*.bin.tar.xz gpgui-source/*.bin.tar.xz
gpgui-source/*.bin.tar.xz.sha256 gpgui-source/*.bin.tar.xz.sha256
gh-release: gh-release:
if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/') }} if: ${{ github.ref == 'refs/heads/dev' || startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: needs:
- tarball - tarball
- tarball-offline - tarball-offline
- build-gp - build-gp
- build-docker-image
- build-gpgui - build-gpgui
steps: steps:
@@ -311,63 +247,22 @@ jobs:
run: rm -rf gh-release && mkdir gh-release run: rm -rf gh-release && mkdir gh-release
- name: Checkout GlobalProtect-openconnect - name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6 uses: actions/checkout@v4
with: with:
token: ${{ secrets.GH_PAT }} token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }} ref: ${{ github.ref }}
path: gh-release/gp path: gh-release/gp
submodules: recursive submodules: recursive
- name: Download all artifacts - name: Download all artifacts
uses: actions/download-artifact@v8 uses: actions/download-artifact@v4
with: with:
path: gh-release/gp/.build/artifacts path: gh-release/gp/.build/artifacts
- name: Rename APK artifacts
run: |
shopt -s nullglob
for file in gh-release/gp/.build/artifacts/artifact-gp-apk-amd64/*.apk; do
mv "$file" "${file%.apk}-x86_64.apk"
done
for file in gh-release/gp/.build/artifacts/artifact-gp-apk-ubuntu-24.04-arm/*.apk; do
mv "$file" "${file%.apk}-aarch64.apk"
done
- name: Create GH release - name: Create GH release
env: env:
GH_TOKEN: ${{ secrets.GH_PAT }} GH_TOKEN: ${{ secrets.GH_PAT }}
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }} RELEASE_TAG: ${{ github.ref == 'refs/heads/dev' && 'snapshot' || github.ref_name }}
run: | run: |
cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG" cd gh-release/gp/scripts && ./gh-release.sh "$RELEASE_TAG"
publish-docker-image:
needs:
- build-docker-image
if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest
steps:
- name: Download digests
uses: actions/download-artifact@v8
with:
path: /tmp/digests
pattern: digests-*
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Publish Docker manifest
working-directory: /tmp/digests
env:
IMAGE: yuezk/globalprotect-openconnect
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && 'snapshot' || github.ref_name }}
run: |
docker buildx imagetools create -t "$IMAGE:$RELEASE_TAG" \
$(printf "$IMAGE@sha256:%s " *)
docker buildx imagetools inspect "$IMAGE:$RELEASE_TAG"
-142
View File
@@ -1,142 +0,0 @@
name: Publish AUR git package
on:
workflow_dispatch:
inputs:
build-package:
type: boolean
description: "Build the package before publishing"
required: true
default: true
publish:
type: boolean
description: "Push PKGBUILD, .SRCINFO, and gp.install to AUR"
required: true
default: true
push:
branches:
- main
paths:
- packaging/aur/globalprotect-openconnect-git/**
- .github/workflows/publish-aur-git.yaml
permissions:
contents: read
jobs:
aur:
runs-on: ubuntu-latest
container: archlinux:base-devel
defaults:
run:
shell: bash
env:
AUR_PACKAGE_DIR: packaging/aur/globalprotect-openconnect-git
AUR_REPO: ssh://[email protected]/globalprotect-openconnect-git.git
steps:
- name: Install checkout tools
run: pacman -Syu --noconfirm --needed git openssh
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
- name: Install build tools
run: |
pacman -Syu --noconfirm --needed \
appmenu-gtk-module \
cargo \
curl \
desktop-file-utils \
file \
git \
libappindicator-gtk3 \
libsecret \
libxml2 \
namcap \
openconnect \
openssl \
pkgconf \
librsvg \
shared-mime-info \
vpnc \
wget \
webkit2gtk-4.1
- name: Save committed .SRCINFO
if: ${{ github.event_name == 'push' }}
run: cp "$AUR_PACKAGE_DIR/.SRCINFO" /tmp/committed.SRCINFO
- name: Prepare build user
run: |
useradd -m builder
chown -R builder:builder "$GITHUB_WORKSPACE"
- name: Refresh VCS package version
if: ${{ github.event_name == 'workflow_dispatch' }}
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- makepkg --nobuild --noconfirm --cleanbuild
- name: Regenerate .SRCINFO
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- makepkg --printsrcinfo > .SRCINFO
- name: Check committed .SRCINFO
if: ${{ github.event_name == 'push' }}
run: |
cmp -s /tmp/committed.SRCINFO "$AUR_PACKAGE_DIR/.SRCINFO" || {
diff -u /tmp/committed.SRCINFO "$AUR_PACKAGE_DIR/.SRCINFO"
echo ".SRCINFO is out of date. Regenerate it with makepkg --printsrcinfo." >&2
exit 1
}
- name: Run namcap
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- namcap PKGBUILD
- name: Build package
if: ${{ github.event_name == 'workflow_dispatch' && inputs['build-package'] }}
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- makepkg --noconfirm --clean --cleanbuild
- name: Configure SSH
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
env:
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
run: |
if [[ -z "$AUR_SSH_PRIVATE_KEY" ]]; then
echo "AUR_SSH_PRIVATE_KEY is required to publish to AUR" >&2
exit 1
fi
install -d -m 700 ~/.ssh
printf '%s\n' "$AUR_SSH_PRIVATE_KEY" > ~/.ssh/aur
chmod 600 ~/.ssh/aur
ssh-keyscan -t rsa,ecdsa,ed25519 aur.archlinux.org > ~/.ssh/known_hosts
- name: Publish to AUR
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
env:
GIT_SSH_COMMAND: ssh -i /github/home/.ssh/aur -o UserKnownHostsFile=/github/home/.ssh/known_hosts -o StrictHostKeyChecking=yes
run: |
workdir="$(mktemp -d)"
git clone "$AUR_REPO" "$workdir/aur"
cp "$AUR_PACKAGE_DIR"/PKGBUILD "$workdir/aur/PKGBUILD"
cp "$AUR_PACKAGE_DIR"/.SRCINFO "$workdir/aur/.SRCINFO"
cp "$AUR_PACKAGE_DIR"/gp.install "$workdir/aur/gp.install"
cd "$workdir/aur"
if git diff --quiet; then
echo "AUR package is already up to date"
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add PKGBUILD .SRCINFO gp.install
git commit -m "Update globalprotect-openconnect-git"
git push origin master
+22 -69
View File
@@ -11,7 +11,12 @@ on:
required: false required: false
default: "1" default: "1"
series: series:
description: 'Space-separated Ubuntu series. Leave empty to publish all supported series.' description: 'Ubuntu series to publish'
type: "string"
required: false
default: ""
excluded_series:
description: 'Additional Ubuntu series to exclude from publishing'
type: "string" type: "string"
required: false required: false
default: "" default: ""
@@ -25,78 +30,24 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Check tag exists - name: Check tag exists
env: uses: mukunku/[email protected]
GH_TOKEN: ${{ github.token }} id: check-tag
TAG: ${{ inputs.tag }} with:
tag: ${{ inputs.tag }}
- name: Exit if tag does not exist
run: | run: |
if ! gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null 2>&1; then if [[ "${{ steps.check-tag.outputs.exists }}" == "false" ]]; then
echo "Tag $TAG does not exist" echo "Tag ${{ inputs.tag }} does not exist"
exit 1 exit 1
fi fi
resolve-series:
needs: check
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.resolve.outputs.matrix }}
steps:
- name: Resolve Ubuntu series
id: resolve
env:
INPUT_SERIES: ${{ inputs.series }}
run: |
sudo apt-get update
sudo apt-get install -y distro-info distro-info-data
if [[ "$INPUT_SERIES" == *","* ]]; then
echo "Use space-separated series, for example: jammy noble" >&2
exit 1
fi
series=()
if [[ -z "${INPUT_SERIES// }" ]]; then
while IFS= read -r item; do
[[ -n "$item" ]] && series+=("$item")
done < <(ubuntu-distro-info --supported)
else
read -r -a series <<< "$INPUT_SERIES"
fi
if [[ "${#series[@]}" -eq 0 ]]; then
echo "No Ubuntu series resolved" >&2
exit 1
fi
for item in "${series[@]}"; do
ubuntu-distro-info --series "$item" >/dev/null
done
matrix="$(printf '%s\n' "${series[@]}" | jq -R . | jq -s -c '{series: .}')"
echo "Resolved matrix: $matrix"
echo "matrix=$matrix" >> "$GITHUB_OUTPUT"
publish-ppa: publish-ppa:
needs: [check, resolve-series] needs: check
name: publish-ppa (${{ matrix.series }})
runs-on: ubuntu-latest runs-on: ubuntu-latest
container:
image: ubuntu:${{ matrix.series }}
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.resolve-series.outputs.matrix) }}
steps: steps:
- name: Install container tools - uses: pnpm/action-setup@v4
run: | with:
apt-get update version: 9
apt-get install -y ca-certificates curl gpg sudo
mkdir -p /etc/apt/keyrings
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \
| gpg --dearmor -o /etc/apt/keyrings/githubcli-archive-keyring.gpg
chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \
> /etc/apt/sources.list.d/github-cli.list
apt-get update
apt-get install -y gh
- name: Prepare workspace - name: Prepare workspace
run: rm -rf publish-ppa && mkdir publish-ppa run: rm -rf publish-ppa && mkdir publish-ppa
- name: Download ${{ inputs.tag }} offline source code - name: Download ${{ inputs.tag }} offline source code
@@ -143,8 +94,10 @@ jobs:
gpg_passphrase: ${{ secrets.PPA_GPG_PASSPHRASE }} gpg_passphrase: ${{ secrets.PPA_GPG_PASSPHRASE }}
tarball: publish-ppa/globalprotect-openconnect-*.tar.gz tarball: publish-ppa/globalprotect-openconnect-*.tar.gz
debian_dir: publish-ppa/globalprotect-openconnect-*/.build/debian debian_dir: publish-ppa/globalprotect-openconnect-*/.build/debian
deb_email: ${{ vars.DEB_EMAIL }} deb_email: "[email protected]"
deb_fullname: ${{ vars.DEB_FULLNAME }} deb_fullname: "Kevin Yue"
extra_ppa: "yuezk/globalprotect-openconnect" extra_ppa: "yuezk/globalprotect-openconnect"
series: ${{ matrix.series }} # Ubuntu 18.04 and 20.04 are excluded because tauri2 no longer supports them
excluded_series: "bionic focal ${{ inputs.excluded_series }}"
series: ${{ inputs.series }}
revision: ${{ inputs.revision }} revision: ${{ inputs.revision }}
+4 -127
View File
@@ -30,21 +30,11 @@ on:
description: 'Build PKG package' description: 'Build PKG package'
required: true required: true
default: true default: true
release-apk:
type: boolean
description: 'Build APK package'
required: true
default: true
release-binary: release-binary:
type: boolean type: boolean
description: 'Build binary package' description: 'Build binary package'
required: true required: true
default: true default: true
release-docker:
type: boolean
description: 'Publish Docker image'
required: true
default: true
gh-release: gh-release:
type: boolean type: boolean
description: 'Update GitHub release' description: 'Update GitHub release'
@@ -89,7 +79,7 @@ jobs:
} }
const package = Object.entries(inputs) const package = Object.entries(inputs)
.filter(([key, value]) => key.startsWith('release-') && key !== 'release-docker' && value) .filter(([key, value]) => key.startsWith('release-') && value)
.map(([key, value]) => key.replace('release-', '')) .map(([key, value]) => key.replace('release-', ''))
return JSON.stringify({ return JSON.stringify({
@@ -137,117 +127,13 @@ jobs:
bash install.sh bash install.sh
- name: Upload ${{ matrix.package }} package - name: Upload ${{ matrix.package }} package
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v4
with: with:
name: artifact-${{ matrix.os }}-${{ matrix.package }} name: artifact-${{ matrix.os }}-${{ matrix.package }}
if-no-files-found: error if-no-files-found: error
path: | path: |
build-${{ matrix.package }}/artifacts/* build-${{ matrix.package }}/artifacts/*
build-docker-image:
needs:
- check
if: ${{ inputs.release-docker }}
strategy:
fail-fast: false
matrix:
include:
- runner: ubuntu-latest
platform: linux/amd64
- runner: ubuntu-24.04-arm
platform: linux/arm64
runs-on: ${{ matrix.runner }}
steps:
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> "$GITHUB_ENV"
- name: Prepare workspace
run: rm -rf docker-image && mkdir -p docker-image/source
- name: Download ${{ inputs.tag }} source code
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
gh -R yuezk/GlobalProtect-openconnect \
release download ${{ inputs.tag }} \
--pattern '*[^offline].tar.gz' \
--dir docker-image
tar -xzf docker-image/*.tar.gz -C docker-image/source --strip-components=1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Build and push by digest
id: build
uses: docker/build-push-action@v7
with:
context: docker-image/source
file: docker-image/source/packaging/docker/alpine/Dockerfile
platforms: ${{ matrix.platform }}
outputs: type=image,name=yuezk/globalprotect-openconnect,push-by-digest=true,name-canonical=true,push=true
- name: Verify CLI tools
env:
IMAGE: yuezk/globalprotect-openconnect
DIGEST: ${{ steps.build.outputs.digest }}
run: |
docker run --rm "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint gpauth "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v7
with:
name: digests-${{ env.PLATFORM_PAIR }}
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
publish-docker-image:
needs:
- build-docker-image
if: ${{ inputs.release-docker }}
runs-on: ubuntu-latest
steps:
- name: Download digests
uses: actions/download-artifact@v8
with:
path: /tmp/digests
pattern: digests-*
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Publish Docker manifest
working-directory: /tmp/digests
env:
IMAGE: yuezk/globalprotect-openconnect
TAG: ${{ inputs.tag }}
run: |
VERSION="${TAG#v}"
tags=(-t "$IMAGE:$TAG")
if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
tags+=(-t "$IMAGE:$VERSION" -t "$IMAGE:latest")
fi
docker buildx imagetools create "${tags[@]}" \
$(printf "$IMAGE@sha256:%s " *)
docker buildx imagetools inspect "$IMAGE:$TAG"
gh-release: gh-release:
needs: needs:
- build - build
@@ -257,19 +143,9 @@ jobs:
- name: Prepare workspace - name: Prepare workspace
run: rm -rf gh-release && mkdir gh-release run: rm -rf gh-release && mkdir gh-release
- name: Download artifact - name: Download artifact
uses: actions/download-artifact@v8 uses: actions/download-artifact@v4
with: with:
path: gh-release path: gh-release
- name: Rename APK artifacts
run: |
shopt -s nullglob
for file in gh-release/artifact-ubuntu-latest-apk/*.apk; do
mv "$file" "${file%.apk}-x86_64.apk"
done
for file in gh-release/artifact-ubuntu-24.04-arm-apk/*.apk; do
mv "$file" "${file%.apk}-aarch64.apk"
done
- name: Update release - name: Update release
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v1
with: with:
@@ -279,3 +155,4 @@ jobs:
tag_name: ${{ inputs.tag }} tag_name: ${{ inputs.tag }}
files: | files: |
gh-release/artifact-*/* gh-release/artifact-*/*
@@ -1,69 +0,0 @@
name: Update flake hashes
on:
workflow_dispatch:
inputs:
version:
description: "Release version. Defaults to Cargo.toml workspace version."
required: false
release:
types:
- published
permissions:
contents: write
pull-requests: write
jobs:
update-flake-hashes:
runs-on: ubuntu-latest
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
- name: Install Nix
uses: cachix/install-nix-action@v31
- name: Update flake hashes
env:
RELEASE_VERSION: ${{ github.event.release.tag_name || inputs.version }}
run: |
if [[ -n "$RELEASE_VERSION" ]]; then
scripts/update-flake-hashes.sh "$RELEASE_VERSION"
else
scripts/update-flake-hashes.sh
fi
- name: Open pull request
env:
GH_TOKEN: ${{ github.token }}
RELEASE_VERSION: ${{ github.event.release.tag_name || inputs.version }}
run: |
if git diff --quiet -- flake.nix; then
echo "flake.nix hashes are already up to date"
exit 0
fi
version="${RELEASE_VERSION:-$(grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/')}"
version="${version#v}"
branch="chore/update-flake-hashes-v${version}"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git switch -c "$branch"
git add flake.nix
git commit -m "chore: update flake hashes for v${version}"
git push --force-with-lease origin "$branch"
if gh pr view "$branch" --json number > /tmp/flake-pr.json 2> /dev/null; then
pr_number="$(jq -r '.number' /tmp/flake-pr.json)"
gh pr edit "$pr_number" \
--title "chore: update flake hashes for v${version}" \
--body "Updates the Nix flake fetchzip hashes for v${version} release assets."
else
gh pr create \
--title "chore: update flake hashes for v${version}" \
--body "Updates the Nix flake fetchzip hashes for v${version} release assets." \
--base main \
--head "$branch"
fi
-1
View File
@@ -8,7 +8,6 @@
.cargo .cargo
.build .build
SNAPSHOT SNAPSHOT
SOURCE_COMMIT
# Tauri generated files # Tauri generated files
gen gen
Generated
+792 -413
View File
File diff suppressed because it is too large. Load diff
+1 -2
View File
@@ -11,7 +11,7 @@ members = [
[workspace.package] [workspace.package]
rust-version = "1.89" rust-version = "1.89"
version = "2.5.4" version = "2.5.1"
authors = ["Kevin Yue <[email protected]>"] authors = ["Kevin Yue <[email protected]>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect" homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2024" edition = "2024"
@@ -59,7 +59,6 @@ which = "8"
uuid = "1" uuid = "1"
netdev = "0.40" netdev = "0.40"
machine-uid = "0.5" machine-uid = "0.5"
humantime = "2"
# Tauri dependencies # Tauri dependencies
tauri = { version = "2" } tauri = { version = "2" }
+4 -38
View File
@@ -7,17 +7,6 @@ RUST_VERSION ?= 1.89
IGNORE_RUST_VERSION ?= 0 IGNORE_RUST_VERSION ?= 0
VERSION = $(shell grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/') VERSION = $(shell grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/')
SOURCE_COMMIT_VALUE := $(shell \
if [ -n "$$SOURCE_GIT_COMMIT" ]; then \
printf '%s' "$$SOURCE_GIT_COMMIT" | cut -c1-9; \
elif [ -n "$$GITHUB_SHA" ]; then \
printf '%s' "$$GITHUB_SHA" | cut -c1-9; \
elif [ -f SOURCE_COMMIT ]; then \
head -n1 SOURCE_COMMIT | tr -d '[:space:]' | cut -c1-9; \
else \
git rev-parse --short=9 HEAD 2>/dev/null || printf unknown; \
fi)
GUI_LIBC_SUFFIX ?= $(shell ldd --version 2>&1 | grep -qi musl && echo -musl || true)
REVISION ?= 1 REVISION ?= 1
RPM_SOURCE ?= %{name}.tar.gz RPM_SOURCE ?= %{name}.tar.gz
@@ -65,13 +54,11 @@ clean-tarball:
rm -rf .vendor rm -rf .vendor
rm -rf vendor.tar.xz rm -rf vendor.tar.xz
rm -rf .cargo rm -rf .cargo
rm -f SOURCE_COMMIT
# Create a tarball, include the cargo dependencies if OFFLINE is set to 1 # Create a tarball, include the cargo dependencies if OFFLINE is set to 1
tarball: clean-tarball tarball: clean-tarball
mkdir -p .cargo mkdir -p .cargo
mkdir -p .build/tarball mkdir -p .build/tarball
printf '%s\n' "$(SOURCE_COMMIT_VALUE)" > SOURCE_COMMIT
# If OFFLINE is set to 1, vendor all cargo dependencies # If OFFLINE is set to 1, vendor all cargo dependencies
# Generate a OFFLINE_BUILD file to indicate offline build # Generate a OFFLINE_BUILD file to indicate offline build
@@ -90,8 +77,8 @@ download-gui:
if [ $(INCLUDE_GUI) -eq 1 ]; then \ if [ $(INCLUDE_GUI) -eq 1 ]; then \
echo "Downloading GlobalProtect GUI..."; \ echo "Downloading GlobalProtect GUI..."; \
mkdir -p .build/gpgui; \ mkdir -p .build/gpgui; \
curl -sSL https://github.com/yuezk/GlobalProtect-openconnect/releases/download/$(RELEASE_TAG)/gpgui_$(shell uname -m)$(GUI_LIBC_SUFFIX).bin.tar.xz \ curl -sSL https://github.com/yuezk/GlobalProtect-openconnect/releases/download/$(RELEASE_TAG)/gpgui_$(shell uname -m).bin.tar.xz \
-o .build/gpgui/gpgui_$(shell uname -m)$(GUI_LIBC_SUFFIX).bin.tar.xz; \ -o .build/gpgui/gpgui_$(shell uname -m).bin.tar.xz; \
tar -xJf .build/gpgui/*.tar.xz -C .build/gpgui; \ tar -xJf .build/gpgui/*.tar.xz -C .build/gpgui; \
else \ else \
echo "Skipping GlobalProtect GUI download (INCLUDE_GUI=0)"; \ echo "Skipping GlobalProtect GUI download (INCLUDE_GUI=0)"; \
@@ -113,7 +100,7 @@ build-rs:
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \ if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth -p gpgui-helper; \ $(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth -p gpgui-helper; \
else \ else \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth --no-default-features; \ $(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth; \
fi fi
clean: clean:
@@ -138,7 +125,7 @@ install:
install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/bin/gpgui; \ install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/bin/gpgui; \
fi fi
install -Dm755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)/usr/libexec/gpclient/vpnc-script # Install the HIP report script
install -Dm755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh install -Dm755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
# Install the disconnect hooks # Install the disconnect hooks
@@ -161,7 +148,6 @@ uninstall:
rm -f $(DESTDIR)/usr/bin/gpgui-helper rm -f $(DESTDIR)/usr/bin/gpgui-helper
rm -f $(DESTDIR)/usr/bin/gpgui 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/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/pre-down.d/gpclient.down
@@ -283,26 +269,6 @@ init-pkgbuild: clean-pkgbuild tarball
pkgbuild: init-pkgbuild pkgbuild: init-pkgbuild
cd .build/pkgbuild && makepkg -s --noconfirm cd .build/pkgbuild && makepkg -s --noconfirm
clean-apk:
rm -rf .build/apk
init-apk: clean-apk tarball
mkdir -p .build/apk
cp .build/tarball/${PKG}.tar.gz .build/apk
cp packaging/apk/APKBUILD.in .build/apk/APKBUILD
sed -i "s/@PKG_NAME@/$(PKG_NAME)/g" .build/apk/APKBUILD
sed -i "s/@VERSION@/$(VERSION)/g" .build/apk/APKBUILD
sed -i "s/@REVISION@/$(REVISION)/g" .build/apk/APKBUILD
checksum=$$(sha512sum .build/apk/${PKG}.tar.gz | cut -d' ' -f1); \
sed -i "s/@SHA512@/$$checksum/g" .build/apk/APKBUILD
apk: init-apk
cd .build/apk && abuild -r -P "$(CURDIR)/.build/apk/packages"
find .build/apk/packages -type f -name "$(PKG_NAME)-*.apk" -exec cp {} .build/apk \;
clean-binary: clean-binary:
rm -rf .build/binary rm -rf .build/binary
+4 -79
View File
@@ -20,10 +20,8 @@ A modern GlobalProtect VPN client for Linux, built on OpenConnect with full supp
- [Fedora 38+ / Rawhide](#fedora-38--rawhide) - [Fedora 38+ / Rawhide](#fedora-38--rawhide)
- [openSUSE Leap 15.6+ / Tumbleweed](#opensuse-leap-156--tumbleweed) - [openSUSE Leap 15.6+ / Tumbleweed](#opensuse-leap-156--tumbleweed)
- [Other RPM-based Distributions](#other-rpm-based-distributions) - [Other RPM-based Distributions](#other-rpm-based-distributions)
- [Alpine Linux](#alpine-linux)
- [Gentoo](#gentoo) - [Gentoo](#gentoo)
- [NixOS](#nixos) - [NixOS](#nixos)
- [Official Docker Image](#official-docker-image)
- [Other Distributions](#other-distributions) - [Other Distributions](#other-distributions)
- [Building from Source](#building-from-source) - [Building from Source](#building-from-source)
- [Frequently Asked Questions](#frequently-asked-questions) - [Frequently Asked Questions](#frequently-asked-questions)
@@ -98,10 +96,6 @@ gpclient launch-gui
## Installation ## Installation
> [!Note]
>
> For older Linux distributions, use [v2.3.13](https://github.com/yuezk/GlobalProtect-openconnect/releases/tag/v2.3.13) instead of the latest release. It provides release assets for common distro families, including Debian/Ubuntu (`.deb`), Arch Linux / Manjaro (`.pkg.tar.zst`), RPM-based distros such as Fedora / RHEL / Rocky / AlmaLinux / CentOS (`.rpm`), and generic Linux tarballs (`.bin.tar.xz`).
### Debian / Ubuntu ### Debian / Ubuntu
#### Option 1: Install from PPA (Recommended) #### Option 1: Install from PPA (Recommended)
@@ -188,16 +182,6 @@ Download the latest RPM package from the [releases](https://github.com/yuezk/Glo
sudo rpm -i globalprotect-openconnect-*.rpm sudo rpm -i globalprotect-openconnect-*.rpm
``` ```
### Alpine Linux
Download the latest `.apk` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
```bash
sudo apk add --allow-untrusted globalprotect-openconnect-*.apk
```
The package uses Alpine's native musl build. Make sure the `community` repository is enabled so GUI dependencies such as `webkit2gtk-4.1`, `libsecret`, and `libayatana-appindicator` can be resolved. GUI-launched connections use polkit, and VPN tunnel creation requires `/dev/net/tun`.
### Gentoo ### Gentoo
Available via the `guru` and `lamdness` overlays: Available via the `guru` and `lamdness` overlays:
@@ -212,14 +196,6 @@ sudo emerge --ask --verbose net-vpn/GlobalProtect-openconnect
This repository includes a flake for NixOS integration. This repository includes a flake for NixOS integration.
If you want a quick user-level install, you can install it directly from the flake:
```bash
nix profile add github:yuezk/GlobalProtect-openconnect
```
If you want it managed as part of your NixOS system configuration, use the steps below.
#### Installation Steps #### Installation Steps
1. Add the flake to your `flake.nix`: 1. Add the flake to your `flake.nix`:
@@ -263,54 +239,6 @@ If you want it managed as part of your NixOS system configuration, use the steps
sudo nixos-rebuild switch sudo nixos-rebuild switch
``` ```
### Official Docker Image
The official Docker image provides the CLI tools on Alpine Linux:
```bash
docker pull yuezk/globalprotect-openconnect:<version>
```
Release images are tagged as `vX.Y.Z`, `X.Y.Z`, and `latest`.
Run it with access to the TUN device:
```bash
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --cookie-on-stdin
```
For browser authentication in a headless environment, use remote browser authentication:
```bash
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --browser remote
```
On a Linux host, add host networking if the VPN routes should affect the host network namespace:
```bash
docker run --rm -it --network host --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --browser remote
```
Without `--network host`, the VPN connection stays inside the container's network namespace. Docker Desktop on macOS and Windows does not make the host use the VPN through `--network host`; run `gpclient` on the host or use a container gateway setup for host traffic.
Alternatively, pipe `gpauth` remote-browser output into `gpclient`:
```bash
docker run --rm -it --entrypoint gpauth yuezk/globalprotect-openconnect:<version> \
<portal> --browser remote 2>/dev/null \
| docker run --rm -i --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --cookie-on-stdin
```
The image includes `gpclient` and `gpauth` only. It does not include embedded webview authentication, `gpgui-helper`, or `gpgui`.
### Other Distributions ### Other Distributions
#### Manual Installation #### Manual Installation
@@ -360,16 +288,13 @@ This project includes a DevContainer configuration that provides a consistent, r
``` ```
3. **Build the project:** 3. **Build the project:**
To build everything including the GUI helper run this command:
```bash ```bash
docker run --privileged --cap-add=NET_ADMIN --device=/dev/net/tun \ docker run --privileged --cap-add=NET_ADMIN --device=/dev/net/tun \
--tty -v "$(pwd)":/workspace -w /workspace gpoc-devcontainer \ -v "$(pwd)":/workspace -w /workspace gpoc-devcontainer \
bash -c "export PATH=/usr/local/cargo/bin:\$PATH && make build" bash -c "export PATH=/usr/local/cargo/bin:\$PATH && make build"
``` ```
To build without the GUI helper run the same command as above, but with `BUILD_GUI_HELPER=0` passed as an argument to `make`.
5. **Locate build artifacts:** 4. **Locate build artifacts:**
The compiled binaries will be available in `target/release/`: The compiled binaries will be available in `target/release/`:
- `gpclient` – CLI client - `gpclient` – CLI client
@@ -392,7 +317,7 @@ This project includes a DevContainer configuration that provides a consistent, r
- [Rust 1.89 or later](https://www.rust-lang.org/tools/install) - [Rust 1.89 or later](https://www.rust-lang.org/tools/install)
- [Tauri dependencies](https://tauri.app/start/prerequisites/) - [Tauri dependencies](https://tauri.app/start/prerequisites/)
- OpenConnect source-build dependencies: `autoconf`, `automake`, `autopoint`/`gettext`, `libtool`, `patch`, `pkg-config`, `libxml2`, `zlib`, `lz4`, `gnutls`, `p11-kit`, `nettle`, and `gmp` development packages - `libopenconnect-dev` (or `openconnect-devel` on RPM-based systems)
- `pkexec` and `gnome-keyring` (or `pam_kwallet` on KDE) - `pkexec` and `gnome-keyring` (or `pam_kwallet` on KDE)
- `nodejs` and `pnpm` (optional) - `nodejs` and `pnpm` (optional)
@@ -454,7 +379,7 @@ See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/iss
### Trial and Pricing ### Trial and Pricing
The **CLI version** is completely free and open source. The **CLI version** is completely free and open source.
The **GUI version** is a paid application with a **7-day trial period** after installation. The **GUI version** is a paid application with a **10-day trial period** after installation.
### Open Source Licenses ### Open Source Licenses
+1 -1
View File
@@ -21,7 +21,7 @@ clap.workspace = true
env_logger.workspace = true env_logger.workspace = true
log.workspace = true log.workspace = true
serde_json.workspace = true serde_json.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] } tokio.workspace = true
tempfile.workspace = true tempfile.workspace = true
compile-time.workspace = true compile-time.workspace = true
-59
View File
@@ -1,63 +1,4 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() { fn main() {
println!("cargo:rerun-if-env-changed=GPAUTH_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPAUTH_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
tauri_build::build() tauri_build::build()
} }
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPAUTH_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+3 -10
View File
@@ -1,9 +1,9 @@
use auth::{BrowserAuthenticator, auth_prelogin}; use auth::{auth_prelogin, BrowserAuthenticator};
use clap::Parser; use clap::Parser;
use common::constants::GP_USER_AGENT; use common::constants::GP_USER_AGENT;
use gpapi::{ use gpapi::{
auth::{SamlAuthData, SamlAuthResult}, auth::{SamlAuthData, SamlAuthResult},
clap::{Args, InfoLevelVerbosity, args::Os, handle_error}, clap::{args::Os, handle_error, Args, InfoLevelVerbosity},
gp_params::{ClientOs, GpParams}, gp_params::{ClientOs, GpParams},
utils::{normalize_server, openssl}, utils::{normalize_server, openssl},
}; };
@@ -11,14 +11,7 @@ use log::info;
use serde_json::json; use serde_json::json;
use tempfile::NamedTempFile; use tempfile::NamedTempFile;
const VERSION: &str = concat!( const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
env!("CARGO_PKG_VERSION"),
" (",
env!("GPAUTH_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[derive(Parser)] #[derive(Parser)]
#[command( #[command(
-56
View File
@@ -1,56 +0,0 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GPCLIENT_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
let commit = env_commit("GPCLIENT_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(&source_commit))
.or_else(|| git_commit(&repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string());
println!("cargo:rustc-env=GPCLIENT_GIT_COMMIT={commit}");
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=12", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+6 -13
View File
@@ -19,14 +19,7 @@ use crate::{
launch_gui::{LaunchGuiArgs, LaunchGuiHandler}, launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
}; };
const VERSION: &str = concat!( const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
env!("CARGO_PKG_VERSION"),
" (",
env!("GPCLIENT_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
pub(crate) struct SharedArgs<'a> { pub(crate) struct SharedArgs<'a> {
pub(crate) fix_openssl: bool, pub(crate) fix_openssl: bool,
@@ -154,11 +147,11 @@ fn init_logger(cli: &Cli) {
// Output the log messages to a file if the command is the auth callback // Output the log messages to a file if the command is the auth callback
if let CliCommand::LaunchGui(args) = &cli.command { if let CliCommand::LaunchGui(args) = &cli.command {
let auth_data = args.auth_data.as_deref().unwrap_or_default(); let auth_data = args.auth_data.as_deref().unwrap_or_default();
if !auth_data.is_empty() if !auth_data.is_empty() {
&& let Ok(log_file) = File::create(temp_dir().join("gpcallback.log")) if let Ok(log_file) = File::create(temp_dir().join("gpcallback.log")) {
{ let target = Box::new(log_file);
let target = Box::new(log_file); builder.target(env_logger::Target::Pipe(target));
builder.target(env_logger::Target::Pipe(target)); }
} }
} }
+83 -292
View File
@@ -1,10 +1,4 @@
use std::{ use std::{borrow::Cow, cell::RefCell, fs, sync::Arc};
borrow::Cow,
cell::RefCell,
fs,
str::FromStr,
sync::{Arc, Mutex},
};
use anyhow::{Context, bail}; use anyhow::{Context, bail};
use clap::Args; use clap::Args;
@@ -14,10 +8,7 @@ use gpapi::{
clap::{ToVerboseArg, args::Os}, clap::{ToVerboseArg, args::Os},
credential::{Credential, PasswordCredential}, credential::{Credential, PasswordCredential},
error::PortalError, error::PortalError,
gateway::{ gateway::{GatewayLogin, gateway_login},
GatewayLogin, GatewayLoginContext, GatewaySelection, SessionExtensionAuth, gateway_login,
gateway_login_with_context,
},
gp_params::{ClientOs, GpParams}, gp_params::{ClientOs, GpParams},
portal::{Prelogin, StandardPrelogin, prelogin, retrieve_config}, portal::{Prelogin, StandardPrelogin, prelogin, retrieve_config},
process::{ process::{
@@ -29,68 +20,8 @@ use gpapi::{
use inquire::{Password, PasswordDisplayMode, Select, Text}; use inquire::{Password, PasswordDisplayMode, Select, Text};
use log::{info, warn}; use log::{info, warn};
use openconnect::Vpn; use openconnect::Vpn;
use tokio::{runtime::Handle, task::JoinHandle};
use crate::{ use crate::{GP_CLIENT_LOCK_FILE, cli::SharedArgs};
GP_CLIENT_LOCK_FILE,
cli::SharedArgs,
session::{SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info},
};
struct GatewayLoginSession {
cookie: String,
extension_auth: SessionExtensionAuth,
}
#[derive(Default)]
struct CleanAuthState {
requested: bool,
}
impl CleanAuthState {
fn new(requested: bool) -> Self {
Self { requested }
}
fn consume_for_webview(&mut self, webview_auth: bool) -> bool {
if !webview_auth || !self.requested {
return false;
}
self.requested = false;
true
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct CscPreferenceArg {
domain: String,
key: String,
value: String,
}
impl FromStr for CscPreferenceArg {
type Err = String;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let (name, value) = input
.split_once('=')
.ok_or_else(|| "expected <domain>:<key>=<value>".to_string())?;
let (domain, key) = name
.split_once(':')
.ok_or_else(|| "expected <domain>:<key>=<value>".to_string())?;
if domain.is_empty() || key.is_empty() || value.is_empty() {
return Err("domain, key, and value must be non-empty".to_string());
}
Ok(Self {
domain: domain.to_string(),
key: key.to_string(),
value: value.to_string(),
})
}
}
#[derive(Args)] #[derive(Args)]
pub(crate) struct ConnectArgs { pub(crate) struct ConnectArgs {
@@ -178,18 +109,8 @@ pub(crate) struct ConnectArgs {
#[arg(long, help = "Disable DTLS and ESP")] #[arg(long, help = "Disable DTLS and ESP")]
no_dtls: bool, no_dtls: bool,
#[arg( #[arg(long, help = "Comma-separated split-DNS domains to pass to the VPNC script")]
long = "local-hostname", split_dns: Option<String>,
help = "Same as the '--local-hostname' option in the openconnect command"
)]
local_hostname: Option<String>,
#[arg(
long = "csc-preference",
help = "Override a Mac CSC plist preference value, in the form <domain>:<key>=<value>",
value_name = "DOMAIN:KEY=VALUE"
)]
csc_preferences: Vec<CscPreferenceArg>,
#[arg( #[arg(
long = "force-dpd", long = "force-dpd",
@@ -197,12 +118,6 @@ pub(crate) struct ConnectArgs {
)] )]
dpd_interval: Option<u32>, dpd_interval: Option<u32>,
#[arg(
long = "no-xmlpost",
help = "Same as the '--no-xmlpost' option in the openconnect command"
)]
no_xmlpost: bool,
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")] #[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
hidpi: bool, hidpi: bool,
@@ -215,6 +130,7 @@ pub(crate) struct ConnectArgs {
#[arg(long, help = "Deprecated: Use the `--browser` option instead")] #[arg(long, help = "Deprecated: Use the `--browser` option instead")]
default_browser: bool, default_browser: bool,
#[cfg(feature = "webview-auth")]
#[arg( #[arg(
long, long,
help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, `remote`.\nOr the path to the browser executable.\nUse 'remote' for headless servers.", help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, `remote`.\nOr the path to the browser executable.\nUse 'remote' for headless servers.",
@@ -245,6 +161,24 @@ impl ConnectArgs {
Os::Mac => host_utils::get_macos_os_string(), Os::Mac => host_utils::get_macos_os_string(),
} }
} }
fn normalized_split_dns(&self) -> anyhow::Result<Option<String>> {
let Some(split_dns) = self.split_dns.as_deref() else {
return Ok(None);
};
let domains = split_dns
.split(',')
.map(str::trim)
.map(str::to_owned)
.collect::<Vec<_>>();
if domains.iter().any(|domain| domain.is_empty()) {
bail!("The '--split-dns' option must contain a comma-separated list of non-empty domains");
}
Ok(Some(domains.join(",")))
}
} }
pub(crate) struct ConnectHandler<'a> { pub(crate) struct ConnectHandler<'a> {
@@ -253,23 +187,16 @@ pub(crate) struct ConnectHandler<'a> {
latest_key_password: RefCell<Option<String>>, latest_key_password: RefCell<Option<String>>,
password_from_stdin: RefCell<Option<String>>, password_from_stdin: RefCell<Option<String>>,
cookie_from_stdin: RefCell<Option<String>>, cookie_from_stdin: RefCell<Option<String>>,
clean_auth_state: RefCell<CleanAuthState>,
} }
impl<'a> ConnectHandler<'a> { impl<'a> ConnectHandler<'a> {
pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self { pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self {
#[cfg(feature = "webview-auth")]
let clean_auth = args.clean;
#[cfg(not(feature = "webview-auth"))]
let clean_auth = false;
Self { Self {
args, args,
shared_args, shared_args,
latest_key_password: Default::default(), latest_key_password: Default::default(),
password_from_stdin: Default::default(), password_from_stdin: Default::default(),
cookie_from_stdin: Default::default(), cookie_from_stdin: Default::default(),
clean_auth_state: RefCell::new(CleanAuthState::new(clean_auth)),
} }
} }
@@ -288,25 +215,15 @@ impl<'a> ConnectHandler<'a> {
} }
fn build_gp_params(&self) -> GpParams { fn build_gp_params(&self) -> GpParams {
let mut builder = GpParams::builder(); GpParams::builder()
builder
.user_agent(&self.user_agent()) .user_agent(&self.user_agent())
.client_os(ClientOs::from(&self.args.os)) .client_os(ClientOs::from(&self.args.os))
.os_version(self.args.os_version().to_owned()) .os_version(self.args.os_version().to_owned())
.ignore_tls_errors(self.shared_args.ignore_tls_errors) .ignore_tls_errors(self.shared_args.ignore_tls_errors)
.certificate(self.args.certificate.clone()) .certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone()) .sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone()); .key_password(self.latest_key_password.borrow().clone())
.build()
if let Some(local_hostname) = self.args.local_hostname.as_deref() {
builder.computer(local_hostname);
}
for preference in &self.args.csc_preferences {
builder.csc_preference_override(&preference.domain, &preference.key, &preference.value);
}
builder.build()
} }
pub(crate) async fn handle(&self) -> anyhow::Result<()> { pub(crate) async fn handle(&self) -> anyhow::Result<()> {
@@ -360,14 +277,14 @@ impl<'a> ConnectHandler<'a> {
} }
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> { pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
self.args.normalized_split_dns()?;
let server = self.args.server.as_str(); let server = self.args.server.as_str();
let as_gateway = self.args.as_gateway; let as_gateway = self.args.as_gateway;
if as_gateway { if as_gateway {
info!("Treating the server as a gateway"); info!("Treating the server as a gateway");
return self return self.connect_gateway_with_prelogin(server).await;
.connect_gateway_with_prelogin(server, server, self.args.client_version.as_deref(), false, None)
.await;
} }
let Err(err) = self.connect_portal_with_prelogin(server).await else { let Err(err) = self.connect_portal_with_prelogin(server).await else {
@@ -377,9 +294,7 @@ impl<'a> ConnectHandler<'a> {
warn!("Failed to connect portal with prelogin: {}", err); warn!("Failed to connect portal with prelogin: {}", err);
if err.root_cause().downcast_ref::<PortalError>().is_some() { if err.root_cause().downcast_ref::<PortalError>().is_some() {
info!("Trying the gateway authentication workflow..."); info!("Trying the gateway authentication workflow...");
self self.connect_gateway_with_prelogin(server).await?;
.connect_gateway_with_prelogin(server, server, self.args.client_version.as_deref(), false, None)
.await?;
eprintln!("\nNOTE: the server may be a gateway, not a portal."); eprintln!("\nNOTE: the server may be a gateway, not a portal.");
eprintln!("NOTE: try to use the `--as-gateway` option if you were authenticated twice."); eprintln!("NOTE: try to use the `--as-gateway` option if you were authenticated twice.");
@@ -398,11 +313,6 @@ impl<'a> ConnectHandler<'a> {
let cred = self.obtain_credential(&prelogin, portal).await?; let cred = self.obtain_credential(&prelogin, portal).await?;
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?; let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
let gateway_selection = if self.args.gateway.is_some() {
GatewaySelection::Manual
} else {
GatewaySelection::Auto
};
let selected_gateway = match &self.args.gateway { let selected_gateway = match &self.args.gateway {
Some(gateway) => portal_config Some(gateway) => portal_config
.find_gateway(gateway) .find_gateway(gateway)
@@ -426,55 +336,23 @@ impl<'a> ConnectHandler<'a> {
let gateway = selected_gateway.server(); let gateway = selected_gateway.server();
let cred = portal_config.auth_cookie().into(); let cred = portal_config.auth_cookie().into();
let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version());
let gateway_context = GatewayLoginContext::new(selected_gateway, gateway_selection)
.with_connect_method(portal_config.connect_method())
.with_client_version(client_version);
let login_session = match self let cookie = match self.login_gateway(gateway, &cred, &gp_params).await {
.login_gateway(gateway, &cred, &gp_params, Some(&gateway_context)) Ok(cookie) => cookie,
.await
{
Ok(login_session) => login_session,
Err(err) => { Err(err) => {
info!("Gateway login failed: {}", err); info!("Gateway login failed: {}", err);
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false); return self.connect_gateway_with_prelogin(gateway).await;
return self
.connect_gateway_with_prelogin(
portal,
gateway,
client_version,
allow_extend_session,
Some(gateway_context),
)
.await;
} }
}; };
// Use the client version from the command line argument if specified, otherwise // Use the client version from the command line argument if specified, otherwise
// use the version from the portal config if available // use the version from the portal config if available
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false); let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version());
self self.connect_gateway(gateway, &cookie, client_version).await
.connect_gateway(
portal,
gateway,
&login_session.cookie,
client_version,
allow_extend_session,
login_session.extension_auth,
)
.await
} }
async fn connect_gateway_with_prelogin( async fn connect_gateway_with_prelogin(&self, gateway: &str) -> anyhow::Result<()> {
&self,
portal: &str,
gateway: &str,
client_version: Option<&str>,
allow_extend_session: bool,
gateway_context: Option<GatewayLoginContext>,
) -> anyhow::Result<()> {
info!("Performing the gateway authentication..."); info!("Performing the gateway authentication...");
let mut gp_params = self.build_gp_params(); let mut gp_params = self.build_gp_params();
@@ -483,44 +361,20 @@ impl<'a> ConnectHandler<'a> {
let prelogin = prelogin(gateway, &gp_params).await?; let prelogin = prelogin(gateway, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, gateway).await?; let cred = self.obtain_credential(&prelogin, gateway).await?;
let login_session = self let cookie = self.login_gateway(gateway, &cred, &gp_params).await?;
.login_gateway(gateway, &cred, &gp_params, gateway_context.as_ref())
.await?;
self // When logging in to a gateway directly, there is no portal config to get the client version from
.connect_gateway( let client_version = self.args.client_version.as_deref();
portal,
gateway, self.connect_gateway(gateway, &cookie, client_version).await
&login_session.cookie,
client_version,
allow_extend_session,
login_session.extension_auth,
)
.await
} }
async fn login_gateway( async fn login_gateway(&self, gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<String> {
&self,
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
gateway_context: Option<&GatewayLoginContext>,
) -> anyhow::Result<GatewayLoginSession> {
let mut gp_params = gp_params.clone(); let mut gp_params = gp_params.clone();
loop { loop {
let login = match gateway_context { match gateway_login(gateway, cred, &gp_params).await? {
Some(context) => gateway_login_with_context(gateway, cred, &gp_params, context).await?, GatewayLogin::Cookie(cookie) => return Ok(cookie),
None => gateway_login(gateway, cred, &gp_params).await?,
};
match login {
GatewayLogin::Cookie(cookie) => {
return Ok(GatewayLoginSession {
cookie,
extension_auth: SessionExtensionAuth::new(cred.clone(), gp_params),
});
}
GatewayLogin::Mfa(message, input_str) => { GatewayLogin::Mfa(message, input_str) => {
let otp = Text::new(&message).prompt()?; let otp = Text::new(&message).prompt()?;
gp_params.set_input_str(&input_str); gp_params.set_input_str(&input_str);
@@ -532,16 +386,9 @@ impl<'a> ConnectHandler<'a> {
} }
} }
async fn connect_gateway( async fn connect_gateway(&self, gateway: &str, cookie: &str, client_version: Option<&str>) -> anyhow::Result<()> {
&self,
portal: &str,
gateway: &str,
cookie: &str,
client_version: Option<&str>,
allow_extend_session: bool,
extension_auth: SessionExtensionAuth,
) -> anyhow::Result<()> {
let mtu = self.args.mtu.unwrap_or(0); let mtu = self.args.mtu.unwrap_or(0);
let split_dns = self.args.normalized_split_dns()?;
let (hip, csd_wrapper) = self.determine_hip_script(); let (hip, csd_wrapper) = self.determine_hip_script();
let hip_user = self.determine_hip_user(); let hip_user = self.determine_hip_user();
let csd_uid = get_uid(&hip_user)?; let csd_uid = get_uid(&hip_user)?;
@@ -549,20 +396,6 @@ impl<'a> ConnectHandler<'a> {
let os = ClientOs::from(&self.args.os).to_openconnect_os().to_owned(); let os = ClientOs::from(&self.args.os).to_openconnect_os().to_owned();
let os_version = self.args.os_version().to_owned(); let os_version = self.args.os_version().to_owned();
let client_version = client_version.map(|s| s.to_owned()); let client_version = client_version.map(|s| s.to_owned());
let session_ctx = build_session_context(SessionContextInput {
portal: portal.to_string(),
gateway: gateway.to_string(),
cookie: cookie.to_string(),
user_agent: self.user_agent().into_owned(),
os: ClientOs::from(&self.args.os),
os_version: os_version.clone(),
client_version: client_version.clone(),
certificate: self.args.certificate.clone(),
sslkey: self.args.sslkey.clone(),
key_password: self.latest_key_password.borrow().clone(),
disable_ipv6: self.args.disable_ipv6,
extension_auth: Some(extension_auth),
});
let vpn = Vpn::builder(gateway, cookie) let vpn = Vpn::builder(gateway, cookie)
.script(self.args.script.clone()) .script(self.args.script.clone())
.interface(self.args.interface.clone()) .interface(self.args.interface.clone())
@@ -571,6 +404,7 @@ impl<'a> ConnectHandler<'a> {
.os(Some(os)) .os(Some(os))
.os_version(Some(os_version)) .os_version(Some(os_version))
.client_version(client_version) .client_version(client_version)
.split_dns(split_dns)
.certificate(self.args.certificate.clone()) .certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone()) .sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone()) .key_password(self.latest_key_password.borrow().clone())
@@ -581,18 +415,11 @@ impl<'a> ConnectHandler<'a> {
.mtu(mtu) .mtu(mtu)
.disable_ipv6(self.args.disable_ipv6) .disable_ipv6(self.args.disable_ipv6)
.no_dtls(self.args.no_dtls) .no_dtls(self.args.no_dtls)
.local_hostname(self.args.local_hostname.clone())
.dpd_interval(self.args.dpd_interval.unwrap_or(0)) .dpd_interval(self.args.dpd_interval.unwrap_or(0))
.no_xmlpost(self.args.no_xmlpost)
.build()?; .build()?;
let vpn = Arc::new(vpn); let vpn = Arc::new(vpn);
let vpn_clone = vpn.clone(); let vpn_clone = vpn.clone();
let runtime_handle = Handle::current();
let session_ctx = Arc::new(Mutex::new(Some(session_ctx)));
let session_task: Arc<Mutex<Option<JoinHandle<()>>>> = Arc::new(Mutex::new(None));
let session_task_on_connect = Arc::clone(&session_task);
let session_ctx_on_connect = Arc::clone(&session_ctx);
// Listen for the interrupt signal in the background // Listen for the interrupt signal in the background
tokio::spawn(async move { tokio::spawn(async move {
@@ -601,22 +428,7 @@ impl<'a> ConnectHandler<'a> {
vpn_clone.disconnect(); vpn_clone.disconnect();
}); });
vpn.connect(move |vpn_session_info| { vpn.connect(write_pid_file);
write_pid_file();
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
return;
};
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
info!("VPN session info: {}", session_info.log_summary());
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info);
session_task_on_connect.lock().unwrap().replace(task);
});
if let Some(task) = session_task.lock().unwrap().take() {
task.abort();
}
if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() { if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() {
info!("Removing PID file"); info!("Removing PID file");
@@ -644,6 +456,7 @@ impl<'a> ConnectHandler<'a> {
} else { } else {
None None
}; };
let os_version = self.args.os_version(); let os_version = self.args.os_version();
let verbose = self.shared_args.verbose.to_verbose_arg(); let verbose = self.shared_args.verbose.to_verbose_arg();
let user_agent = self.user_agent(); let user_agent = self.user_agent();
@@ -652,7 +465,7 @@ impl<'a> ConnectHandler<'a> {
.saml_request(prelogin.saml_request()) .saml_request(prelogin.saml_request())
.user_agent(&user_agent) .user_agent(&user_agent)
.os(self.args.os.as_str()) .os(self.args.os.as_str())
.os_version(Some(os_version)) .os_version(Some(&os_version))
.fix_openssl(self.shared_args.fix_openssl) .fix_openssl(self.shared_args.fix_openssl)
.ignore_tls_errors(self.shared_args.ignore_tls_errors) .ignore_tls_errors(self.shared_args.ignore_tls_errors)
.browser(browser) .browser(browser)
@@ -660,29 +473,10 @@ impl<'a> ConnectHandler<'a> {
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
let use_default_browser = prelogin.support_default_browser() && self.args.default_browser; let use_default_browser = prelogin.support_default_browser() && self.args.default_browser;
#[cfg(feature = "webview-auth")]
let browser_kind = if browser.is_some() || use_default_browser {
"external"
} else {
"embedded"
};
#[cfg(not(feature = "webview-auth"))]
let browser_kind = "external";
let clean_auth = self
.clean_auth_state
.borrow_mut()
.consume_for_webview(browser_kind == "embedded");
info!(
"SAML auth launch: gateway={}, clean={}, browser={}",
is_gateway, clean_auth, browser_kind
);
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
let auth_launcher = auth_launcher let auth_launcher = auth_launcher
.hidpi(self.args.hidpi) .hidpi(self.args.hidpi)
.clean(clean_auth) .clean(self.args.clean)
.default_browser(use_default_browser); .default_browser(use_default_browser);
let cred = auth_launcher.launch().await?; let cred = auth_launcher.launch().await?;
@@ -796,52 +590,49 @@ fn get_uid(user: &Option<String>) -> anyhow::Result<u32> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use clap::Parser;
use super::ConnectArgs;
#[derive(Parser)]
struct TestCli {
#[command(flatten)]
args: ConnectArgs,
}
fn parse_connect_args(args: &[&str]) -> ConnectArgs {
TestCli::parse_from(args).args
}
#[test] #[test]
fn parses_csc_preference_override() { fn parses_split_dns_domains() {
let preference = CscPreferenceArg::from_str("com.example.settings:ExampleKey=ExampleValue").unwrap(); let args = parse_connect_args(&["gpclient", "example.com", "--split-dns", "corp.local,svc.local"]);
assert_eq!( assert_eq!(
preference, args.normalized_split_dns().unwrap(),
CscPreferenceArg { Some("corp.local,svc.local".to_string())
domain: "com.example.settings".to_string(),
key: "ExampleKey".to_string(),
value: "ExampleValue".to_string(),
}
); );
} }
#[test] #[test]
fn rejects_invalid_csc_preference_override() { fn normalizes_split_dns_whitespace() {
assert!(CscPreferenceArg::from_str("com.example.settings:ExampleKey").is_err()); let args = parse_connect_args(&["gpclient", "example.com", "--split-dns", " corp.local , svc.local "]);
assert!(CscPreferenceArg::from_str("com.example.settings=ExampleValue").is_err());
assert!(CscPreferenceArg::from_str(":ExampleKey=ExampleValue").is_err()); assert_eq!(
assert!(CscPreferenceArg::from_str("com.example.settings:=ExampleValue").is_err()); args.normalized_split_dns().unwrap(),
assert!(CscPreferenceArg::from_str("com.example.settings:ExampleKey=").is_err()); Some("corp.local,svc.local".to_string())
);
} }
#[test] #[test]
fn clean_auth_state_is_consumed_once_for_webview() { fn rejects_empty_split_dns_domains() {
let mut state = CleanAuthState::new(true); let args = parse_connect_args(&["gpclient", "example.com", "--split-dns", "corp.local,,svc.local"]);
assert!(state.consume_for_webview(true)); let err = args.normalized_split_dns().unwrap_err();
assert!(!state.consume_for_webview(true));
}
#[test] assert_eq!(
fn clean_auth_state_is_not_consumed_by_external_browser() { err.to_string(),
let mut state = CleanAuthState::new(true); "The '--split-dns' option must contain a comma-separated list of non-empty domains"
);
assert!(!state.consume_for_webview(false));
assert!(state.consume_for_webview(true));
}
#[test]
fn clean_auth_state_remains_false_when_not_requested() {
let mut state = CleanAuthState::new(false);
assert!(!state.consume_for_webview(true));
assert!(!state.consume_for_webview(false));
} }
} }
-1
View File
@@ -3,7 +3,6 @@ mod connect;
mod disconnect; mod disconnect;
mod hip; mod hip;
mod launch_gui; mod launch_gui;
mod session;
pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock"; pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock";
-252
View File
@@ -1,252 +0,0 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use common::constants::GP_CLIENT_VERSION;
use gpapi::{
gateway::{SessionContext, SessionExtensionAuth, extend_session},
gp_params::ClientOs,
session::{SessionInfo, SessionRequestArgs, SessionWarning},
};
use log::{info, warn};
use openconnect::VpnSessionInfo;
use tokio::{runtime::Handle, task::JoinHandle};
#[derive(Debug, PartialEq, Eq)]
struct SessionWarningSchedule {
delay: Duration,
message: String,
should_auto_extend: bool,
}
pub(crate) struct SessionContextInput {
pub(crate) portal: String,
pub(crate) gateway: String,
pub(crate) cookie: String,
pub(crate) user_agent: String,
pub(crate) os: ClientOs,
pub(crate) os_version: String,
pub(crate) client_version: Option<String>,
pub(crate) certificate: Option<String>,
pub(crate) sslkey: Option<String>,
pub(crate) key_password: Option<String>,
pub(crate) disable_ipv6: bool,
pub(crate) extension_auth: Option<SessionExtensionAuth>,
}
pub(crate) fn build_session_context(input: SessionContextInput) -> SessionContext {
let session_args = SessionRequestArgs::new(input.cookie)
.with_user_agent(Some(input.user_agent))
.with_os(Some(input.os))
.with_os_version(Some(input.os_version))
.with_client_version(Some(
input.client_version.unwrap_or_else(|| GP_CLIENT_VERSION.to_string()),
))
.with_certificate(input.certificate)
.with_sslkey(input.sslkey)
.with_key_password(input.key_password)
.with_disable_ipv6(input.disable_ipv6);
let ctx = SessionContext::new(input.gateway, input.portal, session_args);
match input.extension_auth {
Some(extension_auth) => ctx.with_extension_auth(extension_auth),
None => ctx,
}
}
pub(crate) fn session_info_from_vpn(vpn_session_info: VpnSessionInfo, allow_extend_session: bool) -> SessionInfo {
SessionInfo::from_vpn_session_fields(
vpn_session_info.lifetime_secs,
vpn_session_info.user_expires,
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
prior_secs: warning.prior_secs,
message: warning.message,
}),
allow_extend_session,
)
}
pub(crate) fn spawn_session_runtime_with_info(
handle: &Handle,
session_ctx: SessionContext,
session_info: SessionInfo,
) -> JoinHandle<()> {
handle.spawn(run_session_runtime(session_ctx, session_info))
}
async fn run_session_runtime(session_ctx: SessionContext, mut session_info: SessionInfo) {
loop {
let Some(schedule) = build_session_warning_schedule(&session_info) else {
info!("No session warning schedule provided by the gateway");
return;
};
tokio::time::sleep(schedule.delay).await;
eprintln!("\nWARNING: {}", schedule.message);
if !schedule.should_auto_extend {
info!("Session extension is not allowed by the gateway");
return;
}
info!("Attempting to extend the session");
match extend_session(&session_ctx).await {
Ok(()) => {
let Some(next_session_info) = session_info.rescheduled_after_extension() else {
info!("Session extended, but no lifetime is available to schedule another warning");
return;
};
eprintln!("Session extended.");
session_info = next_session_info;
}
Err(err) => {
warn!("Failed to extend session: {}", err);
eprintln!("WARNING: Failed to extend session: {}", err);
return;
}
}
}
}
fn build_session_warning_schedule(session_info: &SessionInfo) -> Option<SessionWarningSchedule> {
let warning = session_info.lifetime_warning.as_ref()?;
let warning_secs = if let Some(user_expires) = session_info.user_expires {
let now = unix_timestamp();
user_expires.saturating_sub(warning.prior_secs).saturating_sub(now)
} else if let Some(lifetime_secs) = session_info.lifetime_secs {
lifetime_secs.saturating_sub(warning.prior_secs)
} else {
return None;
};
Some(SessionWarningSchedule {
delay: Duration::from_secs(warning_secs as u64),
message: warning.message.clone(),
should_auto_extend: session_info.allow_extend_session,
})
}
fn unix_timestamp() -> u32 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as u32
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_session_info(user_expires: Option<u32>, allow_extend_session: bool) -> SessionInfo {
SessionInfo {
user_expires,
lifetime_warning: Some(SessionWarning {
prior_secs: 1800,
message: "Session expires soon".to_string(),
}),
allow_extend_session,
..Default::default()
}
}
#[test]
fn builds_warning_schedule_for_auto_extend() {
let session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
let schedule = build_session_warning_schedule(&session_info).unwrap();
assert_eq!(schedule.message, "Session expires soon");
assert!(schedule.delay <= Duration::from_secs(30));
assert!(schedule.should_auto_extend);
}
#[test]
fn builds_warning_schedule_without_auto_extend() {
let session_info = sample_session_info(Some(unix_timestamp() + 1830), false);
let schedule = build_session_warning_schedule(&session_info).unwrap();
assert!(!schedule.should_auto_extend);
}
#[test]
fn schedules_next_warning_after_extension_from_lifetime() {
let mut session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
session_info.lifetime_secs = Some(7200);
let next_session_info = session_info.rescheduled_after_extension().unwrap();
let schedule = build_session_warning_schedule(&next_session_info).unwrap();
assert!(schedule.delay <= Duration::from_secs(5400));
}
#[test]
fn builds_session_context_from_cli_runtime_values() {
let ctx = build_session_context(SessionContextInput {
portal: "portal.example.com".to_string(),
gateway: "vpn.example.com".to_string(),
cookie: "authcookie=AUTH".to_string(),
user_agent: "UA".to_string(),
os: ClientOs::Mac,
os_version: "macOS 15.0".to_string(),
client_version: Some("6.3.1-12".to_string()),
certificate: Some("/tmp/client.pem".to_string()),
sslkey: Some("/tmp/client.key".to_string()),
key_password: Some("secret".to_string()),
disable_ipv6: true,
extension_auth: None,
});
assert_eq!(ctx.portal(), "portal.example.com");
assert_eq!(ctx.server(), "vpn.example.com");
assert_eq!(ctx.session_args().cookie(), "authcookie=AUTH");
assert_eq!(ctx.session_args().user_agent().as_deref(), Some("UA"));
assert!(matches!(ctx.session_args().os(), Some(ClientOs::Mac)));
assert_eq!(ctx.session_args().os_version().as_deref(), Some("macOS 15.0"));
assert_eq!(ctx.session_args().client_version().as_deref(), Some("6.3.1-12"));
assert_eq!(ctx.session_args().certificate().as_deref(), Some("/tmp/client.pem"));
assert_eq!(ctx.session_args().sslkey().as_deref(), Some("/tmp/client.key"));
assert_eq!(ctx.session_args().key_password().as_deref(), Some("secret"));
assert!(ctx.session_args().disable_ipv6());
}
#[test]
fn maps_openconnect_session_metadata_to_runtime_session_info() {
let info = session_info_from_vpn(
VpnSessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(1_776_828_409),
lifetime_warning: Some(openconnect::VpnSessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
},
true,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(info.allow_extend_session);
}
#[test]
fn direct_gateway_session_info_does_not_allow_extension_without_portal_policy() {
let info = session_info_from_vpn(
VpnSessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(1_776_828_409),
lifetime_warning: Some(openconnect::VpnSessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
},
false,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(!info.allow_extend_session);
}
}
+15 -15
View File
@@ -11,27 +11,27 @@
"dependencies": { "dependencies": {
"@emotion/react": "^11.14.0", "@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1", "@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.3.10", "@mui/icons-material": "^7.3.6",
"@mui/material": "^7.3.10", "@mui/material": "^7.3.6",
"@tauri-apps/api": "^2.11.0", "@tauri-apps/api": "^2.9.1",
"react": "^19.2.5", "react": "^19.2.3",
"react-dom": "^19.2.5" "react-dom": "^19.2.3"
}, },
"devDependencies": { "devDependencies": {
"@tauri-apps/cli": "^2.11.1", "@tauri-apps/cli": "^2.9.6",
"@types/node": "^25.6.0", "@types/node": "^22.19.3",
"@types/react": "^19.2.14", "@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
"@typescript-eslint/eslint-plugin": "^8.59.2", "@typescript-eslint/eslint-plugin": "^8.50.0",
"@typescript-eslint/parser": "^8.59.2", "@typescript-eslint/parser": "^8.50.0",
"@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4", "eslint": "^9.39.2",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-react": "^7.37.5", "eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-hooks": "^7.0.1",
"prettier": "3.8.3", "prettier": "3.4.2",
"typescript": "^6.0.3", "typescript": "^5.9.3",
"vite": "^8.0.10" "vite": "^8.0.1"
}, },
"packageManager": "[email protected]" "packageManager": "[email protected]"
} }
+685 -729
View File
File diff suppressed because it is too large. Load diff
-59
View File
@@ -1,62 +1,3 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() { fn main() {
println!("cargo:rerun-if-env-changed=GPGUI_HELPER_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPGUI_HELPER_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
tauri_build::build() tauri_build::build()
} }
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPGUI_HELPER_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+1 -8
View File
@@ -7,14 +7,7 @@ use log::info;
use crate::app::App; use crate::app::App;
const VERSION: &str = concat!( const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
env!("CARGO_PKG_VERSION"),
" (",
env!("GPGUI_HELPER_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
const GP_API_KEY: &[u8; 32] = &[0; 32]; const GP_API_KEY: &[u8; 32] = &[0; 32];
#[derive(Parser)] #[derive(Parser)]
+6 -17
View File
@@ -15,12 +15,6 @@ const SNAPSHOT: &str = match option_env!("SNAPSHOT") {
None => "false", None => "false",
}; };
#[cfg(target_env = "musl")]
const GUI_LIBC_SUFFIX: &str = "-musl";
#[cfg(not(target_env = "musl"))]
const GUI_LIBC_SUFFIX: &str = "";
pub struct ProgressNotifier { pub struct ProgressNotifier {
win: WebviewWindow, win: WebviewWindow,
} }
@@ -94,10 +88,6 @@ impl GuiUpdater {
} }
pub async fn update(&self) { pub async fn update(&self) {
if !cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) {
info!("GUI version is not supported on this architecture.");
return;
}
info!("Update GUI, version: {}", self.version); info!("Update GUI, version: {}", self.version);
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
@@ -109,15 +99,14 @@ impl GuiUpdater {
format!("v{}", self.version) format!("v{}", self.version)
}; };
let arch = if cfg!(target_arch = "x86_64") { #[cfg(target_arch = "x86_64")]
"x86_64" let arch = "x86_64";
} else { #[cfg(target_arch = "aarch64")]
"aarch64" let arch = "aarch64";
};
let file_url = format!( let file_url = format!(
"https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{}/gpgui_{}{}.bin.tar.xz", "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{}/gpgui_{}.bin.tar.xz",
release_tag, arch, GUI_LIBC_SUFFIX release_tag, arch
); );
let checksum_url = format!("{}.sha256", file_url); let checksum_url = format!("{}.sha256", file_url);
-60
View File
@@ -1,60 +0,0 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=GPSERVICE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPSERVICE_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
}
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPSERVICE_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+2 -9
View File
@@ -16,14 +16,7 @@ use tokio::sync::{mpsc, watch};
use crate::{vpn_task::VpnTask, ws_server::WsServer}; use crate::{vpn_task::VpnTask, ws_server::WsServer};
const VERSION: &str = concat!( const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
env!("CARGO_PKG_VERSION"),
" (",
env!("GPSERVICE_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[derive(Parser)] #[derive(Parser)]
#[command(version = VERSION)] #[command(version = VERSION)]
@@ -166,7 +159,7 @@ mod signals {
pub async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) { pub async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) {
use gpapi::service::event::WsEvent; use gpapi::service::event::WsEvent;
use tokio::signal::unix::{Signal, SignalKind, signal}; use tokio::signal::unix::{signal, Signal, SignalKind};
let (mut user_sig1, mut user_sig2) = match || -> anyhow::Result<(Signal, Signal)> { let (mut user_sig1, mut user_sig2) = match || -> anyhow::Result<(Signal, Signal)> {
let user_sig1 = signal(SignalKind::user_defined1())?; let user_sig1 = signal(SignalKind::user_defined1())?;
+1 -1
View File
@@ -11,8 +11,8 @@ use anyhow::bail;
use axum::{ use axum::{
body::Bytes, body::Bytes,
extract::{ extract::{
State, WebSocketUpgrade,
ws::{self, CloseFrame, Message, Utf8Bytes, WebSocket}, ws::{self, CloseFrame, Message, Utf8Bytes, WebSocket},
State, WebSocketUpgrade,
}, },
http::StatusCode, http::StatusCode,
response::IntoResponse, response::IntoResponse,
+1 -1
View File
@@ -1,8 +1,8 @@
use std::sync::Arc; use std::sync::Arc;
use axum::{ use axum::{
Router,
routing::{get, post}, routing::{get, post},
Router,
}; };
use crate::{handlers, ws_server::WsServerContext}; use crate::{handlers, ws_server::WsServerContext};
+6 -59
View File
@@ -4,13 +4,12 @@ use gpapi::{
logger, logger,
service::{ service::{
request::{ConnectRequest, UpdateLogLevelRequest, WsRequest}, request::{ConnectRequest, UpdateLogLevelRequest, WsRequest},
vpn_state::{ConnectedInfo, VpnState}, vpn_state::VpnState,
}, },
session::{SessionInfo, SessionWarning},
}; };
use log::{info, warn}; use log::{info, warn};
use openconnect::Vpn; use openconnect::Vpn;
use tokio::sync::{RwLock, mpsc, oneshot, watch}; use tokio::sync::{mpsc, oneshot, watch, RwLock};
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
pub(crate) struct VpnTaskContext { pub(crate) struct VpnTaskContext {
@@ -39,7 +38,6 @@ impl VpnTaskContext {
let info = req.info().clone(); let info = req.info().clone();
let vpn_handle = Arc::clone(&self.vpn_handle); let vpn_handle = Arc::clone(&self.vpn_handle);
let args = req.args(); let args = req.args();
let allow_extend_session = args.allow_extend_session();
let vpn = match Vpn::builder(req.gateway().server(), args.cookie()) let vpn = match Vpn::builder(req.gateway().server(), args.cookie())
.script(args.vpnc_script()) .script(args.vpnc_script())
.user_agent(args.user_agent()) .user_agent(args.user_agent())
@@ -56,9 +54,6 @@ impl VpnTaskContext {
.mtu(args.mtu()) .mtu(args.mtu())
.disable_ipv6(args.disable_ipv6()) .disable_ipv6(args.disable_ipv6())
.no_dtls(args.no_dtls()) .no_dtls(args.no_dtls())
.local_hostname(args.local_hostname())
.dpd_interval(args.force_dpd())
.no_xmlpost(args.no_xmlpost())
.build() .build()
{ {
Ok(vpn) => vpn, Ok(vpn) => vpn,
@@ -83,19 +78,9 @@ impl VpnTaskContext {
let vpn_state_tx_clone = vpn_state_tx.clone(); let vpn_state_tx_clone = vpn_state_tx.clone();
vpn_handle.blocking_read().as_ref().map(|vpn| { vpn_handle.blocking_read().as_ref().map(|vpn| {
vpn.connect(move |vpn_session_info| { vpn.connect(move || {
let session_info = SessionInfo::from_vpn_session_fields( let connect_info = Box::new(info.clone());
vpn_session_info.lifetime_secs, vpn_state_tx.send(VpnState::Connected(connect_info)).ok();
vpn_session_info.user_expires,
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
prior_secs: warning.prior_secs,
message: warning.message,
}),
allow_extend_session,
);
info!("VPN session info: {}", session_info.log_summary());
let connected_info = Box::new(ConnectedInfo::new(info.clone(), Some(session_info)));
vpn_state_tx.send(VpnState::Connected(connected_info)).ok();
}) })
}); });
@@ -124,6 +109,7 @@ impl VpnTaskContext {
} else { } else {
info!("VPN is not connected, skip disconnect"); info!("VPN is not connected, skip disconnect");
self.vpn_state_tx.send(VpnState::Disconnected).ok(); self.vpn_state_tx.send(VpnState::Disconnected).ok();
false false
} }
} }
@@ -195,42 +181,3 @@ async fn process_ws_req(req: WsRequest, ctx: Arc<VpnTaskContext>) {
} }
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_openconnect_session_metadata_to_service_session_info() {
let info = SessionInfo::from_vpn_session_fields(
Some(43_200),
None,
Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
true,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.expires_in_human.as_deref(), Some("12h"));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(info.allow_extend_session);
}
#[test]
fn direct_request_session_metadata_keeps_extension_disabled() {
let info = SessionInfo::from_vpn_session_fields(
Some(43_200),
None,
Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
false,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert!(!info.allow_extend_session);
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ use openconnect::{find_csd_wrapper, find_vpnc_script};
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use tokio::{ use tokio::{
net::TcpListener, net::TcpListener,
sync::{RwLock, mpsc, watch}, sync::{mpsc, watch, RwLock},
}; };
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
-21
View File
@@ -1,26 +1,5 @@
# Changelog # Changelog
## 2.5.4 - 2026-05-08
- Add Alpine/musl gpgui release assets for x86_64 and aarch64.
- Use the musl gpgui asset when the helper or package build runs on musl Linux.
## 2.5.3 - 2026-05-08
- Fix systemd-resolved DNS routing when no split-DNS domains are provided (fix [#604](https://github.com/yuezk/GlobalProtect-openconnect/issues/604)).
- Log whether systemd-resolved uses server-provided split DNS or global VPN DNS.
## 2.5.2 - 2026-05-06
- Experimental: GUI/CLI add session expiry warnings and support automatic session extension when allowed by the portal.
- GUI/CLI: expose additional OpenConnect connection options.
- Fix Linux packages to vendor the `vpnc-script`.
- Remove OpenConnect from the packaging dependency.
- Fix reconnect handling by preserving GlobalProtect cookie fields.
- Fix auth callback data parsing
- Improve NixOS packaging and user-level installation docs.
- Upgrade Rust, Tauri, Vite, frontend, and Rust dependencies.
## 2.5.1 - 2025-12-22 ## 2.5.1 - 2025-12-22
- Fix the `.deb` package installation issue (fix [#563](https://github.com/yuezk/GlobalProtect-openconnect/issues/563)) - Fix the `.deb` package installation issue (fix [#563](https://github.com/yuezk/GlobalProtect-openconnect/issues/563))
+1 -1
View File
@@ -1,7 +1,7 @@
use anyhow::bail; use anyhow::bail;
use gpapi::{ use gpapi::{
gp_params::GpParams, gp_params::GpParams,
portal::{Prelogin, prelogin}, portal::{prelogin, Prelogin},
}; };
#[cfg(feature = "browser-auth")] #[cfg(feature = "browser-auth")]
+1 -1
View File
@@ -2,7 +2,7 @@ use anyhow::bail;
use gpapi::{auth::SamlAuthData, error::AuthDataParseError}; use gpapi::{auth::SamlAuthData, error::AuthDataParseError};
use log::{error, info}; use log::{error, info};
use regex::Regex; use regex::Regex;
use tokio::sync::{RwLock, mpsc}; use tokio::sync::{mpsc, RwLock};
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
#[derive(Debug)] #[derive(Debug)]
+1 -1
View File
@@ -1,7 +1,7 @@
use block2::RcBlock; use block2::RcBlock;
use log::warn; use log::warn;
use objc2::runtime::AnyObject; use objc2::runtime::AnyObject;
use objc2_foundation::{NSError, NSString, NSURL, NSURLRequest}; use objc2_foundation::{NSError, NSString, NSURLRequest, NSURL};
use objc2_web_kit::WKWebView; use objc2_web_kit::WKWebView;
use tauri::webview::PlatformWebview; use tauri::webview::PlatformWebview;
+2 -2
View File
@@ -5,8 +5,8 @@ use gpapi::utils::redact::redact_uri;
use log::warn; use log::warn;
use tauri::webview::PlatformWebview; use tauri::webview::PlatformWebview;
use webkit2gtk::{ use webkit2gtk::{
LoadEvent, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt, WebsiteDataManagerExt, gio::Cancellable, glib::GString, LoadEvent, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt,
gio::Cancellable, glib::GString, WebsiteDataManagerExt,
}; };
use super::{ use super::{
+1 -1
View File
@@ -4,8 +4,8 @@ use anyhow::bail;
use gpapi::{auth::SamlAuthData, gp_params::GpParams, utils::redact::redact_uri}; use gpapi::{auth::SamlAuthData, gp_params::GpParams, utils::redact::redact_uri};
use log::{info, warn}; use log::{info, warn};
use tauri::{ use tauri::{
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
webview::{PageLoadEvent, PageLoadPayload}, webview::{PageLoadEvent, PageLoadPayload},
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
}; };
use tokio::{sync::oneshot, time}; use tokio::{sync::oneshot, time};
+5 -17
View File
@@ -4,29 +4,17 @@ pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
pub const GP_CALLBACK_PORT_FILENAME: &str = "gpcallback.port"; pub const GP_CALLBACK_PORT_FILENAME: &str = "gpcallback.port";
// Release binaries - macOS (Apple Silicon Homebrew) // Release binaries - macOS (Apple Silicon Homebrew)
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))] #[cfg(all(not(debug_assertions), target_os = "macos"))]
pub const GP_CLIENT_BINARY: &str = "/opt/homebrew/bin/gpclient"; pub const GP_CLIENT_BINARY: &str = "/opt/homebrew/bin/gpclient";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))] #[cfg(all(not(debug_assertions), target_os = "macos"))]
pub const GP_SERVICE_BINARY: &str = "/opt/homebrew/bin/gpservice"; pub const GP_SERVICE_BINARY: &str = "/opt/homebrew/bin/gpservice";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))] #[cfg(all(not(debug_assertions), target_os = "macos"))]
pub const GP_GUI_BINARY: &str = "/opt/homebrew/bin/gpgui"; pub const GP_GUI_BINARY: &str = "/opt/homebrew/bin/gpgui";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))] #[cfg(all(not(debug_assertions), target_os = "macos"))]
pub const GP_GUI_HELPER_BINARY: &str = "/opt/homebrew/bin/gpgui-helper"; pub const GP_GUI_HELPER_BINARY: &str = "/opt/homebrew/bin/gpgui-helper";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))] #[cfg(all(not(debug_assertions), target_os = "macos"))]
pub const GP_AUTH_BINARY: &str = "/opt/homebrew/bin/gpauth"; pub const GP_AUTH_BINARY: &str = "/opt/homebrew/bin/gpauth";
// Release binaries - macOS (Intel Homebrew)
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_CLIENT_BINARY: &str = "/usr/local/bin/gpclient";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_SERVICE_BINARY: &str = "/usr/local/bin/gpservice";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_GUI_BINARY: &str = "/usr/local/bin/gpgui";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_GUI_HELPER_BINARY: &str = "/usr/local/bin/gpgui-helper";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_AUTH_BINARY: &str = "/usr/local/bin/gpauth";
// Release binaries - Linux // Release binaries - Linux
#[cfg(all(not(debug_assertions), not(target_os = "macos")))] #[cfg(all(not(debug_assertions), not(target_os = "macos")))]
pub const GP_CLIENT_BINARY: &str = "/usr/bin/gpclient"; pub const GP_CLIENT_BINARY: &str = "/usr/bin/gpclient";
+2 -5
View File
@@ -34,9 +34,6 @@ md5.workspace = true
sha256.workspace = true sha256.workspace = true
machine-uid.workspace = true machine-uid.workspace = true
uuid = { workspace = true, features = ["v5"] } uuid = { workspace = true, features = ["v5"] }
chrono.workspace = true
humantime.workspace = true
netdev.workspace = true
# Optional dependencies for features # Optional dependencies for features
tauri = { workspace = true, optional = true } tauri = { workspace = true, optional = true }
@@ -52,10 +49,10 @@ os_info = { version = "3", default-features = false }
# Dependencies for Linux and other OSes only # Dependencies for Linux and other OSes only
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies] [target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
gtk = { version = "0.18", optional = true } gtk = "0.18"
[features] [features]
tauri = ["dep:tauri", "dep:gtk"] tauri = ["dep:tauri"]
clap = ["dep:clap", "dep:clap-verbosity-flag"] clap = ["dep:clap", "dep:clap-verbosity-flag"]
webview-auth = [] webview-auth = []
logger = ["dep:env_logger", "dep:log-reload"] logger = ["dep:env_logger", "dep:log-reload"]
+2 -27
View File
@@ -72,11 +72,7 @@ impl SamlAuthData {
let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie"); let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie");
let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie"); let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie");
let auth_data = SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid)
SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie).map_err(AuthDataParseError::Invalid)?;
auth_data.log_summary("html");
Ok(auth_data)
} }
Some(status) => Err(AuthDataParseError::Invalid(anyhow::anyhow!( Some(status) => Err(AuthDataParseError::Invalid(anyhow::anyhow!(
"SAML auth status: {}", "SAML auth status: {}",
@@ -106,7 +102,6 @@ impl SamlAuthData {
AuthDataParseError::Invalid(anyhow::anyhow!(e)) AuthDataParseError::Invalid(anyhow::anyhow!(e))
})?; })?;
auth_data.log_summary("gpcallback-cas");
return Ok(auth_data); return Ok(auth_data);
} }
@@ -127,28 +122,9 @@ impl SamlAuthData {
self.prelogin_cookie.as_deref() self.prelogin_cookie.as_deref()
} }
pub fn portal_userauthcookie(&self) -> Option<&str> {
self.portal_userauthcookie.as_deref()
}
pub fn token(&self) -> Option<&str> { pub fn token(&self) -> Option<&str> {
self.token.as_deref() self.token.as_deref()
} }
fn log_summary(&self, source: &str) {
info!(
"Parsed SAML auth data: source={}, username_present={}, prelogin_cookie_len={}, portal_userauthcookie_len={}, token_len={}",
source,
!self.username.is_empty(),
optional_len(self.prelogin_cookie.as_deref()),
optional_len(self.portal_userauthcookie.as_deref()),
optional_len(self.token.as_deref())
);
}
}
fn optional_len(value: Option<&str>) -> usize {
value.unwrap_or_default().len()
} }
fn parse_xml_tag(html: &str, tag: &str) -> Option<String> { fn parse_xml_tag(html: &str, tag: &str) -> Option<String> {
@@ -184,12 +160,11 @@ mod tests {
#[test] #[test]
fn auth_data_from_gpcallback_non_cas() { fn auth_data_from_gpcallback_non_cas() {
let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHBvcnRhbC11c2VyYXV0aGNvb2tpZT5wb3J0YWwtdXNlcmF1dGhjb29raWU8L3BvcnRhbC11c2VyYXV0aGNvb2tpZT48c2FtbC11c2VybmFtZT54eXpAZW1haWwuY29tPC9zYW1sLXVzZXJuYW1lPjxzYW1sLXNsbz5ubzwvc2FtbC1zbG8+IC0tPjwvaHRtbD4="; let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHNhbWwtdXNlcm5hbWU+eHl6QGVtYWlsLmNvbTwvc2FtbC11c2VybmFtZT48c2FtbC1zbG8+bm88L3NhbWwtc2xvPjxzYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+PC9zYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+IC0tPjwvaHRtbD4=";
let auth_data = SamlAuthData::from_gpcallback(auth_data).unwrap(); let auth_data = SamlAuthData::from_gpcallback(auth_data).unwrap();
assert_eq!(auth_data.username(), "[email protected]"); assert_eq!(auth_data.username(), "[email protected]");
assert_eq!(auth_data.prelogin_cookie(), Some("prelogin-cookie")); assert_eq!(auth_data.prelogin_cookie(), Some("prelogin-cookie"));
assert_eq!(auth_data.portal_userauthcookie(), Some("portal-userauthcookie"));
} }
} }
+1 -1
View File
@@ -1,4 +1,4 @@
use clap::{ValueEnum, builder::PossibleValue}; use clap::{builder::PossibleValue, ValueEnum};
use crate::gp_params::ClientOs; use crate::gp_params::ClientOs;
+3 -60
View File
@@ -41,21 +41,14 @@ impl From<&CachedCredential> for PasswordCredential {
pub struct PreloginCredential { pub struct PreloginCredential {
username: String, username: String,
prelogin_cookie: Option<String>, prelogin_cookie: Option<String>,
portal_userauthcookie: Option<String>,
token: Option<String>, token: Option<String>,
} }
impl PreloginCredential { impl PreloginCredential {
pub fn new( pub fn new(username: &str, prelogin_cookie: Option<&str>, token: Option<&str>) -> Self {
username: &str,
prelogin_cookie: Option<&str>,
portal_userauthcookie: Option<&str>,
token: Option<&str>,
) -> Self {
Self { Self {
username: username.to_string(), username: username.to_string(),
prelogin_cookie: prelogin_cookie.map(|s| s.to_string()), prelogin_cookie: prelogin_cookie.map(|s| s.to_string()),
portal_userauthcookie: portal_userauthcookie.map(|s| s.to_string()),
token: token.map(|s| s.to_string()), token: token.map(|s| s.to_string()),
} }
} }
@@ -68,10 +61,6 @@ impl PreloginCredential {
self.prelogin_cookie.as_deref() self.prelogin_cookie.as_deref()
} }
pub fn portal_userauthcookie(&self) -> Option<&str> {
self.portal_userauthcookie.as_deref()
}
pub fn token(&self) -> Option<&str> { pub fn token(&self) -> Option<&str> {
self.token.as_deref() self.token.as_deref()
} }
@@ -81,10 +70,9 @@ impl From<SamlAuthData> for PreloginCredential {
fn from(value: SamlAuthData) -> Self { fn from(value: SamlAuthData) -> Self {
let username = value.username().to_string(); let username = value.username().to_string();
let prelogin_cookie = value.prelogin_cookie(); let prelogin_cookie = value.prelogin_cookie();
let portal_userauthcookie = value.portal_userauthcookie();
let token = value.token(); let token = value.token();
Self::new(&username, prelogin_cookie, portal_userauthcookie, token) Self::new(&username, prelogin_cookie, token)
} }
} }
@@ -198,13 +186,7 @@ impl Credential {
let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match self { let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match self {
Credential::Password(cred) => (Some(cred.password()), None, None, None, None), Credential::Password(cred) => (Some(cred.password()), None, None, None, None),
Credential::Prelogin(cred) => ( Credential::Prelogin(cred) => (None, cred.prelogin_cookie(), None, None, cred.token()),
None,
cred.prelogin_cookie(),
cred.portal_userauthcookie(),
None,
cred.token(),
),
Credential::AuthCookie(cred) => ( Credential::AuthCookie(cred) => (
None, None,
None, None,
@@ -273,42 +255,3 @@ impl From<&CachedCredential> for Credential {
Self::Cached(value.clone()) Self::Cached(value.clone())
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prelogin_credential_params_include_saml_cookies() {
let auth_data = SamlAuthData::new(
Some("[email protected]".to_string()),
Some("prelogin-cookie".to_string()),
Some("portal-userauthcookie".to_string()),
)
.unwrap();
let cred = Credential::from(auth_data);
let params = cred.to_params();
assert_eq!(params.get("user"), Some(&"[email protected]"));
assert_eq!(params.get("passwd"), Some(&""));
assert_eq!(params.get("prelogin-cookie"), Some(&"prelogin-cookie"));
assert_eq!(params.get("portal-userauthcookie"), Some(&"portal-userauthcookie"));
assert_eq!(params.get("portal-prelogonuserauthcookie"), Some(&""));
}
#[test]
fn prelogin_credential_params_keep_cas_token_without_cookies() {
let auth_data =
SamlAuthData::from_gpcallback("globalprotectcallback:cas-as=1&[email protected]&token=cas-token").unwrap();
let cred = Credential::from(auth_data);
let params = cred.to_params();
assert_eq!(params.get("user"), Some(&"[email protected]"));
assert_eq!(params.get("prelogin-cookie"), Some(&""));
assert_eq!(params.get("portal-userauthcookie"), Some(&""));
assert_eq!(params.get("portal-prelogonuserauthcookie"), Some(&""));
assert_eq!(params.get("token"), Some(&"cas-token"));
}
}
+21 -324
View File
@@ -1,15 +1,14 @@
use std::{borrow::Cow, collections::HashMap, net::UdpSocket}; use std::borrow::Cow;
use anyhow::bail; use anyhow::bail;
use log::{debug, info, warn}; use log::{debug, info, warn};
use reqwest::Client; use reqwest::Client;
use urlencoding::{decode, encode}; use urlencoding::encode;
use xmltree::Element; use xmltree::Element;
use crate::{ use crate::{
credential::Credential, credential::Credential,
error::PortalError, error::PortalError,
gateway::GatewayLoginContext,
gp_params::GpParams, gp_params::GpParams,
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
}; };
@@ -20,56 +19,19 @@ pub enum GatewayLogin {
} }
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> { pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, None, false).await
}
pub async fn gateway_login_with_context(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
context: &GatewayLoginContext,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, Some(context), false).await
}
pub async fn gateway_login_with_extend_lifetime(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, None, true).await
}
async fn gateway_login_with_options(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
context: Option<&GatewayLoginContext>,
extend_lifetime: bool,
) -> anyhow::Result<GatewayLogin> {
let url = normalize_server(gateway)?; let url = normalize_server(gateway)?;
let gateway = remove_url_scheme(&url); let gateway = remove_url_scheme(&url);
let login_url = format!("{}/ssl-vpn/login.esp", url); let login_url = format!("{}/ssl-vpn/login.esp", url);
let client = Client::try_from(gp_params)?; let client = Client::try_from(gp_params)?;
let client_ip = context.and_then(|context| { let mut params = cred.to_params();
context let extra_params = gp_params.to_params();
.client_ip()
.map(|ip| ip.to_string()) params.extend(extra_params);
.or_else(|| detect_local_ipv4(context.host())) params.insert("server", &gateway);
});
let params = build_gateway_login_params(
&gateway,
cred,
gp_params,
context,
client_ip.as_deref(),
extend_lifetime,
);
info!("Perform gateway login, user_agent: {}", gp_params.user_agent()); info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
log_gateway_login_context(context, client_ip.as_deref());
let res = client.post(&login_url).form(&params).send().await.map_err(|e| { let res = client.post(&login_url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e); warn!("Network error: {:?}", e);
@@ -83,7 +45,7 @@ async fn gateway_login_with_options(
// It's possible to get an empty response, log the response headers for debugging // It's possible to get an empty response, log the response headers for debugging
if res.trim().is_empty() { if res.trim().is_empty() {
info!("Empty gateway login response headers: {:?}", res); debug!("Empty gateway login response headers: {:?}", res);
bail!("Got empty gateway login response"); bail!("Got empty gateway login response");
} }
@@ -105,84 +67,6 @@ async fn gateway_login_with_options(
Ok(GatewayLogin::Cookie(cookie)) Ok(GatewayLogin::Cookie(cookie))
} }
fn build_gateway_login_params(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
context: Option<&GatewayLoginContext>,
client_ip: Option<&str>,
extend_lifetime: bool,
) -> HashMap<String, String> {
let mut params = cred
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect::<HashMap<_, _>>();
params.extend(
gp_params
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string())),
);
params.insert("server".to_string(), gateway.to_string());
if let Some(context) = context {
params.insert("host".to_string(), context.host().to_string());
params.insert("gw".to_string(), context.name().to_string());
params.insert("gateway-name".to_string(), context.name().to_string());
params.insert("internal".to_string(), context.kind().as_login_param().to_string());
params.insert(
"selection-type".to_string(),
context.selection().as_login_param().to_string(),
);
params.insert("client-ipv6".to_string(), String::new());
if let Some(connect_method) = context.connect_method() {
params.insert("connect-method".to_string(), connect_method.to_string());
}
if let Some(client_version) = context.client_version().or_else(|| gp_params.client_version()) {
params.insert("clientgpversion".to_string(), client_version.to_string());
}
if let Some(client_ip) = client_ip {
params.insert("client-ip".to_string(), client_ip.to_string());
}
}
if extend_lifetime {
params.insert("extend-lifetime".to_string(), "true".to_string());
}
params
}
fn detect_local_ipv4(host: &str) -> Option<String> {
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
socket.connect((host, 443)).ok()?;
let ip = socket.local_addr().ok()?.ip();
if ip.is_ipv4() { Some(ip.to_string()) } else { None }
}
fn log_gateway_login_context(context: Option<&GatewayLoginContext>, client_ip: Option<&str>) {
let Some(context) = context else {
return;
};
info!(
"Gateway login context: host_present={}, gateway_name_present={}, connect_method_present={}, selection_type={}, internal={}, clientgpversion_present={}, client_ip_present={}",
!context.host().is_empty(),
!context.name().is_empty(),
context.connect_method().is_some(),
context.selection().as_login_param(),
context.kind().as_login_param(),
context.client_version().is_some(),
client_ip.is_some()
);
}
fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> { fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
let args = element let args = element
.descendants("argument") .descendants("argument")
@@ -190,19 +74,14 @@ fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<Stri
.map(|e| e.get_text().unwrap_or_default()) .map(|e| e.get_text().unwrap_or_default())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let mut params = vec![ let params = [
read_required_arg(&args, 1, "authcookie")?, read_args(&args, 1, "authcookie")?,
read_optional_arg(&args, 2, "persistent-cookie")?, read_args(&args, 3, "portal")?,
read_optional_arg(&args, 3, "portal")?, read_args(&args, 4, "user")?,
read_required_arg(&args, 4, "user")?, read_args(&args, 7, "domain")?,
read_optional_arg(&args, 7, "domain")?, read_args(&args, 15, "preferred-ip")?,
read_optional_arg(&args, 15, "preferred-ip")?, ("computer", computer),
read_optional_arg(&args, 18, "preferred-ipv6")?, ];
]
.into_iter()
.flatten()
.collect::<Vec<_>>();
params.push(("computer", computer.to_string()));
let token = params let token = params
.iter() .iter()
@@ -213,43 +92,11 @@ fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<Stri
Ok(token) Ok(token)
} }
fn read_required_arg( fn read_args<'a>(args: &'a [Cow<'_, str>], index: usize, key: &'a str) -> anyhow::Result<(&'a str, &'a str)> {
args: &[Cow<'_, str>], args
index: usize, .get(index)
key: &'static str, .ok_or_else(|| anyhow::anyhow!("Failed to read {key} from args"))
) -> anyhow::Result<Option<(&'static str, String)>> { .map(|s| (key, s.as_ref()))
let Some(value) = read_arg_value(args, index)? else {
bail!("Failed to read {key} from args");
};
Ok(Some((key, value)))
}
fn read_optional_arg(
args: &[Cow<'_, str>],
index: usize,
key: &'static str,
) -> anyhow::Result<Option<(&'static str, String)>> {
Ok(read_arg_value(args, index)?.map(|value| (key, value)))
}
fn read_arg_value(args: &[Cow<'_, str>], index: usize) -> anyhow::Result<Option<String>> {
Ok(
args
.get(index)
.map(|s| normalize_arg_value(s.as_ref()))
.transpose()
.map_err(|err| anyhow::anyhow!("Failed to decode gateway login argument {index}: {err}"))?
.flatten(),
)
}
fn normalize_arg_value(value: &str) -> anyhow::Result<Option<String>> {
if value.is_empty() || value == "(null)" || value == "-1" {
return Ok(None);
}
Ok(Some(decode(value)?.into_owned()))
} }
fn parse_mfa(res: &str) -> Option<(String, String)> { fn parse_mfa(res: &str) -> Option<(String, String)> {
@@ -269,7 +116,6 @@ fn parse_mfa(res: &str) -> Option<(String, String)> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::gateway::{Gateway, GatewayKind, GatewaySelection};
#[test] #[test]
fn mfa() { fn mfa() {
@@ -281,153 +127,4 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
assert_eq!(message, "MFA message"); assert_eq!(message, "MFA message");
assert_eq!(input_str, "5ef64e83000119ed"); assert_eq!(input_str, "5ef64e83000119ed");
} }
#[test]
fn normal_gateway_login_params_do_not_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, None, None, false);
assert!(!params.contains_key("extend-lifetime"));
assert!(!params.contains_key("host"));
assert!(!params.contains_key("gw"));
assert!(!params.contains_key("gateway-name"));
assert!(!params.contains_key("connect-method"));
assert!(!params.contains_key("selection-type"));
assert!(!params.contains_key("internal"));
assert!(!params.contains_key("client-ip"));
assert!(!params.contains_key("client-ipv6"));
}
#[test]
fn extension_gateway_login_params_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, None, None, true);
assert_eq!(params.get("extend-lifetime").map(String::as_str), Some("true"));
}
#[test]
fn gateway_login_params_include_official_context_fields() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let gateway = Gateway {
name: "US_East".to_string(),
address: "us1.vpn.example.com".to_string(),
kind: GatewayKind::External,
priority: 1,
priority_rules: vec![],
};
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Auto)
.with_connect_method(Some("on-demand"))
.with_client_version(Some("6.3.3-915"));
let params = build_gateway_login_params(
"us1.vpn.example.com",
&cred,
&gp_params,
Some(&context),
Some("192.168.0.102"),
false,
);
assert_eq!(params.get("host").map(String::as_str), Some("us1.vpn.example.com"));
assert_eq!(params.get("gw").map(String::as_str), Some("US_East"));
assert_eq!(params.get("gateway-name").map(String::as_str), Some("US_East"));
assert_eq!(params.get("connect-method").map(String::as_str), Some("on-demand"));
assert_eq!(params.get("selection-type").map(String::as_str), Some("auto"));
assert_eq!(params.get("internal").map(String::as_str), Some("no"));
assert_eq!(params.get("clientgpversion").map(String::as_str), Some("6.3.3-915"));
assert_eq!(params.get("client-ip").map(String::as_str), Some("192.168.0.102"));
assert_eq!(params.get("client-ipv6").map(String::as_str), Some(""));
}
#[test]
fn manual_gateway_selection_maps_to_manual_param() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
let context = GatewayLoginContext::new(&gateway, GatewaySelection::Manual);
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, Some(&context), None, false);
assert_eq!(params.get("selection-type").map(String::as_str), Some("manual"));
}
#[test]
fn gateway_token_keeps_upstream_cookie_fields() {
let res = r#"
<jnlp>
<application-desc>
<argument></argument>
<argument>AUTHCOOKIE</argument>
<argument>PERSISTENTCOOKIE</argument>
<argument>vpn.example.com</argument>
<argument>alice</argument>
<argument>LDAP-auth</argument>
<argument>vsys1</argument>
<argument>%28empty_domain%29</argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument>tunnel</argument>
<argument>-1</argument>
<argument>4100</argument>
<argument>10.0.0.10</argument>
<argument>unused-user-cookie</argument>
<argument>unused-prelogon-cookie</argument>
<argument>2001:db8::10</argument>
</application-desc>
</jnlp>
"#;
let root = Element::parse(res.as_bytes()).unwrap();
let token = build_gateway_token(&root, "metalklesk").unwrap();
assert_eq!(
token,
"authcookie=AUTHCOOKIE&persistent-cookie=PERSISTENTCOOKIE&portal=vpn.example.com&user=alice&domain=%28empty_domain%29&preferred-ip=10.0.0.10&preferred-ipv6=2001%3Adb8%3A%3A10&computer=metalklesk"
);
}
#[test]
fn gateway_token_omits_empty_optional_fields() {
let res = r#"
<jnlp>
<application-desc>
<argument></argument>
<argument>AUTHCOOKIE</argument>
<argument></argument>
<argument>vpn.example.com</argument>
<argument>alice</argument>
<argument>LDAP-auth</argument>
<argument>vsys1</argument>
<argument>-1</argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument>tunnel</argument>
<argument>-1</argument>
<argument>4100</argument>
<argument></argument>
<argument>unused-user-cookie</argument>
<argument>unused-prelogon-cookie</argument>
<argument>(null)</argument>
</application-desc>
</jnlp>
"#;
let root = Element::parse(res.as_bytes()).unwrap();
let token = build_gateway_token(&root, "metalklesk").unwrap();
assert_eq!(
token,
"authcookie=AUTHCOOKIE&portal=vpn.example.com&user=alice&computer=metalklesk"
);
}
} }
+1 -148
View File
@@ -1,11 +1,9 @@
pub mod hip;
mod login; mod login;
mod parse_gateways; mod parse_gateways;
pub mod session; pub mod hip;
pub use login::*; pub use login::*;
pub(crate) use parse_gateways::*; pub(crate) use parse_gateways::*;
pub use session::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
@@ -23,130 +21,10 @@ pub(crate) struct PriorityRule {
pub struct Gateway { pub struct Gateway {
pub(crate) name: String, pub(crate) name: String,
pub(crate) address: String, pub(crate) address: String,
#[serde(default)]
pub(crate) kind: GatewayKind,
pub(crate) priority: u32, pub(crate) priority: u32,
pub(crate) priority_rules: Vec<PriorityRule>, pub(crate) priority_rules: Vec<PriorityRule>,
} }
#[derive(Debug, Serialize, Deserialize, Type, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum GatewayKind {
Internal,
External,
}
impl GatewayKind {
pub fn as_login_param(self) -> &'static str {
match self {
GatewayKind::Internal => "yes",
GatewayKind::External => "no",
}
}
}
impl Default for GatewayKind {
fn default() -> Self {
Self::External
}
}
#[derive(Debug, Serialize, Deserialize, Type, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum GatewaySelection {
Auto,
Manual,
}
impl GatewaySelection {
pub fn as_login_param(self) -> &'static str {
match self {
GatewaySelection::Auto => "auto",
GatewaySelection::Manual => "manual",
}
}
}
impl Default for GatewaySelection {
fn default() -> Self {
Self::Auto
}
}
#[derive(Debug, Clone)]
pub struct GatewayLoginContext {
host: String,
name: String,
kind: GatewayKind,
selection: GatewaySelection,
connect_method: Option<String>,
client_version: Option<String>,
client_ip: Option<String>,
}
impl GatewayLoginContext {
pub fn new(gateway: &Gateway, selection: GatewaySelection) -> Self {
let name = if gateway.name().is_empty() {
gateway.server()
} else {
gateway.name()
};
Self {
host: gateway.server().to_string(),
name: name.to_string(),
kind: gateway.kind(),
selection,
connect_method: None,
client_version: None,
client_ip: None,
}
}
pub fn with_connect_method(mut self, connect_method: Option<&str>) -> Self {
self.connect_method = connect_method.filter(|s| !s.is_empty()).map(|s| s.to_string());
self
}
pub fn with_client_version(mut self, client_version: Option<&str>) -> Self {
self.client_version = client_version.filter(|s| !s.is_empty()).map(|s| s.to_string());
self
}
pub fn with_client_ip(mut self, client_ip: Option<String>) -> Self {
self.client_ip = client_ip.filter(|s| !s.is_empty());
self
}
pub(crate) fn host(&self) -> &str {
&self.host
}
pub(crate) fn name(&self) -> &str {
&self.name
}
pub(crate) fn kind(&self) -> GatewayKind {
self.kind
}
pub(crate) fn selection(&self) -> GatewaySelection {
self.selection
}
pub(crate) fn connect_method(&self) -> Option<&str> {
self.connect_method.as_deref()
}
pub(crate) fn client_version(&self) -> Option<&str> {
self.client_version.as_deref()
}
pub(crate) fn client_ip(&self) -> Option<&str> {
self.client_ip.as_deref()
}
}
impl Display for Gateway { impl Display for Gateway {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.name, self.address) write!(f, "{} ({})", self.name, self.address)
@@ -158,7 +36,6 @@ impl Gateway {
Self { Self {
name, name,
address, address,
kind: GatewayKind::External,
priority: 0, priority: 0,
priority_rules: vec![], priority_rules: vec![],
} }
@@ -171,28 +48,4 @@ impl Gateway {
pub fn server(&self) -> &str { pub fn server(&self) -> &str {
&self.address &self.address
} }
pub fn kind(&self) -> GatewayKind {
self.kind
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserializes_gateway_without_kind_as_external() {
let gateway: Gateway = serde_json::from_str(
r#"{
"name": "US East",
"address": "us-east.example.com",
"priority": 1,
"priorityRules": []
}"#,
)
.unwrap();
assert_eq!(gateway.kind(), GatewayKind::External);
}
} }
+4 -63
View File
@@ -3,28 +3,21 @@ use xmltree::Element;
use crate::utils::xml::ElementExt; use crate::utils::xml::ElementExt;
use super::{Gateway, GatewayKind, PriorityRule}; use super::{Gateway, PriorityRule};
pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option<Vec<Gateway>> { pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option<Vec<Gateway>> {
let node_gateways = element.descendant("gateways")?; let node_gateways = element.descendant("gateways")?;
let internal_gateway_list = if prefer_internal { let internal_gateway_list = if prefer_internal {
info!("Try to parse the internal gateways..."); info!("Try to parse the internal gateways...");
node_gateways node_gateways.descendant("internal").and_then(|n| n.child("list"))
.descendant("internal")
.and_then(|n| n.child("list"))
.map(|list| (list, GatewayKind::Internal))
} else { } else {
None None
}; };
let gateway_list = internal_gateway_list.or_else(|| { let gateway_list = internal_gateway_list.or_else(|| {
info!("Try to parse the external gateways..."); info!("Try to parse the external gateways...");
node_gateways node_gateways.descendant("external").and_then(|n| n.child("list"))
.descendant("external")
.and_then(|n| n.child("list"))
.map(|list| (list, GatewayKind::External))
})?; })?;
let (gateway_list, kind) = gateway_list;
let gateways = gateway_list let gateways = gateway_list
.children("entry") .children("entry")
@@ -35,13 +28,12 @@ pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option
let priority = parse_priority(gateway_item); let priority = parse_priority(gateway_item);
let priority_rules = gateway_item let priority_rules = gateway_item
.child("priority-rule") .child("priority-rule")
.map(parse_priority_rules) .map(|n| parse_priority_rules(n))
.unwrap_or_default(); .unwrap_or_default();
Gateway { Gateway {
name, name,
address, address,
kind,
priority, priority,
priority_rules, priority_rules,
} }
@@ -70,54 +62,3 @@ fn parse_priority(element: &Element) -> u32 {
.and_then(|s| s.parse().ok()) .and_then(|s| s.parse().ok())
.unwrap_or(u32::MAX) .unwrap_or(u32::MAX)
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_external_gateways_marks_gateway_kind() {
let xml = r#"
<policy>
<gateways>
<external>
<list>
<entry name="us1.vpn.example.com">
<description>US_East</description>
</entry>
</list>
</external>
</gateways>
</policy>
"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let gateways = parse_gateways(&root, false).unwrap();
assert_eq!(gateways[0].name(), "US_East");
assert_eq!(gateways[0].server(), "us1.vpn.example.com");
assert_eq!(gateways[0].kind(), GatewayKind::External);
}
#[test]
fn parse_internal_gateways_marks_gateway_kind_when_preferred() {
let xml = r#"
<policy>
<gateways>
<internal>
<list>
<entry name="internal.vpn.example.com">
<description>Internal</description>
</entry>
</list>
</internal>
</gateways>
</policy>
"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let gateways = parse_gateways(&root, true).unwrap();
assert_eq!(gateways[0].kind(), GatewayKind::Internal);
}
}
-246
View File
@@ -1,246 +0,0 @@
use std::{
collections::HashMap,
time::{SystemTime, UNIX_EPOCH},
};
use anyhow::bail;
use log::{info, warn};
use reqwest::Client;
use xmltree::Element;
use crate::{
credential::Credential,
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
gp_params::GpParams,
session::SessionRequestArgs,
utils::{normalize_server, parse_gp_response, xml::ElementExt},
};
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime";
#[derive(Clone)]
pub struct SessionExtensionAuth {
credential: Credential,
gp_params: GpParams,
}
impl SessionExtensionAuth {
pub fn new(credential: Credential, gp_params: GpParams) -> Self {
Self { credential, gp_params }
}
}
impl std::fmt::Debug for SessionExtensionAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionExtensionAuth")
.field("username", &self.credential.username())
.field("gp_params", &"<redacted>")
.finish()
}
}
#[derive(Debug, Clone)]
pub struct SessionContext {
server: String,
portal: String,
session_args: SessionRequestArgs,
extension_auth: Option<SessionExtensionAuth>,
}
impl SessionContext {
pub fn new(server: String, portal: String, session_args: SessionRequestArgs) -> Self {
Self {
server,
portal,
session_args,
extension_auth: None,
}
}
pub fn with_extension_auth(mut self, extension_auth: SessionExtensionAuth) -> Self {
self.extension_auth = Some(extension_auth);
self
}
pub fn server(&self) -> &str {
&self.server
}
pub fn portal(&self) -> &str {
&self.portal
}
pub fn session_args(&self) -> &SessionRequestArgs {
&self.session_args
}
fn extension_auth(&self) -> Option<&SessionExtensionAuth> {
self.extension_auth.as_ref()
}
}
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
extend_session_lifetime(ctx).await?;
let base_url = normalize_server(ctx.server())?;
let client = build_session_client(ctx.session_args())?;
let form = build_extend_session_form(ctx)?;
let url = format!("{base_url}/ssl-vpn/agentmessage.esp");
info!("Sending extend-session request");
let response = client.post(&url).form(&form).send().await?;
let response = parse_gp_response(response).await?;
let root = Element::parse(response.as_bytes())?;
let status = parse_extend_session_status(&root, &response)?;
info!("Extend-session gateway response status: {}", status);
match status.as_str() {
"success" => Ok(()),
status => bail!("Extend session rejected: {status}"),
}
}
async fn extend_session_lifetime(ctx: &SessionContext) -> anyhow::Result<()> {
let auth = ctx
.extension_auth()
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
let login = gateway_login_with_extend_lifetime(ctx.server(), &auth.credential, &auth.gp_params).await?;
validate_extension_login(login)
}
fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
match login {
GatewayLogin::Cookie(_) => Ok(()),
GatewayLogin::Mfa(_, _) => bail!("Session extension requires an interactive gateway challenge"),
}
}
fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
let mut builder = GpParams::builder();
builder.user_agent(args.user_agent().as_deref().unwrap_or_default());
builder.client_os(args.os().unwrap_or_default());
builder.os_version(args.os_version());
builder.client_version(args.client_version());
builder.certificate(args.certificate());
builder.sslkey(args.sslkey());
builder.key_password(args.key_password());
Client::try_from(&builder.build())
}
fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
Ok(serde_urlencoded::from_str(args.cookie())?)
}
fn build_extend_session_form(ctx: &SessionContext) -> anyhow::Result<HashMap<String, String>> {
let mut form = parse_cookie_form(ctx.session_args())?;
form.insert("portal".to_string(), ctx.portal().to_string());
form.insert("timestamp".to_string(), unix_timestamp().to_string());
form.insert("message".to_string(), EXTEND_SESSION_MESSAGE.to_string());
form.insert("comment".to_string(), EXTEND_SESSION_COMMENT.to_string());
Ok(form)
}
fn parse_extend_session_status(root: &Element, response: &str) -> anyhow::Result<String> {
match root.attr("status") {
Some(status) => Ok(status.to_string()),
None => {
warn!("Malformed extend-session response body: {}", response.trim());
bail!("Malformed extend session response")
}
}
}
fn unix_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
#[cfg(test)]
mod tests {
use crate::{gp_params::ClientOs, session::SessionRequestArgs};
use super::*;
fn build_session_args() -> SessionRequestArgs {
SessionRequestArgs::new("authcookie=AUTH&portal=vpn.example.com&user=alice&preferred-ip=10.0.0.10".to_string())
.with_os(Some(ClientOs::Mac))
.with_os_version(Some("macOS 15.0".to_string()))
.with_client_version(Some("6.3.1-12".to_string()))
.with_disable_ipv6(true)
}
#[test]
fn active_session_context_preserves_connect_args_for_extension() {
let session_args = build_session_args();
let ctx = SessionContext::new(
"vpn.example.com".to_string(),
"portal.example.com".to_string(),
session_args,
);
let form = parse_cookie_form(ctx.session_args()).unwrap();
assert_eq!(form.get("authcookie").map(String::as_str), Some("AUTH"));
assert_eq!(form.get("portal").map(String::as_str), Some("vpn.example.com"));
assert_eq!(form.get("user").map(String::as_str), Some("alice"));
assert_eq!(form.get("preferred-ip").map(String::as_str), Some("10.0.0.10"));
}
#[test]
fn builds_extend_session_form() {
let session_args = build_session_args();
let ctx = SessionContext::new(
"vpn.example.com".to_string(),
"portal.example.com".to_string(),
session_args,
);
let form = build_extend_session_form(&ctx).unwrap();
assert_eq!(form.get("authcookie").map(String::as_str), Some("AUTH"));
assert_eq!(form.get("portal").map(String::as_str), Some("portal.example.com"));
assert_eq!(form.get("message").map(String::as_str), Some(EXTEND_SESSION_MESSAGE));
assert_eq!(form.get("comment").map(String::as_str), Some(EXTEND_SESSION_COMMENT));
assert!(form.contains_key("timestamp"));
}
#[test]
fn parses_extend_session_status_attribute() {
let root = Element::parse(r#"<response status="success"></response>"#.as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root, r#"<response status="success"></response>"#).unwrap(),
"success"
);
}
#[test]
fn rejects_extend_session_response_without_status() {
let root = Element::parse("<response><result>ok</result></response>".as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root, "<response><result>ok</result></response>")
.unwrap_err()
.to_string(),
"Malformed extend session response"
);
}
#[test]
fn rejects_extension_login_mfa_challenge() {
assert_eq!(
validate_extension_login(GatewayLogin::Mfa("MFA required".to_string(), "input".to_string()))
.unwrap_err()
.to_string(),
"Session extension requires an interactive gateway challenge"
);
}
}
-22
View File
@@ -58,7 +58,6 @@ pub struct GpParams {
certificate: Option<String>, certificate: Option<String>,
sslkey: Option<String>, sslkey: Option<String>,
key_password: Option<String>, key_password: Option<String>,
csc_preference_overrides: HashMap<String, String>,
// Used for MFA // Used for MFA
input_str: Option<String>, input_str: Option<String>,
otp: Option<String>, otp: Option<String>,
@@ -101,13 +100,6 @@ impl GpParams {
self.client_version.as_deref() self.client_version.as_deref()
} }
pub fn csc_preference_override(&self, domain: &str, key: &str) -> Option<&str> {
self
.csc_preference_overrides
.get(&csc_preference_key(domain, key))
.map(String::as_str)
}
pub fn set_input_str(&mut self, input_str: &str) { pub fn set_input_str(&mut self, input_str: &str) {
self.input_str = Some(input_str.to_string()); self.input_str = Some(input_str.to_string());
} }
@@ -160,7 +152,6 @@ pub struct GpParamsBuilder {
certificate: Option<String>, certificate: Option<String>,
sslkey: Option<String>, sslkey: Option<String>,
key_password: Option<String>, key_password: Option<String>,
csc_preference_overrides: HashMap<String, String>,
} }
impl GpParamsBuilder { impl GpParamsBuilder {
@@ -178,7 +169,6 @@ impl GpParamsBuilder {
certificate: Default::default(), certificate: Default::default(),
sslkey: Default::default(), sslkey: Default::default(),
key_password: Default::default(), key_password: Default::default(),
csc_preference_overrides: Default::default(),
} }
} }
@@ -232,13 +222,6 @@ impl GpParamsBuilder {
self self
} }
pub fn csc_preference_override(&mut self, domain: &str, key: &str, value: &str) -> &mut Self {
self
.csc_preference_overrides
.insert(csc_preference_key(domain, key), value.to_string());
self
}
pub fn build(&self) -> GpParams { pub fn build(&self) -> GpParams {
GpParams { GpParams {
is_gateway: self.is_gateway, is_gateway: self.is_gateway,
@@ -251,17 +234,12 @@ impl GpParamsBuilder {
certificate: self.certificate.clone(), certificate: self.certificate.clone(),
sslkey: self.sslkey.clone(), sslkey: self.sslkey.clone(),
key_password: self.key_password.clone(), key_password: self.key_password.clone(),
csc_preference_overrides: self.csc_preference_overrides.clone(),
input_str: Default::default(), input_str: Default::default(),
otp: Default::default(), otp: Default::default(),
} }
} }
} }
fn csc_preference_key(domain: &str, key: &str) -> String {
format!("{domain}:{key}")
}
impl Default for GpParamsBuilder { impl Default for GpParamsBuilder {
fn default() -> Self { fn default() -> Self {
Self::new() Self::new()
-1
View File
@@ -6,7 +6,6 @@ pub mod gp_params;
pub mod portal; pub mod portal;
pub mod process; pub mod process;
pub mod service; pub mod service;
pub mod session;
pub mod utils; pub mod utils;
#[cfg(feature = "logger")] #[cfg(feature = "logger")]
+1 -1
View File
@@ -2,7 +2,7 @@ use std::sync::OnceLock;
use anyhow::bail; use anyhow::bail;
use env_logger::Logger; use env_logger::Logger;
use log::{Level, warn}; use log::{warn, Level};
use log_reload::{ReloadHandle, ReloadLog}; use log_reload::{ReloadHandle, ReloadLog};
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<Logger>>> = OnceLock::new(); static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<Logger>>> = OnceLock::new();
+25 -236
View File
@@ -1,5 +1,3 @@
use std::collections::HashMap;
use anyhow::bail; use anyhow::bail;
use dns_lookup::lookup_addr; use dns_lookup::lookup_addr;
use log::{debug, info, warn}; use log::{debug, info, warn};
@@ -13,11 +11,9 @@ use crate::{
error::PortalError, error::PortalError,
gateway::{Gateway, parse_gateways}, gateway::{Gateway, parse_gateways},
gp_params::GpParams, gp_params::GpParams,
utils::{normalize_server, parse_gp_response, redact::redact_form_params, remove_url_scheme, xml::ElementExt}, utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt},
}; };
use super::csc;
#[derive(Debug, Serialize, Type)] #[derive(Debug, Serialize, Type)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct PortalConfig { pub struct PortalConfig {
@@ -25,7 +21,6 @@ pub struct PortalConfig {
auth_cookie: AuthCookieCredential, auth_cookie: AuthCookieCredential,
config_cred: Credential, config_cred: Credential,
gateways: Vec<Gateway>, gateways: Vec<Gateway>,
connect_method: Option<String>,
config_digest: Option<String>, config_digest: Option<String>,
/** /**
* Variants: * Variants:
@@ -38,10 +33,6 @@ pub struct PortalConfig {
* The version returned by the portal config, if any * The version returned by the portal config, if any
*/ */
version: Option<String>, version: Option<String>,
/**
* Whether the portal policy allows extending the gateway session.
*/
allow_extend_session: Option<bool>,
} }
impl PortalConfig { impl PortalConfig {
@@ -65,18 +56,10 @@ impl PortalConfig {
self.internal_host_detection self.internal_host_detection
} }
pub fn connect_method(&self) -> Option<&str> {
self.connect_method.as_deref()
}
pub fn version(&self) -> Option<&str> { pub fn version(&self) -> Option<&str> {
self.version.as_deref() self.version.as_deref()
} }
pub fn allow_extend_session(&self) -> Option<bool> {
self.allow_extend_session
}
/// In-place sort the gateways by region /// In-place sort the gateways by region
pub fn sort_gateways(&mut self, region: &str) { pub fn sort_gateways(&mut self, region: &str) {
let preferred_gateway = self.find_preferred_gateway(region); let preferred_gateway = self.find_preferred_gateway(region);
@@ -127,11 +110,14 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
let url = format!("{}/global-protect/getconfig.esp", portal); let url = format!("{}/global-protect/getconfig.esp", portal);
let client = Client::try_from(gp_params)?; let client = Client::try_from(gp_params)?;
let swg_nonce = csc::swg_nonce(); let mut params = cred.to_params();
let params = build_config_params(cred, gp_params, &server, &swg_nonce); let extra_params = gp_params.to_params();
params.extend(extra_params);
params.insert("server", &server);
params.insert("host", &server);
info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent()); info!("Retrieve the portal config, user_agent: {}", gp_params.user_agent());
info!("Portal config request params: {}", redact_params(&params));
let res = client.post(&url).form(&params).send().await.map_err(|e| { let res = client.post(&url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e); warn!("Network error: {:?}", e);
@@ -158,102 +144,11 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
debug!("Portal config response: {}", res_xml); debug!("Portal config response: {}", res_xml);
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?; let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
if csc::is_config_criteria(&root) {
info!("Portal returned CSC criteria: {}", csc_criteria_summary(&root));
let csc_xml = retrieve_csc_config(&client, &portal, &root, cred.username(), gp_params).await?;
debug!("Portal CSC config response: {}", csc_xml);
let root = Element::parse(csc_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?;
return parse_portal_config(&server, cred, root);
}
info!("Portal did not return CSC criteria");
parse_portal_config(&server, cred, root)
}
fn build_config_params<'a>(
cred: &'a Credential,
gp_params: &'a GpParams,
server: &'a str,
swg_nonce: &'a str,
) -> HashMap<&'a str, &'a str> {
let mut params = cred.to_params();
let extra_params = gp_params.to_params();
params.extend(extra_params);
params.insert("server", server);
params.insert("host", server);
params.insert("csc-digest", "");
params.insert("config-digest", "");
params.insert("csc-support", "yes");
params.insert("swg-auth-token", "0");
params.insert("swg-nonce", swg_nonce);
params
}
async fn retrieve_csc_config(
client: &Client,
portal: &str,
root: &Element,
username: &str,
gp_params: &GpParams,
) -> anyhow::Result<String> {
let csc_req = csc::build_csc_request(root, username, gp_params)?;
let swg_nonce = csc::swg_nonce();
let params = csc::csc_params(&csc_req, username, gp_params, &swg_nonce);
let url = format!("{}/global-protect/getconfig_csc.esp", portal);
info!("Portal CSC config request summary: {}", csc_req.summary());
info!("Portal CSC config request params: {}", redact_params(&params));
let res = client.post(&url).form(&params).send().await.map_err(|e| {
warn!("Network error: {:?}", e);
anyhow::anyhow!(PortalError::NetworkError(e))
})?;
parse_gp_response(res).await.or_else(|err| {
if err.status == StatusCode::NOT_FOUND {
bail!(PortalError::ConfigError("CSC config endpoint not found".to_string()));
}
if err.is_status_error() {
warn!("{err}");
bail!("Portal CSC config error: {}", err.reason);
}
Err(anyhow::anyhow!(PortalError::ConfigError(err.reason)))
})
}
fn redact_params(params: &HashMap<&str, &str>) -> String {
let params = params.iter().map(|(key, value)| (*key, *value)).collect::<Vec<_>>();
redact_form_params(&params)
}
fn csc_criteria_summary(root: &Element) -> String {
let auth_cookie = present(root.descendant_text("portal-csc-auth-cookie").as_deref());
let config_digest = present(root.descendant_text("config-digest").as_deref());
let custom_check_entries = root
.descendant("custom-checks")
.map(|custom_checks| custom_checks.descendants("entry").len())
.unwrap_or_default();
format!("auth_cookie={auth_cookie}, config_digest={config_digest}, custom_check_entries={custom_check_entries}")
}
fn present(value: Option<&str>) -> &'static str {
match value {
Some(value) if !value.is_empty() => "present",
_ => "empty",
}
}
fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow::Result<PortalConfig> {
let mut ihd_enabled = false; let mut ihd_enabled = false;
let mut prefer_internal = false; let mut prefer_internal = false;
if let Some(ihd_node) = root.descendant("internal-host-detection") { if let Some(ihd_node) = root.descendant("internal-host-detection") {
ihd_enabled = true; 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(|| { let mut gateways = parse_gateways(&root, prefer_internal).unwrap_or_else(|| {
@@ -266,46 +161,25 @@ fn parse_portal_config(server: &str, cred: &Credential, root: Element) -> anyhow
.descendant_text("portal-prelogonuserauthcookie") .descendant_text("portal-prelogonuserauthcookie")
.unwrap_or_default(); .unwrap_or_default();
let config_digest = root.descendant_text("config-digest"); let config_digest = root.descendant_text("config-digest");
let connect_method = parse_connect_method(&root);
if gateways.is_empty() { if gateways.is_empty() {
gateways.push(Gateway::new(server.to_string(), server.to_string())); gateways.push(Gateway::new(server.to_string(), server.to_string()));
} else {
info!("Found {} gateways in portal config", gateways.len());
} }
let version = root.descendant_text("version").map(|s| s.to_string()); let version = root.descendant_text("version").map(|s| s.to_string());
info!("Detected portal version: {:?}", version); info!("Detected portal version: {:?}", version);
let allow_extend_session = parse_allow_extend_session(&root);
Ok(PortalConfig { Ok(PortalConfig {
portal: server.to_string(), 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(), config_cred: cred.clone(),
gateways, gateways,
connect_method,
config_digest: config_digest.map(|s| s.to_string()), config_digest: config_digest.map(|s| s.to_string()),
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None }, internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
version, version,
allow_extend_session,
}) })
} }
fn parse_allow_extend_session(root: &Element) -> Option<bool> {
match root.descendant_text("allow-extend-session")?.trim() {
"yes" => Some(true),
"no" => Some(false),
_ => None,
}
}
fn parse_connect_method(root: &Element) -> Option<String> {
root
.descendant_text("connect-method")
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
}
// Perform DNS lookup and compare the result with the expected hostname // Perform DNS lookup and compare the result with the expected hostname
fn internal_host_detect(element: &Element) -> bool { fn internal_host_detect(element: &Element) -> bool {
let ip_info = [ let ip_info = [
@@ -316,111 +190,26 @@ fn internal_host_detect(element: &Element) -> bool {
info!("Found internal-host-detection, performing DNS lookup"); info!("Found internal-host-detection, performing DNS lookup");
for (ip_address, host) in ip_info.iter() { for (ip_address, host) in ip_info.iter() {
if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref()) if let (Some(ip_address), Some(host)) = (ip_address.as_deref(), host.as_deref()) {
&& !ip_address.is_empty() if !ip_address.is_empty() && !host.is_empty() {
&& !host.is_empty() match ip_address.parse::<std::net::IpAddr>() {
{ Ok(ip) => match lookup_addr(&ip) {
match ip_address.parse::<std::net::IpAddr>() { Ok(host_lookup) if host_lookup.to_lowercase() == host.to_lowercase() => {
Ok(ip) => match lookup_addr(&ip) { return true;
Ok(host_lookup) if host_lookup.to_lowercase() == host.to_lowercase() => { }
return true; Ok(host_lookup) => {
} info!(
Ok(host_lookup) => { "rDNS lookup for {} returned {}, expected {}",
info!( ip_address, host_lookup, host
"rDNS lookup for {} returned {}, expected {}", );
ip_address, host_lookup, host }
); Err(err) => warn!("rDNS lookup failed for {}: {}", ip_address, err),
} },
Err(err) => warn!("rDNS lookup failed for {}: {}", ip_address, err), Err(err) => warn!("Invalid IP address {}: {}", ip_address, err),
}, }
Err(err) => warn!("Invalid IP address {}: {}", ip_address, err),
} }
} }
} }
false false
} }
#[cfg(test)]
mod tests {
use super::*;
fn parse_xml(xml: &str) -> Element {
Element::parse(xml.as_bytes()).unwrap()
}
#[test]
fn getconfig_params_include_csc_support_fields() {
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_config_params(&cred, &gp_params, "vpn.example.com", "123");
assert_eq!(params.get("csc-support"), Some(&"yes"));
assert_eq!(params.get("csc-digest"), Some(&""));
assert_eq!(params.get("config-digest"), Some(&""));
assert_eq!(params.get("swg-auth-token"), Some(&"0"));
assert_eq!(params.get("swg-nonce"), Some(&"123"));
assert_eq!(params.get("host"), Some(&"vpn.example.com"));
}
#[test]
fn parses_allow_extend_session_yes() {
let root = parse_xml("<response><allow-extend-session>yes</allow-extend-session></response>");
assert_eq!(parse_allow_extend_session(&root), Some(true));
}
#[test]
fn parses_allow_extend_session_no() {
let root = parse_xml("<response><allow-extend-session>no</allow-extend-session></response>");
assert_eq!(parse_allow_extend_session(&root), Some(false));
}
#[test]
fn leaves_absent_allow_extend_session_unknown() {
let root = parse_xml("<response></response>");
assert_eq!(parse_allow_extend_session(&root), None);
}
#[test]
fn ignores_non_official_allow_extend_session_values() {
let root = parse_xml("<response><allow-extend-session>true</allow-extend-session></response>");
assert_eq!(parse_allow_extend_session(&root), None);
}
#[test]
fn parses_connect_method() {
let root = parse_xml("<policy><connect-method>on-demand</connect-method></policy>");
assert_eq!(parse_connect_method(&root).as_deref(), Some("on-demand"));
}
#[test]
fn parses_csc_policy_response_as_portal_config() {
let root = parse_xml(
r#"<policy>
<portal-userauthcookie>user-cookie</portal-userauthcookie>
<portal-prelogonuserauthcookie>prelogon-cookie</portal-prelogonuserauthcookie>
<gateways>
<external>
<list>
<entry name="US_East">
<description>us1.vpn.example.com</description>
</entry>
</list>
</external>
</gateways>
</policy>"#,
);
let cred = Credential::from(crate::credential::PasswordCredential::new("alice", "secret"));
let config = parse_portal_config("vpn.example.com", &cred, root).unwrap();
assert_eq!(config.auth_cookie().user_auth_cookie(), "user-cookie");
assert_eq!(config.auth_cookie().prelogon_user_auth_cookie(), "prelogon-cookie");
assert_eq!(config.gateways().len(), 1);
}
}
-715
View File
@@ -1,715 +0,0 @@
use std::{
collections::HashMap,
fmt::Write,
fs,
process::Command,
time::{SystemTime, UNIX_EPOCH},
};
use xmltree::{Element, EmitterConfig, XMLNode};
use crate::{
gp_params::GpParams,
utils::{host_utils, xml::ElementExt},
};
const DIGEST_PLACEHOLDER: &str = "__#_PAN_CSC_DATA_DIGEST_#__";
pub(super) struct CscRequest {
pub(super) auth_cookie: String,
pub(super) config_digest: String,
pub(super) csc_digest: String,
pub(super) csc_data: String,
summary: CscBuildSummary,
host_id: String,
serial_number: String,
}
impl CscRequest {
pub(super) fn summary(&self) -> String {
format!(
"digest_len={}, xml_len={}, plist_entries={}, plist_present={}, plist_missing={}, process_entries={}, process_present={}, process_missing={}",
self.csc_digest.len(),
self.csc_data.len(),
self.summary.plist_entries,
self.summary.plist_present,
self.summary.plist_missing,
self.summary.process_entries,
self.summary.process_present,
self.summary.process_missing,
)
}
}
#[derive(Default)]
struct CscBuildSummary {
plist_entries: usize,
plist_present: usize,
plist_missing: usize,
process_entries: usize,
process_present: usize,
process_missing: usize,
}
struct CscDataInput<'a> {
criteria: &'a Element,
auth_cookie: &'a str,
username: &'a str,
gp_params: &'a GpParams,
host_id: &'a str,
serial_number: &'a str,
csc_digest: &'a str,
}
pub(super) trait CscDataReader {
fn read_preference(&self, domain: &str, key: &str) -> Option<String>;
fn process_exists(&self, name: &str) -> bool;
}
struct SystemCscDataReader;
impl CscDataReader for SystemCscDataReader {
fn read_preference(&self, domain: &str, key: &str) -> Option<String> {
read_macos_preference(domain, key)
}
fn process_exists(&self, name: &str) -> bool {
linux_process_names().iter().any(|process_name| process_name == name)
}
}
pub(super) fn swg_nonce() -> String {
let millis = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_millis())
.unwrap_or_default();
(millis % 2_147_483_647).to_string()
}
pub(super) fn is_config_criteria(root: &Element) -> bool {
root.name == "config-criteria"
}
pub(super) fn build_csc_request(root: &Element, username: &str, gp_params: &GpParams) -> anyhow::Result<CscRequest> {
let reader = SystemCscDataReader;
build_csc_request_with_reader(root, username, gp_params, &reader)
}
pub(super) fn build_csc_request_with_reader(
root: &Element,
username: &str,
gp_params: &GpParams,
reader: &dyn CscDataReader,
) -> anyhow::Result<CscRequest> {
let auth_cookie = root
.descendant_text("portal-csc-auth-cookie")
.filter(|value| !value.is_empty())
.ok_or_else(|| anyhow::anyhow!("CSC criteria response does not contain portal-csc-auth-cookie"))?;
let config_digest = root.descendant_text("config-digest").unwrap_or_default();
let host_id = collect_host_id(gp_params);
let serial_number = collect_serial_number();
let mut summary = CscBuildSummary::default();
let csc_data = build_csc_data(
CscDataInput {
criteria: root,
auth_cookie: &auth_cookie,
username,
gp_params,
host_id: &host_id,
serial_number: &serial_number,
csc_digest: DIGEST_PLACEHOLDER,
},
reader,
&mut summary,
)?;
let csc_digest = pan_md5_hex(csc_data.as_bytes());
let csc_data = csc_data.replace(DIGEST_PLACEHOLDER, &csc_digest);
Ok(CscRequest {
auth_cookie,
config_digest,
csc_digest,
csc_data,
summary,
host_id,
serial_number,
})
}
pub(super) fn csc_params<'a>(
req: &'a CscRequest,
username: &'a str,
gp_params: &'a GpParams,
swg_nonce: &'a str,
) -> HashMap<&'a str, &'a str> {
let mut params = HashMap::new();
params.insert("user", username);
params.insert("clientVer", "4100");
params.insert("clientos", gp_params.client_os());
params.insert("os-version", gp_params.os_version().unwrap_or_default());
params.insert("hostid", req.host_id.as_str());
params.insert("serialno", req.serial_number.as_str());
params.insert("portal-cc-auth-cookie", req.auth_cookie.as_str());
params.insert("config-digest", req.config_digest.as_str());
params.insert("csc-digest", req.csc_digest.as_str());
params.insert("csc-data", req.csc_data.as_str());
params.insert("swg-auth-token", "0");
params.insert("swg-nonce", swg_nonce);
params
}
fn build_csc_data(
input: CscDataInput<'_>,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> anyhow::Result<String> {
let mut root = Element::new("hip-report");
push_text(&mut root, "portal-csc-auth-cookie", input.auth_cookie);
push_text(&mut root, "user-name", &urlencoding::encode(input.username));
push_text(&mut root, "client-os", &client_os_report_value(input.gp_params));
push_text(&mut root, "host-id", input.host_id);
push_text(&mut root, "device-serial-number", input.serial_number);
push_text(&mut root, "csc-digest", input.csc_digest);
root.children.push(XMLNode::Element(Element::new("categories")));
root.children.push(XMLNode::Element(build_custom_checks(
input.criteria,
input.gp_params,
reader,
summary,
)));
let mut bytes = Vec::new();
root.write_with_config(
&mut bytes,
EmitterConfig::new()
.perform_indent(true)
.write_document_declaration(true),
)?;
String::from_utf8(bytes).map_err(Into::into)
}
fn build_custom_checks(
criteria: &Element,
gp_params: &GpParams,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> Element {
let mut custom_checks = Element::new("custom-checks");
let Some(requested_checks) = criteria.descendant("custom-checks") else {
return custom_checks;
};
if gp_params.client_os() == "Mac"
&& let Some(plist) = requested_checks
.child("mac-os")
.and_then(|mac_os| mac_os.child("plist"))
{
custom_checks
.children
.push(XMLNode::Element(build_plist_checks(plist, gp_params, reader, summary)));
}
if gp_params.client_os() == "Linux"
&& let Some(process_list) = requested_checks
.child("linux")
.and_then(|linux| linux.child("process-list"))
.or_else(|| requested_checks.child("process-list"))
{
custom_checks.children.push(XMLNode::Element(build_process_list_checks(
process_list,
reader,
summary,
)));
}
custom_checks
}
fn build_plist_checks(
plist: &Element,
gp_params: &GpParams,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> Element {
let mut out = Element::new("plist");
for entry in plist.children("entry") {
let domain = entry.attr("name").unwrap_or_default();
let mut out_entry = Element::new("entry");
out_entry.attributes.insert("name".to_string(), domain.to_string());
let keys = plist_entry_keys(entry);
let values: Vec<_> = keys
.iter()
.map(|key| {
let value = gp_params
.csc_preference_override(domain, key)
.map(str::to_string)
.or_else(|| reader.read_preference(domain, key));
(key.as_str(), value)
})
.collect();
let plist_exists = values.iter().any(|(_, value)| value.is_some());
summary.plist_entries += keys.len();
summary.plist_present += values.iter().filter(|(_, value)| value.is_some()).count();
summary.plist_missing += values.iter().filter(|(_, value)| value.is_none()).count();
push_text(&mut out_entry, "exist", yes_no(plist_exists));
push_text(&mut out_entry, "value", "");
let mut preference_value = Element::new("preference-value");
for (key, value) in values {
let mut pref_entry = Element::new("entry");
pref_entry.attributes.insert("name".to_string(), key.to_string());
push_text(&mut pref_entry, "exist", yes_no(value.is_some()));
push_text(&mut pref_entry, "value", value.as_deref().unwrap_or_default());
preference_value.children.push(XMLNode::Element(pref_entry));
}
out_entry.children.push(XMLNode::Element(preference_value));
out.children.push(XMLNode::Element(out_entry));
}
out
}
fn build_process_list_checks(
process_list: &Element,
reader: &dyn CscDataReader,
summary: &mut CscBuildSummary,
) -> Element {
let mut out = Element::new("process-list");
for process_name in process_list_names(process_list) {
let exists = reader.process_exists(&process_name);
summary.process_entries += 1;
if exists {
summary.process_present += 1;
} else {
summary.process_missing += 1;
}
let mut entry = Element::new("entry");
entry.attributes.insert("name".to_string(), process_name.clone());
push_text(&mut entry, "exist", yes_no(exists));
push_text(&mut entry, "value", if exists { &process_name } else { "" });
out.children.push(XMLNode::Element(entry));
}
out
}
fn plist_entry_keys(entry: &Element) -> Vec<String> {
let keys: Vec<String> = entry
.descendants("member")
.into_iter()
.filter_map(|element| element.get_text())
.map(|text| text.to_string())
.collect();
if keys.is_empty() {
entry
.attr("name")
.map(|name| vec![name.to_string()])
.unwrap_or_default()
} else {
keys
}
}
fn process_list_names(process_list: &Element) -> Vec<String> {
let mut names: Vec<String> = process_list
.descendants("member")
.into_iter()
.filter_map(|element| element.get_text())
.map(|text| text.trim().to_string())
.filter(|text| !text.is_empty())
.collect();
names.extend(
process_list
.children("entry")
.into_iter()
.filter_map(|entry| entry.attr("name"))
.map(str::to_string),
);
names.sort();
names.dedup();
names
}
fn pan_md5_hex(value: &[u8]) -> String {
let digest = md5::compute(value);
let mut out = String::new();
for byte in digest.0 {
write!(&mut out, "{:x}", byte).expect("writing to String should not fail");
}
out
}
fn collect_host_id(gp_params: &GpParams) -> String {
match gp_params.client_os() {
"Mac" => netdev::get_default_interface()
.ok()
.and_then(|iface| iface.mac_addr.map(|mac| mac.address()))
.unwrap_or_default(),
"Windows" => host_utils::get_machine_id().to_string(),
_ => host_utils::derive_uuid(&[]),
}
}
fn collect_serial_number() -> String {
collect_macos_serial_number()
.or_else(collect_linux_serial_number)
.or_else(collect_windows_serial_number)
.unwrap_or_default()
}
fn collect_macos_serial_number() -> Option<String> {
let output = Command::new("ioreg")
.args(["-rd1", "-c", "IOPlatformExpertDevice"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout.lines().find_map(|line| {
line
.split_once("IOPlatformSerialNumber")
.and_then(|(_, value)| value.split_once('='))
.map(|(_, value)| value.trim().trim_matches('"').to_string())
.filter(|value| !value.is_empty())
})
}
fn collect_linux_serial_number() -> Option<String> {
["/sys/class/dmi/id/product_serial", "/sys/class/dmi/id/product_uuid"]
.into_iter()
.filter_map(|path| fs::read_to_string(path).ok())
.map(|value| value.trim().to_string())
.find(|value| !value.is_empty() && value != "None" && value != "To Be Filled By O.E.M.")
}
fn collect_windows_serial_number() -> Option<String> {
let output = Command::new("wmic")
.args(["bios", "get", "serialnumber"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "SerialNumber")
.map(str::to_string)
.next()
}
fn read_macos_preference(domain: &str, key: &str) -> Option<String> {
if cfg!(not(target_os = "macos")) {
return None;
}
let output = Command::new("defaults").args(["read", domain, key]).output().ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
}
fn linux_process_names() -> Vec<String> {
let Ok(entries) = fs::read_dir("/proc") else {
return Vec::new();
};
entries
.filter_map(Result::ok)
.filter_map(|entry| {
entry
.file_name()
.to_str()
.filter(|name| name.chars().all(|ch| ch.is_ascii_digit()))
.map(|_| entry.path().join("stat"))
})
.filter_map(|path| fs::read_to_string(path).ok())
.filter_map(|stat| {
let start = stat.find('(')?;
let end = stat.rfind(')')?;
stat.get(start + 1..end).map(str::to_string)
})
.filter(|name| !name.is_empty())
.collect()
}
fn client_os_report_value(gp_params: &GpParams) -> String {
gp_params
.os_version()
.unwrap_or_else(|| gp_params.client_os())
.replace(' ', "+")
}
fn push_text(parent: &mut Element, name: &str, value: &str) {
let mut element = Element::new(name);
element.children.push(XMLNode::Text(value.to_string()));
parent.children.push(XMLNode::Element(element));
}
fn yes_no(value: bool) -> &'static str {
if value { "yes" } else { "no" }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::gp_params::{ClientOs, GpParams};
struct TestCscDataReader {
values: HashMap<String, String>,
processes: Vec<String>,
}
impl CscDataReader for TestCscDataReader {
fn read_preference(&self, domain: &str, key: &str) -> Option<String> {
self.values.get(&format!("{domain}:{key}")).cloned()
}
fn process_exists(&self, name: &str) -> bool {
self.processes.iter().any(|process| process == name)
}
}
fn parse_xml(xml: &str) -> Element {
Element::parse(xml.as_bytes()).unwrap()
}
fn gp_params(client_os: ClientOs) -> GpParams {
GpParams::builder()
.client_os(client_os)
.os_version(Some("Apple Mac OS X 26.4.1".to_string()))
.build()
}
#[test]
fn detects_config_criteria_response() {
assert!(is_config_criteria(&parse_xml("<config-criteria/>")));
assert!(!is_config_criteria(&parse_xml("<policy/>")));
}
#[test]
fn builds_macos_plist_csc_report_with_existing_value() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example.settings">
<key><member>ExampleKey</member></key>
</entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::from([(
"com.example.settings:ExampleKey".to_string(),
"ExampleValue".to_string(),
)]),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "[email protected]", &gp_params(ClientOs::Mac), &reader).unwrap();
assert_eq!(req.auth_cookie, "cookie");
assert!(req.csc_data.contains("<user-name>alice%40example.com</user-name>"));
assert!(req.csc_data.contains("<client-os>Apple+Mac+OS+X+26.4.1</client-os>"));
assert!(req.csc_data.contains("<exist>yes</exist>"));
assert!(req.csc_data.contains("<value>ExampleValue</value>"));
assert!(
req
.csc_data
.contains(&format!("<csc-digest>{}</csc-digest>", req.csc_digest))
);
assert!(!req.csc_data.contains(DIGEST_PLACEHOLDER));
}
#[test]
fn reports_missing_macos_plist_value() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example"><key><member>Missing</member></key></entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Mac), &reader).unwrap();
assert!(req.csc_data.contains("<exist>no</exist>"));
assert!(req.csc_data.contains("<value />") || req.csc_data.contains("<value></value>"));
}
#[test]
fn macos_plist_override_works_without_native_preference() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example.settings"><key><member>ExampleKey</member></key></entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: Vec::new(),
};
let gp_params = GpParams::builder()
.client_os(ClientOs::Mac)
.os_version(Some("Apple Mac OS X 26.4.1".to_string()))
.csc_preference_override("com.example.settings", "ExampleKey", "ExampleValue")
.build();
let req = build_csc_request_with_reader(&root, "alice", &gp_params, &reader).unwrap();
assert!(req.csc_data.contains("<exist>yes</exist>"));
assert!(req.csc_data.contains("<value>ExampleValue</value>"));
}
#[test]
fn unsupported_client_os_ignores_macos_plist_branch() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<mac-os>
<plist>
<entry name="com.example"><key><member>HipID</member></key></entry>
</plist>
</mac-os>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::from([("com.example:HipID".to_string(), "present".to_string())]),
processes: Vec::new(),
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Linux), &reader).unwrap();
assert!(!req.csc_data.contains("<plist>"));
assert!(!req.csc_data.contains("<exist>no</exist>"));
assert!(!req.csc_data.contains("present"));
}
#[test]
fn builds_linux_process_list_report() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks>
<linux>
<process-list>
<entry name="present-process" />
<entry name="missing-process" />
</process-list>
</linux>
</custom-checks>
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: vec!["present-process".to_string()],
};
let req = build_csc_request_with_reader(&root, "alice", &gp_params(ClientOs::Linux), &reader).unwrap();
assert!(req.csc_data.contains(r#"<entry name="present-process">"#));
assert!(req.csc_data.contains("<value>present-process</value>"));
assert!(req.csc_data.contains(r#"<entry name="missing-process">"#));
assert!(req.summary().contains("process_entries=2"));
assert!(req.summary().contains("process_present=1"));
assert!(req.summary().contains("process_missing=1"));
}
#[test]
fn uses_pan_non_padded_md5_digest() {
assert_eq!(pan_md5_hex(b""), "d41d8cd98f0b24e980998ecf8427e");
assert_ne!(pan_md5_hex(b""), format!("{:x}", md5::compute(b"")));
}
#[test]
fn builds_getconfig_csc_params() {
let req = CscRequest {
auth_cookie: "cookie".to_string(),
config_digest: "config-digest".to_string(),
csc_digest: "csc-digest".to_string(),
csc_data: "<hip-report><host-id>host</host-id><device-serial-number>serial</device-serial-number></hip-report>"
.to_string(),
summary: CscBuildSummary::default(),
host_id: "host".to_string(),
serial_number: "serial".to_string(),
};
let nonce = "123";
let gp_params = gp_params(ClientOs::Mac);
let params = csc_params(&req, "alice", &gp_params, nonce);
assert_eq!(params.get("user"), Some(&"alice"));
assert_eq!(params.get("hostid"), Some(&"host"));
assert_eq!(params.get("serialno"), Some(&"serial"));
assert_eq!(params.get("portal-cc-auth-cookie"), Some(&"cookie"));
assert_eq!(params.get("config-digest"), Some(&"config-digest"));
assert_eq!(params.get("csc-digest"), Some(&"csc-digest"));
assert_eq!(params.get("csc-data"), Some(&req.csc_data.as_str()));
assert_eq!(params.get("swg-auth-token"), Some(&"0"));
assert_eq!(params.get("swg-nonce"), Some(&"123"));
}
#[test]
fn generated_getconfig_csc_params_include_final_digest_and_data() {
let root = parse_xml(
r#"<config-criteria>
<custom-checks />
<portal-csc-auth-cookie>cookie</portal-csc-auth-cookie>
</config-criteria>"#,
);
let reader = TestCscDataReader {
values: HashMap::new(),
processes: Vec::new(),
};
let gp_params = gp_params(ClientOs::Linux);
let req = build_csc_request_with_reader(&root, "alice", &gp_params, &reader).unwrap();
let params = csc_params(&req, "alice", &gp_params, "123");
assert_eq!(params.get("csc-digest"), Some(&req.csc_digest.as_str()));
assert_eq!(params.get("csc-data"), Some(&req.csc_data.as_str()));
assert!(
req
.csc_data
.contains(&format!("<csc-digest>{}</csc-digest>", req.csc_digest))
);
assert!(!req.csc_data.contains(DIGEST_PLACEHOLDER));
}
}
-1
View File
@@ -1,5 +1,4 @@
mod config; mod config;
mod csc;
mod prelogin; mod prelogin;
pub use config::*; pub use config::*;
+6 -10
View File
@@ -177,16 +177,12 @@ impl<'a> SamlAuthLauncher<'a> {
} }
let mut non_root_cmd = auth_cmd.into_non_root()?; let mut non_root_cmd = auth_cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn(); let output = non_root_cmd
.kill_on_drop(true)
let child = match child { .stdout(Stdio::piped())
Ok(child) => child, .spawn()?
Err(err) => { .wait_with_output()
bail!("Failed to spawn {}: {}", program, err); .await?;
}
};
let output = child.wait_with_output().await?;
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else { let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
bail!("Failed to parse auth data") bail!("Failed to parse auth data")
@@ -50,12 +50,7 @@ impl<'a> GuiHelperLauncher<'a> {
info!("Launching gpgui-helper"); info!("Launching gpgui-helper");
let mut non_root_cmd = cmd.into_non_root()?; let mut non_root_cmd = cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn(); let mut child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn()?;
let mut child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
};
let Some(mut stdin) = child.stdin.take() else { let Some(mut stdin) = child.stdin.take() else {
bail!("Failed to open stdin"); bail!("Failed to open stdin");
}; };
+1 -6
View File
@@ -69,12 +69,7 @@ impl<'a> GuiLauncher<'a> {
info!("Launching gpgui"); info!("Launching gpgui");
let mut non_root_cmd = cmd.into_non_root()?; let mut non_root_cmd = cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn(); let mut child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn()?;
let mut child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
};
let Some(mut stdin) = child.stdin.take() else { let Some(mut stdin) = child.stdin.take() else {
bail!("Failed to open stdin"); bail!("Failed to open stdin");
}; };
+6 -8
View File
@@ -72,14 +72,12 @@ impl<'a> HipLauncher<'a> {
cmd.env("APP_VERSION", client_version); cmd.env("APP_VERSION", client_version);
} }
let child = cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn(); let output = cmd
.kill_on_drop(true)
let child = match child { .stdout(Stdio::piped())
Ok(child) => child, .spawn()?
Err(err) => bail!("Failed to spawn {}: {}", self.program, err), .wait_with_output()
}; .await?;
let output = child.wait_with_output().await?;
if let Some(exit_status) = output.status.code() { if let Some(exit_status) = output.status.code() {
if exit_status != 0 { if exit_status != 0 {
+2 -68
View File
@@ -27,7 +27,7 @@ impl LaunchGuiRequest {
} }
} }
#[derive(Debug, Deserialize, Serialize, Type, Clone)] #[derive(Debug, Deserialize, Serialize, Type)]
pub struct ConnectArgs { pub struct ConnectArgs {
cookie: String, cookie: String,
vpnc_script: Option<String>, vpnc_script: Option<String>,
@@ -49,11 +49,6 @@ pub struct ConnectArgs {
mtu: u32, mtu: u32,
disable_ipv6: bool, disable_ipv6: bool,
no_dtls: bool, no_dtls: bool,
local_hostname: Option<String>,
force_dpd: u32,
no_xmlpost: bool,
#[serde(rename = "allowExtendSession")]
allow_extend_session: bool,
} }
impl ConnectArgs { impl ConnectArgs {
@@ -75,10 +70,6 @@ impl ConnectArgs {
mtu: 0, mtu: 0,
disable_ipv6: false, disable_ipv6: false,
no_dtls: false, no_dtls: false,
local_hostname: None,
force_dpd: 0,
no_xmlpost: false,
allow_extend_session: false,
} }
} }
@@ -98,10 +89,6 @@ impl ConnectArgs {
self.os.as_ref().map(|os| os.to_openconnect_os().to_string()) self.os.as_ref().map(|os| os.to_openconnect_os().to_string())
} }
pub fn os(&self) -> Option<ClientOs> {
self.os.clone()
}
pub fn os_version(&self) -> Option<String> { pub fn os_version(&self) -> Option<String> {
self.os_version.clone() self.os_version.clone()
} }
@@ -149,25 +136,9 @@ impl ConnectArgs {
pub fn no_dtls(&self) -> bool { pub fn no_dtls(&self) -> bool {
self.no_dtls self.no_dtls
} }
pub fn local_hostname(&self) -> Option<String> {
self.local_hostname.clone()
}
pub fn force_dpd(&self) -> u32 {
self.force_dpd
}
pub fn no_xmlpost(&self) -> bool {
self.no_xmlpost
}
pub fn allow_extend_session(&self) -> bool {
self.allow_extend_session
}
} }
#[derive(Debug, Deserialize, Serialize, Type, Clone)] #[derive(Debug, Deserialize, Serialize, Type)]
pub struct ConnectRequest { pub struct ConnectRequest {
info: ConnectInfo, info: ConnectInfo,
args: ConnectArgs, args: ConnectArgs,
@@ -256,26 +227,6 @@ impl ConnectRequest {
self self
} }
pub fn with_local_hostname<T: Into<Option<String>>>(mut self, local_hostname: T) -> Self {
self.args.local_hostname = local_hostname.into();
self
}
pub fn with_force_dpd(mut self, force_dpd: u32) -> Self {
self.args.force_dpd = force_dpd;
self
}
pub fn with_no_xmlpost(mut self, no_xmlpost: bool) -> Self {
self.args.no_xmlpost = no_xmlpost;
self
}
pub fn with_allow_extend_session(mut self, allow_extend_session: bool) -> Self {
self.args.allow_extend_session = allow_extend_session;
self
}
pub fn gateway(&self) -> &Gateway { pub fn gateway(&self) -> &Gateway {
self.info.gateway() self.info.gateway()
} }
@@ -308,20 +259,3 @@ pub struct UpdateGuiRequest {
pub path: String, pub path: String,
pub checksum: String, pub checksum: String,
} }
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn connect_request_serializes_allow_extend_session() {
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
let req = ConnectRequest::new(info, "authcookie=AUTH".to_string()).with_allow_extend_session(true);
let value = serde_json::to_value(req).unwrap();
assert_eq!(value["args"]["allowExtendSession"], json!(true));
}
}
+2 -51
View File
@@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
use crate::{gateway::Gateway, session::SessionInfo}; use crate::gateway::Gateway;
#[derive(Debug, Deserialize, Serialize, Type, Clone)] #[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectInfo { pub struct ConnectInfo {
@@ -10,30 +10,6 @@ pub struct ConnectInfo {
gateways: Vec<Gateway>, gateways: Vec<Gateway>,
} }
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ConnectedInfo {
info: Box<ConnectInfo>,
session_info: Option<SessionInfo>,
}
impl ConnectedInfo {
pub fn new(info: ConnectInfo, session_info: Option<SessionInfo>) -> Self {
Self {
info: Box::new(info),
session_info,
}
}
pub fn info(&self) -> &ConnectInfo {
&self.info
}
pub fn session_info(&self) -> Option<&SessionInfo> {
self.session_info.as_ref()
}
}
impl ConnectInfo { impl ConnectInfo {
pub fn new(portal: String, gateway: Gateway, gateways: Vec<Gateway>) -> Self { pub fn new(portal: String, gateway: Gateway, gateways: Vec<Gateway>) -> Self {
Self { Self {
@@ -53,31 +29,6 @@ impl ConnectInfo {
pub enum VpnState { pub enum VpnState {
Disconnected, Disconnected,
Connecting(Box<ConnectInfo>), Connecting(Box<ConnectInfo>),
Connected(Box<ConnectedInfo>), Connected(Box<ConnectInfo>),
Disconnecting, Disconnecting,
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn connected_state_serializes_session_info() {
let gateway = Gateway::new("vpn".to_string(), "vpn.example.com".to_string());
let connect_info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
let session_info = SessionInfo {
lifetime_secs: Some(43_200),
allow_extend_session: true,
..Default::default()
};
let value = serde_json::to_value(VpnState::Connected(Box::new(ConnectedInfo::new(
connect_info,
Some(session_info),
))))
.unwrap();
assert_eq!(value["connected"]["sessionInfo"]["lifetimeSecs"], 43_200);
assert_eq!(value["connected"]["sessionInfo"]["allowExtendSession"], true);
}
}
-302
View File
@@ -1,302 +0,0 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use chrono::{Local, TimeZone};
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::gp_params::ClientOs;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct SessionWarning {
pub prior_secs: u32,
pub message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct SessionRequestArgs {
cookie: String,
user_agent: Option<String>,
os: Option<ClientOs>,
os_version: Option<String>,
client_version: Option<String>,
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
disable_ipv6: bool,
}
impl SessionRequestArgs {
pub fn new(cookie: String) -> Self {
Self {
cookie,
user_agent: None,
os: None,
os_version: None,
client_version: None,
certificate: None,
sslkey: None,
key_password: None,
disable_ipv6: false,
}
}
pub fn with_user_agent<T: Into<Option<String>>>(mut self, user_agent: T) -> Self {
self.user_agent = user_agent.into();
self
}
pub fn with_os<T: Into<Option<ClientOs>>>(mut self, os: T) -> Self {
self.os = os.into();
self
}
pub fn with_os_version<T: Into<Option<String>>>(mut self, os_version: T) -> Self {
self.os_version = os_version.into();
self
}
pub fn with_client_version<T: Into<Option<String>>>(mut self, client_version: T) -> Self {
self.client_version = client_version.into();
self
}
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
self.certificate = certificate.into();
self
}
pub fn with_sslkey<T: Into<Option<String>>>(mut self, sslkey: T) -> Self {
self.sslkey = sslkey.into();
self
}
pub fn with_key_password<T: Into<Option<String>>>(mut self, key_password: T) -> Self {
self.key_password = key_password.into();
self
}
pub fn with_disable_ipv6(mut self, disable_ipv6: bool) -> Self {
self.disable_ipv6 = disable_ipv6;
self
}
pub fn cookie(&self) -> &str {
&self.cookie
}
pub fn user_agent(&self) -> Option<String> {
self.user_agent.clone()
}
pub fn os(&self) -> Option<ClientOs> {
self.os.clone()
}
pub fn os_version(&self) -> Option<String> {
self.os_version.clone()
}
pub fn client_version(&self) -> Option<String> {
self.client_version.clone()
}
pub fn certificate(&self) -> Option<String> {
self.certificate.clone()
}
pub fn sslkey(&self) -> Option<String> {
self.sslkey.clone()
}
pub fn key_password(&self) -> Option<String> {
self.key_password.clone()
}
pub fn disable_ipv6(&self) -> bool {
self.disable_ipv6
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SessionInfo {
pub lifetime_secs: Option<u32>,
pub user_expires: Option<u32>,
pub expires_in_human: Option<String>,
pub lifetime_warning: Option<SessionWarning>,
pub inactivity_warning: Option<SessionWarning>,
pub admin_logout_message: Option<String>,
pub allow_extend_session: bool,
}
impl SessionInfo {
pub fn with_computed_human_times(mut self) -> Self {
self.expires_in_human = build_human_readable_expiry(self.user_expires, self.lifetime_secs);
self
}
pub fn from_vpn_session_fields(
lifetime_secs: Option<u32>,
user_expires: Option<u32>,
lifetime_warning: Option<SessionWarning>,
allow_extend_session: bool,
) -> Self {
Self {
lifetime_secs,
user_expires,
expires_in_human: None,
lifetime_warning,
inactivity_warning: None,
admin_logout_message: None,
allow_extend_session,
}
.with_computed_human_times()
}
pub fn rescheduled_after_extension(&self) -> Option<Self> {
let lifetime_secs = self.lifetime_secs?;
let mut session_info = self.clone();
session_info.user_expires = Some(unix_timestamp().saturating_add(lifetime_secs));
Some(session_info.with_computed_human_times())
}
pub fn log_summary(&self) -> String {
let lifetime_secs = self
.lifetime_secs
.map(format_secs_with_duration)
.unwrap_or_else(|| "none".to_string());
let user_expires = self
.user_expires
.map(format_epoch_with_local_time)
.unwrap_or_else(|| "none".to_string());
let lifetime_warning_prior = self
.lifetime_warning
.as_ref()
.map(|warning| format_secs_with_duration(warning.prior_secs))
.unwrap_or_else(|| "none".to_string());
format!(
"lifetime_secs={lifetime_secs}, user_expires={user_expires}, lifetime_warning_prior={lifetime_warning_prior}, allow_extend_session={}",
self.allow_extend_session
)
}
}
pub fn format_duration_secs(total_secs: u32) -> String {
humantime::format_duration(Duration::from_secs(total_secs as u64)).to_string()
}
fn format_secs_with_duration(secs: u32) -> String {
format!("{secs} ({})", format_duration_secs(secs))
}
fn format_epoch_with_local_time(epoch: u32) -> String {
let local_time = Local
.timestamp_opt(epoch as i64, 0)
.single()
.map(|time| time.format("%Y-%m-%d %H:%M:%S").to_string())
.unwrap_or_else(|| "invalid time".to_string());
let now = unix_timestamp();
let relative = if epoch >= now {
format!("in {}", format_duration_secs(epoch.saturating_sub(now)))
} else {
format!("{} ago", format_duration_secs(now.saturating_sub(epoch)))
};
format!("{epoch} ({local_time}, {relative})")
}
fn build_human_readable_expiry(user_expires: Option<u32>, lifetime_secs: Option<u32>) -> Option<String> {
if let Some(user_expires) = user_expires {
let now = unix_timestamp();
return Some(format_duration_secs(user_expires.saturating_sub(now)));
}
lifetime_secs.map(format_duration_secs)
}
fn unix_timestamp() -> u32 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as u32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_duration_secs() {
assert_eq!(format_duration_secs(43_200), "12h");
assert_eq!(format_duration_secs(1_830), "30m 30s");
}
#[test]
fn logs_session_info_with_human_readable_times() {
let info = SessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(unix_timestamp().saturating_add(43_200)),
lifetime_warning: Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
allow_extend_session: true,
..Default::default()
};
let summary = info.log_summary();
assert!(summary.contains("lifetime_secs=43200 (12h)"));
assert!(summary.contains("user_expires="));
assert!(summary.contains(", in "));
assert!(summary.contains("lifetime_warning_prior=1800 (30m)"));
assert!(summary.contains("allow_extend_session=true"));
}
#[test]
fn computes_expires_in_human_from_lifetime_or_epoch() {
let from_lifetime = SessionInfo {
lifetime_secs: Some(43_200),
..Default::default()
}
.with_computed_human_times();
assert_eq!(from_lifetime.expires_in_human.as_deref(), Some("12h"));
let from_epoch = SessionInfo {
user_expires: Some(unix_timestamp().saturating_add(1_830)),
..Default::default()
}
.with_computed_human_times();
assert!(
from_epoch
.expires_in_human
.as_deref()
.is_some_and(|value| value.starts_with("30m"))
);
}
#[test]
fn reschedules_after_extension_from_lifetime() {
let now = unix_timestamp();
let info = SessionInfo {
lifetime_secs: Some(7_200),
user_expires: Some(now.saturating_add(1_830)),
..Default::default()
};
let next = info.rescheduled_after_extension().unwrap();
assert!(
next
.user_expires
.is_some_and(|expires| expires >= now.saturating_add(7_200))
);
assert!(next.expires_in_human.is_some());
}
#[test]
fn reschedule_after_extension_requires_lifetime() {
assert!(SessionInfo::default().rescheduled_after_extension().is_none());
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
use base64::{Engine, engine::general_purpose}; use base64::{engine::general_purpose, Engine};
pub fn encode(data: &[u8]) -> String { pub fn encode(data: &[u8]) -> String {
let engine = general_purpose::STANDARD; let engine = general_purpose::STANDARD;
+2 -2
View File
@@ -1,8 +1,8 @@
use chacha20poly1305::{ use chacha20poly1305::{
AeadCore, ChaCha20Poly1305, Key, KeyInit,
aead::{Aead, OsRng}, aead::{Aead, OsRng},
AeadCore, ChaCha20Poly1305, Key, KeyInit,
}; };
use serde::{Serialize, de::DeserializeOwned}; use serde::{de::DeserializeOwned, Serialize};
pub fn generate_key() -> Key { pub fn generate_key() -> Key {
ChaCha20Poly1305::generate_key(&mut OsRng) ChaCha20Poly1305::generate_key(&mut OsRng)
-51
View File
@@ -1,6 +1,5 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::env; use std::env;
use std::ffi::OsStr;
use std::io::Write; use std::io::Write;
use std::path::Path; use std::path::Path;
@@ -42,15 +41,6 @@ pub fn patch_gui_runtime_env(hidpi: bool) {
// This is to avoid blank screen on some systems // This is to avoid blank screen on some systems
unsafe { std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1") }; unsafe { std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1") };
if is_wayland_session(
env::var_os("WAYLAND_DISPLAY").as_deref(),
env::var("XDG_SESSION_TYPE").ok().as_deref(),
) {
info!("Wayland session detected, enabling Linux WebKit rendering fallbacks");
set_env_if_missing("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
set_env_if_missing("LIBGL_ALWAYS_SOFTWARE", "1");
}
if hidpi { if hidpi {
info!("Setting GDK_SCALE=2 and GDK_DPI_SCALE=0.5"); info!("Setting GDK_SCALE=2 and GDK_DPI_SCALE=0.5");
unsafe { unsafe {
@@ -59,44 +49,3 @@ pub fn patch_gui_runtime_env(hidpi: bool) {
}; };
} }
} }
fn is_wayland_session(wayland_display: Option<&OsStr>, xdg_session_type: Option<&str>) -> bool {
if wayland_display.is_some() {
return true;
}
matches!(xdg_session_type, Some("wayland"))
}
fn set_env_if_missing(key: &str, value: &str) {
if env::var_os(key).is_some() {
return;
}
info!("Setting {}={}", key, value);
unsafe { env::set_var(key, value) };
}
#[cfg(test)]
mod tests {
use std::ffi::OsStr;
use super::is_wayland_session;
#[test]
fn detects_wayland_from_wayland_display() {
assert!(is_wayland_session(Some(OsStr::new("wayland-1")), None));
}
#[test]
fn detects_wayland_from_session_type() {
assert!(is_wayland_session(None, Some("wayland")));
}
#[test]
fn ignores_non_wayland_sessions() {
assert!(!is_wayland_session(None, None));
assert!(!is_wayland_session(None, Some("x11")));
assert!(!is_wayland_session(None, Some("tty")));
}
}
+3 -3
View File
@@ -1,4 +1,4 @@
pub mod xml; pub(crate) mod xml;
pub mod base64; pub mod base64;
pub mod checksum; pub mod checksum;
@@ -48,7 +48,7 @@ pub fn remove_url_scheme(s: &str) -> String {
#[derive(Error, Debug)] #[derive(Error, Debug)]
#[error("GP response error: reason={reason}, status={status}, body={body}")] #[error("GP response error: reason={reason}, status={status}, body={body}")]
pub struct GpError { pub(crate) struct GpError {
pub status: StatusCode, pub status: StatusCode,
pub reason: String, pub reason: String,
body: String, body: String,
@@ -60,7 +60,7 @@ impl GpError {
} }
} }
pub async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError> { pub(crate) async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError> {
let status = res.status(); let status = res.status();
if status.is_client_error() || status.is_server_error() { if status.is_client_error() || status.is_server_error() {
+1 -1
View File
@@ -3,7 +3,7 @@ use std::path::Path;
use log::{info, warn}; use log::{info, warn};
use regex::Regex; use regex::Regex;
use tempfile::NamedTempFile; use tempfile::NamedTempFile;
use version_compare::{Cmp, compare_to}; use version_compare::{compare_to, Cmp};
pub fn openssl_conf() -> String { pub fn openssl_conf() -> String {
let option = get_openssl_option(); let option = get_openssl_option();
+1 -55
View File
@@ -2,7 +2,7 @@ use std::sync::RwLock;
use redact_engine::{Pattern, Redaction as RedactEngine}; use redact_engine::{Pattern, Redaction as RedactEngine};
use regex::Regex; use regex::Regex;
use url::{Url, form_urlencoded}; use url::{form_urlencoded, Url};
pub struct Redaction { pub struct Redaction {
redact_engine: RwLock<Option<RedactEngine>>, redact_engine: RwLock<Option<RedactEngine>>,
@@ -123,46 +123,6 @@ pub fn redact_uri(uri: &str) -> String {
url.to_string() url.to_string()
} }
pub fn redact_form_params(params: &[(&str, &str)]) -> String {
let mut pairs = params
.iter()
.map(|(key, value)| (*key, redact_form_value(key, value)))
.collect::<Vec<_>>();
pairs.sort_by(|(left, _), (right, _)| left.cmp(right));
form_urlencoded::Serializer::new(String::new())
.extend_pairs(pairs)
.finish()
}
fn redact_form_value(key: &str, value: &str) -> String {
if value.is_empty() || is_safe_form_param(key) {
return value.to_string();
}
format!("redacted-{}", value.len())
}
fn is_safe_form_param(key: &str) -> bool {
matches!(
key,
"clientVer"
| "clientos"
| "config-digest"
| "csc-digest"
| "csc-support"
| "direct"
| "ipv6-support"
| "jnlpReady"
| "ok"
| "os-version"
| "prot"
| "swg-auth-token"
| "swg-nonce"
)
}
fn redact_query(query: Option<&str>) -> Option<String> { fn redact_query(query: Option<&str>) -> Option<String> {
let query = query?; let query = query?;
@@ -230,20 +190,6 @@ mod tests {
assert_eq!(redact_uri(uri), "https://f**********r/baz?qux=q**********x"); assert_eq!(redact_uri(uri), "https://f**********r/baz?qux=q**********x");
} }
#[test]
fn it_should_redact_form_params() {
let params = [
("portal-userauthcookie", "secret-cookie"),
("csc-support", "yes"),
("prelogin-cookie", ""),
];
assert_eq!(
redact_form_params(&params),
"csc-support=yes&portal-userauthcookie=redacted-13&prelogin-cookie="
);
}
#[test] #[test]
fn it_should_redact_data_uri() { fn it_should_redact_data_uri() {
let uri = "data:text/plain;a"; let uri = "data:text/plain;a";
+1 -1
View File
@@ -23,9 +23,9 @@ mod unix {
use anyhow::bail; use anyhow::bail;
use gtk::{ use gtk::{
EventBox,
glib::Cast, glib::Cast,
traits::{EventBoxExt, GtkWindowExt, WidgetExt}, traits::{EventBoxExt, GtkWindowExt, WidgetExt},
EventBox,
}; };
use log::info; use log::info;
use tauri::WebviewWindow; use tauri::WebviewWindow;
+5 -5
View File
@@ -1,6 +1,6 @@
use xmltree::Element; use xmltree::Element;
pub trait ElementExt { pub(crate) trait ElementExt {
/// Recursively find all descendants with the given name /// Recursively find all descendants with the given name
fn descendants(&self, name: &str) -> Vec<&Element>; fn descendants(&self, name: &str) -> Vec<&Element>;
@@ -46,10 +46,10 @@ impl ElementExt for Element {
} }
for child in &self.children { for child in &self.children {
if let Some(element) = child.as_element() if let Some(element) = child.as_element() {
&& let Some(found) = element.descendant(name) if let Some(found) = element.descendant(name) {
{ return Some(found);
return Some(found); }
} }
} }
+8 -20
View File
@@ -1,10 +1,6 @@
use std::{ use std::{env, path::PathBuf, process::Command};
env,
path::{Path, PathBuf},
process::Command,
};
fn apply_patches(patches_dir: &Path, build_src: &Path) { fn apply_patches(patches_dir: &PathBuf, build_src: &PathBuf) {
let patches = std::fs::read_dir(patches_dir) let patches = std::fs::read_dir(patches_dir)
.expect("Failed to read patches directory") .expect("Failed to read patches directory")
.filter_map(|entry| entry.ok()) .filter_map(|entry| entry.ok())
@@ -34,7 +30,7 @@ fn apply_patches(patches_dir: &Path, build_src: &Path) {
} }
} }
fn build_libxml2(deps_dir: &Path, out_dir: &Path) -> PathBuf { fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
let libxml2_dir = deps_dir.join("libxml2"); let libxml2_dir = deps_dir.join("libxml2");
// The temporary location where we will build // The temporary location where we will build
@@ -93,7 +89,7 @@ fn build_libxml2(deps_dir: &Path, out_dir: &Path) -> PathBuf {
dst dst
} }
fn build_openconnect(deps_dir: &Path, out_dir: &Path) -> PathBuf { fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
let openconnect_dir = deps_dir.join("openconnect"); let openconnect_dir = deps_dir.join("openconnect");
let patches_dir = deps_dir.join("patches"); let patches_dir = deps_dir.join("patches");
@@ -125,8 +121,7 @@ fn build_openconnect(deps_dir: &Path, out_dir: &Path) -> PathBuf {
// We explicitly enable static and disable shared to ensure we get a .a file. // We explicitly enable static and disable shared to ensure we get a .a file.
// .reconf("-ivf") is CRITICAL for git submodules because 'configure' // .reconf("-ivf") is CRITICAL for git submodules because 'configure'
// usually doesn't exist yet and needs to be generated. // usually doesn't exist yet and needs to be generated.
let mut config = autotools::Config::new(&build_src); let dst = autotools::Config::new(&build_src)
config
.reconf("-ivf") .reconf("-ivf")
.enable_static() .enable_static()
.disable_shared() .disable_shared()
@@ -139,15 +134,8 @@ fn build_openconnect(deps_dir: &Path, out_dir: &Path) -> PathBuf {
.without("libpskc", None) .without("libpskc", None)
.without("gssapi", None) .without("gssapi", None)
.with("gnutls-tss2", Some("no")) .with("gnutls-tss2", Some("no"))
.with("vpnc-script", Some("/etc/vpnc/vpnc-script")); // Specify vpnc-script, otherwise it will fail on macOS .with("vpnc-script", Some("/etc/vpnc/vpnc-script")) // Specify vpnc-script, otherwise it will fail on macOS
.build();
#[cfg(target_os = "macos")]
{
config.ldflag("-liconv");
config.env("LIBS", "-liconv");
}
let dst = config.build();
let lib_dir = dst.join("lib"); let lib_dir = dst.join("lib");
let include_dir = dst.join("include"); let include_dir = dst.join("include");
@@ -204,6 +192,6 @@ fn main() {
cc::Build::new() cc::Build::new()
.file("src/ffi/vpn.c") .file("src/ffi/vpn.c")
.include("src/ffi") .include("src/ffi")
.include(oc_dst.join("include")) .include(&oc_dst.join("include"))
.compile("vpn"); .compile("vpn");
} }
@@ -1,124 +0,0 @@
diff --git a/gpst.c b/gpst.c
index 244aaf04..78c16d1c 100644
--- a/gpst.c
+++ b/gpst.c
@@ -438,8 +438,19 @@ static int gpst_parse_config_xml(struct openconnect_info *vpninfo, xmlNode *xml_
new_ip_info.netmask = add_option_steal(&new_opts, "netmask", &s);
} else if (!xmlnode_get_val(xml_node, "mtu", &s))
new_ip_info.mtu = atoi(s);
- else if (!xmlnode_get_val(xml_node, "lifetime", &s))
+ else if (!xmlnode_get_val(xml_node, "lifetime", &s)) {
+ vpninfo->gp_session_lifetime = atoi(s);
vpninfo->auth_expiration = time(NULL) + atol(s);
+ } else if (!xmlnode_get_val(xml_node, "user-expires", &s) ||
+ !xmlnode_get_val(xml_node, "user_expires", &s)) {
+ vpninfo->gp_user_expires = atol(s);
+ } else if (!xmlnode_get_val(xml_node, "lifetime-notify-prior", &s)) {
+ vpninfo->gp_lifetime_notify_prior = atoi(s);
+ } else if (!xmlnode_get_val(xml_node, "lifetime-notify-message", &s)) {
+ free(vpninfo->gp_lifetime_notify_message);
+ vpninfo->gp_lifetime_notify_message = s;
+ s = NULL;
+ }
else if (!xmlnode_get_val(xml_node, "quarantine", &s)) {
if (strcmp(s, "no"))
vpn_progress(vpninfo, PRG_DEBUG,
diff --git a/libopenconnect.map.in b/libopenconnect.map.in
index f036c071..44110486 100644
--- a/libopenconnect.map.in
+++ b/libopenconnect.map.in
@@ -113,6 +113,10 @@ OPENCONNECT_5_7 {
openconnect_set_cookie;
openconnect_set_allow_insecure_crypto;
openconnect_get_auth_expiration;
+ openconnect_get_gp_session_lifetime;
+ openconnect_get_gp_user_expires;
+ openconnect_get_gp_lifetime_notify_prior;
+ openconnect_get_gp_lifetime_notify_message;
openconnect_disable_dtls;
openconnect_get_connect_url;
openconnect_set_webview_callback;
diff --git a/libopenconnect5.symbols b/libopenconnect5.symbols
index 7cb04d05..2c7af781 100644
--- a/libopenconnect5.symbols
+++ b/libopenconnect5.symbols
@@ -94,6 +94,10 @@ libopenconnect.so.5 libopenconnect5 #MINVER#
openconnect_set_cookie@OPENCONNECT_5_7 8.20
openconnect_set_allow_insecure_crypto@OPENCONNECT_5_7 8.20
openconnect_get_auth_expiration@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_session_lifetime@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_user_expires@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_lifetime_notify_prior@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_lifetime_notify_message@OPENCONNECT_5_7 8.20
openconnect_disable_dtls@OPENCONNECT_5_7 8.20
openconnect_get_connect_url@OPENCONNECT_5_7 8.20
openconnect_set_webview_callback@OPENCONNECT_5_7 8.20
diff --git a/library.c b/library.c
index b5e74e9b..03f47004 100644
--- a/library.c
+++ b/library.c
@@ -838,6 +838,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
free(vpninfo->dtls_cipher);
free(vpninfo->peer_cert_hash);
free(vpninfo->ciphersuite_config);
+ free(vpninfo->gp_lifetime_notify_message);
#if defined(OPENCONNECT_OPENSSL)
free(vpninfo->cstp_cipher);
#if defined(HAVE_BIO_METH_FREE)
@@ -1137,6 +1138,26 @@ time_t openconnect_get_auth_expiration(struct openconnect_info *vpninfo)
return vpninfo->auth_expiration;
}
+int openconnect_get_gp_session_lifetime(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_session_lifetime;
+}
+
+time_t openconnect_get_gp_user_expires(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_user_expires;
+}
+
+int openconnect_get_gp_lifetime_notify_prior(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_lifetime_notify_prior;
+}
+
+const char *openconnect_get_gp_lifetime_notify_message(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_lifetime_notify_message;
+}
+
int openconnect_get_ip_info(struct openconnect_info *vpninfo,
const struct oc_ip_info **info,
const struct oc_vpn_option **cstp_options,
diff --git a/openconnect-internal.h b/openconnect-internal.h
index abf45bbd..dd5507ca 100644
--- a/openconnect-internal.h
+++ b/openconnect-internal.h
@@ -647,6 +647,10 @@ struct openconnect_info {
int dtls_attempt_period;
int udp_probes_sent;
time_t auth_expiration;
+ int gp_session_lifetime;
+ time_t gp_user_expires;
+ int gp_lifetime_notify_prior;
+ char *gp_lifetime_notify_message;
time_t new_dtls_started;
#if defined(OPENCONNECT_OPENSSL)
SSL_CTX *dtls_ctx;
diff --git a/openconnect.h b/openconnect.h
index 136f181a..febf15cc 100644
--- a/openconnect.h
+++ b/openconnect.h
@@ -655,6 +655,10 @@ void openconnect_set_dpd(struct openconnect_info *, int min_seconds);
void openconnect_set_trojan_interval(struct openconnect_info *, int seconds);
int openconnect_get_idle_timeout(struct openconnect_info *);
time_t openconnect_get_auth_expiration(struct openconnect_info *);
+int openconnect_get_gp_session_lifetime(struct openconnect_info *);
+time_t openconnect_get_gp_user_expires(struct openconnect_info *);
+int openconnect_get_gp_lifetime_notify_prior(struct openconnect_info *);
+const char *openconnect_get_gp_lifetime_notify_message(struct openconnect_info *);
/* The returned structures are owned by the library and may be freed/replaced
due to rekey or reconnect. Assume that once the mainloop starts, the
@@ -1,15 +0,0 @@
diff --git a/gpst.c b/gpst.c
index 244aaf04..fb8d945d 100644
--- a/gpst.c
+++ b/gpst.c
@@ -669,6 +669,10 @@ static int gpst_get_config(struct openconnect_info *vpninfo)
result = do_https_request(vpninfo, "POST", "application/x-www-form-urlencoded", request_body, &xml_buf, NULL, HTTP_NO_FLAGS);
free(vpninfo->urlpath);
vpninfo->urlpath = orig_path;
+ if (result >= 0 && xml_buf)
+ vpn_progress(vpninfo, PRG_DEBUG,
+ "GlobalProtect getconfig.esp response:\n%s\n",
+ xml_buf);
/* parse getconfig result */
if (result >= 0)
+5 -19
View File
@@ -1,6 +1,6 @@
use crate::Vpn; use crate::Vpn;
use log::{debug, info, trace, warn}; use log::{debug, info, trace, warn};
use std::ffi::{c_char, c_int, c_long, c_void}; use std::ffi::{c_char, c_int, c_void};
/// ConnectOptions struct for FFI, the field names and order must match the C definition. /// ConnectOptions struct for FFI, the field names and order must match the C definition.
#[repr(C)] #[repr(C)]
@@ -15,7 +15,7 @@ pub(crate) struct ConnectOptions {
pub os: *const c_char, pub os: *const c_char,
pub os_version: *const c_char, pub os_version: *const c_char,
pub client_version: *const c_char, pub client_version: *const c_char,
pub local_hostname: *const c_char, pub split_dns: *const c_char,
pub script: *const c_char, pub script: *const c_char,
pub interface: *const c_char, pub interface: *const c_char,
@@ -35,26 +35,12 @@ pub(crate) struct ConnectOptions {
pub no_dtls: u32, pub no_dtls: u32,
pub dpd_interval: u32, pub dpd_interval: u32,
pub no_xmlpost: u32,
}
#[repr(C)]
#[derive(Debug)]
pub(crate) struct VpnSessionInfoRaw {
pub auth_expiration: c_long,
pub lifetime_secs: c_int,
pub user_expires: c_long,
pub lifetime_warning_prior: c_int,
pub lifetime_warning_message: *const c_char,
} }
#[link(name = "vpn")] #[link(name = "vpn")]
unsafe extern "C" { unsafe extern "C" {
#[link_name = "vpn_connect"] #[link_name = "vpn_connect"]
fn vpn_connect( fn vpn_connect(options: *const ConnectOptions, callback: extern "C" fn(i32, *mut c_void)) -> c_int;
options: *const ConnectOptions,
callback: extern "C" fn(i32, *const VpnSessionInfoRaw, *mut c_void),
) -> c_int;
#[link_name = "vpn_disconnect"] #[link_name = "vpn_disconnect"]
fn vpn_disconnect(); fn vpn_disconnect();
@@ -69,9 +55,9 @@ pub(crate) fn disconnect() {
} }
#[unsafe(no_mangle)] #[unsafe(no_mangle)]
extern "C" fn on_vpn_connected(pipe_fd: i32, session_info: *const VpnSessionInfoRaw, vpn: *mut c_void) { extern "C" fn on_vpn_connected(pipe_fd: i32, vpn: *mut c_void) {
let vpn = unsafe { &*(vpn as *const Vpn) }; let vpn = unsafe { &*(vpn as *const Vpn) };
vpn.on_connected(pipe_fd, crate::vpn::session_info_from_raw(session_info)); vpn.on_connected(pipe_fd);
} }
// Logger used in the C code. // Logger used in the C code.
+18 -27
View File
@@ -12,6 +12,7 @@ void *g_user_data;
static int g_cmd_pipe_fd; static int g_cmd_pipe_fd;
static const char *g_vpnc_script; static const char *g_vpnc_script;
static const char *g_vpnc_interface; static const char *g_vpnc_interface;
static const char *g_split_dns;
static int g_script_tun; static int g_script_tun;
static vpn_connected_callback on_vpn_connected; static vpn_connected_callback on_vpn_connected;
@@ -40,9 +41,19 @@ static void print_progress(__attribute__((unused)) void *_vpninfo, int level,
} }
} }
static void sync_split_dns_env()
{
if (g_split_dns && *g_split_dns) {
setenv("CISCO_SPLIT_DNS", g_split_dns, 1);
} else {
unsetenv("CISCO_SPLIT_DNS");
}
}
static void setup_tun_handler(void *_vpninfo) static void setup_tun_handler(void *_vpninfo)
{ {
int ret; int ret;
sync_split_dns_env();
if (g_script_tun) { if (g_script_tun) {
ret = openconnect_setup_tun_script(_vpninfo, g_vpnc_script); ret = openconnect_setup_tun_script(_vpninfo, g_vpnc_script);
} else { } else {
@@ -51,16 +62,7 @@ static void setup_tun_handler(void *_vpninfo)
} }
if (!ret) { if (!ret) {
vpn_session_info session_info = { on_vpn_connected(g_cmd_pipe_fd, g_user_data);
.auth_expiration = (long)openconnect_get_auth_expiration(_vpninfo),
.lifetime_secs = openconnect_get_gp_session_lifetime(_vpninfo),
.user_expires = (long)openconnect_get_gp_user_expires(_vpninfo),
.lifetime_warning_prior =
openconnect_get_gp_lifetime_notify_prior(_vpninfo),
.lifetime_warning_message =
openconnect_get_gp_lifetime_notify_message(_vpninfo),
};
on_vpn_connected(g_cmd_pipe_fd, &session_info, g_user_data);
} }
} }
@@ -69,11 +71,11 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
{ {
struct openconnect_info *vpninfo; struct openconnect_info *vpninfo;
struct utsname utsbuf; struct utsname utsbuf;
const char *effective_local_hostname = NULL;
g_user_data = options->user_data; g_user_data = options->user_data;
g_vpnc_script = options->script; g_vpnc_script = options->script;
g_vpnc_interface = options->interface; g_vpnc_interface = options->interface;
g_split_dns = options->split_dns;
g_script_tun = options->script_tun; g_script_tun = options->script_tun;
on_vpn_connected = callback; on_vpn_connected = callback;
@@ -89,7 +91,6 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
INFO("DISABLE_IPV6: %d", options->disable_ipv6); INFO("DISABLE_IPV6: %d", options->disable_ipv6);
INFO("NO_DTLS: %d", options->no_dtls); INFO("NO_DTLS: %d", options->no_dtls);
INFO("DPD_INTERVAL: %d", options->dpd_interval); INFO("DPD_INTERVAL: %d", options->dpd_interval);
INFO("NO_XMLPOST: %d", options->no_xmlpost);
vpninfo = vpninfo =
openconnect_vpninfo_new(options->user_agent, validate_peer_cert, openconnect_vpninfo_new(options->user_agent, validate_peer_cert,
@@ -120,17 +121,6 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
options->client_version); options->client_version);
} }
effective_local_hostname = options->local_hostname;
if (!effective_local_hostname && !uname(&utsbuf)) {
effective_local_hostname = utsbuf.nodename;
}
if (effective_local_hostname) {
openconnect_set_localname(vpninfo, effective_local_hostname);
}
INFO("LOCAL_HOSTNAME: %s",
effective_local_hostname ? effective_local_hostname : "(not set)");
if (options->certificate) { if (options->certificate) {
INFO("Setting client certificate: %s", options->certificate); INFO("Setting client certificate: %s", options->certificate);
openconnect_set_client_cert(vpninfo, options->certificate, openconnect_set_client_cert(vpninfo, options->certificate,
@@ -141,10 +131,6 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
openconnect_set_key_password(vpninfo, options->key_password); openconnect_set_key_password(vpninfo, options->key_password);
} }
if (options->no_xmlpost) {
openconnect_set_xmlpost(vpninfo, 0);
}
if (options->csd_wrapper) { if (options->csd_wrapper) {
openconnect_setup_csd(vpninfo, options->csd_uid, 1, openconnect_setup_csd(vpninfo, options->csd_uid, 1,
options->csd_wrapper); options->csd_wrapper);
@@ -169,6 +155,10 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
return 1; return 1;
} }
if (!uname(&utsbuf)) {
openconnect_set_localname(vpninfo, utsbuf.nodename);
}
// Essential step // Essential step
if (openconnect_make_cstp_connection(vpninfo) != 0) { if (openconnect_make_cstp_connection(vpninfo) != 0) {
ERROR("openconnect_make_cstp_connection failed"); ERROR("openconnect_make_cstp_connection failed");
@@ -188,6 +178,7 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
if (ret) { if (ret) {
INFO("openconnect_mainloop returned %d, exiting", ret); INFO("openconnect_mainloop returned %d, exiting", ret);
unsetenv("CISCO_SPLIT_DNS");
openconnect_vpninfo_free(vpninfo); openconnect_vpninfo_free(vpninfo);
return ret; return ret;
} }
+2 -13
View File
@@ -3,17 +3,7 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
typedef struct vpn_session_info { typedef void (*vpn_connected_callback)(int cmd_pipe_fd, void *user_data);
long auth_expiration;
int lifetime_secs;
long user_expires;
int lifetime_warning_prior;
const char *lifetime_warning_message;
} vpn_session_info;
typedef void (*vpn_connected_callback)(int cmd_pipe_fd,
const vpn_session_info *session_info,
void *user_data);
typedef struct vpn_options { typedef struct vpn_options {
void *user_data; void *user_data;
@@ -25,7 +15,7 @@ typedef struct vpn_options {
const char *os; const char *os;
const char *os_version; const char *os_version;
const char *client_version; const char *client_version;
const char *local_hostname; const char *split_dns;
const char *script; const char *script;
const char *interface; const char *interface;
@@ -45,7 +35,6 @@ typedef struct vpn_options {
const int no_dtls; const int no_dtls;
const int dpd_interval; const int dpd_interval;
const int no_xmlpost;
} vpn_options; } vpn_options;
int vpn_connect(const vpn_options *options, vpn_connected_callback callback); int vpn_connect(const vpn_options *options, vpn_connected_callback callback);
+45 -101
View File
@@ -1,5 +1,5 @@
use std::{ use std::{
ffi::{CStr, CString, c_char}, ffi::{CString, c_char},
fmt, fmt,
sync::{Arc, RwLock}, sync::{Arc, RwLock},
}; };
@@ -9,52 +9,7 @@ use log::info;
use crate::ffi; use crate::ffi;
use crate::vpn_utils::{check_executable, find_csd_wrapper, find_vpnc_script}; use crate::vpn_utils::{check_executable, find_csd_wrapper, find_vpnc_script};
type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce(VpnSessionInfo) + 'static + Send + Sync>>>>; type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce() + 'static + Send + Sync>>>>;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct VpnSessionInfo {
pub lifetime_secs: Option<u32>,
pub user_expires: Option<u32>,
pub lifetime_warning: Option<VpnSessionWarning>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VpnSessionWarning {
pub prior_secs: u32,
pub message: String,
}
pub(crate) fn session_info_from_raw(raw: *const ffi::VpnSessionInfoRaw) -> VpnSessionInfo {
if raw.is_null() {
return VpnSessionInfo::default();
}
let raw = unsafe { &*raw };
let warning_message =
unsafe { optional_c_string(raw.lifetime_warning_message) }.filter(|message| !message.is_empty());
let user_expires = positive_i64_to_u32(raw.user_expires).or_else(|| positive_i64_to_u32(raw.auth_expiration));
VpnSessionInfo {
lifetime_secs: positive_i64_to_u32(raw.lifetime_secs as i64),
user_expires,
lifetime_warning: match (positive_i64_to_u32(raw.lifetime_warning_prior as i64), warning_message) {
(Some(prior_secs), Some(message)) => Some(VpnSessionWarning { prior_secs, message }),
_ => None,
},
}
}
unsafe fn optional_c_string(value: *const c_char) -> Option<String> {
if value.is_null() {
return None;
}
unsafe { CStr::from_ptr(value) }.to_str().ok().map(ToOwned::to_owned)
}
fn positive_i64_to_u32(value: i64) -> Option<u32> {
u32::try_from(value).ok().filter(|value| *value > 0)
}
pub struct Vpn { pub struct Vpn {
server: CString, server: CString,
@@ -64,7 +19,7 @@ pub struct Vpn {
os: CString, os: CString,
os_version: Option<CString>, os_version: Option<CString>,
client_version: Option<CString>, client_version: Option<CString>,
local_hostname: Option<CString>, split_dns: Option<CString>,
script: CString, script: CString,
interface: Option<CString>, interface: Option<CString>,
@@ -84,7 +39,6 @@ pub struct Vpn {
no_dtls: bool, no_dtls: bool,
dpd_interval: u32, dpd_interval: u32,
no_xmlpost: bool,
callback: OnConnectedCallback, callback: OnConnectedCallback,
} }
@@ -94,18 +48,18 @@ impl Vpn {
VpnBuilder::new(server, cookie) VpnBuilder::new(server, cookie)
} }
pub fn connect(&self, on_connected: impl FnOnce(VpnSessionInfo) + 'static + Send + Sync) -> i32 { pub fn connect(&self, on_connected: impl FnOnce() + 'static + Send + Sync) -> i32 {
self.callback.write().unwrap().replace(Box::new(on_connected)); self.callback.write().unwrap().replace(Box::new(on_connected));
let options = self.build_connect_options(); let options = self.build_connect_options();
ffi::connect(&options) ffi::connect(&options)
} }
pub(crate) fn on_connected(&self, pipe_fd: i32, session_info: VpnSessionInfo) { pub(crate) fn on_connected(&self, pipe_fd: i32) {
info!("Connected to VPN, pipe_fd: {}", pipe_fd); info!("Connected to VPN, pipe_fd: {}", pipe_fd);
if let Some(callback) = self.callback.write().unwrap().take() { if let Some(callback) = self.callback.write().unwrap().take() {
callback(session_info); callback();
} }
} }
@@ -124,7 +78,7 @@ impl Vpn {
os: self.os.as_ptr(), os: self.os.as_ptr(),
os_version: Self::option_to_ptr(&self.os_version), os_version: Self::option_to_ptr(&self.os_version),
client_version: Self::option_to_ptr(&self.client_version), client_version: Self::option_to_ptr(&self.client_version),
local_hostname: Self::option_to_ptr(&self.local_hostname), split_dns: Self::option_to_ptr(&self.split_dns),
script: self.script.as_ptr(), script: self.script.as_ptr(),
interface: Self::option_to_ptr(&self.interface), interface: Self::option_to_ptr(&self.interface),
@@ -143,7 +97,6 @@ impl Vpn {
disable_ipv6: self.disable_ipv6 as u32, disable_ipv6: self.disable_ipv6 as u32,
no_dtls: self.no_dtls as u32, no_dtls: self.no_dtls as u32,
dpd_interval: self.dpd_interval, dpd_interval: self.dpd_interval,
no_xmlpost: self.no_xmlpost as u32,
} }
} }
@@ -185,7 +138,7 @@ pub struct VpnBuilder {
os: Option<String>, os: Option<String>,
os_version: Option<String>, os_version: Option<String>,
client_version: Option<String>, client_version: Option<String>,
local_hostname: Option<String>, split_dns: Option<String>,
certificate: Option<String>, certificate: Option<String>,
sslkey: Option<String>, sslkey: Option<String>,
@@ -201,7 +154,6 @@ pub struct VpnBuilder {
no_dtls: bool, no_dtls: bool,
dpd_interval: u32, dpd_interval: u32,
no_xmlpost: bool,
} }
impl VpnBuilder { impl VpnBuilder {
@@ -217,7 +169,7 @@ impl VpnBuilder {
os: None, os: None,
os_version: None, os_version: None,
client_version: None, client_version: None,
local_hostname: None, split_dns: None,
certificate: None, certificate: None,
sslkey: None, sslkey: None,
@@ -232,7 +184,6 @@ impl VpnBuilder {
disable_ipv6: false, disable_ipv6: false,
no_dtls: false, no_dtls: false,
dpd_interval: 0, dpd_interval: 0,
no_xmlpost: false,
} }
} }
@@ -271,8 +222,8 @@ impl VpnBuilder {
self self
} }
pub fn local_hostname<T: Into<Option<String>>>(mut self, local_hostname: T) -> Self { pub fn split_dns<T: Into<Option<String>>>(mut self, split_dns: T) -> Self {
self.local_hostname = local_hostname.into(); self.split_dns = split_dns.into();
self self
} }
@@ -331,11 +282,6 @@ impl VpnBuilder {
self self
} }
pub fn no_xmlpost(mut self, no_xmlpost: bool) -> Self {
self.no_xmlpost = no_xmlpost;
self
}
fn determine_script(&self) -> Result<&str, VpnError> { fn determine_script(&self) -> Result<&str, VpnError> {
match &self.script { match &self.script {
Some(script) => { Some(script) => {
@@ -378,7 +324,7 @@ impl VpnBuilder {
os: Self::to_cstring(&os), os: Self::to_cstring(&os),
os_version: self.os_version.as_deref().map(Self::to_cstring), os_version: self.os_version.as_deref().map(Self::to_cstring),
client_version: self.client_version.as_deref().map(Self::to_cstring), client_version: self.client_version.as_deref().map(Self::to_cstring),
local_hostname: self.local_hostname.as_deref().map(Self::to_cstring), split_dns: self.split_dns.as_deref().map(Self::to_cstring),
script: Self::to_cstring(&script), script: Self::to_cstring(&script),
interface: self.interface.as_deref().map(Self::to_cstring), interface: self.interface.as_deref().map(Self::to_cstring),
@@ -397,7 +343,6 @@ impl VpnBuilder {
disable_ipv6: self.disable_ipv6, disable_ipv6: self.disable_ipv6,
no_dtls: self.no_dtls, no_dtls: self.no_dtls,
dpd_interval: self.dpd_interval, dpd_interval: self.dpd_interval,
no_xmlpost: self.no_xmlpost,
callback: Default::default(), callback: Default::default(),
}) })
@@ -410,47 +355,46 @@ impl VpnBuilder {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use std::{
use std::ffi::CString; ffi::CStr,
fs,
time::{SystemTime, UNIX_EPOCH},
};
#[test] #[cfg(unix)]
fn maps_session_info_from_callback_payload() { use std::os::unix::fs::PermissionsExt;
let message = CString::new("Session expires soon").unwrap();
let raw = ffi::VpnSessionInfoRaw {
auth_expiration: 0,
lifetime_secs: 43_200,
user_expires: 1_776_828_409,
lifetime_warning_prior: 1_800,
lifetime_warning_message: message.as_ptr(),
};
let info = session_info_from_raw(&raw); use super::Vpn;
assert_eq!(info.lifetime_secs, Some(43_200)); #[cfg(unix)]
assert_eq!(info.user_expires, Some(1_776_828_409)); fn create_executable_script() -> String {
assert_eq!( let nanos = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
info.lifetime_warning, let path = std::env::temp_dir().join(format!("gp-openconnect-test-{nanos}.sh"));
Some(VpnSessionWarning {
prior_secs: 1_800, fs::write(&path, "#!/bin/sh\nexit 0\n").unwrap();
message: "Session expires soon".to_string(),
}) let mut permissions = fs::metadata(&path).unwrap().permissions();
); permissions.set_mode(0o755);
fs::set_permissions(&path, permissions).unwrap();
path.to_string_lossy().into_owned()
} }
#[cfg(unix)]
#[test] #[test]
fn falls_back_to_auth_expiration_when_user_expires_is_absent() { fn split_dns_survives_into_connect_options() {
let raw = ffi::VpnSessionInfoRaw { let script = create_executable_script();
auth_expiration: 1_776_828_409, let vpn = Vpn::builder("https://vpn.example.com", "cookie")
lifetime_secs: 0, .script(Some(script.clone()))
user_expires: 0, .split_dns(Some("corp.local,svc.local".to_string()))
lifetime_warning_prior: 0, .build()
lifetime_warning_message: std::ptr::null(), .unwrap();
};
let info = session_info_from_raw(&raw); let options = vpn.build_connect_options();
let split_dns = unsafe { CStr::from_ptr(options.split_dns) }.to_str().unwrap();
assert_eq!(info.user_expires, Some(1_776_828_409)); assert_eq!(split_dns, "corp.local,svc.local");
assert_eq!(info.lifetime_secs, None);
assert_eq!(info.lifetime_warning, None); fs::remove_file(script).unwrap();
} }
} }
+4 -10
View File
@@ -3,8 +3,6 @@ use std::{io, path::Path};
use is_executable::IsExecutable; use is_executable::IsExecutable;
const VPNC_SCRIPT_LOCATIONS: &[&str] = &[ const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
"/usr/libexec/gpclient/vpnc-script",
"/usr/lib/gpclient/vpnc-script",
"/usr/local/share/vpnc-scripts/vpnc-script", "/usr/local/share/vpnc-scripts/vpnc-script",
"/usr/local/sbin/vpnc-script", "/usr/local/sbin/vpnc-script",
"/usr/share/vpnc-scripts/vpnc-script", "/usr/share/vpnc-scripts/vpnc-script",
@@ -12,10 +10,8 @@ const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
"/etc/vpnc/vpnc-script", "/etc/vpnc/vpnc-script",
"/etc/openconnect/vpnc-script", "/etc/openconnect/vpnc-script",
"/usr/libexec/vpnc-scripts/vpnc-script", "/usr/libexec/vpnc-scripts/vpnc-script",
#[cfg(all(target_os = "macos", target_arch = "aarch64"))] #[cfg(target_os = "macos")]
"/opt/homebrew/etc/vpnc/vpnc-script", "/opt/homebrew/etc/vpnc/vpnc-script",
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
"/usr/local/etc/vpnc/vpnc-script",
]; ];
const CSD_WRAPPER_LOCATIONS: &[&str] = &[ const CSD_WRAPPER_LOCATIONS: &[&str] = &[
@@ -26,10 +22,8 @@ const CSD_WRAPPER_LOCATIONS: &[&str] = &[
"/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh", "/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh",
"/usr/lib/openconnect/hipreport.sh", "/usr/lib/openconnect/hipreport.sh",
"/usr/libexec/openconnect/hipreport.sh", "/usr/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "aarch64"))] #[cfg(target_os = "macos")]
"/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh", "/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
"/usr/local/opt/openconnect/libexec/openconnect/hipreport.sh",
]; ];
fn find_executable(locations: &[&'static str]) -> Option<&'static str> { fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
@@ -44,11 +38,11 @@ fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
} }
pub fn find_vpnc_script() -> Option<&'static str> { pub fn find_vpnc_script() -> Option<&'static str> {
find_executable(VPNC_SCRIPT_LOCATIONS) find_executable(&VPNC_SCRIPT_LOCATIONS)
} }
pub fn find_csd_wrapper() -> Option<&'static str> { pub fn find_csd_wrapper() -> Option<&'static str> {
find_executable(CSD_WRAPPER_LOCATIONS) find_executable(&CSD_WRAPPER_LOCATIONS)
} }
/// If file exists, check if it is executable /// If file exists, check if it is executable
+7 -5
View File
@@ -35,7 +35,7 @@
src = pkgs.fetchzip { src = pkgs.fetchzip {
url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/v${version}/globalprotect-openconnect-${version}.tar.gz"; url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/v${version}/globalprotect-openconnect-${version}.tar.gz";
hash = "sha256-NS3tIZxkT9A4eqmfkcl29bHHJrrgVs/XSQBOz99cP30="; hash = "sha256-4hlWP7yvwk4rTvQWuh60D40DJ20GfHhLTYA5+dkc4Hc=";
}; };
cpu = pkgs.stdenv.hostPlatform.parsed.cpu.name; cpu = pkgs.stdenv.hostPlatform.parsed.cpu.name;
@@ -43,8 +43,8 @@
gpgui = pkgs.fetchzip { gpgui = pkgs.fetchzip {
url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/v${version}/gpgui_${cpu}.bin.tar.xz"; url = "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/v${version}/gpgui_${cpu}.bin.tar.xz";
hash = { hash = {
x86_64 = "sha256-1XBdrKJOhSViZOgfqohZjdzV6qzx/qpy0yhkbZ8DumA="; x86_64 = "sha256-SayWyWJBDoIgqQG/z7v4FEr0uYHNZDJHokHPYqIgrJ0=";
aarch64 = "sha256-humujgf/M31SkBABc14g/ujjacGHxqElzNuCClhTAfA="; aarch64 = "sha256-Q8yJW2ecv6zsuzzpfVAjSaDhLHQQJyVGFzZuLl0RV8Q=";
}.${cpu}; }.${cpu};
}; };
in in
@@ -59,6 +59,7 @@
buildInputs = buildInputs =
with pkgs; with pkgs;
[ [
vpnc-scripts
libxml2 libxml2
zlib zlib
lz4 lz4
@@ -102,8 +103,9 @@
{ {
postPatch = '' postPatch = ''
substituteInPlace crates/openconnect/src/vpn_utils.rs \ substituteInPlace crates/openconnect/src/vpn_utils.rs \
--replace-fail /usr/libexec/gpclient/vpnc-script $out/libexec/gpclient/vpnc-script \ --replace-fail /etc/vpnc/vpnc-script ${pkgs.vpnc-scripts}/bin/vpnc-script \
--replace-fail /usr/libexec/gpclient/hipreport.sh $out/libexec/gpclient/hipreport.sh --replace-fail /usr/libexec/gpclient/hipreport.sh $out/libexec/gpclient/hipreport.sh \
--replace-fail /usr/lib/openconnect/hipreport.sh ${pkgs.openconnect}/libexec/openconnect/hipreport.sh
substituteInPlace crates/common/src/constants.rs \ substituteInPlace crates/common/src/constants.rs \
--replace-fail /usr/bin/gpclient $out/bin/gpclient \ --replace-fail /usr/bin/gpclient $out/bin/gpclient \
-74
View File
@@ -1,74 +0,0 @@
# Maintainer: Kevin Yue <[email protected]>
pkgname=@PKG_NAME@
pkgver=@VERSION@
pkgrel=@REVISION@
pkgdesc="A GUI client for GlobalProtect VPN, based on OpenConnect, supports the SSO authentication method."
url="https://github.com/yuezk/GlobalProtect-openconnect"
arch="x86_64 aarch64"
license="GPL-3.0-only"
depends="
gmp
gnutls
libayatana-appindicator
libsecret
libxml2
lz4
nettle
openssl
p11-kit
polkit
webkit2gtk-4.1
xdg-utils
zlib
"
makedepends="
autoconf
automake
cargo
file
gettext-dev
gmp-dev
gnutls-dev
gtk+3.0-dev
libayatana-appindicator-dev
libsecret-dev
librsvg-dev
libtool
libxml2-dev
lz4-dev
make
nettle-dev
openssl-dev
p11-kit-dev
patch
pkgconf
zlib-dev
"
source="$pkgname-$pkgver.tar.gz"
builddir="$srcdir/$pkgname-$pkgver"
options="!check"
build() {
cd "$builddir"
unset CFLAGS
unset RUSTFLAGS
make build \
INCLUDE_GUI="${INCLUDE_GUI:-0}" \
BUILD_GUI_HELPER="${BUILD_GUI_HELPER:-1}" \
LIBXML2_STATIC="${LIBXML2_STATIC:-1}"
}
package() {
cd "$builddir"
make install \
DESTDIR="$pkgdir" \
BUILD_GUI_HELPER="${BUILD_GUI_HELPER:-1}"
}
sha512sums="
@SHA512@ $pkgname-$pkgver.tar.gz
"
@@ -1,42 +0,0 @@
pkgbase = globalprotect-openconnect-git
pkgdesc = A GUI client for GlobalProtect VPN, based on OpenConnect, supports the SSO authentication method.
pkgver = 2.5.1.r1.g24f9bbb
pkgrel = 2
url = https://github.com/yuezk/GlobalProtect-openconnect
install = gp.install
arch = x86_64
arch = aarch64
license = GPL3
makedepends = git
makedepends = pkg-config
makedepends = openconnect>=8.20
makedepends = webkit2gtk-4.1
makedepends = curl
makedepends = wget
makedepends = file
makedepends = openssl
makedepends = appmenu-gtk-module
makedepends = libappindicator-gtk3
makedepends = librsvg
makedepends = libsecret
makedepends = cargo
depends = vpnc
depends = openssl
depends = webkit2gtk-4.1
depends = libappindicator-gtk3
depends = libsecret
depends = libxml2
depends = shared-mime-info
depends = desktop-file-utils
optdepends = wmctrl: for window management
provides = globalprotect-openconnect
provides = gpclient
provides = gpservice
provides = gpauth
provides = gpgui
conflicts = globalprotect-openconnect
options = !strip
source = globalprotect-openconnect::git+https://github.com/yuezk/GlobalProtect-openconnect.git#branch=main
sha256sums = SKIP
pkgname = globalprotect-openconnect-git
@@ -1,52 +0,0 @@
# Maintainer: Kevin Yue <[email protected]>
_pkgname_prefix=globalprotect-openconnect
pkgname="${_pkgname_prefix}-git"
pkgver=2.5.1.r1.g24f9bbb
pkgrel=2
pkgdesc="A GUI client for GlobalProtect VPN, based on OpenConnect, supports the SSO authentication method."
arch=(x86_64 aarch64)
url="https://github.com/yuezk/GlobalProtect-openconnect"
license=('GPL3')
makedepends=(git pkg-config 'openconnect>=8.20' webkit2gtk-4.1 curl wget file openssl appmenu-gtk-module libappindicator-gtk3 librsvg libsecret cargo)
depends=(vpnc openssl webkit2gtk-4.1 libappindicator-gtk3 libsecret libxml2 shared-mime-info desktop-file-utils)
optdepends=('wmctrl: for window management')
conflicts=('globalprotect-openconnect')
provides=('globalprotect-openconnect' 'gpclient' 'gpservice' 'gpauth' 'gpgui')
install=gp.install
source=("${_pkgname_prefix}::git+https://github.com/yuezk/GlobalProtect-openconnect.git#branch=main")
sha256sums=("SKIP")
options=('!strip')
pkgver() {
cd "${_pkgname_prefix}"
git describe --long --tags | sed 's/^v//;s/\([^-]*-g\)/r\1/;s/-/./g'
}
prepare() {
cd "${_pkgname_prefix}"
git submodule update --init --recursive
cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')"
}
build() {
# Must unset the CFLAGS, otherwise the build fails on linking openssl, don't know why
unset CFLAGS
cd "${_pkgname_prefix}"
cargo build --frozen --release
}
package() {
cd "${_pkgname_prefix}"
DESTDIR="$pkgdir" make install
}
@@ -1,19 +0,0 @@
post_install() {
update-mime-database /usr/share/mime
update-desktop-database -q
}
pre_upgrade() {
rm -f /usr/bin/gpgui
}
post_upgrade() {
update-mime-database /usr/share/mime
update-desktop-database -q
}
post_remove() {
rm -f /usr/bin/gpgui
update-mime-database /usr/share/mime
update-desktop-database -q
}
+1 -2
View File
@@ -10,7 +10,7 @@ install:
install -Dm755 artifacts/usr/bin/gpgui $(DESTDIR)/usr/bin/gpgui; \ install -Dm755 artifacts/usr/bin/gpgui $(DESTDIR)/usr/bin/gpgui; \
fi fi
install -Dm755 artifacts/usr/libexec/gpclient/vpnc-script $(DESTDIR)/usr/libexec/gpclient/vpnc-script # Install the HIP report script
install -Dm755 artifacts/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh install -Dm755 artifacts/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
# Install the disconnect hooks # Install the disconnect hooks
@@ -33,7 +33,6 @@ uninstall:
rm -f $(DESTDIR)/usr/bin/gpgui-helper rm -f $(DESTDIR)/usr/bin/gpgui-helper
rm -f $(DESTDIR)/usr/bin/gpgui 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/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/pre-down.d/gpclient.down
+2 -12
View File
@@ -4,25 +4,14 @@ Priority: optional
Maintainer: Kevin Yue <[email protected]> Maintainer: Kevin Yue <[email protected]>
Standards-Version: 4.1.4 Standards-Version: 4.1.4
Build-Depends: debhelper (>= 9), Build-Depends: debhelper (>= 9),
autoconf,
automake,
autopoint,
libtool,
patch,
pkg-config, pkg-config,
make (>= 4), make (>= 4),
libssl-dev, libssl-dev,
libxml2-dev,
zlib1g-dev,
liblz4-dev,
libgnutls28-dev,
libp11-kit-dev,
nettle-dev,
libgmp-dev,
libsecret-1-0, libsecret-1-0,
libayatana-appindicator3-1, libayatana-appindicator3-1,
gnome-keyring, gnome-keyring,
libwebkit2gtk-4.1-dev, libwebkit2gtk-4.1-dev,
libopenconnect-dev (>= 8.20),
rust-@RUST_VERSION@-all rust-@RUST_VERSION@-all
Homepage: https://github.com/yuezk/GlobalProtect-openconnect Homepage: https://github.com/yuezk/GlobalProtect-openconnect
@@ -32,6 +21,7 @@ Multi-Arch: foreign
Depends: Depends:
${misc:Depends}, ${misc:Depends},
${shlibs:Depends}, ${shlibs:Depends},
vpnc-scripts,
libsecret-1-0, libsecret-1-0,
libayatana-appindicator3-1, libayatana-appindicator3-1,
gnome-keyring, gnome-keyring,
-68
View File
@@ -1,68 +0,0 @@
# syntax=docker/dockerfile:1
ARG ALPINE_VERSION=3.23
ARG RUST_VERSION=1.89
FROM rust:${RUST_VERSION}-alpine AS builder
WORKDIR /src
RUN apk add --no-cache \
autoconf \
automake \
build-base \
file \
gettext-dev \
gmp-dev \
gnutls-dev \
libtool \
libxml2-dev \
linux-headers \
lz4-dev \
make \
nettle-dev \
openssl-dev \
p11-kit-dev \
patch \
pkgconf \
zlib-dev
COPY . .
RUN RUSTFLAGS="-C target-feature=-crt-static" \
make build \
BUILD_GUI_HELPER=0 \
INCLUDE_GUI=0 \
LIBXML2_STATIC=1
RUN install -Dm755 target/release/gpclient /out/usr/bin/gpclient \
&& install -Dm755 target/release/gpauth /out/usr/bin/gpauth \
&& install -Dm755 packaging/files/usr/libexec/gpclient/vpnc-script /out/usr/libexec/gpclient/vpnc-script \
&& install -Dm755 packaging/files/usr/libexec/gpclient/hipreport.sh /out/usr/libexec/gpclient/hipreport.sh
FROM alpine:${ALPINE_VERSION}
ENV SUDO_UID=1000 \
HOME=/root
RUN apk add --no-cache \
ca-certificates \
gmp \
gnutls \
iproute2 \
iputils \
libgcc \
libxml2 \
lz4-libs \
nettle \
openssl \
p11-kit \
zlib \
&& addgroup -g 1000 gp \
&& adduser -D -u 1000 -G gp gp \
&& update-ca-certificates
COPY --from=builder /out/ /
ENTRYPOINT ["gpclient"]
CMD ["--help"]
@@ -4,16 +4,13 @@
LOGFILE="/tmp/gpclient-hipreport.log" LOGFILE="/tmp/gpclient-hipreport.log"
LINUX_GPCLIENT_BIN="/usr/bin/gpclient" LINUX_GPCLIENT_BIN="/usr/bin/gpclient"
ARM64_HOMEBREW_GPCLIENT_BIN="/opt/homebrew/bin/gpclient" HOMEBREW_GPCLIENT_BIN="/opt/homebrew/bin/gpclient"
X86_64_HOMEBREW_GPCLIENT_BIN="/usr/local/bin/gpclient"
GPCLIENT_BIN="" GPCLIENT_BIN=""
if [ -x "$LINUX_GPCLIENT_BIN" ]; then if [ -x "$LINUX_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$LINUX_GPCLIENT_BIN" GPCLIENT_BIN="$LINUX_GPCLIENT_BIN"
elif [ -x "$ARM64_HOMEBREW_GPCLIENT_BIN" ]; then elif [ -x "$HOMEBREW_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$ARM64_HOMEBREW_GPCLIENT_BIN" GPCLIENT_BIN="$HOMEBREW_GPCLIENT_BIN"
elif [ -x "$X86_64_HOMEBREW_GPCLIENT_BIN" ]; then
GPCLIENT_BIN="$X86_64_HOMEBREW_GPCLIENT_BIN"
else else
echo "Error: gpclient binary not found." > "$LOGFILE" echo "Error: gpclient binary not found." > "$LOGFILE"
exit 1 exit 1
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -8,9 +8,10 @@ pkgdesc="A GUI client for GlobalProtect VPN, based on OpenConnect, supports the
arch=('x86_64' 'aarch64') arch=('x86_64' 'aarch64')
url="https://github.com/yuezk/GlobalProtect-openconnect" url="https://github.com/yuezk/GlobalProtect-openconnect"
license=('GPL3') license=('GPL3')
makedepends=('make' 'pkg-config' 'cargo' 'file' 'autoconf' 'automake' 'gettext' 'libtool' 'patch') makedepends=('make' 'pkg-config' 'cargo' 'file')
depends=('webkit2gtk-4.1' 'libappindicator-gtk3' 'librsvg' 'libsecret' 'openssl' 'appmenu-gtk-module' depends=('webkit2gtk-4.1' 'libappindicator-gtk3' 'librsvg' 'libsecret' 'openssl' 'appmenu-gtk-module'
'gnutls' 'libxml2' 'zlib' 'lz4' 'libp11-kit' 'nettle' 'gmp' 'xdg-utils') 'gnutls' 'libxml2' 'vpnc' 'lz4' 'libp11-kit' 'nettle' 'xdg-utils'
'openconnect>=8.20')
optdepends=('wmctrl: for window management') optdepends=('wmctrl: for window management')
provides=('globalprotect-openconnect' 'gpclient' 'gpservice' 'gpauth' 'gpgui') provides=('globalprotect-openconnect' 'gpclient' 'gpservice' 'gpauth' 'gpgui')
@@ -12,18 +12,11 @@ BuildRequires: make
BuildRequires: libtool BuildRequires: libtool
BuildRequires: autoconf BuildRequires: autoconf
BuildRequires: automake BuildRequires: automake
BuildRequires: gettext
BuildRequires: gcc-c++ BuildRequires: gcc-c++
BuildRequires: cargo BuildRequires: cargo
BuildRequires: pkg-config BuildRequires: pkg-config
BuildRequires: openconnect-devel
BuildRequires: (openssl-devel or libopenssl-devel) BuildRequires: (openssl-devel or libopenssl-devel)
BuildRequires: libxml2-devel
BuildRequires: zlib-devel
BuildRequires: (lz4-devel or liblz4-devel)
BuildRequires: gnutls-devel
BuildRequires: p11-kit-devel
BuildRequires: (nettle-devel or libnettle-devel)
BuildRequires: gmp-devel
BuildRequires: wget BuildRequires: wget
BuildRequires: file BuildRequires: file
BuildRequires: perl BuildRequires: perl
@@ -37,6 +30,9 @@ BuildRequires: webkit2gtk4.1-devel
BuildRequires: (libappindicator-gtk3-devel or libappindicator3-1) BuildRequires: (libappindicator-gtk3-devel or libappindicator3-1)
BuildRequires: (librsvg2-devel or librsvg-devel) BuildRequires: (librsvg2-devel or librsvg-devel)
# Still requires openconnect because of the latest vpnc-script it provides on
# some distros (e.g., opensuse)
Requires: openconnect >= 8.20
Requires: (libappindicator-gtk3 or libayatana-appindicator) Requires: (libappindicator-gtk3 or libayatana-appindicator)
Conflicts: globalprotect-openconnect-snapshot Conflicts: globalprotect-openconnect-snapshot
@@ -62,7 +58,6 @@ make build
%files %files
%defattr(-,root,root) %defattr(-,root,root)
%{_bindir}/* %{_bindir}/*
%{_libexecdir}/gpclient/vpnc-script
%{_libexecdir}/gpclient/hipreport.sh %{_libexecdir}/gpclient/hipreport.sh
%{_datadir}/applications/gpgui.desktop %{_datadir}/applications/gpgui.desktop
%{_datadir}/icons/hicolor/32x32/apps/gpgui.png %{_datadir}/icons/hicolor/32x32/apps/gpgui.png
-90
View File
@@ -1,90 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
REPO="yuezk/GlobalProtect-openconnect"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
FLAKE_FILE="$PROJECT_DIR/flake.nix"
usage() {
echo "Usage: $0 [version]"
echo
echo "Updates flake.nix fetchzip hashes from the published GitHub release assets."
echo "When version is omitted, the workspace package version from Cargo.toml is used."
}
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
usage
exit 0
fi
if ! command -v nix > /dev/null; then
echo "nix is required to calculate unpacked fetchzip hashes" >&2
exit 1
fi
if ! command -v jq > /dev/null; then
echo "jq is required to read nix prefetch output" >&2
exit 1
fi
version="${1:-}"
if [[ -z "$version" ]]; then
version="$(grep '^version' "$PROJECT_DIR/Cargo.toml" | head -1 | sed 's/version *= *"\(.*\)"/\1/')"
fi
version="${version#v}"
if [[ -z "$version" ]]; then
echo "Could not determine release version" >&2
exit 1
fi
prefetch_hash() {
local url="$1"
local attempt
for attempt in {1..12}; do
if nix \
--extra-experimental-features nix-command \
store prefetch-file \
--hash-type sha256 \
--json \
--unpack \
"$url" \
| jq -r '.hash'; then
return 0
fi
echo "Asset is not ready yet, retrying ($attempt/12): $url" >&2
sleep 10
done
echo "Failed to prefetch release asset: $url" >&2
return 1
}
release_url() {
local asset="$1"
echo "https://github.com/$REPO/releases/download/v$version/$asset"
}
source_hash="$(prefetch_hash "$(release_url "globalprotect-openconnect-$version.tar.gz")")"
gpgui_x86_64_hash="$(prefetch_hash "$(release_url "gpgui_x86_64.bin.tar.xz")")"
gpgui_aarch64_hash="$(prefetch_hash "$(release_url "gpgui_aarch64.bin.tar.xz")")"
SOURCE_HASH="$source_hash" \
GPGUI_X86_64_HASH="$gpgui_x86_64_hash" \
GPGUI_AARCH64_HASH="$gpgui_aarch64_hash" \
perl -0pi -e '
s|(url = "https://github\.com/yuezk/GlobalProtect-openconnect/releases/download/v\$\{version\}/globalprotect-openconnect-\$\{version\}\.tar\.gz";\n\s*hash = ")[^"]+(";)|$1 . $ENV{"SOURCE_HASH"} . $2|e;
s|(x86_64 = ")[^"]+(";)|$1 . $ENV{"GPGUI_X86_64_HASH"} . $2|e;
s|(aarch64 = ")[^"]+(";)|$1 . $ENV{"GPGUI_AARCH64_HASH"} . $2|e;
' "$FLAKE_FILE"
grep -F "$source_hash" "$FLAKE_FILE" > /dev/null
grep -F "$gpgui_x86_64_hash" "$FLAKE_FILE" > /dev/null
grep -F "$gpgui_aarch64_hash" "$FLAKE_FILE" > /dev/null
echo "Updated flake.nix hashes for v$version"